potential fix for crashing bug caused by mutex lifetime in ~AudioDiskstream
[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
39 #include <ardour/ardour.h>
40 #include <ardour/audioengine.h>
41 #include <ardour/audio_diskstream.h>
42 #include <ardour/utils.h>
43 #include <ardour/configuration.h>
44 #include <ardour/audiofilesource.h>
45 #include <ardour/destructive_filesource.h>
46 #include <ardour/send.h>
47 #include <ardour/region_factory.h>
48 #include <ardour/audioplaylist.h>
49 #include <ardour/playlist_factory.h>
50 #include <ardour/cycle_timer.h>
51 #include <ardour/audioregion.h>
52 #include <ardour/source_factory.h>
53
54 #include "i18n.h"
55 #include <locale.h>
56
57 using namespace std;
58 using namespace ARDOUR;
59 using namespace PBD;
60
61 size_t  AudioDiskstream::_working_buffers_size = 0;
62 Sample* AudioDiskstream::_mixdown_buffer       = 0;
63 gain_t* AudioDiskstream::_gain_buffer          = 0;
64
65 AudioDiskstream::AudioDiskstream (Session &sess, const string &name, Diskstream::Flag flag)
66         : Diskstream(sess, name, flag)
67         , deprecated_io_node(NULL)
68 {
69         /* prevent any write sources from being created */
70
71         in_set_state = true;
72
73         init(flag);
74         use_new_playlist ();
75
76         in_set_state = false;
77 }
78         
79 AudioDiskstream::AudioDiskstream (Session& sess, const XMLNode& node)
80         : Diskstream(sess, node)
81         , deprecated_io_node(NULL)
82 {
83         in_set_state = true;
84         init (Recordable);
85
86         if (set_state (node)) {
87                 in_set_state = false;
88                 throw failed_constructor();
89         }
90
91         in_set_state = false;
92
93         if (destructive()) {
94                 use_destructive_playlist ();
95         }
96 }
97
98 void
99 AudioDiskstream::init_channel (ChannelInfo &chan)
100 {
101         chan.playback_wrap_buffer = 0;
102         chan.capture_wrap_buffer = 0;
103         chan.speed_buffer = 0;
104         chan.peak_power = 0.0f;
105         chan.source = 0;
106         chan.current_capture_buffer = 0;
107         chan.current_playback_buffer = 0;
108         chan.curr_capture_cnt = 0;
109         
110         chan.playback_buf = new RingBufferNPT<Sample> (_session.diskstream_buffer_size());
111         chan.capture_buf = new RingBufferNPT<Sample> (_session.diskstream_buffer_size());
112         chan.capture_transition_buf = new RingBufferNPT<CaptureTransition> (128);
113         
114         
115         /* touch the ringbuffer buffers, which will cause
116            them to be mapped into locked physical RAM if
117            we're running with mlockall(). this doesn't do
118            much if we're not.  
119         */
120         memset (chan.playback_buf->buffer(), 0, sizeof (Sample) * chan.playback_buf->bufsize());
121         memset (chan.capture_buf->buffer(), 0, sizeof (Sample) * chan.capture_buf->bufsize());
122         memset (chan.capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * chan.capture_transition_buf->bufsize());
123 }
124
125
126 void
127 AudioDiskstream::init (Diskstream::Flag f)
128 {
129         Diskstream::init(f);
130
131         /* there are no channels at this point, so these
132            two calls just get speed_buffer_size and wrap_buffer
133            size setup without duplicating their code.
134         */
135
136         set_block_size (_session.get_block_size());
137         allocate_temporary_buffers ();
138
139         add_channel ();
140         assert(_n_channels == 1);
141 }
142
143 void
144 AudioDiskstream::destroy_channel (ChannelInfo &chan)
145 {
146         if (chan.write_source) {
147                 chan.write_source.reset ();
148         }
149                 
150         if (chan.speed_buffer) {
151                 delete [] chan.speed_buffer;
152         }
153
154         if (chan.playback_wrap_buffer) {
155                 delete [] chan.playback_wrap_buffer;
156         }
157         if (chan.capture_wrap_buffer) {
158                 delete [] chan.capture_wrap_buffer;
159         }
160         
161         delete chan.playback_buf;
162         delete chan.capture_buf;
163         delete chan.capture_transition_buf;
164         
165         chan.playback_buf = 0;
166         chan.capture_buf = 0;
167 }
168
169 AudioDiskstream::~AudioDiskstream ()
170 {
171         {
172                 /* don't be holding this lock as we exit the destructor, glib will wince
173                    visibly since the mutex gets destroyed before we release it.
174                 */
175
176                 Glib::Mutex::Lock lm (state_lock);
177                 
178                 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan)
179                         destroy_channel((*chan));
180                 
181                 channels.clear();
182         }
183 }
184
185 void
186 AudioDiskstream::allocate_working_buffers()
187 {
188         assert(disk_io_frames() > 0);
189
190         _working_buffers_size = disk_io_frames();
191         _mixdown_buffer       = new Sample[_working_buffers_size];
192         _gain_buffer          = new gain_t[_working_buffers_size];
193 }
194
195 void
196 AudioDiskstream::free_working_buffers()
197 {
198         delete [] _mixdown_buffer;
199         delete [] _gain_buffer;
200         _working_buffers_size = 0;
201         _mixdown_buffer       = 0;
202         _gain_buffer          = 0;
203 }
204
205 void
206 AudioDiskstream::non_realtime_input_change ()
207 {
208         { 
209                 Glib::Mutex::Lock lm (state_lock);
210
211                 if (input_change_pending == NoChange) {
212                         return;
213                 }
214
215                 if (input_change_pending & ConfigurationChanged) {
216
217                         if (_io->n_inputs() > _n_channels) {
218                                 
219                                 // we need to add new channel infos
220                                 
221                                 int diff = _io->n_inputs() - channels.size();
222                                 
223                                 for (int i = 0; i < diff; ++i) {
224                                         add_channel ();
225                                 }
226                                 
227                 } else if (_io->n_inputs() < _n_channels) {
228                                 
229                                 // we need to get rid of channels
230                                 
231                                 int diff = channels.size() - _io->n_inputs();
232                                 
233                                 for (int i = 0; i < diff; ++i) {
234                                         remove_channel ();
235                                 }
236                         }
237                 } 
238
239                 get_input_sources ();
240                 set_capture_offset ();
241                 
242                 if (first_input_change) {
243                         set_align_style (_persistent_alignment_style);
244                         first_input_change = false;
245                 } else {
246                         set_align_style_from_io ();
247                 }
248
249                 input_change_pending = NoChange;
250         }
251
252         /* reset capture files */
253
254         reset_write_sources (false);
255
256         /* now refill channel buffers */
257
258         if (speed() != 1.0f || speed() != -1.0f) {
259                 seek ((nframes_t) (_session.transport_frame() * (double) speed()));
260         } else {
261                 seek (_session.transport_frame());
262         }
263 }
264
265 void
266 AudioDiskstream::get_input_sources ()
267 {
268         uint32_t ni = _io->n_inputs();
269         
270         for (uint32_t n = 0; n < ni; ++n) {
271                 
272                 const char **connections = _io->input(n)->get_connections ();
273                 ChannelInfo& chan = channels[n];
274                 
275                 if (connections == 0 || connections[0] == 0) {
276                         
277                         if (chan.source) {
278                                 // _source->disable_metering ();
279                         }
280                         
281                         chan.source = 0;
282                         
283                 } else {
284                         chan.source = _session.engine().get_port_by_name (connections[0]);
285                 }
286                 
287                 if (connections) {
288                         free (connections);
289                 }
290         }
291 }               
292
293 int
294 AudioDiskstream::find_and_use_playlist (const string& name)
295 {
296         boost::shared_ptr<AudioPlaylist> playlist;
297                 
298         if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (_session.playlist_by_name (name))) == 0) {
299                 playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (_session, name));
300         }
301
302         if (!playlist) {
303                 error << string_compose(_("AudioDiskstream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
304                 return -1;
305         }
306
307         return use_playlist (playlist);
308 }
309
310 int
311 AudioDiskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
312 {
313         assert(boost::dynamic_pointer_cast<AudioPlaylist>(playlist));
314
315         Diskstream::use_playlist(playlist);
316
317         return 0;
318 }
319
320 int
321 AudioDiskstream::use_new_playlist ()
322 {
323         string newname;
324         boost::shared_ptr<AudioPlaylist> playlist;
325
326         if (!in_set_state && destructive()) {
327                 return 0;
328         }
329
330         if (_playlist) {
331                 newname = Playlist::bump_name (_playlist->name(), _session);
332         } else {
333                 newname = Playlist::bump_name (_name, _session);
334         }
335
336         if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (_session, newname, hidden()))) != 0) {
337                 
338                 playlist->set_orig_diskstream_id (id());
339                 return use_playlist (playlist);
340
341         } else { 
342                 return -1;
343         }
344 }
345
346 int
347 AudioDiskstream::use_copy_playlist ()
348 {
349         assert(audio_playlist());
350
351         if (destructive()) {
352                 return 0;
353         }
354
355         if (_playlist == 0) {
356                 error << string_compose(_("AudioDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
357                 return -1;
358         }
359
360         string newname;
361         boost::shared_ptr<AudioPlaylist> playlist;
362
363         newname = Playlist::bump_name (_playlist->name(), _session);
364         
365         if ((playlist  = boost::dynamic_pointer_cast<AudioPlaylist>(PlaylistFactory::create (audio_playlist(), newname))) != 0) {
366                 playlist->set_orig_diskstream_id (id());
367                 return use_playlist (playlist);
368         } else { 
369                 return -1;
370         }
371 }
372
373 void
374 AudioDiskstream::setup_destructive_playlist ()
375 {
376         SourceList srcs;
377
378         for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
379                 srcs.push_back ((*chan).write_source);
380         }
381
382         /* a single full-sized region */
383
384         boost::shared_ptr<Region> region (RegionFactory::create (srcs, 0, max_frames - srcs.front()->natural_position(), _name));
385         _playlist->add_region (region, srcs.front()->natural_position());               
386 }
387
388 void
389 AudioDiskstream::use_destructive_playlist ()
390 {
391         /* this is called from the XML-based constructor or ::set_destructive. when called,
392            we already have a playlist and a region, but we need to
393            set up our sources for write. we use the sources associated 
394            with the (presumed single, full-extent) region.
395         */
396
397         boost::shared_ptr<Region> rp = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
398
399         if (!rp) {
400                 reset_write_sources (false, true);
401                 return;
402         }
403
404         boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
405
406         if (region == 0) {
407                 throw failed_constructor();
408         }
409
410         /* be sure to stretch the region out to the maximum length */
411
412         region->set_length (max_frames - region->position(), this);
413
414         uint32_t n;
415         ChannelList::iterator chan;
416
417         for (n = 0, chan = channels.begin(); chan != channels.end(); ++chan, ++n) {
418                 (*chan).write_source = boost::dynamic_pointer_cast<AudioFileSource>(region->source (n));
419                 assert((*chan).write_source);
420                 (*chan).write_source->set_allow_remove_if_empty (false);
421
422                 /* this might be false if we switched modes, so force it */
423
424                 (*chan).write_source->set_destructive (true);
425         }
426
427         /* the source list will never be reset for a destructive track */
428 }
429
430 void
431 AudioDiskstream::check_record_status (nframes_t transport_frame, nframes_t nframes, bool can_record)
432 {
433         int possibly_recording;
434         int rolling;
435         int change;
436         const int transport_rolling = 0x4;
437         const int track_rec_enabled = 0x2;
438         const int global_rec_enabled = 0x1;
439
440         /* merge together the 3 factors that affect record status, and compute
441            what has changed.
442         */
443
444         rolling = _session.transport_speed() != 0.0f;
445         possibly_recording = (rolling << 2) | (record_enabled() << 1) | can_record;
446         change = possibly_recording ^ last_possibly_recording;
447
448         if (possibly_recording == last_possibly_recording) {
449                 return;
450         }
451
452         /* change state */
453
454         /* if per-track or global rec-enable turned on while the other was already on, we've started recording */
455
456         if ((change & track_rec_enabled) && record_enabled() && (!(change & global_rec_enabled) && can_record) || 
457             ((change & global_rec_enabled) && can_record && (!(change & track_rec_enabled) && record_enabled()))) {
458                 
459                 /* starting to record: compute first+last frames */
460
461                 first_recordable_frame = transport_frame + _capture_offset;
462                 last_recordable_frame = max_frames;
463                 capture_start_frame = transport_frame;
464
465                 if (!(last_possibly_recording & transport_rolling) && (possibly_recording & transport_rolling)) {
466
467                         /* was stopped, now rolling (and recording) */
468
469                         if (_alignment_style == ExistingMaterial) {
470                                 first_recordable_frame += _session.worst_output_latency();
471                         } else {
472                                 first_recordable_frame += _roll_delay;
473                         }
474
475                 } else {
476
477                         /* was rolling, but record state changed */
478
479                         if (_alignment_style == ExistingMaterial) {
480
481                                 if (!Config->get_punch_in()) {
482
483                                         /* manual punch in happens at the correct transport frame
484                                            because the user hit a button. but to get alignment correct 
485                                            we have to back up the position of the new region to the 
486                                            appropriate spot given the roll delay.
487                                         */
488
489                                         capture_start_frame -= _roll_delay;
490
491                                         /* XXX paul notes (august 2005): i don't know why
492                                            this is needed.
493                                         */
494
495                                         first_recordable_frame += _capture_offset;
496
497                                 } else {
498
499                                         /* autopunch toggles recording at the precise
500                                            transport frame, and then the DS waits
501                                            to start recording for a time that depends
502                                            on the output latency.
503                                         */
504
505                                         first_recordable_frame += _session.worst_output_latency();
506                                 }
507
508                         } else {
509
510                                 if (Config->get_punch_in()) {
511                                         first_recordable_frame += _roll_delay;
512                                 } else {
513                                         capture_start_frame -= _roll_delay;
514                                 }
515                         }
516                         
517                 }
518
519                 if (_flags & Recordable) {
520                         for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
521                                 
522                                 RingBufferNPT<CaptureTransition>::rw_vector transvec;
523                                 (*chan).capture_transition_buf->get_write_vector(&transvec);
524                                 
525                                 if (transvec.len[0] > 0) {
526                                         transvec.buf[0]->type = CaptureStart;
527                                         transvec.buf[0]->capture_val = capture_start_frame;
528                                         (*chan).capture_transition_buf->increment_write_ptr(1);
529                                 }
530                                 else {
531                                         // bad!
532                                         fatal << X_("programming error: capture_transition_buf is full on rec start!  inconceivable!") 
533                                               << endmsg;
534                                 }
535                         }
536                 }
537
538         } else if (!record_enabled() || !can_record) {
539                 
540                 /* stop recording */
541
542                 last_recordable_frame = transport_frame + _capture_offset;
543                 
544                 if (_alignment_style == ExistingMaterial) {
545                         last_recordable_frame += _session.worst_output_latency();
546                 } else {
547                         last_recordable_frame += _roll_delay;
548                 }
549         }
550
551         last_possibly_recording = possibly_recording;
552 }
553
554 int
555 AudioDiskstream::process (nframes_t transport_frame, nframes_t nframes, nframes_t offset, bool can_record, bool rec_monitors_input)
556 {
557         uint32_t n;
558         ChannelList::iterator c;
559         int ret = -1;
560         nframes_t rec_offset = 0;
561         nframes_t rec_nframes = 0;
562         bool nominally_recording;
563         bool re = record_enabled ();
564         bool collect_playback = false;
565
566         /* if we've already processed the frames corresponding to this call,
567            just return. this allows multiple routes that are taking input
568            from this diskstream to call our ::process() method, but have
569            this stuff only happen once. more commonly, it allows both
570            the AudioTrack that is using this AudioDiskstream *and* the Session
571            to call process() without problems.
572         */
573
574         if (_processed) {
575                 return 0;
576         }
577
578         check_record_status (transport_frame, nframes, can_record);
579
580         nominally_recording = (can_record && re);
581
582         if (nframes == 0) {
583                 _processed = true;
584                 return 0;
585         }
586
587         /* This lock is held until the end of AudioDiskstream::commit, so these two functions
588            must always be called as a pair. The only exception is if this function
589            returns a non-zero value, in which case, ::commit should not be called.
590         */
591
592         // If we can't take the state lock return.
593         if (!state_lock.trylock()) {
594                 return 1;
595         }
596
597         adjust_capture_position = 0;
598
599         for (c = channels.begin(); c != channels.end(); ++c) {
600                 (*c).current_capture_buffer = 0;
601                 (*c).current_playback_buffer  = 0;
602         }
603
604         if (nominally_recording || (_session.get_record_enabled() && Config->get_punch_in())) {
605                 OverlapType ot;
606                 
607                 ot = coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
608
609                 switch (ot) {
610                 case OverlapNone:
611                         rec_nframes = 0;
612                         break;
613                         
614                 case OverlapInternal:
615                 /*     ----------    recrange
616                          |---|       transrange
617                 */
618                         rec_nframes = nframes;
619                         rec_offset = 0;
620                         break;
621                         
622                 case OverlapStart:
623                         /*    |--------|    recrange
624                             -----|          transrange
625                         */
626                         rec_nframes = transport_frame + nframes - first_recordable_frame;
627                         if (rec_nframes) {
628                                 rec_offset = first_recordable_frame - transport_frame;
629                         }
630                         break;
631                         
632                 case OverlapEnd:
633                         /*    |--------|    recrange
634                                  |--------  transrange
635                         */
636                         rec_nframes = last_recordable_frame - transport_frame;
637                         rec_offset = 0;
638                         break;
639                         
640                 case OverlapExternal:
641                         /*    |--------|    recrange
642                             --------------  transrange
643                         */
644                         rec_nframes = last_recordable_frame - last_recordable_frame;
645                         rec_offset = first_recordable_frame - transport_frame;
646                         break;
647                 }
648
649                 if (rec_nframes && !was_recording) {
650                         capture_captured = 0;
651                         was_recording = true;
652                 }
653         }
654
655
656         if (can_record && !_last_capture_regions.empty()) {
657                 _last_capture_regions.clear ();
658         }
659
660         if (nominally_recording || rec_nframes) {
661
662                 for (n = 0, c = channels.begin(); c != channels.end(); ++c, ++n) {
663                         
664                         ChannelInfo& chan (*c);
665                 
666                         chan.capture_buf->get_write_vector (&chan.capture_vector);
667
668                         if (rec_nframes <= chan.capture_vector.len[0]) {
669                                 
670                                 chan.current_capture_buffer = chan.capture_vector.buf[0];
671
672                                 /* note: grab the entire port buffer, but only copy what we were supposed to for recording, and use
673                                    rec_offset
674                                 */
675
676                                 memcpy (chan.current_capture_buffer, _io->input(n)->get_buffer (rec_nframes) + offset + rec_offset, sizeof (Sample) * rec_nframes);
677
678                         } else {
679
680                                 nframes_t total = chan.capture_vector.len[0] + chan.capture_vector.len[1];
681
682                                 if (rec_nframes > total) {
683                                         DiskOverrun ();
684                                         goto out;
685                                 }
686
687                                 Sample* buf = _io->input (n)->get_buffer (nframes) + offset;
688                                 nframes_t first = chan.capture_vector.len[0];
689
690                                 memcpy (chan.capture_wrap_buffer, buf, sizeof (Sample) * first);
691                                 memcpy (chan.capture_vector.buf[0], buf, sizeof (Sample) * first);
692                                 memcpy (chan.capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
693                                 memcpy (chan.capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
694                                 
695                                 chan.current_capture_buffer = chan.capture_wrap_buffer;
696                         }
697                 }
698
699         } else {
700
701                 if (was_recording) {
702                         finish_capture (rec_monitors_input);
703                 }
704
705         }
706         
707         if (rec_nframes) {
708                 
709                 /* data will be written to disk */
710
711                 if (rec_nframes == nframes && rec_offset == 0) {
712
713                         for (c = channels.begin(); c != channels.end(); ++c) {
714                                 (*c).current_playback_buffer = (*c).current_capture_buffer;
715                         }
716
717                         playback_distance = nframes;
718
719                 } else {
720
721
722                         /* we can't use the capture buffer as the playback buffer, because
723                            we recorded only a part of the current process' cycle data
724                            for capture.
725                         */
726
727                         collect_playback = true;
728                 }
729
730                 adjust_capture_position = rec_nframes;
731
732         } else if (nominally_recording) {
733
734                 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
735
736                 for (c = channels.begin(); c != channels.end(); ++c) {
737                         (*c).current_playback_buffer = (*c).current_capture_buffer;
738                 }
739
740                 playback_distance = nframes;
741
742         } else {
743
744                 collect_playback = true;
745         }
746
747         if (collect_playback) {
748
749                 /* we're doing playback */
750
751                 nframes_t necessary_samples;
752
753                 /* no varispeed playback if we're recording, because the output .... TBD */
754
755                 if (rec_nframes == 0 && _actual_speed != 1.0f) {
756                         necessary_samples = (nframes_t) floor ((nframes * fabs (_actual_speed))) + 1;
757                 } else {
758                         necessary_samples = nframes;
759                 }
760                 
761                 for (c = channels.begin(); c != channels.end(); ++c) {
762                         (*c).playback_buf->get_read_vector (&(*c).playback_vector);
763                 }
764
765                 n = 0;                  
766
767                 for (c = channels.begin(); c != channels.end(); ++c, ++n) {
768                 
769                         ChannelInfo& chan (*c);
770
771                         if (necessary_samples <= chan.playback_vector.len[0]) {
772
773                                 chan.current_playback_buffer = chan.playback_vector.buf[0];
774
775                         } else {
776                                 nframes_t total = chan.playback_vector.len[0] + chan.playback_vector.len[1];
777                                 
778                                 if (necessary_samples > total) {
779                                         DiskUnderrun ();
780                                         goto out;
781                                         
782                                 } else {
783                                         
784                                         memcpy ((char *) chan.playback_wrap_buffer, chan.playback_vector.buf[0],
785                                                 chan.playback_vector.len[0] * sizeof (Sample));
786                                         memcpy (chan.playback_wrap_buffer + chan.playback_vector.len[0], chan.playback_vector.buf[1], 
787                                                 (necessary_samples - chan.playback_vector.len[0]) * sizeof (Sample));
788                                         
789                                         chan.current_playback_buffer = chan.playback_wrap_buffer;
790                                 }
791                         }
792                 } 
793
794                 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
795                         
796                         uint64_t phase = last_phase;
797                         nframes_t i = 0;
798
799                         // Linearly interpolate into the alt buffer
800                         // using 40.24 fixp maths (swh)
801
802                         for (c = channels.begin(); c != channels.end(); ++c) {
803
804                                 float fr;
805                                 ChannelInfo& chan (*c);
806
807                                 i = 0;
808                                 phase = last_phase;
809
810                                 for (nframes_t outsample = 0; outsample < nframes; ++outsample) {
811                                         i = phase >> 24;
812                                         fr = (phase & 0xFFFFFF) / 16777216.0f;
813                                         chan.speed_buffer[outsample] = 
814                                                 chan.current_playback_buffer[i] * (1.0f - fr) +
815                                                 chan.current_playback_buffer[i+1] * fr;
816                                         phase += phi;
817                                 }
818                                 
819                                 chan.current_playback_buffer = chan.speed_buffer;
820                         }
821
822                         playback_distance = i + 1;
823                         last_phase = (phase & 0xFFFFFF);
824
825                 } else {
826                         playback_distance = nframes;
827                 }
828
829         }
830
831         ret = 0;
832
833   out:
834         _processed = true;
835
836         if (ret) {
837
838                 /* we're exiting with failure, so ::commit will not
839                    be called. unlock the state lock.
840                 */
841                 
842                 state_lock.unlock();
843         } 
844
845         return ret;
846 }
847
848 bool
849 AudioDiskstream::commit (nframes_t nframes)
850 {
851         bool need_butler = false;
852
853         if (_actual_speed < 0.0) {
854                 playback_sample -= playback_distance;
855         } else {
856                 playback_sample += playback_distance;
857         }
858
859         for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
860
861                 (*chan).playback_buf->increment_read_ptr (playback_distance);
862                 
863                 if (adjust_capture_position) {
864                         (*chan).capture_buf->increment_write_ptr (adjust_capture_position);
865                 }
866         }
867         
868         if (adjust_capture_position != 0) {
869                 capture_captured += adjust_capture_position;
870                 adjust_capture_position = 0;
871         }
872         
873         if (_slaved) {
874                 need_butler = channels[0].playback_buf->write_space() >= channels[0].playback_buf->bufsize() / 2;
875         } else {
876                 need_butler = channels[0].playback_buf->write_space() >= disk_io_chunk_frames
877                         || channels[0].capture_buf->read_space() >= disk_io_chunk_frames;
878         }
879
880         state_lock.unlock();
881
882         _processed = false;
883
884         return need_butler;
885 }
886
887 void
888 AudioDiskstream::set_pending_overwrite (bool yn)
889 {
890         /* called from audio thread, so we can use the read ptr and playback sample as we wish */
891         
892         pending_overwrite = yn;
893
894         overwrite_frame = playback_sample;
895         overwrite_offset = channels.front().playback_buf->get_read_ptr();
896 }
897
898 int
899 AudioDiskstream::overwrite_existing_buffers ()
900 {
901         Sample* mixdown_buffer;
902         float* gain_buffer;
903         int ret = -1;
904         bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
905
906         overwrite_queued = false;
907
908         /* assume all are the same size */
909         nframes_t size = channels[0].playback_buf->bufsize();
910         
911         mixdown_buffer = new Sample[size];
912         gain_buffer = new float[size];
913         
914         /* reduce size so that we can fill the buffer correctly. */
915         size--;
916         
917         uint32_t n=0;
918         nframes_t start;
919
920         for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan, ++n) {
921
922                 start = overwrite_frame;
923                 nframes_t cnt = size;
924                 
925                 /* to fill the buffer without resetting the playback sample, we need to
926                    do it one or two chunks (normally two).
927
928                    |----------------------------------------------------------------------|
929
930                                        ^
931                                        overwrite_offset
932                     |<- second chunk->||<----------------- first chunk ------------------>|
933                    
934                 */
935                 
936                 nframes_t to_read = size - overwrite_offset;
937
938                 if (read ((*chan).playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, *chan, n, reversed)) {
939                         error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
940                                          _id, size, playback_sample) << endmsg;
941                         goto out;
942                 }
943                         
944                 if (cnt > to_read) {
945
946                         cnt -= to_read;
947                 
948                         if (read ((*chan).playback_buf->buffer(), mixdown_buffer, gain_buffer,
949                                   start, cnt, *chan, n, reversed)) {
950                                 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
951                                                  _id, size, playback_sample) << endmsg;
952                                 goto out;
953                         }
954                 }
955         }
956
957         ret = 0;
958  
959   out:
960         pending_overwrite = false;
961         delete [] gain_buffer;
962         delete [] mixdown_buffer;
963         return ret;
964 }
965
966 int
967 AudioDiskstream::seek (nframes_t frame, bool complete_refill)
968 {
969         Glib::Mutex::Lock lm (state_lock);
970         uint32_t n;
971         int ret;
972         ChannelList::iterator chan;
973
974         for (n = 0, chan = channels.begin(); chan != channels.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
1002         for (chan = channels.begin(); chan != channels.end(); ++chan) {
1003                 if ((*chan).playback_buf->read_space() < distance) {
1004                         return false;
1005                 } 
1006         }
1007         return true;
1008 }
1009
1010 int
1011 AudioDiskstream::internal_playback_seek (nframes_t distance)
1012 {
1013         ChannelList::iterator chan;
1014
1015         for (chan = channels.begin(); chan != channels.end(); ++chan) {
1016                 (*chan).playback_buf->increment_read_ptr (distance);
1017         }
1018
1019         first_recordable_frame += distance;
1020         playback_sample += distance;
1021         
1022         return 0;
1023 }
1024
1025 int
1026 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer, nframes_t& start, nframes_t cnt, 
1027                   ChannelInfo& channel_info, int channel, bool reversed)
1028 {
1029         nframes_t this_read = 0;
1030         bool reloop = false;
1031         nframes_t loop_end = 0;
1032         nframes_t loop_start = 0;
1033         nframes_t loop_length = 0;
1034         nframes_t offset = 0;
1035         Location *loc = 0;
1036
1037         if (!reversed) {
1038                 /* Make the use of a Location atomic for this read operation.
1039                    
1040                    Note: Locations don't get deleted, so all we care about
1041                    when I say "atomic" is that we are always pointing to
1042                    the same one and using a start/length values obtained
1043                    just once.
1044                 */
1045                 
1046                 if ((loc = loop_location) != 0) {
1047                         loop_start = loc->start();
1048                         loop_end = loc->end();
1049                         loop_length = loop_end - loop_start;
1050                 }
1051                 
1052                 /* if we are looping, ensure that the first frame we read is at the correct
1053                    position within the loop.
1054                 */
1055                 
1056                 if (loc && start >= loop_end) {
1057                         //cerr << "start adjusted from " << start;
1058                         start = loop_start + ((start - loop_start) % loop_length);
1059                         //cerr << "to " << start << endl;
1060                 }
1061                 //cerr << "start is " << start << "  loopstart: " << loop_start << "  loopend: " << loop_end << endl;
1062         }
1063
1064         while (cnt) {
1065
1066                 /* take any loop into account. we can't read past the end of the loop. */
1067
1068                 if (loc && (loop_end - start < cnt)) {
1069                         this_read = loop_end - start;
1070                         //cerr << "reloop true: thisread: " << this_read << "  cnt: " << cnt << endl;
1071                         reloop = true;
1072                 } else {
1073                         reloop = false;
1074                         this_read = cnt;
1075                 }
1076
1077                 if (this_read == 0) {
1078                         break;
1079                 }
1080
1081                 this_read = min(cnt,this_read);
1082
1083                 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
1084                         error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), _id, this_read, 
1085                                          start) << endmsg;
1086                         return -1;
1087                 }
1088
1089                 _read_data_count = _playlist->read_data_count();
1090                 
1091                 if (reversed) {
1092
1093                         /* don't adjust start, since caller has already done that
1094                          */
1095
1096                         swap_by_ptr (buf, buf + this_read - 1);
1097                         
1098                 } else {
1099                         
1100                         /* if we read to the end of the loop, go back to the beginning */
1101                         
1102                         if (reloop) {
1103                                 start = loop_start;
1104                         } else {
1105                                 start += this_read;
1106                         }
1107                 } 
1108
1109                 cnt -= this_read;
1110                 offset += this_read;
1111         }
1112
1113         return 0;
1114 }
1115
1116 int
1117 AudioDiskstream::do_refill_with_alloc()
1118 {
1119         Sample* mix_buf  = new Sample[disk_io_chunk_frames];
1120         float*  gain_buf = new float[disk_io_chunk_frames];
1121
1122         int ret = _do_refill(mix_buf, gain_buf);
1123         
1124         delete [] mix_buf;
1125         delete [] gain_buf;
1126
1127         return ret;
1128 }
1129
1130 int
1131 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer)
1132 {
1133         int32_t ret = 0;
1134         nframes_t to_read;
1135         RingBufferNPT<Sample>::rw_vector vector;
1136         bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1137         nframes_t total_space;
1138         nframes_t zero_fill;
1139         uint32_t chan_n;
1140         ChannelList::iterator i;
1141         nframes_t ts;
1142
1143         assert(mixdown_buffer);
1144         assert(gain_buffer);
1145
1146         channels.front().playback_buf->get_write_vector (&vector);
1147         
1148         if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1149                 return 0;
1150         }
1151         
1152         /* if there are 2+ chunks of disk i/o possible for
1153            this track, let the caller know so that it can arrange
1154            for us to be called again, ASAP.
1155         */
1156         
1157         if (total_space >= (_slaved?3:2) * disk_io_chunk_frames) {
1158                 ret = 1;
1159         }
1160         
1161         /* if we're running close to normal speed and there isn't enough 
1162            space to do disk_io_chunk_frames of I/O, then don't bother.  
1163            
1164            at higher speeds, just do it because the sync between butler
1165            and audio thread may not be good enough.
1166         */
1167         
1168         if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1169                 return 0;
1170         }
1171         
1172         /* when slaved, don't try to get too close to the read pointer. this
1173            leaves space for the buffer reversal to have something useful to
1174            work with.
1175         */
1176         
1177         if (_slaved && total_space < (channels.front().playback_buf->bufsize() / 2)) {
1178                 return 0;
1179         }
1180
1181         total_space = min (disk_io_chunk_frames, total_space);
1182
1183         if (reversed) {
1184
1185                 if (file_frame == 0) {
1186
1187                         /* at start: nothing to do but fill with silence */
1188
1189                         for (chan_n = 0, i = channels.begin(); i != channels.end(); ++i, ++chan_n) {
1190                                         
1191                                 ChannelInfo& chan (*i);
1192                                 chan.playback_buf->get_write_vector (&vector);
1193                                 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1194                                 if (vector.len[1]) {
1195                                         memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1196                                 }
1197                                 chan.playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1198                         }
1199                         return 0;
1200                 }
1201
1202                 if (file_frame < total_space) {
1203
1204                         /* too close to the start: read what we can, 
1205                            and then zero fill the rest 
1206                         */
1207
1208                         zero_fill = total_space - file_frame;
1209                         total_space = file_frame;
1210                         file_frame = 0;
1211
1212                 } else {
1213                         
1214                         /* move read position backwards because we are going
1215                            to reverse the data.
1216                         */
1217                         
1218                         file_frame -= total_space;
1219                         zero_fill = 0;
1220                 }
1221
1222         } else {
1223
1224                 if (file_frame == max_frames) {
1225
1226                         /* at end: nothing to do but fill with silence */
1227                         
1228                         for (chan_n = 0, i = channels.begin(); i != channels.end(); ++i, ++chan_n) {
1229                                         
1230                                 ChannelInfo& chan (*i);
1231                                 chan.playback_buf->get_write_vector (&vector);
1232                                 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1233                                 if (vector.len[1]) {
1234                                         memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1235                                 }
1236                                 chan.playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1237                         }
1238                         return 0;
1239                 }
1240                 
1241                 if (file_frame > max_frames - total_space) {
1242
1243                         /* to close to the end: read what we can, and zero fill the rest */
1244
1245                         zero_fill = total_space - (max_frames - file_frame);
1246                         total_space = max_frames - file_frame;
1247
1248                 } else {
1249                         zero_fill = 0;
1250                 }
1251         }
1252         
1253         nframes_t file_frame_tmp = 0;
1254
1255         for (chan_n = 0, i = channels.begin(); i != channels.end(); ++i, ++chan_n) {
1256
1257                 ChannelInfo& chan (*i);
1258                 Sample* buf1;
1259                 Sample* buf2;
1260                 nframes_t len1, len2;
1261
1262                 chan.playback_buf->get_write_vector (&vector);
1263
1264                 ts = total_space;
1265                 file_frame_tmp = file_frame;
1266
1267                 if (reversed) {
1268                         buf1 = vector.buf[1];
1269                         len1 = vector.len[1];
1270                         buf2 = vector.buf[0];
1271                         len2 = vector.len[0];
1272                 } else {
1273                         buf1 = vector.buf[0];
1274                         len1 = vector.len[0];
1275                         buf2 = vector.buf[1];
1276                         len2 = vector.len[1];
1277                 }
1278
1279
1280                 to_read = min (ts, len1);
1281                 to_read = min (to_read, disk_io_chunk_frames);
1282
1283                 if (to_read) {
1284
1285                         if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1286                                 ret = -1;
1287                                 goto out;
1288                         }
1289                         
1290                         chan.playback_buf->increment_write_ptr (to_read);
1291                         ts -= to_read;
1292                 }
1293
1294                 to_read = min (ts, len2);
1295
1296                 if (to_read) {
1297
1298                         
1299                         /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1300                            so read some or all of vector.len[1] as well.
1301                         */
1302
1303                         if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1304                                 ret = -1;
1305                                 goto out;
1306                         }
1307                 
1308                         chan.playback_buf->increment_write_ptr (to_read);
1309                 }
1310
1311                 if (zero_fill) {
1312                         /* do something */
1313                 }
1314
1315         }
1316         
1317         file_frame = file_frame_tmp;
1318
1319   out:
1320
1321         return ret;
1322 }       
1323
1324 /** Flush pending data to disk.
1325  *
1326  * Important note: this function will write *AT MOST* disk_io_chunk_frames
1327  * of data to disk. it will never write more than that.  If it writes that
1328  * much and there is more than that waiting to be written, it will return 1,
1329  * otherwise 0 on success or -1 on failure.
1330  * 
1331  * If there is less than disk_io_chunk_frames to be written, no data will be
1332  * written at all unless @a force_flush is true.
1333  */
1334 int
1335 AudioDiskstream::do_flush (Session::RunContext context, bool force_flush)
1336 {
1337         uint32_t to_write;
1338         int32_t ret = 0;
1339         RingBufferNPT<Sample>::rw_vector vector;
1340         RingBufferNPT<CaptureTransition>::rw_vector transvec;
1341         nframes_t total;
1342
1343         _write_data_count = 0;
1344
1345         for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
1346         
1347                 (*chan).capture_buf->get_read_vector (&vector);
1348
1349                 total = vector.len[0] + vector.len[1];
1350
1351                 
1352                 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1353                         goto out;
1354                 }
1355
1356                 /* if there are 2+ chunks of disk i/o possible for
1357                    this track, let the caller know so that it can arrange
1358                    for us to be called again, ASAP.
1359                    
1360                    if we are forcing a flush, then if there is* any* extra
1361                    work, let the caller know.
1362
1363                    if we are no longer recording and there is any extra work,
1364                    let the caller know too.
1365                 */
1366
1367                 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1368                         ret = 1;
1369                 } 
1370
1371                 to_write = min (disk_io_chunk_frames, (nframes_t) vector.len[0]);
1372                 
1373                 // check the transition buffer when recording destructive
1374                 // important that we get this after the capture buf
1375
1376                 if (destructive()) {
1377                         (*chan).capture_transition_buf->get_read_vector(&transvec);
1378                         size_t transcount = transvec.len[0] + transvec.len[1];
1379                         bool have_start = false;
1380                         size_t ti;
1381
1382                         for (ti=0; ti < transcount; ++ti) {
1383                                 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1384                                 
1385                                 if (captrans.type == CaptureStart) {
1386                                         // by definition, the first data we got above represents the given capture pos
1387
1388                                         (*chan).write_source->mark_capture_start (captrans.capture_val);
1389                                         (*chan).curr_capture_cnt = 0;
1390
1391                                         have_start = true;
1392                                 }
1393                                 else if (captrans.type == CaptureEnd) {
1394
1395                                         // capture end, the capture_val represents total frames in capture
1396
1397                                         if (captrans.capture_val <= (*chan).curr_capture_cnt + to_write) {
1398
1399                                                 // shorten to make the write a perfect fit
1400                                                 uint32_t nto_write = (captrans.capture_val - (*chan).curr_capture_cnt); 
1401
1402                                                 if (nto_write < to_write) {
1403                                                         ret = 1; // should we?
1404                                                 }
1405                                                 to_write = nto_write;
1406
1407                                                 (*chan).write_source->mark_capture_end ();
1408                                                 
1409                                                 // increment past this transition, but go no further
1410                                                 ++ti;
1411                                                 break;
1412                                         }
1413                                         else {
1414                                                 // actually ends just beyond this chunk, so force more work
1415                                                 ret = 1;
1416                                                 break;
1417                                         }
1418                                 }
1419                         }
1420
1421                         if (ti > 0) {
1422                                 (*chan).capture_transition_buf->increment_read_ptr(ti);
1423                         }
1424                 }
1425
1426                 if ((!(*chan).write_source) || (*chan).write_source->write (vector.buf[0], to_write) != to_write) {
1427                         error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1428                         return -1;
1429                 }
1430
1431                 (*chan).capture_buf->increment_read_ptr (to_write);
1432                 (*chan).curr_capture_cnt += to_write;
1433                 
1434                 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1435                 
1436                         /* we wrote all of vector.len[0] but it wasn't an entire
1437                            disk_io_chunk_frames of data, so arrange for some part 
1438                            of vector.len[1] to be flushed to disk as well.
1439                         */
1440                 
1441                         to_write = min ((nframes_t)(disk_io_chunk_frames - to_write), (nframes_t) vector.len[1]);
1442                 
1443                         if ((*chan).write_source->write (vector.buf[1], to_write) != to_write) {
1444                                 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1445                                 return -1;
1446                         }
1447
1448                         _write_data_count += (*chan).write_source->write_data_count();
1449         
1450                         (*chan).capture_buf->increment_read_ptr (to_write);
1451                         (*chan).curr_capture_cnt += to_write;
1452                 }
1453         }
1454
1455   out:
1456         return ret;
1457 }
1458
1459 void
1460 AudioDiskstream::transport_stopped (struct tm& when, time_t twhen, bool abort_capture)
1461 {
1462         uint32_t buffer_position;
1463         bool more_work = true;
1464         int err = 0;
1465         boost::shared_ptr<AudioRegion> region;
1466         nframes_t total_capture;
1467         SourceList srcs;
1468         SourceList::iterator src;
1469         ChannelList::iterator chan;
1470         vector<CaptureInfo*>::iterator ci;
1471         uint32_t n = 0; 
1472         bool mark_write_completed = false;
1473
1474         finish_capture (true);
1475
1476         /* butler is already stopped, but there may be work to do 
1477            to flush remaining data to disk.
1478         */
1479
1480         while (more_work && !err) {
1481                 switch (do_flush (Session::TransportContext, true)) {
1482                 case 0:
1483                         more_work = false;
1484                         break;
1485                 case 1:
1486                         break;
1487                 case -1:
1488                         error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1489                         err++;
1490                 }
1491         }
1492
1493         /* XXX is there anything we can do if err != 0 ? */
1494         Glib::Mutex::Lock lm (capture_info_lock);
1495         
1496         if (capture_info.empty()) {
1497                 return;
1498         }
1499
1500         if (abort_capture) {
1501                 
1502                 if (destructive()) {
1503                         goto outout;
1504                 }
1505
1506                 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
1507
1508                         if ((*chan).write_source) {
1509                                 
1510                                 (*chan).write_source->mark_for_remove ();
1511                                 (*chan).write_source->drop_references ();
1512                                 (*chan).write_source.reset ();
1513                         }
1514                         
1515                         /* new source set up in "out" below */
1516                 }
1517
1518                 goto out;
1519         } 
1520
1521         for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1522                 total_capture += (*ci)->frames;
1523         }
1524
1525         /* figure out the name for this take */
1526
1527         for (n = 0, chan = channels.begin(); chan != channels.end(); ++chan, ++n) {
1528
1529                 boost::shared_ptr<AudioFileSource> s = (*chan).write_source;
1530                 
1531                 if (s) {
1532                         srcs.push_back (s);
1533                         s->update_header (capture_info.front()->start, when, twhen);
1534                         s->set_captured_for (_name);
1535                         
1536                 }
1537         }
1538
1539         /* destructive tracks have a single, never changing region */
1540
1541         if (destructive()) {
1542
1543                 /* send a signal that any UI can pick up to do the right thing. there is 
1544                    a small problem here in that a UI may need the peak data to be ready
1545                    for the data that was recorded and this isn't interlocked with that
1546                    process. this problem is deferred to the UI.
1547                  */
1548                 
1549                 _playlist->Modified();
1550
1551         } else {
1552
1553                 string whole_file_region_name;
1554                 whole_file_region_name = region_name_from_path (channels[0].write_source->name());
1555
1556                 /* Register a new region with the Session that
1557                    describes the entire source. Do this first
1558                    so that any sub-regions will obviously be
1559                    children of this one (later!)
1560                 */
1561                 
1562                 try {
1563                         boost::shared_ptr<Region> rx (RegionFactory::create (srcs, channels[0].write_source->last_capture_start_frame(), total_capture, 
1564                                                                              whole_file_region_name,
1565                                                                              0, AudioRegion::Flag (AudioRegion::DefaultFlags|AudioRegion::Automatic|AudioRegion::WholeFile)));
1566
1567                         region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1568                         region->special_set_position (capture_info.front()->start);
1569                 }
1570                 
1571                 
1572                 catch (failed_constructor& err) {
1573                         error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1574                         /* XXX what now? */
1575                 }
1576                 
1577                 _last_capture_regions.push_back (region);
1578
1579                 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1580                 
1581                 XMLNode &before = _playlist->get_state();
1582                 _playlist->freeze ();
1583                 
1584                 for (buffer_position = channels[0].write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1585                         
1586                         string region_name;
1587
1588                         _session.region_name (region_name, whole_file_region_name, false);
1589                         
1590                         // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->frames << " add region " << region_name << endl;
1591                         
1592                         try {
1593                                 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, buffer_position, (*ci)->frames, region_name));
1594                                 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1595                         }
1596                         
1597                         catch (failed_constructor& err) {
1598                                 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1599                                 continue; /* XXX is this OK? */
1600                         }
1601                         
1602                         region->GoingAway.connect (bind (mem_fun (*this, &Diskstream::remove_region_from_last_capture), boost::weak_ptr<Region>(region)));
1603                         
1604                         _last_capture_regions.push_back (region);
1605                         
1606                         i_am_the_modifier++;
1607                         _playlist->add_region (region, (*ci)->start);
1608                         i_am_the_modifier--;
1609                         
1610                         buffer_position += (*ci)->frames;
1611                 }
1612
1613                 _playlist->thaw ();
1614                 XMLNode &after = _playlist->get_state();
1615                 _session.add_command (new MementoCommand<Playlist>(*_playlist, &before, &after));
1616         }
1617
1618         mark_write_completed = true;
1619
1620   out:
1621         reset_write_sources (mark_write_completed);
1622
1623   outout:
1624
1625         for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1626                 delete *ci;
1627         }
1628
1629         capture_info.clear ();
1630         capture_start_frame = 0;
1631 }
1632
1633 void
1634 AudioDiskstream::finish_capture (bool rec_monitors_input)
1635 {
1636         was_recording = false;
1637         
1638         if (capture_captured == 0) {
1639                 return;
1640         }
1641
1642         if (recordable() && destructive()) {
1643                 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
1644                         
1645                         RingBufferNPT<CaptureTransition>::rw_vector transvec;
1646                         (*chan).capture_transition_buf->get_write_vector(&transvec);
1647                         
1648                         
1649                         if (transvec.len[0] > 0) {
1650                                 transvec.buf[0]->type = CaptureEnd;
1651                                 transvec.buf[0]->capture_val = capture_captured;
1652                                 (*chan).capture_transition_buf->increment_write_ptr(1);
1653                         }
1654                         else {
1655                                 // bad!
1656                                 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record!  inconceivable!")) << endmsg;
1657                         }
1658                 }
1659         }
1660         
1661         
1662         CaptureInfo* ci = new CaptureInfo;
1663         
1664         ci->start =  capture_start_frame;
1665         ci->frames = capture_captured;
1666         
1667         /* XXX theoretical race condition here. Need atomic exchange ? 
1668            However, the circumstances when this is called right 
1669            now (either on record-disable or transport_stopped)
1670            mean that no actual race exists. I think ...
1671            We now have a capture_info_lock, but it is only to be used
1672            to synchronize in the transport_stop and the capture info
1673            accessors, so that invalidation will not occur (both non-realtime).
1674         */
1675
1676         // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1677
1678         capture_info.push_back (ci);
1679         capture_captured = 0;
1680 }
1681
1682 void
1683 AudioDiskstream::set_record_enabled (bool yn)
1684 {
1685         if (!recordable() || !_session.record_enabling_legal()) {
1686                 return;
1687         }
1688
1689         /* can't rec-enable in destructive mode if transport is before start */
1690
1691         if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1692                 return;
1693         }
1694
1695         if (yn && channels[0].source == 0) {
1696
1697                 /* pick up connections not initiated *from* the IO object
1698                    we're associated with.
1699                 */
1700
1701                 get_input_sources ();
1702         }
1703
1704         /* yes, i know that this not proof against race conditions, but its
1705            good enough. i think.
1706         */
1707
1708         if (record_enabled() != yn) {
1709                 if (yn) {
1710                         engage_record_enable ();
1711                 } else {
1712                         disengage_record_enable ();
1713                 }
1714         }
1715 }
1716
1717 void
1718 AudioDiskstream::engage_record_enable ()
1719 {
1720     bool rolling = _session.transport_speed() != 0.0f;
1721
1722         g_atomic_int_set (&_record_enabled, 1);
1723         capturing_sources.clear ();
1724         if (Config->get_monitoring_model() == HardwareMonitoring) {
1725                 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
1726                         if ((*chan).source) {
1727                                 (*chan).source->ensure_monitor_input (!(Config->get_auto_input() && rolling));
1728                         }
1729                         capturing_sources.push_back ((*chan).write_source);
1730                 }
1731         } else {
1732                 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
1733                         capturing_sources.push_back ((*chan).write_source);
1734                 }
1735         }
1736
1737         RecordEnableChanged (); /* EMIT SIGNAL */
1738 }
1739
1740 void
1741 AudioDiskstream::disengage_record_enable ()
1742 {
1743         g_atomic_int_set (&_record_enabled, 0);
1744         if (Config->get_monitoring_model() == HardwareMonitoring) {
1745                 for (ChannelList::iterator chan = channels.begin(); chan != channels.end(); ++chan) {
1746                         if ((*chan).source) {
1747                                 (*chan).source->ensure_monitor_input (false);
1748                         }
1749                 }
1750         }
1751         capturing_sources.clear ();
1752         RecordEnableChanged (); /* EMIT SIGNAL */
1753 }
1754                 
1755
1756 XMLNode&
1757 AudioDiskstream::get_state ()
1758 {
1759         XMLNode* node = new XMLNode ("AudioDiskstream");
1760         char buf[64] = "";
1761         LocaleGuard lg (X_("POSIX"));
1762
1763         snprintf (buf, sizeof(buf), "0x%x", _flags);
1764         node->add_property ("flags", buf);
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 = strtol (prop->value().c_str(), 0, 0);
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()), 
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())));
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 |= Destructive;
2262                         use_destructive_playlist ();
2263                 } else {
2264                         _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 }