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