33e7c373cd288e6d1817b1c16926273c0d679056
[ardour.git] / libs / ardour / audio_diskstream.cc
1 /*
2     Copyright (C) 2000-2006 Paul Davis 
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17 */
18
19 #include <fstream>
20 #include <cstdio>
21 #include <unistd.h>
22 #include <cmath>
23 #include <cerrno>
24 #include <cassert>
25 #include <string>
26 #include <climits>
27 #include <fcntl.h>
28 #include <cstdlib>
29 #include <ctime>
30 #include <sys/stat.h>
31 #include <sys/mman.h>
32
33 #include <pbd/error.h>
34 #include <pbd/basename.h>
35 #include <glibmm/thread.h>
36 #include <pbd/xml++.h>
37 #include <pbd/memento_command.h>
38 #include <pbd/enumwriter.h>
39 #include <pbd/stacktrace.h>
40
41 #include <ardour/ardour.h>
42 #include <ardour/audioengine.h>
43 #include <ardour/analyser.h>
44 #include <ardour/audio_diskstream.h>
45 #include <ardour/utils.h>
46 #include <ardour/configuration.h>
47 #include <ardour/audiofilesource.h>
48 #include <ardour/send.h>
49 #include <ardour/region_factory.h>
50 #include <ardour/audioplaylist.h>
51 #include <ardour/playlist_factory.h>
52 #include <ardour/cycle_timer.h>
53 #include <ardour/audioregion.h>
54 #include <ardour/source_factory.h>
55
56 #include "i18n.h"
57 #include <locale.h>
58
59 using namespace std;
60 using namespace ARDOUR;
61 using namespace PBD;
62
63 size_t  AudioDiskstream::_working_buffers_size = 0;
64 Sample* AudioDiskstream::_mixdown_buffer       = 0;
65 gain_t* AudioDiskstream::_gain_buffer          = 0;
66
67 AudioDiskstream::AudioDiskstream (Session &sess, const string &name, Diskstream::Flag flag)
68         : Diskstream(sess, name, flag)
69         , deprecated_io_node(NULL)
70         , channels (new ChannelList)
71 {
72         /* prevent any write sources from being created */
73
74         in_set_state = true;
75
76         init(flag);
77         use_new_playlist ();
78
79         in_set_state = false;
80 }
81         
82 AudioDiskstream::AudioDiskstream (Session& sess, const XMLNode& node)
83         : Diskstream(sess, node)
84         , deprecated_io_node(NULL)
85         , channels (new ChannelList)
86 {
87         in_set_state = true;
88         init (Recordable);
89
90         if (set_state (node)) {
91                 in_set_state = false;
92                 throw failed_constructor();
93         }
94
95         in_set_state = false;
96
97         if (destructive()) {
98                 use_destructive_playlist ();
99         }
100 }
101
102 void
103 AudioDiskstream::init (Diskstream::Flag f)
104 {
105         Diskstream::init(f);
106
107         /* there are no channels at this point, so these
108            two calls just get speed_buffer_size and wrap_buffer
109            size setup without duplicating their code.
110         */
111
112         set_block_size (_session.get_block_size());
113         allocate_temporary_buffers ();
114
115         add_channel (1);
116         assert(_n_channels == 1);
117 }
118
119 AudioDiskstream::~AudioDiskstream ()
120 {
121         notify_callbacks ();
122
123         {
124                 RCUWriter<ChannelList> writer (channels);
125                 boost::shared_ptr<ChannelList> c = writer.get_copy();
126                 
127                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
128                         delete *chan;
129                 }
130
131                 c->clear();
132         }
133
134         channels.flush ();
135 }
136
137 void
138 AudioDiskstream::allocate_working_buffers()
139 {
140         assert(disk_io_frames() > 0);
141
142         _working_buffers_size = disk_io_frames();
143         _mixdown_buffer       = new Sample[_working_buffers_size];
144         _gain_buffer          = new gain_t[_working_buffers_size];
145 }
146
147 void
148 AudioDiskstream::free_working_buffers()
149 {
150         delete [] _mixdown_buffer;
151         delete [] _gain_buffer;
152         _working_buffers_size = 0;
153         _mixdown_buffer       = 0;
154         _gain_buffer          = 0;
155 }
156
157 void
158 AudioDiskstream::non_realtime_input_change ()
159 {
160         {
161                 Glib::Mutex::Lock lm (state_lock);
162
163                 if (input_change_pending == NoChange) {
164                         return;
165                 }
166
167                 {
168                         RCUWriter<ChannelList> writer (channels);
169                         boost::shared_ptr<ChannelList> c = writer.get_copy();
170                         
171                         _n_channels = c->size();
172                         
173                         if (_io->n_inputs() > _n_channels) {
174                                 add_channel_to (c, _io->n_inputs() - _n_channels);
175                         } else if (_io->n_inputs() < _n_channels) {
176                                 remove_channel_from (c, _n_channels - _io->n_inputs());
177                         }
178                 }
179                 
180                 get_input_sources ();
181                 set_capture_offset ();
182                 
183                 if (first_input_change) {
184                         set_align_style (_persistent_alignment_style);
185                         first_input_change = false;
186                 } else {
187                         set_align_style_from_io ();
188                 }
189                 
190                 input_change_pending = NoChange;
191
192                 /* implicit unlock */
193         }
194         
195         /* reset capture files */
196
197         reset_write_sources (false);
198
199         /* now refill channel buffers */
200
201         if (speed() != 1.0f || speed() != -1.0f) {
202                 seek ((nframes_t) (_session.transport_frame() * (double) speed()));
203         } else {
204                 seek (_session.transport_frame());
205         }
206 }
207
208 void
209 AudioDiskstream::get_input_sources ()
210 {
211         boost::shared_ptr<ChannelList> c = channels.reader();
212
213         uint32_t n;
214         ChannelList::iterator chan;
215         uint32_t ni = _io->n_inputs();
216
217         for (n = 0, chan = c->begin(); chan != c->end() && n < ni; ++chan, ++n) {
218                 
219                 const char **connections = _io->input(n)->get_connections ();
220                 
221                 if (connections == 0 || connections[0] == 0) {
222                         
223                         if ((*chan)->source) {
224                                 // _source->disable_metering ();
225                         }
226                         
227                         (*chan)->source = 0;
228                         
229                 } else {
230                         (*chan)->source = _session.engine().get_port_by_name (connections[0]);
231                 }
232                 
233                 if (connections) {
234                         free (connections);
235                 }
236         }
237 }               
238
239 int
240 AudioDiskstream::find_and_use_playlist (const string& name)
241 {
242         boost::shared_ptr<AudioPlaylist> playlist;
243                 
244         if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (_session.playlist_by_name (name))) == 0) {
245                 playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (_session, name));
246         }
247
248         if (!playlist) {
249                 error << string_compose(_("AudioDiskstream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
250                 return -1;
251         }
252
253         return use_playlist (playlist);
254 }
255
256 int
257 AudioDiskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
258 {
259         assert(boost::dynamic_pointer_cast<AudioPlaylist>(playlist));
260
261         Diskstream::use_playlist(playlist);
262
263         return 0;
264 }
265
266 int
267 AudioDiskstream::use_new_playlist ()
268 {
269         string newname;
270         boost::shared_ptr<AudioPlaylist> playlist;
271         
272         if (!in_set_state && destructive()) {
273                 return 0;
274         }
275
276         if (_playlist) {
277                 newname = Playlist::bump_name (_playlist->name(), _session);
278         } else {
279                 newname = Playlist::bump_name (_name, _session);
280         }
281
282         if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (_session, newname, hidden()))) != 0) {
283                 
284                 playlist->set_orig_diskstream_id (id());
285                 return use_playlist (playlist);
286
287         } else { 
288                 return -1;
289         }
290 }
291
292 int
293 AudioDiskstream::use_copy_playlist ()
294 {
295         assert(audio_playlist());
296
297         if (destructive()) {
298                 return 0;
299         }
300
301         if (_playlist == 0) {
302                 error << string_compose(_("AudioDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
303                 return -1;
304         }
305
306         string newname;
307         boost::shared_ptr<AudioPlaylist> playlist;
308
309         newname = Playlist::bump_name (_playlist->name(), _session);
310         
311         if ((playlist  = boost::dynamic_pointer_cast<AudioPlaylist>(PlaylistFactory::create (audio_playlist(), newname))) != 0) {
312                 playlist->set_orig_diskstream_id (id());
313                 return use_playlist (playlist);
314         } else { 
315                 return -1;
316         }
317 }
318
319 void
320 AudioDiskstream::setup_destructive_playlist ()
321 {
322         SourceList srcs;
323         boost::shared_ptr<ChannelList> c = channels.reader();
324         
325         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
326                 srcs.push_back ((*chan)->write_source);
327         }
328
329         /* a single full-sized region */
330
331         boost::shared_ptr<Region> region (RegionFactory::create (srcs, 0, max_frames - srcs.front()->natural_position(), _name));
332         _playlist->add_region (region, srcs.front()->natural_position());               
333 }
334
335 void
336 AudioDiskstream::use_destructive_playlist ()
337 {
338         /* this is called from the XML-based constructor or ::set_destructive. when called,
339            we already have a playlist and a region, but we need to
340            set up our sources for write. we use the sources associated 
341            with the (presumed single, full-extent) region.
342         */
343
344         boost::shared_ptr<Region> rp = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
345
346         if (!rp) {
347                 reset_write_sources (false, true);
348                 return;
349         }
350
351         boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
352
353         if (region == 0) {
354                 throw failed_constructor();
355         }
356
357         /* be sure to stretch the region out to the maximum length */
358
359         region->set_length (max_frames - region->position(), this);
360
361         uint32_t n;
362         ChannelList::iterator chan;
363         boost::shared_ptr<ChannelList> c = channels.reader();
364
365         for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
366                 (*chan)->write_source = boost::dynamic_pointer_cast<AudioFileSource>(region->source (n));
367                 assert((*chan)->write_source);
368                 (*chan)->write_source->set_allow_remove_if_empty (false);
369
370                 /* this might be false if we switched modes, so force it */
371
372                 (*chan)->write_source->set_destructive (true);
373         }
374
375         /* the source list will never be reset for a destructive track */
376 }
377
378 void
379 AudioDiskstream::check_record_status (nframes_t transport_frame, nframes_t nframes, bool can_record)
380 {
381         int possibly_recording;
382         int rolling;
383         int change;
384         const int transport_rolling = 0x4;
385         const int track_rec_enabled = 0x2;
386         const int global_rec_enabled = 0x1;
387
388         /* merge together the 3 factors that affect record status, and compute
389            what has changed.
390         */
391
392         rolling = _session.transport_speed() != 0.0f;
393         possibly_recording = (rolling << 2) | (record_enabled() << 1) | can_record;
394         change = possibly_recording ^ last_possibly_recording;
395
396         if (possibly_recording == last_possibly_recording) {
397                 return;
398         }
399
400         /* change state */
401
402         /* if per-track or global rec-enable turned on while the other was already on, we've started recording */
403
404         if ((change & track_rec_enabled) && record_enabled() && (!(change & global_rec_enabled) && can_record) || 
405             ((change & global_rec_enabled) && can_record && (!(change & track_rec_enabled) && record_enabled()))) {
406                 
407                 /* starting to record: compute first+last frames */
408
409                 first_recordable_frame = transport_frame + _capture_offset;
410                 last_recordable_frame = max_frames;
411                 capture_start_frame = transport_frame;
412
413                 if (!(last_possibly_recording & transport_rolling) && (possibly_recording & transport_rolling)) {
414
415                         /* was stopped, now rolling (and recording) */
416
417                         if (_alignment_style == ExistingMaterial) {
418                                 first_recordable_frame += _session.worst_output_latency();
419                         } else {
420                                 first_recordable_frame += _roll_delay;
421                         }
422
423                 } else {
424
425                         /* was rolling, but record state changed */
426
427                         if (_alignment_style == ExistingMaterial) {
428
429                                 if (!Config->get_punch_in()) {
430
431                                         /* manual punch in happens at the correct transport frame
432                                            because the user hit a button. but to get alignment correct 
433                                            we have to back up the position of the new region to the 
434                                            appropriate spot given the roll delay.
435                                         */
436
437                                         capture_start_frame -= _roll_delay;
438
439                                         /* XXX paul notes (august 2005): i don't know why
440                                            this is needed.
441                                         */
442
443                                         first_recordable_frame += _capture_offset;
444
445                                 } else {
446
447                                         /* autopunch toggles recording at the precise
448                                            transport frame, and then the DS waits
449                                            to start recording for a time that depends
450                                            on the output latency.
451                                         */
452
453                                         first_recordable_frame += _session.worst_output_latency();
454                                 }
455
456                         } else {
457
458                                 if (Config->get_punch_in()) {
459                                         first_recordable_frame += _roll_delay;
460                                 } else {
461                                         capture_start_frame -= _roll_delay;
462                                 }
463                         }
464                         
465                 }
466
467                 if (recordable() && destructive()) {
468                         boost::shared_ptr<ChannelList> c = channels.reader();
469                         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
470                                 
471                                 RingBufferNPT<CaptureTransition>::rw_vector transvec;
472                                 (*chan)->capture_transition_buf->get_write_vector(&transvec);
473                                 
474                                 if (transvec.len[0] > 0) {
475                                         transvec.buf[0]->type = CaptureStart;
476                                         transvec.buf[0]->capture_val = capture_start_frame;
477                                         (*chan)->capture_transition_buf->increment_write_ptr(1);
478                                 }
479                                 else {
480                                         // bad!
481                                         fatal << X_("programming error: capture_transition_buf is full on rec start!  inconceivable!") 
482                                               << endmsg;
483                                 }
484                         }
485                 }
486
487         } else if (!record_enabled() || !can_record) {
488                 
489                 /* stop recording */
490
491                 last_recordable_frame = transport_frame + _capture_offset;
492                 
493                 if (_alignment_style == ExistingMaterial) {
494                         last_recordable_frame += _session.worst_output_latency();
495                 } else {
496                         last_recordable_frame += _roll_delay;
497                 }
498         }
499
500         last_possibly_recording = possibly_recording;
501 }
502
503 int
504 AudioDiskstream::process (nframes_t transport_frame, nframes_t nframes, nframes_t offset, bool can_record, bool rec_monitors_input)
505 {
506         uint32_t n;
507         boost::shared_ptr<ChannelList> c = channels.reader();
508         ChannelList::iterator chan;
509         int ret = -1;
510         nframes_t rec_offset = 0;
511         nframes_t rec_nframes = 0;
512         bool nominally_recording;
513         bool re = record_enabled ();
514         bool collect_playback = false;
515
516         /* if we've already processed the frames corresponding to this call,
517            just return. this allows multiple routes that are taking input
518            from this diskstream to call our ::process() method, but have
519            this stuff only happen once. more commonly, it allows both
520            the AudioTrack that is using this AudioDiskstream *and* the Session
521            to call process() without problems.
522         */
523
524         if (_processed) {
525                 return 0;
526         }
527
528         commit_should_unlock = false;
529
530         if (!_io->active()) {
531                 _processed = true;
532                 return 0;
533         }
534
535         check_record_status (transport_frame, nframes, can_record);
536
537         nominally_recording = (can_record && re);
538
539         if (nframes == 0) {
540                 _processed = true;
541                 return 0;
542         }
543
544         /* This lock is held until the end of AudioDiskstream::commit, so these two functions
545            must always be called as a pair. The only exception is if this function
546            returns a non-zero value, in which case, ::commit should not be called.
547         */
548
549         // If we can't take the state lock return.
550         if (!state_lock.trylock()) {
551                 return 1;
552         } 
553         commit_should_unlock = true;
554         adjust_capture_position = 0;
555
556         for (chan = c->begin(); chan != c->end(); ++chan) {
557                 (*chan)->current_capture_buffer = 0;
558                 (*chan)->current_playback_buffer  = 0;
559         }
560
561         if (nominally_recording || (_session.get_record_enabled() && Config->get_punch_in())) {
562                 OverlapType ot;
563                 
564                 // Safeguard against situations where process() goes haywire when autopunching and last_recordable_frame < first_recordable_frame
565                 if (last_recordable_frame < first_recordable_frame) {
566                         last_recordable_frame = max_frames;
567
568                 }
569                 
570                 ot = coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
571
572                 switch (ot) {
573                 case OverlapNone:
574                         rec_nframes = 0;
575                         break;
576                         
577                 case OverlapInternal:
578                 /*     ----------    recrange
579                          |---|       transrange
580                 */
581                         rec_nframes = nframes;
582                         rec_offset = 0;
583                         break;
584                         
585                 case OverlapStart:
586                         /*    |--------|    recrange
587                             -----|          transrange
588                         */
589                         rec_nframes = transport_frame + nframes - first_recordable_frame;
590                         if (rec_nframes) {
591                                 rec_offset = first_recordable_frame - transport_frame;
592                         }
593                         break;
594                         
595                 case OverlapEnd:
596                         /*    |--------|    recrange
597                                  |--------  transrange
598                         */
599                         rec_nframes = last_recordable_frame - transport_frame;
600                         rec_offset = 0;
601                         break;
602                         
603                 case OverlapExternal:
604                         /*    |--------|    recrange
605                             --------------  transrange
606                         */
607                         rec_nframes = last_recordable_frame - first_recordable_frame;
608                         rec_offset = first_recordable_frame - transport_frame;
609                         break;
610                 }
611
612                 if (rec_nframes && !was_recording) {
613                         capture_captured = 0;
614                         was_recording = true;
615                 }
616         }
617
618
619         if (can_record && !_last_capture_regions.empty()) {
620                 _last_capture_regions.clear ();
621         }
622
623         if (nominally_recording || rec_nframes) {
624
625                 uint32_t limit = _io->n_inputs ();
626
627                 /* one or more ports could already have been removed from _io, but our
628                    channel setup hasn't yet been updated. prevent us from trying to
629                    use channels that correspond to missing ports. note that the
630                    process callback (from which this is called) is always atomic
631                    with respect to port removal/addition.
632                 */
633
634                 for (n = 0, chan = c->begin(); chan != c->end() && n < limit; ++chan, ++n) {
635                         
636                         ChannelInfo* chaninfo (*chan);
637
638                         chaninfo->capture_buf->get_write_vector (&chaninfo->capture_vector);
639
640                         if (rec_nframes <= chaninfo->capture_vector.len[0]) {
641                                 
642                                 chaninfo->current_capture_buffer = chaninfo->capture_vector.buf[0];
643
644                                 /* note: grab the entire port buffer, but only copy what we were supposed to for recording, and use
645                                    rec_offset
646                                 */
647
648                                 memcpy (chaninfo->current_capture_buffer, _io->input(n)->get_buffer (rec_nframes) + offset + rec_offset, sizeof (Sample) * rec_nframes);
649
650                         } else {
651
652                                 nframes_t total = chaninfo->capture_vector.len[0] + chaninfo->capture_vector.len[1];
653
654                                 if (rec_nframes > total) {
655                                         DiskOverrun ();
656                                         goto out;
657                                 }
658
659                                 Sample* buf = _io->input (n)->get_buffer (nframes) + offset;
660                                 nframes_t first = chaninfo->capture_vector.len[0];
661
662                                 memcpy (chaninfo->capture_wrap_buffer, buf, sizeof (Sample) * first);
663                                 memcpy (chaninfo->capture_vector.buf[0], buf, sizeof (Sample) * first);
664                                 memcpy (chaninfo->capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
665                                 memcpy (chaninfo->capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
666                                 
667                                 chaninfo->current_capture_buffer = chaninfo->capture_wrap_buffer;
668                         }
669                 }
670
671         } else {
672
673                 if (was_recording) {
674                         finish_capture (rec_monitors_input, c);
675                 }
676
677         }
678         
679         if (rec_nframes) {
680                 
681                 /* data will be written to disk */
682
683                 if (rec_nframes == nframes && rec_offset == 0) {
684
685                         for (chan = c->begin(); chan != c->end(); ++chan) {
686                                 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
687                         }
688
689                         playback_distance = nframes;
690
691                 } else {
692
693
694                         /* we can't use the capture buffer as the playback buffer, because
695                            we recorded only a part of the current process' cycle data
696                            for capture.
697                         */
698
699                         collect_playback = true;
700                 }
701
702                 adjust_capture_position = rec_nframes;
703
704         } else if (nominally_recording) {
705
706                 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
707
708                 for (chan = c->begin(); chan != c->end(); ++chan) {
709                         (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
710                 }
711
712                 playback_distance = nframes;
713
714         } else {
715
716                 collect_playback = true;
717         }
718
719         if (collect_playback) {
720
721                 /* we're doing playback */
722
723                 nframes_t necessary_samples;
724
725                 /* no varispeed playback if we're recording, because the output .... TBD */
726
727                 if (rec_nframes == 0 && _actual_speed != 1.0f) {
728                         necessary_samples = (nframes_t) floor ((nframes * fabs (_actual_speed))) + 1;
729                 } else {
730                         necessary_samples = nframes;
731                 }
732                 
733                 for (chan = c->begin(); chan != c->end(); ++chan) {
734                         (*chan)->playback_buf->get_read_vector (&(*chan)->playback_vector);
735                 }
736
737                 n = 0;                  
738
739                 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
740                         
741                         ChannelInfo* chaninfo (*chan);
742
743                         if (necessary_samples <= chaninfo->playback_vector.len[0]) {
744
745                                 chaninfo->current_playback_buffer = chaninfo->playback_vector.buf[0];
746
747                         } else {
748                                 nframes_t total = chaninfo->playback_vector.len[0] + chaninfo->playback_vector.len[1];
749                                 
750                                 if (necessary_samples > total) {
751                                         cerr << "underrun for " << _name << endl;
752                                         DiskUnderrun ();
753                                         goto out;
754                                         
755                                 } else {
756                                         
757                                         memcpy ((char *) chaninfo->playback_wrap_buffer, chaninfo->playback_vector.buf[0],
758                                                 chaninfo->playback_vector.len[0] * sizeof (Sample));
759                                         memcpy (chaninfo->playback_wrap_buffer + chaninfo->playback_vector.len[0], chaninfo->playback_vector.buf[1], 
760                                                 (necessary_samples - chaninfo->playback_vector.len[0]) * sizeof (Sample));
761                                         
762                                         chaninfo->current_playback_buffer = chaninfo->playback_wrap_buffer;
763                                 }
764                         }
765                 } 
766
767                 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
768                         
769                         uint64_t phase = last_phase;
770                         int64_t phi_delta;
771                         nframes_t i = 0;
772
773                         // Linearly interpolate into the alt buffer
774                         // using 40.24 fixp maths (swh)
775
776                         if (phi != target_phi) {
777                                 phi_delta = ((int64_t)(target_phi - phi)) / nframes;
778                         } else {
779                                 phi_delta = 0;
780                         }
781
782                         for (chan = c->begin(); chan != c->end(); ++chan) {
783
784                                 float fr;
785                                 ChannelInfo* chaninfo (*chan);
786
787                                 i = 0;
788                                 phase = last_phase;
789
790                                 for (nframes_t outsample = 0; outsample < nframes; ++outsample) {
791                                         i = phase >> 24;
792                                         fr = (phase & 0xFFFFFF) / 16777216.0f;
793                                         chaninfo->speed_buffer[outsample] = 
794                                                 chaninfo->current_playback_buffer[i] * (1.0f - fr) +
795                                                 chaninfo->current_playback_buffer[i+1] * fr;
796                                         phase += phi + phi_delta;
797                                 }
798                                 
799                                 chaninfo->current_playback_buffer = chaninfo->speed_buffer;
800                         }
801
802                         playback_distance = i; // + 1;
803                         last_phase = (phase & 0xFFFFFF);
804
805                 } else {
806                         playback_distance = nframes;
807                 }
808
809                 phi = target_phi;
810         }
811
812         ret = 0;
813
814   out:
815         _processed = true;
816
817         if (ret) {
818
819                 /* we're exiting with failure, so ::commit will not
820                    be called. unlock the state lock.
821                 */
822                 
823                 commit_should_unlock = false;
824                 state_lock.unlock();
825         } 
826
827         return ret;
828 }
829
830 bool
831 AudioDiskstream::commit (nframes_t nframes)
832 {
833         bool need_butler = false;
834
835         if (!_io->active()) {
836                 return false;
837         }
838
839         if (_actual_speed < 0.0) {
840                 playback_sample -= playback_distance;
841         } else {
842                 playback_sample += playback_distance;
843         }
844
845         boost::shared_ptr<ChannelList> c = channels.reader();
846         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
847
848                 (*chan)->playback_buf->increment_read_ptr (playback_distance);
849                 
850                 if (adjust_capture_position) {
851                         (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
852                 }
853         }
854         
855         if (adjust_capture_position != 0) {
856                 capture_captured += adjust_capture_position;
857                 adjust_capture_position = 0;
858         }
859         
860         if (_slaved) {
861                 if (_io && _io->active()) {
862                         need_butler = c->front()->playback_buf->write_space() >= c->front()->playback_buf->bufsize() / 2;
863                 } else {
864                         need_butler = false;
865                 }
866         } else {
867                 if (_io && _io->active()) {
868                         need_butler = c->front()->playback_buf->write_space() >= disk_io_chunk_frames
869                                 || c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
870                 } else {
871                         need_butler = c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
872                 }
873         }
874
875         if (commit_should_unlock) {
876                 state_lock.unlock();
877         }
878
879         _processed = false;
880
881         return need_butler;
882 }
883
884 void
885 AudioDiskstream::set_pending_overwrite (bool yn)
886 {
887         /* called from audio thread, so we can use the read ptr and playback sample as we wish */
888         
889         pending_overwrite = yn;
890
891         overwrite_frame = playback_sample;
892         overwrite_offset = channels.reader()->front()->playback_buf->get_read_ptr();
893 }
894
895 int
896 AudioDiskstream::overwrite_existing_buffers ()
897 {
898         boost::shared_ptr<ChannelList> c = channels.reader();
899         Sample* mixdown_buffer;
900         float* gain_buffer;
901         int ret = -1;
902         bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
903
904         overwrite_queued = false;
905
906         /* assume all are the same size */
907         nframes_t size = c->front()->playback_buf->bufsize();
908         
909         mixdown_buffer = new Sample[size];
910         gain_buffer = new float[size];
911         
912         /* reduce size so that we can fill the buffer correctly. */
913         size--;
914         
915         uint32_t n=0;
916         nframes_t start;
917
918         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
919
920                 start = overwrite_frame;
921                 nframes_t cnt = size;
922                 
923                 /* to fill the buffer without resetting the playback sample, we need to
924                    do it one or two chunks (normally two).
925
926                    |----------------------------------------------------------------------|
927
928                                        ^
929                                        overwrite_offset
930                     |<- second chunk->||<----------------- first chunk ------------------>|
931                    
932                 */
933                 
934                 nframes_t to_read = size - overwrite_offset;
935
936                 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, *chan, n, reversed)) {
937                         error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
938                                          _id, size, playback_sample) << endmsg;
939                         goto out;
940                 }
941                         
942                 if (cnt > to_read) {
943
944                         cnt -= to_read;
945                 
946                         if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer,
947                                   start, cnt, *chan, n, reversed)) {
948                                 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
949                                                  _id, size, playback_sample) << endmsg;
950                                 goto out;
951                         }
952                 }
953         }
954
955         ret = 0;
956  
957   out:
958         pending_overwrite = false;
959         delete [] gain_buffer;
960         delete [] mixdown_buffer;
961         return ret;
962 }
963
964 int
965 AudioDiskstream::seek (nframes_t frame, bool complete_refill)
966 {
967         uint32_t n;
968         int ret;
969         ChannelList::iterator chan;
970         boost::shared_ptr<ChannelList> c = channels.reader();
971
972         Glib::Mutex::Lock lm (state_lock);
973         
974         for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
975                 (*chan)->playback_buf->reset ();
976                 (*chan)->capture_buf->reset ();
977         }
978         
979         /* can't rec-enable in destructive mode if transport is before start */
980         
981         if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
982                 disengage_record_enable ();
983         }
984         
985         playback_sample = frame;
986         file_frame = frame;
987         
988         if (complete_refill) {
989                 while ((ret = do_refill_with_alloc ()) > 0) ;
990         } else {
991                 ret = do_refill_with_alloc ();
992         }
993
994         return ret;
995 }
996
997 int
998 AudioDiskstream::can_internal_playback_seek (nframes_t distance)
999 {
1000         ChannelList::iterator chan;
1001         boost::shared_ptr<ChannelList> c = channels.reader();
1002
1003         for (chan = c->begin(); chan != c->end(); ++chan) {
1004                 if ((*chan)->playback_buf->read_space() < distance) {
1005                         return false;
1006                 } 
1007         }
1008         return true;
1009 }
1010
1011 int
1012 AudioDiskstream::internal_playback_seek (nframes_t distance)
1013 {
1014         ChannelList::iterator chan;
1015         boost::shared_ptr<ChannelList> c = channels.reader();
1016
1017         for (chan = c->begin(); chan != c->end(); ++chan) {
1018                 (*chan)->playback_buf->increment_read_ptr (distance);
1019         }
1020
1021         first_recordable_frame += distance;
1022         playback_sample += distance;
1023         
1024         return 0;
1025 }
1026
1027 int
1028 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer, nframes_t& start, nframes_t cnt, 
1029                        ChannelInfo* channel_info, int channel, bool reversed)
1030 {
1031         nframes_t this_read = 0;
1032         bool reloop = false;
1033         nframes_t loop_end = 0;
1034         nframes_t loop_start = 0;
1035         nframes_t loop_length = 0;
1036         nframes_t offset = 0;
1037         nframes_t xfade_samples = 0;
1038         Sample    xfade_buf[128];
1039         Location *loc = 0;
1040
1041         /* XXX we don't currently play loops in reverse. not sure why */
1042
1043         if (!reversed) {
1044
1045                 /* Make the use of a Location atomic for this read operation.
1046                    
1047                    Note: Locations don't get deleted, so all we care about
1048                    when I say "atomic" is that we are always pointing to
1049                    the same one and using a start/length values obtained
1050                    just once.
1051                 */
1052                 
1053                 if ((loc = loop_location) != 0) {
1054                         loop_start = loc->start();
1055                         loop_end = loc->end();
1056                         loop_length = loop_end - loop_start;
1057                 }
1058                 
1059                 /* if we are looping, ensure that the first frame we read is at the correct
1060                    position within the loop.
1061                 */
1062                 
1063                 if (loc && start >= loop_end) {
1064                         //cerr << "start adjusted from " << start;
1065                         start = loop_start + ((start - loop_start) % loop_length);
1066                         //cerr << "to " << start << endl;
1067                 }
1068
1069                 //cerr << "start is " << start << "  loopstart: " << loop_start << "  loopend: " << loop_end << endl;
1070         }
1071
1072         while (cnt) {
1073
1074                 if (reversed) {
1075                         start -= cnt;
1076                 }
1077                         
1078                 /* take any loop into account. we can't read past the end of the loop. */
1079
1080                 if (loc && (loop_end - start < cnt)) {
1081                         this_read = loop_end - start;
1082                         //cerr << "reloop true: thisread: " << this_read << "  cnt: " << cnt << endl;
1083                         reloop = true;
1084                 } else {
1085                         reloop = false;
1086                         this_read = cnt;
1087                 }
1088
1089                 if (this_read == 0) {
1090                         break;
1091                 }
1092
1093                 this_read = min(cnt,this_read);
1094
1095                 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
1096                         error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), _id, this_read, 
1097                                          start) << endmsg;
1098                         return -1;
1099                 }
1100
1101                 // xfade loop boundary if appropriate
1102
1103                 if (xfade_samples > 0) {
1104                         // just do a linear xfade for this short bit
1105
1106                         xfade_samples = min(xfade_samples, this_read);
1107
1108                         float delta = 1.0f / xfade_samples;
1109                         float scale = 0.0f;
1110                         Sample * tmpbuf = buf+offset;
1111
1112                         for (size_t i=0; i < xfade_samples; ++i) {
1113                                 *tmpbuf = (*tmpbuf * scale) + xfade_buf[i]*(1.0f - scale);
1114                                 ++tmpbuf;
1115                                 scale += delta; 
1116                         }
1117
1118                         xfade_samples = 0;
1119                 }
1120
1121                 _read_data_count = _playlist->read_data_count();
1122                 
1123                 if (reversed) {
1124
1125                         swap_by_ptr (buf, buf + this_read - 1);
1126                         
1127                 } else {
1128                         start += this_read;
1129                 
1130                         /* if we read to the end of the loop, go back to the beginning */
1131                         
1132                         if (reloop) {
1133                                 // read crossfade samples to apply to the next read
1134
1135                                 xfade_samples = min((nframes_t) 128, cnt-this_read);
1136
1137                                 if (audio_playlist()->read (xfade_buf, mixdown_buffer, gain_buffer, start, xfade_samples, channel) != xfade_samples) {
1138                                         error << string_compose(_("AudioDiskstream %1: cannot read xfade samples %2 from playlist at frame %3"), 
1139                                                                 _id, xfade_samples,start) << endmsg;
1140                                         memset(xfade_buf, 0, xfade_samples * sizeof(Sample)); // just in case
1141                                 }
1142
1143                                 start = loop_start;
1144                         }
1145                 } 
1146
1147                 cnt -= this_read;
1148                 offset += this_read;
1149         }
1150
1151         return 0;
1152 }
1153
1154 int
1155 AudioDiskstream::do_refill_with_alloc ()
1156 {
1157         Sample* mix_buf  = new Sample[disk_io_chunk_frames];
1158         float*  gain_buf = new float[disk_io_chunk_frames];
1159
1160         int ret = _do_refill(mix_buf, gain_buf);
1161         
1162         delete [] mix_buf;
1163         delete [] gain_buf;
1164
1165         return ret;
1166 }
1167
1168 int
1169 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer)
1170 {
1171         int32_t ret = 0;
1172         nframes_t to_read;
1173         RingBufferNPT<Sample>::rw_vector vector;
1174         bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1175         nframes_t total_space;
1176         nframes_t zero_fill;
1177         uint32_t chan_n;
1178         ChannelList::iterator i;
1179         boost::shared_ptr<ChannelList> c = channels.reader();
1180         nframes_t ts;
1181
1182         if (c->empty()) {
1183                 return 0;
1184         }
1185
1186         assert(mixdown_buffer);
1187         assert(gain_buffer);
1188
1189         vector.buf[0] = 0;
1190         vector.len[0] = 0;
1191         vector.buf[1] = 0;
1192         vector.len[1] = 0;
1193
1194         c->front()->playback_buf->get_write_vector (&vector);
1195         
1196         if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1197                 return 0;
1198         }
1199
1200         /* if there are 2+ chunks of disk i/o possible for
1201            this track, let the caller know so that it can arrange
1202            for us to be called again, ASAP.
1203         */
1204         
1205         if (total_space >= (_slaved?3:2) * disk_io_chunk_frames) {
1206                 ret = 1;
1207         }
1208         
1209         /* if we're running close to normal speed and there isn't enough 
1210            space to do disk_io_chunk_frames of I/O, then don't bother.  
1211            
1212            at higher speeds, just do it because the sync between butler
1213            and audio thread may not be good enough.
1214         */
1215         
1216         if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1217                 return 0;
1218         }
1219         
1220         /* when slaved, don't try to get too close to the read pointer. this
1221            leaves space for the buffer reversal to have something useful to
1222            work with.
1223         */
1224         
1225         if (_slaved && total_space < (c->front()->playback_buf->bufsize() / 2)) {
1226                 return 0;
1227         }
1228
1229         /* never do more than disk_io_chunk_frames worth of disk input per call (limit doesn't apply for memset) */
1230
1231         total_space = min (disk_io_chunk_frames, total_space);
1232
1233         if (reversed) {
1234
1235                 if (file_frame == 0) {
1236
1237                         /* at start: nothing to do but fill with silence */
1238
1239                         for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1240                                         
1241                                 ChannelInfo* chan (*i);
1242                                 chan->playback_buf->get_write_vector (&vector);
1243                                 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1244                                 if (vector.len[1]) {
1245                                         memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1246                                 }
1247                                 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1248                         }
1249                         return 0;
1250                 }
1251
1252                 if (file_frame < total_space) {
1253
1254                         /* too close to the start: read what we can, 
1255                            and then zero fill the rest 
1256                         */
1257
1258                         zero_fill = total_space - file_frame;
1259                         total_space = file_frame;
1260                         file_frame = 0;
1261
1262                 } else {
1263                         
1264                         zero_fill = 0;
1265                 }
1266
1267         } else {
1268
1269                 if (file_frame == max_frames) {
1270
1271                         /* at end: nothing to do but fill with silence */
1272                         
1273                         for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1274                                         
1275                                 ChannelInfo* chan (*i);
1276                                 chan->playback_buf->get_write_vector (&vector);
1277                                 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1278                                 if (vector.len[1]) {
1279                                         memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1280                                 }
1281                                 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1282                         }
1283                         return 0;
1284                 }
1285                 
1286                 if (file_frame > max_frames - total_space) {
1287
1288                         /* to close to the end: read what we can, and zero fill the rest */
1289
1290                         zero_fill = total_space - (max_frames - file_frame);
1291                         total_space = max_frames - file_frame;
1292
1293                 } else {
1294                         zero_fill = 0;
1295                 }
1296         }
1297         
1298         nframes_t file_frame_tmp = 0;
1299
1300         for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1301
1302                 ChannelInfo* chan (*i);
1303                 Sample* buf1;
1304                 Sample* buf2;
1305                 nframes_t len1, len2;
1306
1307                 chan->playback_buf->get_write_vector (&vector);
1308
1309                 if (vector.len[0] > disk_io_chunk_frames) {
1310                         
1311                         /* we're not going to fill the first chunk, so certainly do not bother with the
1312                            other part. it won't be connected with the part we do fill, as in:
1313                            
1314                            .... => writable space
1315                            ++++ => readable space
1316                            ^^^^ => 1 x disk_io_chunk_frames that would be filled
1317                            
1318                            |......|+++++++++++++|...............................|
1319                            buf1                buf0
1320                                                 ^^^^^^^^^^^^^^^
1321                            
1322                            
1323                            So, just pretend that the buf1 part isn't there.                                     
1324                            
1325                         */
1326                 
1327                         vector.buf[1] = 0;
1328                         vector.len[1] = 0;
1329                 
1330                 } 
1331
1332                 ts = total_space;
1333                 file_frame_tmp = file_frame;
1334
1335                 buf1 = vector.buf[0];
1336                 len1 = vector.len[0];
1337                 buf2 = vector.buf[1];
1338                 len2 = vector.len[1];
1339
1340                 to_read = min (ts, len1);
1341                 to_read = min (to_read, disk_io_chunk_frames);
1342
1343                 if (to_read) {
1344
1345                         if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1346                                 ret = -1;
1347                                 goto out;
1348                         }
1349
1350                         chan->playback_buf->increment_write_ptr (to_read);
1351                         ts -= to_read;
1352                 }
1353
1354                 to_read = min (ts, len2);
1355
1356                 if (to_read) {
1357
1358                         /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1359                            so read some or all of vector.len[1] as well.
1360                         */
1361
1362                         if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1363                                 ret = -1;
1364                                 goto out;
1365                         }
1366                 
1367                         chan->playback_buf->increment_write_ptr (to_read);
1368                 }
1369
1370                 if (zero_fill) {
1371                         /* do something */
1372                 }
1373
1374         }
1375         
1376         file_frame = file_frame_tmp;
1377
1378   out:
1379
1380         return ret;
1381 }       
1382
1383 /** Flush pending data to disk.
1384  *
1385  * Important note: this function will write *AT MOST* disk_io_chunk_frames
1386  * of data to disk. it will never write more than that.  If it writes that
1387  * much and there is more than that waiting to be written, it will return 1,
1388  * otherwise 0 on success or -1 on failure.
1389  * 
1390  * If there is less than disk_io_chunk_frames to be written, no data will be
1391  * written at all unless @a force_flush is true.
1392  */
1393 int
1394 AudioDiskstream::do_flush (Session::RunContext context, bool force_flush)
1395 {
1396         uint32_t to_write;
1397         int32_t ret = 0;
1398         RingBufferNPT<Sample>::rw_vector vector;
1399         RingBufferNPT<CaptureTransition>::rw_vector transvec;
1400         nframes_t total;
1401
1402         _write_data_count = 0;
1403
1404         transvec.buf[0] = 0;
1405         transvec.buf[1] = 0;
1406         vector.buf[0] = 0;
1407         vector.buf[1] = 0;
1408
1409         boost::shared_ptr<ChannelList> c = channels.reader();
1410         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1411         
1412                 (*chan)->capture_buf->get_read_vector (&vector);
1413
1414                 total = vector.len[0] + vector.len[1];
1415
1416                 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1417                         goto out;
1418                 }
1419
1420                 /* if there are 2+ chunks of disk i/o possible for
1421                    this track, let the caller know so that it can arrange
1422                    for us to be called again, ASAP.
1423                    
1424                    if we are forcing a flush, then if there is* any* extra
1425                    work, let the caller know.
1426
1427                    if we are no longer recording and there is any extra work,
1428                    let the caller know too.
1429                 */
1430
1431                 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1432                         ret = 1;
1433                 } 
1434
1435                 to_write = min (disk_io_chunk_frames, (nframes_t) vector.len[0]);
1436                 
1437                 // check the transition buffer when recording destructive
1438                 // important that we get this after the capture buf
1439
1440                 if (destructive()) {
1441                         (*chan)->capture_transition_buf->get_read_vector(&transvec);
1442                         size_t transcount = transvec.len[0] + transvec.len[1];
1443                         bool have_start = false;
1444                         size_t ti;
1445
1446                         for (ti=0; ti < transcount; ++ti) {
1447                                 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1448                                 
1449                                 if (captrans.type == CaptureStart) {
1450                                         // by definition, the first data we got above represents the given capture pos
1451
1452                                         (*chan)->write_source->mark_capture_start (captrans.capture_val);
1453                                         (*chan)->curr_capture_cnt = 0;
1454
1455                                         have_start = true;
1456                                 }
1457                                 else if (captrans.type == CaptureEnd) {
1458
1459                                         // capture end, the capture_val represents total frames in capture
1460
1461                                         if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1462
1463                                                 // shorten to make the write a perfect fit
1464                                                 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt); 
1465
1466                                                 if (nto_write < to_write) {
1467                                                         ret = 1; // should we?
1468                                                 }
1469                                                 to_write = nto_write;
1470
1471                                                 (*chan)->write_source->mark_capture_end ();
1472                                                 
1473                                                 // increment past this transition, but go no further
1474                                                 ++ti;
1475                                                 break;
1476                                         }
1477                                         else {
1478                                                 // actually ends just beyond this chunk, so force more work
1479                                                 ret = 1;
1480                                                 break;
1481                                         }
1482                                 }
1483                         }
1484
1485                         if (ti > 0) {
1486                                 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1487                         }
1488                 }
1489
1490                 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1491                         error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1492                         return -1;
1493                 }
1494
1495                 (*chan)->capture_buf->increment_read_ptr (to_write);
1496                 (*chan)->curr_capture_cnt += to_write;
1497                 
1498                 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1499                 
1500                         /* we wrote all of vector.len[0] but it wasn't an entire
1501                            disk_io_chunk_frames of data, so arrange for some part 
1502                            of vector.len[1] to be flushed to disk as well.
1503                         */
1504                         
1505                         to_write = min ((nframes_t)(disk_io_chunk_frames - to_write), (nframes_t) vector.len[1]);
1506
1507                         if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1508                                 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1509                                 return -1;
1510                         }
1511
1512                         _write_data_count += (*chan)->write_source->write_data_count();
1513         
1514                         (*chan)->capture_buf->increment_read_ptr (to_write);
1515                         (*chan)->curr_capture_cnt += to_write;
1516                 }
1517         }
1518
1519   out:
1520         return ret;
1521 }
1522
1523 void
1524 AudioDiskstream::transport_stopped (struct tm& when, time_t twhen, bool abort_capture)
1525 {
1526         uint32_t buffer_position;
1527         bool more_work = true;
1528         int err = 0;
1529         boost::shared_ptr<AudioRegion> region;
1530         nframes_t total_capture;
1531         SourceList srcs;
1532         SourceList::iterator src;
1533         ChannelList::iterator chan;
1534         vector<CaptureInfo*>::iterator ci;
1535         boost::shared_ptr<ChannelList> c = channels.reader();
1536         uint32_t n = 0; 
1537         bool mark_write_completed = false;
1538
1539         finish_capture (true, c);
1540
1541         /* butler is already stopped, but there may be work to do 
1542            to flush remaining data to disk.
1543         */
1544
1545         while (more_work && !err) {
1546                 switch (do_flush (Session::TransportContext, true)) {
1547                 case 0:
1548                         more_work = false;
1549                         break;
1550                 case 1:
1551                         break;
1552                 case -1:
1553                         error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1554                         err++;
1555                 }
1556         }
1557
1558         /* XXX is there anything we can do if err != 0 ? */
1559         Glib::Mutex::Lock lm (capture_info_lock);
1560         
1561         if (capture_info.empty()) {
1562                 return;
1563         }
1564
1565         if (abort_capture) {
1566                 
1567                 if (destructive()) {
1568                         goto outout;
1569                 }
1570
1571                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1572
1573                         if ((*chan)->write_source) {
1574                                 
1575                                 (*chan)->write_source->mark_for_remove ();
1576                                 (*chan)->write_source->drop_references ();
1577                                 (*chan)->write_source.reset ();
1578                         }
1579                         
1580                         /* new source set up in "out" below */
1581                 }
1582
1583                 goto out;
1584         } 
1585
1586         for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1587                 total_capture += (*ci)->frames;
1588         }
1589
1590         /* figure out the name for this take */
1591
1592         for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1593
1594                 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1595                 
1596                 if (s) {
1597                         srcs.push_back (s);
1598                         s->update_header (capture_info.front()->start, when, twhen);
1599                         s->set_captured_for (_name);
1600                         s->mark_immutable ();
1601                         if (Config->get_auto_analyse_audio()) {
1602                                 Analyser::queue_source_for_analysis (s, true);
1603                         }
1604                 }
1605         }
1606
1607         /* destructive tracks have a single, never changing region */
1608
1609         if (destructive()) {
1610
1611                 /* send a signal that any UI can pick up to do the right thing. there is 
1612                    a small problem here in that a UI may need the peak data to be ready
1613                    for the data that was recorded and this isn't interlocked with that
1614                    process. this problem is deferred to the UI.
1615                  */
1616                 
1617                 _playlist->Modified();
1618
1619         } else {
1620
1621                 string whole_file_region_name;
1622                 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1623
1624                 /* Register a new region with the Session that
1625                    describes the entire source. Do this first
1626                    so that any sub-regions will obviously be
1627                    children of this one (later!)
1628                 */
1629                 
1630                 try {
1631                         boost::shared_ptr<Region> rx (RegionFactory::create (srcs, c->front()->write_source->last_capture_start_frame(), total_capture, 
1632                                                                              whole_file_region_name,
1633                                                                              0, AudioRegion::Flag (AudioRegion::DefaultFlags|AudioRegion::Automatic|AudioRegion::WholeFile)));
1634
1635                         region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1636                         region->special_set_position (capture_info.front()->start);
1637                 }
1638                 
1639                 
1640                 catch (failed_constructor& err) {
1641                         error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1642                         /* XXX what now? */
1643                 }
1644                 
1645                 _last_capture_regions.push_back (region);
1646
1647                 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1648                 
1649                 XMLNode &before = _playlist->get_state();
1650                 _playlist->freeze ();
1651                 
1652                 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1653                         
1654                         string region_name;
1655
1656                         _session.region_name (region_name, whole_file_region_name, false);
1657                         
1658                         // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->frames << " add region " << region_name << endl;
1659                         
1660                         try {
1661                                 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, buffer_position, (*ci)->frames, region_name));
1662                                 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1663                         }
1664                         
1665                         catch (failed_constructor& err) {
1666                                 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1667                                 continue; /* XXX is this OK? */
1668                         }
1669                         
1670                         region->GoingAway.connect (bind (mem_fun (*this, &Diskstream::remove_region_from_last_capture), boost::weak_ptr<Region>(region)));
1671                         
1672                         _last_capture_regions.push_back (region);
1673                         
1674                         i_am_the_modifier++;
1675                         _playlist->add_region (region, (*ci)->start);
1676                         i_am_the_modifier--;
1677                         
1678                         buffer_position += (*ci)->frames;
1679                 }
1680
1681                 _playlist->thaw ();
1682                 XMLNode &after = _playlist->get_state();
1683                 _session.add_command (new MementoCommand<Playlist>(*_playlist, &before, &after));
1684         }
1685
1686         mark_write_completed = true;
1687
1688   out:
1689         reset_write_sources (mark_write_completed);
1690
1691   outout:
1692
1693         for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1694                 delete *ci;
1695         }
1696
1697         capture_info.clear ();
1698         capture_start_frame = 0;
1699 }
1700
1701 void
1702 AudioDiskstream::transport_looped (nframes_t transport_frame)
1703 {
1704         if (was_recording) {
1705                 // all we need to do is finish this capture, with modified capture length
1706                 boost::shared_ptr<ChannelList> c = channels.reader();
1707
1708                 // adjust the capture length knowing that the data will be recorded to disk
1709                 // only necessary after the first loop where we're recording
1710                 if (capture_info.size() == 0) {
1711                         capture_captured += _capture_offset;
1712
1713                         if (_alignment_style == ExistingMaterial) {
1714                                 capture_captured += _session.worst_output_latency();
1715                         } else {
1716                                 capture_captured += _roll_delay;
1717                         }
1718                 }
1719
1720                 finish_capture (true, c);
1721
1722                 // the next region will start recording via the normal mechanism
1723                 // we'll set the start position to the current transport pos
1724                 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1725                 capture_start_frame = transport_frame;
1726                 first_recordable_frame = transport_frame; // mild lie
1727                 last_recordable_frame = max_frames;
1728                 was_recording = true;
1729
1730                 if (recordable() && destructive()) {
1731                         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1732                                 
1733                                 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1734                                 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1735                                 
1736                                 if (transvec.len[0] > 0) {
1737                                         transvec.buf[0]->type = CaptureStart;
1738                                         transvec.buf[0]->capture_val = capture_start_frame;
1739                                         (*chan)->capture_transition_buf->increment_write_ptr(1);
1740                                 }
1741                                 else {
1742                                         // bad!
1743                                         fatal << X_("programming error: capture_transition_buf is full on rec loop!  inconceivable!") 
1744                                               << endmsg;
1745                                 }
1746                         }
1747                 }
1748
1749         }
1750 }
1751
1752 void
1753 AudioDiskstream::finish_capture (bool rec_monitors_input, boost::shared_ptr<ChannelList> c)
1754 {
1755         was_recording = false;
1756         
1757         if (capture_captured == 0) {
1758                 return;
1759         }
1760
1761         if (recordable() && destructive()) {
1762                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1763                         
1764                         RingBufferNPT<CaptureTransition>::rw_vector transvec;
1765                         (*chan)->capture_transition_buf->get_write_vector(&transvec);
1766                         
1767                         if (transvec.len[0] > 0) {
1768                                 transvec.buf[0]->type = CaptureEnd;
1769                                 transvec.buf[0]->capture_val = capture_captured;
1770                                 (*chan)->capture_transition_buf->increment_write_ptr(1);
1771                         }
1772                         else {
1773                                 // bad!
1774                                 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record!  inconceivable!")) << endmsg;
1775                         }
1776                 }
1777         }
1778         
1779         
1780         CaptureInfo* ci = new CaptureInfo;
1781         
1782         ci->start =  capture_start_frame;
1783         ci->frames = capture_captured;
1784         
1785         /* XXX theoretical race condition here. Need atomic exchange ? 
1786            However, the circumstances when this is called right 
1787            now (either on record-disable or transport_stopped)
1788            mean that no actual race exists. I think ...
1789            We now have a capture_info_lock, but it is only to be used
1790            to synchronize in the transport_stop and the capture info
1791            accessors, so that invalidation will not occur (both non-realtime).
1792         */
1793
1794         // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1795
1796         capture_info.push_back (ci);
1797         capture_captured = 0;
1798 }
1799
1800 void
1801 AudioDiskstream::set_record_enabled (bool yn)
1802 {
1803         if (!recordable() || !_session.record_enabling_legal() || _io->n_inputs() == 0) {
1804                 return;
1805         }
1806
1807         /* can't rec-enable in destructive mode if transport is before start */
1808
1809         if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1810                 return;
1811         }
1812
1813         if (yn && channels.reader()->front()->source == 0) {
1814
1815                 /* pick up connections not initiated *from* the IO object
1816                    we're associated with.
1817                 */
1818
1819                 get_input_sources ();
1820         }
1821
1822         /* yes, i know that this not proof against race conditions, but its
1823            good enough. i think.
1824         */
1825
1826         if (record_enabled() != yn) {
1827                 if (yn) {
1828                         engage_record_enable ();
1829                 } else {
1830                         disengage_record_enable ();
1831                 }
1832         }
1833 }
1834
1835 void
1836 AudioDiskstream::engage_record_enable ()
1837 {
1838         bool rolling = _session.transport_speed() != 0.0f;
1839         boost::shared_ptr<ChannelList> c = channels.reader();
1840
1841         g_atomic_int_set (&_record_enabled, 1);
1842         capturing_sources.clear ();
1843
1844         if (Config->get_monitoring_model() == HardwareMonitoring) {
1845
1846                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1847                         if ((*chan)->source) {
1848                                 (*chan)->source->ensure_monitor_input (!(Config->get_auto_input() && rolling));
1849                         }
1850                         capturing_sources.push_back ((*chan)->write_source);
1851                 }
1852                 
1853         } else {
1854                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1855                         capturing_sources.push_back ((*chan)->write_source);
1856                 }
1857         }
1858
1859         RecordEnableChanged (); /* EMIT SIGNAL */
1860 }
1861
1862 void
1863 AudioDiskstream::disengage_record_enable ()
1864 {
1865         g_atomic_int_set (&_record_enabled, 0);
1866         boost::shared_ptr<ChannelList> c = channels.reader();
1867         if (Config->get_monitoring_model() == HardwareMonitoring) {
1868                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1869                         if ((*chan)->source) {
1870                                 (*chan)->source->ensure_monitor_input (false);
1871                         }
1872                 }
1873         }
1874         capturing_sources.clear ();
1875         RecordEnableChanged (); /* EMIT SIGNAL */
1876 }
1877
1878 XMLNode&
1879 AudioDiskstream::get_state ()
1880 {
1881         XMLNode* node = new XMLNode ("AudioDiskstream");
1882         char buf[64] = "";
1883         LocaleGuard lg (X_("POSIX"));
1884         boost::shared_ptr<ChannelList> c = channels.reader();
1885
1886         node->add_property ("flags", enum_2_string (_flags));
1887
1888         snprintf (buf, sizeof(buf), "%zd", c->size());
1889         node->add_property ("channels", buf);
1890
1891         node->add_property ("playlist", _playlist->name());
1892         
1893         snprintf (buf, sizeof(buf), "%.12g", _visible_speed);
1894         node->add_property ("speed", buf);
1895
1896         node->add_property("name", _name);
1897         id().print (buf, sizeof (buf));
1898         node->add_property("id", buf);
1899
1900         if (!capturing_sources.empty() && _session.get_record_enabled()) {
1901
1902                 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1903                 XMLNode* cs_grandchild;
1904
1905                 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1906                         cs_grandchild = new XMLNode (X_("file"));
1907                         cs_grandchild->add_property (X_("path"), (*i)->path());
1908                         cs_child->add_child_nocopy (*cs_grandchild);
1909                 }
1910
1911                 /* store the location where capture will start */
1912
1913                 Location* pi;
1914
1915                 if (Config->get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1916                         snprintf (buf, sizeof (buf), "%" PRIu32, pi->start());
1917                 } else {
1918                         snprintf (buf, sizeof (buf), "%" PRIu32, _session.transport_frame());
1919                 }
1920
1921                 cs_child->add_property (X_("at"), buf);
1922                 node->add_child_nocopy (*cs_child);
1923         }
1924
1925         if (_extra_xml) {
1926                 node->add_child_copy (*_extra_xml);
1927         }
1928
1929         return* node;
1930 }
1931
1932 int
1933 AudioDiskstream::set_state (const XMLNode& node)
1934 {
1935         const XMLProperty* prop;
1936         XMLNodeList nlist = node.children();
1937         XMLNodeIterator niter;
1938         uint32_t nchans = 1;
1939         XMLNode* capture_pending_node = 0;
1940         LocaleGuard lg (X_("POSIX"));
1941
1942         in_set_state = true;
1943
1944         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1945                 if ((*niter)->name() == IO::state_node_name) {
1946                         deprecated_io_node = new XMLNode (**niter);
1947                 }
1948
1949                 if ((*niter)->name() == X_("CapturingSources")) {
1950                         capture_pending_node = *niter;
1951                 }
1952         }
1953
1954         /* prevent write sources from being created */
1955         
1956         in_set_state = true;
1957         
1958         if ((prop = node.property ("name")) != 0) {
1959                 _name = prop->value();
1960         } 
1961
1962         if (deprecated_io_node) {
1963                 if ((prop = deprecated_io_node->property ("id")) != 0) {
1964                         _id = prop->value ();
1965                 }
1966         } else {
1967                 if ((prop = node.property ("id")) != 0) {
1968                         _id = prop->value ();
1969                 }
1970         }
1971
1972         if ((prop = node.property ("flags")) != 0) {
1973                 _flags = Flag (string_2_enum (prop->value(), _flags));
1974         }
1975
1976         if ((prop = node.property ("channels")) != 0) {
1977                 nchans = atoi (prop->value().c_str());
1978         }
1979         
1980         // create necessary extra channels
1981         // we are always constructed with one and we always need one
1982
1983         _n_channels = channels.reader()->size();
1984         
1985         if (nchans > _n_channels) {
1986
1987                 add_channel (nchans - _n_channels);
1988                 IO::MoreOutputs(_n_channels);
1989
1990         } else if (nchans < _n_channels) {
1991
1992                 remove_channel (_n_channels - nchans);
1993         }
1994
1995         if ((prop = node.property ("playlist")) == 0) {
1996                 return -1;
1997         }
1998
1999         {
2000                 bool had_playlist = (_playlist != 0);
2001         
2002                 if (find_and_use_playlist (prop->value())) {
2003                         return -1;
2004                 }
2005
2006                 if (!had_playlist) {
2007                         _playlist->set_orig_diskstream_id (_id);
2008                 }
2009                 
2010                 if (!destructive() && capture_pending_node) {
2011                         /* destructive streams have one and only one source per channel,
2012                            and so they never end up in pending capture in any useful
2013                            sense.
2014                         */
2015                         use_pending_capture_data (*capture_pending_node);
2016                 }
2017
2018         }
2019
2020         if ((prop = node.property ("speed")) != 0) {
2021                 double sp = atof (prop->value().c_str());
2022
2023                 if (realtime_set_speed (sp, false)) {
2024                         non_realtime_set_speed ();
2025                 }
2026         }
2027
2028         in_set_state = false;
2029
2030         /* make sure this is clear before we do anything else */
2031
2032         capturing_sources.clear ();
2033
2034         /* write sources are handled when we handle the input set 
2035            up of the IO that owns this DS (::non_realtime_input_change())
2036         */
2037                 
2038         return 0;
2039 }
2040
2041 int
2042 AudioDiskstream::use_new_write_source (uint32_t n)
2043 {
2044         boost::shared_ptr<ChannelList> c = channels.reader();
2045
2046         if (!recordable()) {
2047                 return 1;
2048         }
2049
2050         if (n >= c->size()) {
2051                 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
2052                 return -1;
2053         }
2054
2055         ChannelInfo* chan = (*c)[n];
2056         
2057         if (chan->write_source) {
2058                 chan->write_source->done_with_peakfile_writes ();
2059                 chan->write_source->set_allow_remove_if_empty (true);
2060                 chan->write_source.reset ();
2061         }
2062
2063         try {
2064                 if ((chan->write_source = _session.create_audio_source_for_session (*this, n, destructive())) == 0) {
2065                         throw failed_constructor();
2066                 }
2067         } 
2068
2069         catch (failed_constructor &err) {
2070                 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
2071                 chan->write_source.reset ();
2072                 return -1;
2073         }
2074
2075         /* do not remove destructive files even if they are empty */
2076
2077         chan->write_source->set_allow_remove_if_empty (!destructive());
2078
2079         return 0;
2080 }
2081
2082 void
2083 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool force)
2084 {
2085         ChannelList::iterator chan;
2086         boost::shared_ptr<ChannelList> c = channels.reader();
2087         uint32_t n;
2088
2089         if (!recordable()) {
2090                 return;
2091         }
2092         
2093         capturing_sources.clear ();
2094
2095         for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
2096                 if (!destructive()) {
2097
2098                         if ((*chan)->write_source && mark_write_complete) {
2099                                 (*chan)->write_source->mark_streaming_write_completed ();
2100                         }
2101                         use_new_write_source (n);
2102
2103                         if (record_enabled()) {
2104                                 capturing_sources.push_back ((*chan)->write_source);
2105                         }
2106
2107                 } else {
2108                         if ((*chan)->write_source == 0) {
2109                                 use_new_write_source (n);
2110                         }
2111                 }
2112         }
2113
2114         if (destructive()) {
2115
2116                 /* we now have all our write sources set up, so create the
2117                    playlist's single region.
2118                 */
2119
2120                 if (_playlist->empty()) {
2121                         setup_destructive_playlist ();
2122                 }
2123         }
2124 }
2125
2126 int
2127 AudioDiskstream::rename_write_sources ()
2128 {
2129         ChannelList::iterator chan;
2130         boost::shared_ptr<ChannelList> c = channels.reader();
2131         uint32_t n;
2132
2133         for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
2134                 if ((*chan)->write_source != 0) {
2135                         (*chan)->write_source->set_name (_name, destructive());
2136                         /* XXX what to do if one of them fails ? */
2137                 }
2138         }
2139
2140         return 0;
2141 }
2142
2143 void
2144 AudioDiskstream::set_block_size (nframes_t nframes)
2145 {
2146         if (_session.get_block_size() > speed_buffer_size) {
2147                 speed_buffer_size = _session.get_block_size();
2148                 boost::shared_ptr<ChannelList> c = channels.reader();
2149
2150                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2151                         if ((*chan)->speed_buffer) delete [] (*chan)->speed_buffer;
2152                         (*chan)->speed_buffer = new Sample[speed_buffer_size];
2153                 }
2154         }
2155         allocate_temporary_buffers ();
2156 }
2157
2158 void
2159 AudioDiskstream::allocate_temporary_buffers ()
2160 {
2161         /* make sure the wrap buffer is at least large enough to deal
2162            with the speeds up to 1.2, to allow for micro-variation
2163            when slaving to MTC, SMPTE etc.
2164         */
2165
2166         double sp = max (fabsf (_actual_speed), 1.2f);
2167         nframes_t required_wrap_size = (nframes_t) floor (_session.get_block_size() * sp) + 1;
2168
2169         if (required_wrap_size > wrap_buffer_size) {
2170
2171                 boost::shared_ptr<ChannelList> c = channels.reader();
2172
2173                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2174                         if ((*chan)->playback_wrap_buffer) delete [] (*chan)->playback_wrap_buffer;
2175                         (*chan)->playback_wrap_buffer = new Sample[required_wrap_size]; 
2176                         if ((*chan)->capture_wrap_buffer) delete [] (*chan)->capture_wrap_buffer;
2177                         (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];  
2178                 }
2179
2180                 wrap_buffer_size = required_wrap_size;
2181         }
2182 }
2183
2184 void
2185 AudioDiskstream::monitor_input (bool yn)
2186 {
2187         boost::shared_ptr<ChannelList> c = channels.reader();
2188
2189         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2190                 
2191                 if ((*chan)->source) {
2192                         (*chan)->source->ensure_monitor_input (yn);
2193                 }
2194         }
2195 }
2196
2197 void
2198 AudioDiskstream::set_align_style_from_io ()
2199 {
2200         bool have_physical = false;
2201
2202         if (_io == 0) {
2203                 return;
2204         }
2205
2206         get_input_sources ();
2207         
2208         boost::shared_ptr<ChannelList> c = channels.reader();
2209
2210         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2211                 if ((*chan)->source && (*chan)->source->flags() & JackPortIsPhysical) {
2212                         have_physical = true;
2213                         break;
2214                 }
2215         }
2216
2217         if (have_physical) {
2218                 set_align_style (ExistingMaterial);
2219         } else {
2220                 set_align_style (CaptureTime);
2221         }
2222 }
2223
2224 int
2225 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2226 {
2227         while (how_many--) {
2228                 c->push_back (new ChannelInfo(_session.diskstream_buffer_size(), speed_buffer_size, wrap_buffer_size));
2229         }
2230
2231         _n_channels = c->size();
2232
2233         return 0;
2234 }
2235
2236 int
2237 AudioDiskstream::add_channel (uint32_t how_many)
2238 {
2239         RCUWriter<ChannelList> writer (channels);
2240         boost::shared_ptr<ChannelList> c = writer.get_copy();
2241
2242         return add_channel_to (c, how_many);
2243 }
2244
2245 int
2246 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2247 {
2248         while (how_many-- && !c->empty()) {
2249                 delete c->back();
2250                 c->pop_back();
2251         }
2252
2253         _n_channels = c->size();
2254
2255         return 0;
2256 }
2257
2258 int
2259 AudioDiskstream::remove_channel (uint32_t how_many)
2260 {
2261         RCUWriter<ChannelList> writer (channels);
2262         boost::shared_ptr<ChannelList> c = writer.get_copy();
2263         
2264         return remove_channel_from (c, how_many);
2265 }
2266
2267 float
2268 AudioDiskstream::playback_buffer_load () const
2269 {
2270         boost::shared_ptr<ChannelList> c = channels.reader();
2271
2272         return (float) ((double) c->front()->playback_buf->read_space()/
2273                         (double) c->front()->playback_buf->bufsize());
2274 }
2275
2276 float
2277 AudioDiskstream::capture_buffer_load () const
2278 {
2279         boost::shared_ptr<ChannelList> c = channels.reader();
2280
2281         return (float) ((double) c->front()->capture_buf->write_space()/
2282                         (double) c->front()->capture_buf->bufsize());
2283 }
2284
2285 int
2286 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2287 {
2288         const XMLProperty* prop;
2289         XMLNodeList nlist = node.children();
2290         XMLNodeIterator niter;
2291         boost::shared_ptr<AudioFileSource> fs;
2292         boost::shared_ptr<AudioFileSource> first_fs;
2293         SourceList pending_sources;
2294         nframes_t position;
2295
2296         if ((prop = node.property (X_("at"))) == 0) {
2297                 return -1;
2298         }
2299
2300         if (sscanf (prop->value().c_str(), "%" PRIu32, &position) != 1) {
2301                 return -1;
2302         }
2303
2304         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2305                 if ((*niter)->name() == X_("file")) {
2306
2307                         if ((prop = (*niter)->property (X_("path"))) == 0) {
2308                                 continue;
2309                         }
2310
2311                         // This protects sessions from errant CapturingSources in stored sessions
2312                         struct stat sbuf;
2313                         if (stat (prop->value().c_str(), &sbuf)) {
2314                                 continue;
2315                         }
2316
2317                         try {
2318                                 fs = boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createWritable (_session, prop->value(), false, _session.frame_rate()));
2319                         }
2320
2321                         catch (failed_constructor& err) {
2322                                 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2323                                                   _name, prop->value())
2324                                       << endmsg;
2325                                 return -1;
2326                         }
2327
2328                         pending_sources.push_back (fs);
2329                         
2330                         if (first_fs == 0) {
2331                                 first_fs = fs;
2332                         }
2333
2334                         fs->set_captured_for (_name);
2335                 }
2336         }
2337
2338         if (pending_sources.size() == 0) {
2339                 /* nothing can be done */
2340                 return 1;
2341         }
2342
2343         if (pending_sources.size() != _n_channels) {
2344                 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2345                       << endmsg;
2346                 return -1;
2347         }
2348
2349         boost::shared_ptr<AudioRegion> region;
2350         
2351         try {
2352                 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, 0, first_fs->length(),
2353                                                                                           region_name_from_path (first_fs->name(), true), 
2354                                                                                           0, AudioRegion::Flag (AudioRegion::DefaultFlags|AudioRegion::Automatic|AudioRegion::WholeFile)));
2355                 region->special_set_position (0);
2356         }
2357
2358         catch (failed_constructor& err) {
2359                 error << string_compose (_("%1: cannot create whole-file region from pending capture sources"),
2360                                   _name)
2361                       << endmsg;
2362                 
2363                 return -1;
2364         }
2365
2366         try {
2367                 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, 0, first_fs->length(), region_name_from_path (first_fs->name(), true)));
2368         }
2369
2370         catch (failed_constructor& err) {
2371                 error << string_compose (_("%1: cannot create region from pending capture sources"),
2372                                   _name)
2373                       << endmsg;
2374                 
2375                 return -1;
2376         }
2377
2378         _playlist->add_region (region, position);
2379
2380         return 0;
2381 }
2382
2383 int
2384 AudioDiskstream::set_destructive (bool yn)
2385 {
2386         bool bounce_ignored;
2387
2388         if (yn != destructive()) {
2389                 
2390                 if (yn) {
2391                         /* requestor should already have checked this and
2392                            bounced if necessary and desired 
2393                         */
2394                         if (!can_become_destructive (bounce_ignored)) {
2395                                 return -1;
2396                         }
2397                         _flags = Flag (_flags | Destructive);
2398                         use_destructive_playlist ();
2399                 } else {
2400                         _flags = Flag (_flags & ~Destructive);
2401                         reset_write_sources (true, true);
2402                 }
2403         }
2404
2405         return 0;
2406 }
2407
2408 bool
2409 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2410 {
2411         if (!_playlist) {
2412                 requires_bounce = false;
2413                 return false;
2414         }
2415
2416         /* is there only one region ? */
2417
2418         if (_playlist->n_regions() != 1) {
2419                 requires_bounce = true;
2420                 return false;
2421         }
2422
2423         boost::shared_ptr<Region> first = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
2424         assert (first);
2425
2426         /* do the source(s) for the region cover the session start position ? */
2427         
2428         if (first->position() != _session.current_start_frame()) {
2429                 if (first->start() > _session.current_start_frame()) {
2430                         requires_bounce = true;
2431                         return false;
2432                 }
2433         }
2434
2435         /* is the source used by only 1 playlist ? */
2436
2437         boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2438
2439         assert (afirst);
2440
2441         if (afirst->source()->used() > 1) {
2442                 requires_bounce = true; 
2443                 return false;
2444         }
2445
2446         requires_bounce = false;
2447         return true;
2448 }
2449
2450 AudioDiskstream::ChannelInfo::ChannelInfo (nframes_t bufsize, nframes_t speed_size, nframes_t wrap_size)
2451 {
2452         peak_power = 0.0f;
2453         source = 0;
2454         current_capture_buffer = 0;
2455         current_playback_buffer = 0;
2456         curr_capture_cnt = 0;
2457
2458         speed_buffer = new Sample[speed_size];
2459         playback_wrap_buffer = new Sample[wrap_size];
2460         capture_wrap_buffer = new Sample[wrap_size];
2461
2462         playback_buf = new RingBufferNPT<Sample> (bufsize);
2463         capture_buf = new RingBufferNPT<Sample> (bufsize);
2464         capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2465         
2466         /* touch the ringbuffer buffers, which will cause
2467            them to be mapped into locked physical RAM if
2468            we're running with mlockall(). this doesn't do
2469            much if we're not.  
2470         */
2471
2472         memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2473         memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2474         memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2475 }
2476
2477 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2478 {
2479         if (write_source) {
2480                 write_source.reset ();
2481         }
2482                 
2483         if (speed_buffer) {
2484                 delete [] speed_buffer;
2485                 speed_buffer = 0;
2486         }
2487
2488         if (playback_wrap_buffer) {
2489                 delete [] playback_wrap_buffer;
2490                 playback_wrap_buffer = 0;
2491         }
2492
2493         if (capture_wrap_buffer) {
2494                 delete [] capture_wrap_buffer;
2495                 capture_wrap_buffer = 0;
2496         }
2497         
2498         if (playback_buf) {
2499                 delete playback_buf;
2500                 playback_buf = 0;
2501         }
2502
2503         if (capture_buf) {
2504                 delete capture_buf;
2505                 capture_buf = 0;
2506         }
2507
2508         if (capture_transition_buf) {
2509                 delete capture_transition_buf;
2510                 capture_transition_buf = 0;
2511         }
2512 }