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