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