Bypass disk xrun bail out goto's when stop on xrun option is not selected. For now...
[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 (recordable() && destructive()) {
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                 // Safeguard against situations where process() goes haywire when autopunching and last_recordable_frame < first_recordable_frame
559                 if (last_recordable_frame < first_recordable_frame) {
560                         last_recordable_frame = max_frames;
561
562                 }
563                 
564                 ot = coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
565
566                 switch (ot) {
567                 case OverlapNone:
568                         rec_nframes = 0;
569                         break;
570                         
571                 case OverlapInternal:
572                 /*     ----------    recrange
573                          |---|       transrange
574                 */
575                         rec_nframes = nframes;
576                         rec_offset = 0;
577                         break;
578                         
579                 case OverlapStart:
580                         /*    |--------|    recrange
581                             -----|          transrange
582                         */
583                         rec_nframes = transport_frame + nframes - first_recordable_frame;
584                         if (rec_nframes) {
585                                 rec_offset = first_recordable_frame - transport_frame;
586                         }
587                         break;
588                         
589                 case OverlapEnd:
590                         /*    |--------|    recrange
591                                  |--------  transrange
592                         */
593                         rec_nframes = last_recordable_frame - transport_frame;
594                         rec_offset = 0;
595                         break;
596                         
597                 case OverlapExternal:
598                         /*    |--------|    recrange
599                             --------------  transrange
600                         */
601                         rec_nframes = last_recordable_frame - first_recordable_frame;
602                         rec_offset = first_recordable_frame - transport_frame;
603                         break;
604                 }
605
606                 if (rec_nframes && !was_recording) {
607                         capture_captured = 0;
608                         was_recording = true;
609                 }
610         }
611
612
613         if (can_record && !_last_capture_regions.empty()) {
614                 _last_capture_regions.clear ();
615         }
616
617         if (nominally_recording || rec_nframes) {
618
619                 uint32_t limit = _io->n_inputs ();
620
621                 /* one or more ports could already have been removed from _io, but our
622                    channel setup hasn't yet been updated. prevent us from trying to
623                    use channels that correspond to missing ports. note that the
624                    process callback (from which this is called) is always atomic
625                    with respect to port removal/addition.
626                 */
627
628                 for (n = 0, chan = c->begin(); chan != c->end() && n < limit; ++chan, ++n) {
629                         
630                         ChannelInfo* chaninfo (*chan);
631
632                         chaninfo->capture_buf->get_write_vector (&chaninfo->capture_vector);
633
634                         if (rec_nframes <= chaninfo->capture_vector.len[0]) {
635                                 
636                                 chaninfo->current_capture_buffer = chaninfo->capture_vector.buf[0];
637
638                                 /* note: grab the entire port buffer, but only copy what we were supposed to for recording, and use
639                                    rec_offset
640                                 */
641
642                                 memcpy (chaninfo->current_capture_buffer, _io->input(n)->get_buffer (rec_nframes) + offset + rec_offset, sizeof (Sample) * rec_nframes);
643
644                         } else {
645
646                                 nframes_t total = chaninfo->capture_vector.len[0] + chaninfo->capture_vector.len[1];
647
648                                 if (rec_nframes > total) {
649                                         DiskOverrun ();
650                                         if (Config->get_stop_recording_on_xrun()) {
651                                                 goto out;
652                                         }
653                                 }
654
655                                 Sample* buf = _io->input (n)->get_buffer (nframes) + offset;
656                                 nframes_t first = chaninfo->capture_vector.len[0];
657
658                                 memcpy (chaninfo->capture_wrap_buffer, buf, sizeof (Sample) * first);
659                                 memcpy (chaninfo->capture_vector.buf[0], buf, sizeof (Sample) * first);
660                                 memcpy (chaninfo->capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
661                                 memcpy (chaninfo->capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
662                                 
663                                 chaninfo->current_capture_buffer = chaninfo->capture_wrap_buffer;
664                         }
665                 }
666
667         } else {
668
669                 if (was_recording) {
670                         finish_capture (rec_monitors_input, c);
671                 }
672
673         }
674         
675         if (rec_nframes) {
676                 
677                 /* data will be written to disk */
678
679                 if (rec_nframes == nframes && rec_offset == 0) {
680
681                         for (chan = c->begin(); chan != c->end(); ++chan) {
682                                 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
683                         }
684
685                         playback_distance = nframes;
686
687                 } else {
688
689
690                         /* we can't use the capture buffer as the playback buffer, because
691                            we recorded only a part of the current process' cycle data
692                            for capture.
693                         */
694
695                         collect_playback = true;
696                 }
697
698                 adjust_capture_position = rec_nframes;
699
700         } else if (nominally_recording) {
701
702                 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
703
704                 for (chan = c->begin(); chan != c->end(); ++chan) {
705                         (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
706                 }
707
708                 playback_distance = nframes;
709
710         } else {
711
712                 collect_playback = true;
713         }
714
715         if (collect_playback) {
716
717                 /* we're doing playback */
718
719                 nframes_t necessary_samples;
720
721                 /* no varispeed playback if we're recording, because the output .... TBD */
722
723                 if (rec_nframes == 0 && _actual_speed != 1.0f) {
724                         necessary_samples = (nframes_t) floor ((nframes * fabs (_actual_speed))) + 1;
725                 } else {
726                         necessary_samples = nframes;
727                 }
728                 
729                 for (chan = c->begin(); chan != c->end(); ++chan) {
730                         (*chan)->playback_buf->get_read_vector (&(*chan)->playback_vector);
731                 }
732
733                 n = 0;                  
734
735                 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
736                         
737                         ChannelInfo* chaninfo (*chan);
738
739                         if (necessary_samples <= chaninfo->playback_vector.len[0]) {
740
741                                 chaninfo->current_playback_buffer = chaninfo->playback_vector.buf[0];
742
743                         } else {
744                                 nframes_t total = chaninfo->playback_vector.len[0] + chaninfo->playback_vector.len[1];
745                                 
746                                 if (necessary_samples > total) {
747                                         DiskUnderrun ();
748                                         if (Config->get_stop_recording_on_xrun()) {
749                                                 goto out;
750                                         }
751                                         
752                                 } else {
753                                         
754                                         memcpy ((char *) chaninfo->playback_wrap_buffer, chaninfo->playback_vector.buf[0],
755                                                 chaninfo->playback_vector.len[0] * sizeof (Sample));
756                                         memcpy (chaninfo->playback_wrap_buffer + chaninfo->playback_vector.len[0], chaninfo->playback_vector.buf[1], 
757                                                 (necessary_samples - chaninfo->playback_vector.len[0]) * sizeof (Sample));
758                                         
759                                         chaninfo->current_playback_buffer = chaninfo->playback_wrap_buffer;
760                                 }
761                         }
762                 } 
763
764                 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
765                         
766                         uint64_t phase = last_phase;
767                         int64_t phi_delta;
768                         nframes_t i = 0;
769
770                         // Linearly interpolate into the alt buffer
771                         // using 40.24 fixp maths (swh)
772
773                         if (phi != target_phi) {
774                                 phi_delta = ((int64_t)(target_phi - phi)) / nframes;
775                         } else {
776                                 phi_delta = 0;
777                         }
778
779                         for (chan = c->begin(); chan != c->end(); ++chan) {
780
781                                 float fr;
782                                 ChannelInfo* chaninfo (*chan);
783
784                                 i = 0;
785                                 phase = last_phase;
786
787                                 for (nframes_t outsample = 0; outsample < nframes; ++outsample) {
788                                         i = phase >> 24;
789                                         fr = (phase & 0xFFFFFF) / 16777216.0f;
790                                         chaninfo->speed_buffer[outsample] = 
791                                                 chaninfo->current_playback_buffer[i] * (1.0f - fr) +
792                                                 chaninfo->current_playback_buffer[i+1] * fr;
793                                         phase += phi + phi_delta;
794                                 }
795                                 
796                                 chaninfo->current_playback_buffer = chaninfo->speed_buffer;
797                         }
798
799                         playback_distance = i; // + 1;
800                         last_phase = (phase & 0xFFFFFF);
801
802                 } else {
803                         playback_distance = nframes;
804                 }
805
806                 phi = target_phi;
807         }
808
809         ret = 0;
810
811   out:
812         _processed = true;
813
814         if (ret) {
815
816                 /* we're exiting with failure, so ::commit will not
817                    be called. unlock the state lock.
818                 */
819                 
820                 commit_should_unlock = false;
821                 state_lock.unlock();
822         } 
823
824         return ret;
825 }
826
827 bool
828 AudioDiskstream::commit (nframes_t nframes)
829 {
830         bool need_butler = false;
831
832         if (_actual_speed < 0.0) {
833                 playback_sample -= playback_distance;
834         } else {
835                 playback_sample += playback_distance;
836         }
837
838         boost::shared_ptr<ChannelList> c = channels.reader();
839         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
840
841                 (*chan)->playback_buf->increment_read_ptr (playback_distance);
842                 
843                 if (adjust_capture_position) {
844                         (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
845                 }
846         }
847         
848         if (adjust_capture_position != 0) {
849                 capture_captured += adjust_capture_position;
850                 adjust_capture_position = 0;
851         }
852         
853         if (_slaved) {
854                 need_butler = c->front()->playback_buf->write_space() >= c->front()->playback_buf->bufsize() / 2;
855         } else {
856                 need_butler = c->front()->playback_buf->write_space() >= disk_io_chunk_frames
857                         || c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
858         }
859
860         if (commit_should_unlock) {
861                 state_lock.unlock();
862         }
863
864         _processed = false;
865
866         return need_butler;
867 }
868
869 void
870 AudioDiskstream::set_pending_overwrite (bool yn)
871 {
872         /* called from audio thread, so we can use the read ptr and playback sample as we wish */
873         
874         pending_overwrite = yn;
875
876         overwrite_frame = playback_sample;
877         overwrite_offset = channels.reader()->front()->playback_buf->get_read_ptr();
878 }
879
880 int
881 AudioDiskstream::overwrite_existing_buffers ()
882 {
883         boost::shared_ptr<ChannelList> c = channels.reader();
884         Sample* mixdown_buffer;
885         float* gain_buffer;
886         int ret = -1;
887         bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
888
889         overwrite_queued = false;
890
891         /* assume all are the same size */
892         nframes_t size = c->front()->playback_buf->bufsize();
893         
894         mixdown_buffer = new Sample[size];
895         gain_buffer = new float[size];
896         
897         /* reduce size so that we can fill the buffer correctly. */
898         size--;
899         
900         uint32_t n=0;
901         nframes_t start;
902
903         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
904
905                 start = overwrite_frame;
906                 nframes_t cnt = size;
907                 
908                 /* to fill the buffer without resetting the playback sample, we need to
909                    do it one or two chunks (normally two).
910
911                    |----------------------------------------------------------------------|
912
913                                        ^
914                                        overwrite_offset
915                     |<- second chunk->||<----------------- first chunk ------------------>|
916                    
917                 */
918                 
919                 nframes_t to_read = size - overwrite_offset;
920
921                 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, *chan, n, reversed)) {
922                         error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
923                                          _id, size, playback_sample) << endmsg;
924                         goto out;
925                 }
926                         
927                 if (cnt > to_read) {
928
929                         cnt -= to_read;
930                 
931                         if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer,
932                                   start, cnt, *chan, n, reversed)) {
933                                 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
934                                                  _id, size, playback_sample) << endmsg;
935                                 goto out;
936                         }
937                 }
938         }
939
940         ret = 0;
941  
942   out:
943         pending_overwrite = false;
944         delete [] gain_buffer;
945         delete [] mixdown_buffer;
946         return ret;
947 }
948
949 int
950 AudioDiskstream::seek (nframes_t frame, bool complete_refill)
951 {
952         uint32_t n;
953         int ret;
954         ChannelList::iterator chan;
955         boost::shared_ptr<ChannelList> c = channels.reader();
956
957         Glib::Mutex::Lock lm (state_lock);
958         
959         for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
960                 (*chan)->playback_buf->reset ();
961                 (*chan)->capture_buf->reset ();
962         }
963         
964         /* can't rec-enable in destructive mode if transport is before start */
965         
966         if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
967                 disengage_record_enable ();
968         }
969         
970         playback_sample = frame;
971         file_frame = frame;
972         
973         if (complete_refill) {
974                 while ((ret = do_refill_with_alloc ()) > 0) ;
975         } else {
976                 ret = do_refill_with_alloc ();
977         }
978
979         return ret;
980 }
981
982 int
983 AudioDiskstream::can_internal_playback_seek (nframes_t distance)
984 {
985         ChannelList::iterator chan;
986         boost::shared_ptr<ChannelList> c = channels.reader();
987
988         for (chan = c->begin(); chan != c->end(); ++chan) {
989                 if ((*chan)->playback_buf->read_space() < distance) {
990                         return false;
991                 } 
992         }
993         return true;
994 }
995
996 int
997 AudioDiskstream::internal_playback_seek (nframes_t distance)
998 {
999         ChannelList::iterator chan;
1000         boost::shared_ptr<ChannelList> c = channels.reader();
1001
1002         for (chan = c->begin(); chan != c->end(); ++chan) {
1003                 (*chan)->playback_buf->increment_read_ptr (distance);
1004         }
1005
1006         first_recordable_frame += distance;
1007         playback_sample += distance;
1008         
1009         return 0;
1010 }
1011
1012 int
1013 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer, nframes_t& start, nframes_t cnt, 
1014                        ChannelInfo* channel_info, int channel, bool reversed)
1015 {
1016         nframes_t this_read = 0;
1017         bool reloop = false;
1018         nframes_t loop_end = 0;
1019         nframes_t loop_start = 0;
1020         nframes_t loop_length = 0;
1021         nframes_t offset = 0;
1022         nframes_t xfade_samples = 0;
1023         Sample    xfade_buf[128];
1024         Location *loc = 0;
1025
1026         /* XXX we don't currently play loops in reverse. not sure why */
1027
1028         if (!reversed) {
1029
1030                 /* Make the use of a Location atomic for this read operation.
1031                    
1032                    Note: Locations don't get deleted, so all we care about
1033                    when I say "atomic" is that we are always pointing to
1034                    the same one and using a start/length values obtained
1035                    just once.
1036                 */
1037                 
1038                 if ((loc = loop_location) != 0) {
1039                         loop_start = loc->start();
1040                         loop_end = loc->end();
1041                         loop_length = loop_end - loop_start;
1042                 }
1043                 
1044                 /* if we are looping, ensure that the first frame we read is at the correct
1045                    position within the loop.
1046                 */
1047                 
1048                 if (loc && start >= loop_end) {
1049                         //cerr << "start adjusted from " << start;
1050                         start = loop_start + ((start - loop_start) % loop_length);
1051                         //cerr << "to " << start << endl;
1052                 }
1053
1054                 //cerr << "start is " << start << "  loopstart: " << loop_start << "  loopend: " << loop_end << endl;
1055         }
1056
1057         while (cnt) {
1058
1059                 if (reversed) {
1060                         start -= cnt;
1061                 }
1062                         
1063                 /* take any loop into account. we can't read past the end of the loop. */
1064
1065                 if (loc && (loop_end - start < cnt)) {
1066                         this_read = loop_end - start;
1067                         //cerr << "reloop true: thisread: " << this_read << "  cnt: " << cnt << endl;
1068                         reloop = true;
1069                 } else {
1070                         reloop = false;
1071                         this_read = cnt;
1072                 }
1073
1074                 if (this_read == 0) {
1075                         break;
1076                 }
1077
1078                 this_read = min(cnt,this_read);
1079
1080                 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
1081                         error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), _id, this_read, 
1082                                          start) << endmsg;
1083                         return -1;
1084                 }
1085
1086                 // xfade loop boundary if appropriate
1087
1088                 if (xfade_samples > 0) {
1089                         // just do a linear xfade for this short bit
1090
1091                         xfade_samples = min(xfade_samples, this_read);
1092
1093                         float delta = 1.0f / xfade_samples;
1094                         float scale = 0.0f;
1095                         Sample * tmpbuf = buf+offset;
1096
1097                         for (size_t i=0; i < xfade_samples; ++i) {
1098                                 *tmpbuf = (*tmpbuf * scale) + xfade_buf[i]*(1.0f - scale);
1099                                 ++tmpbuf;
1100                                 scale += delta; 
1101                         }
1102
1103                         xfade_samples = 0;
1104                 }
1105
1106                 _read_data_count = _playlist->read_data_count();
1107                 
1108                 if (reversed) {
1109
1110                         swap_by_ptr (buf, buf + this_read - 1);
1111                         
1112                 } else {
1113                         start += this_read;
1114                 
1115                         /* if we read to the end of the loop, go back to the beginning */
1116                         
1117                         if (reloop) {
1118                                 // read crossfade samples to apply to the next read
1119
1120                                 xfade_samples = min((nframes_t) 128, cnt-this_read);
1121
1122                                 if (audio_playlist()->read (xfade_buf, mixdown_buffer, gain_buffer, start, xfade_samples, channel) != xfade_samples) {
1123                                         error << string_compose(_("AudioDiskstream %1: cannot read xfade samples %2 from playlist at frame %3"), 
1124                                                                 _id, xfade_samples,start) << endmsg;
1125                                         memset(xfade_buf, 0, xfade_samples * sizeof(Sample)); // just in case
1126                                 }
1127
1128                                 start = loop_start;
1129                         }
1130                 } 
1131
1132                 cnt -= this_read;
1133                 offset += this_read;
1134         }
1135
1136         return 0;
1137 }
1138
1139 int
1140 AudioDiskstream::do_refill_with_alloc ()
1141 {
1142         Sample* mix_buf  = new Sample[disk_io_chunk_frames];
1143         float*  gain_buf = new float[disk_io_chunk_frames];
1144
1145         int ret = _do_refill(mix_buf, gain_buf);
1146         
1147         delete [] mix_buf;
1148         delete [] gain_buf;
1149
1150         return ret;
1151 }
1152
1153 int
1154 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer)
1155 {
1156         int32_t ret = 0;
1157         nframes_t to_read;
1158         RingBufferNPT<Sample>::rw_vector vector;
1159         bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1160         nframes_t total_space;
1161         nframes_t zero_fill;
1162         uint32_t chan_n;
1163         ChannelList::iterator i;
1164         boost::shared_ptr<ChannelList> c = channels.reader();
1165         nframes_t ts;
1166
1167         if (c->empty()) {
1168                 return 0;
1169         }
1170
1171         assert(mixdown_buffer);
1172         assert(gain_buffer);
1173
1174         vector.buf[0] = 0;
1175         vector.len[0] = 0;
1176         vector.buf[1] = 0;
1177         vector.len[1] = 0;
1178
1179         c->front()->playback_buf->get_write_vector (&vector);
1180         
1181         if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1182                 return 0;
1183         }
1184
1185         /* if there are 2+ chunks of disk i/o possible for
1186            this track, let the caller know so that it can arrange
1187            for us to be called again, ASAP.
1188         */
1189         
1190         if (total_space >= (_slaved?3:2) * disk_io_chunk_frames) {
1191                 ret = 1;
1192         }
1193         
1194         /* if we're running close to normal speed and there isn't enough 
1195            space to do disk_io_chunk_frames of I/O, then don't bother.  
1196            
1197            at higher speeds, just do it because the sync between butler
1198            and audio thread may not be good enough.
1199         */
1200         
1201         if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1202                 return 0;
1203         }
1204         
1205         /* when slaved, don't try to get too close to the read pointer. this
1206            leaves space for the buffer reversal to have something useful to
1207            work with.
1208         */
1209         
1210         if (_slaved && total_space < (c->front()->playback_buf->bufsize() / 2)) {
1211                 return 0;
1212         }
1213
1214         /* never do more than disk_io_chunk_frames worth of disk input per call (limit doesn't apply for memset) */
1215
1216         total_space = min (disk_io_chunk_frames, total_space);
1217
1218         if (reversed) {
1219
1220                 if (file_frame == 0) {
1221
1222                         /* at start: nothing to do but fill with silence */
1223
1224                         for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1225                                         
1226                                 ChannelInfo* chan (*i);
1227                                 chan->playback_buf->get_write_vector (&vector);
1228                                 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1229                                 if (vector.len[1]) {
1230                                         memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1231                                 }
1232                                 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1233                         }
1234                         return 0;
1235                 }
1236
1237                 if (file_frame < total_space) {
1238
1239                         /* too close to the start: read what we can, 
1240                            and then zero fill the rest 
1241                         */
1242
1243                         zero_fill = total_space - file_frame;
1244                         total_space = file_frame;
1245                         file_frame = 0;
1246
1247                 } else {
1248                         
1249                         zero_fill = 0;
1250                 }
1251
1252         } else {
1253
1254                 if (file_frame == max_frames) {
1255
1256                         /* at end: nothing to do but fill with silence */
1257                         
1258                         for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1259                                         
1260                                 ChannelInfo* chan (*i);
1261                                 chan->playback_buf->get_write_vector (&vector);
1262                                 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1263                                 if (vector.len[1]) {
1264                                         memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1265                                 }
1266                                 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1267                         }
1268                         return 0;
1269                 }
1270                 
1271                 if (file_frame > max_frames - total_space) {
1272
1273                         /* to close to the end: read what we can, and zero fill the rest */
1274
1275                         zero_fill = total_space - (max_frames - file_frame);
1276                         total_space = max_frames - file_frame;
1277
1278                 } else {
1279                         zero_fill = 0;
1280                 }
1281         }
1282         
1283         nframes_t file_frame_tmp = 0;
1284
1285         for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1286
1287                 ChannelInfo* chan (*i);
1288                 Sample* buf1;
1289                 Sample* buf2;
1290                 nframes_t len1, len2;
1291
1292                 chan->playback_buf->get_write_vector (&vector);
1293
1294                 if (vector.len[0] > disk_io_chunk_frames) {
1295                         
1296                         /* we're not going to fill the first chunk, so certainly do not bother with the
1297                            other part. it won't be connected with the part we do fill, as in:
1298                            
1299                            .... => writable space
1300                            ++++ => readable space
1301                            ^^^^ => 1 x disk_io_chunk_frames that would be filled
1302                            
1303                            |......|+++++++++++++|...............................|
1304                            buf1                buf0
1305                                                 ^^^^^^^^^^^^^^^
1306                            
1307                            
1308                            So, just pretend that the buf1 part isn't there.                                     
1309                            
1310                         */
1311                 
1312                         vector.buf[1] = 0;
1313                         vector.len[1] = 0;
1314                 
1315                 } 
1316
1317                 ts = total_space;
1318                 file_frame_tmp = file_frame;
1319
1320                 buf1 = vector.buf[0];
1321                 len1 = vector.len[0];
1322                 buf2 = vector.buf[1];
1323                 len2 = vector.len[1];
1324
1325                 to_read = min (ts, len1);
1326                 to_read = min (to_read, disk_io_chunk_frames);
1327
1328                 if (to_read) {
1329
1330                         if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1331                                 ret = -1;
1332                                 goto out;
1333                         }
1334
1335                         chan->playback_buf->increment_write_ptr (to_read);
1336                         ts -= to_read;
1337                 }
1338
1339                 to_read = min (ts, len2);
1340
1341                 if (to_read) {
1342
1343                         /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1344                            so read some or all of vector.len[1] as well.
1345                         */
1346
1347                         if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1348                                 ret = -1;
1349                                 goto out;
1350                         }
1351                 
1352                         chan->playback_buf->increment_write_ptr (to_read);
1353                 }
1354
1355                 if (zero_fill) {
1356                         /* do something */
1357                 }
1358
1359         }
1360         
1361         file_frame = file_frame_tmp;
1362
1363   out:
1364
1365         return ret;
1366 }       
1367
1368 /** Flush pending data to disk.
1369  *
1370  * Important note: this function will write *AT MOST* disk_io_chunk_frames
1371  * of data to disk. it will never write more than that.  If it writes that
1372  * much and there is more than that waiting to be written, it will return 1,
1373  * otherwise 0 on success or -1 on failure.
1374  * 
1375  * If there is less than disk_io_chunk_frames to be written, no data will be
1376  * written at all unless @a force_flush is true.
1377  */
1378 int
1379 AudioDiskstream::do_flush (Session::RunContext context, bool force_flush)
1380 {
1381         uint32_t to_write;
1382         int32_t ret = 0;
1383         RingBufferNPT<Sample>::rw_vector vector;
1384         RingBufferNPT<CaptureTransition>::rw_vector transvec;
1385         nframes_t total;
1386
1387         _write_data_count = 0;
1388
1389         transvec.buf[0] = 0;
1390         transvec.buf[1] = 0;
1391         vector.buf[0] = 0;
1392         vector.buf[1] = 0;
1393
1394         boost::shared_ptr<ChannelList> c = channels.reader();
1395         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1396         
1397                 (*chan)->capture_buf->get_read_vector (&vector);
1398
1399                 total = vector.len[0] + vector.len[1];
1400
1401                 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1402                         goto out;
1403                 }
1404
1405                 /* if there are 2+ chunks of disk i/o possible for
1406                    this track, let the caller know so that it can arrange
1407                    for us to be called again, ASAP.
1408                    
1409                    if we are forcing a flush, then if there is* any* extra
1410                    work, let the caller know.
1411
1412                    if we are no longer recording and there is any extra work,
1413                    let the caller know too.
1414                 */
1415
1416                 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1417                         ret = 1;
1418                 } 
1419
1420                 to_write = min (disk_io_chunk_frames, (nframes_t) vector.len[0]);
1421                 
1422                 // check the transition buffer when recording destructive
1423                 // important that we get this after the capture buf
1424
1425                 if (destructive()) {
1426                         (*chan)->capture_transition_buf->get_read_vector(&transvec);
1427                         size_t transcount = transvec.len[0] + transvec.len[1];
1428                         bool have_start = false;
1429                         size_t ti;
1430
1431                         for (ti=0; ti < transcount; ++ti) {
1432                                 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1433                                 
1434                                 if (captrans.type == CaptureStart) {
1435                                         // by definition, the first data we got above represents the given capture pos
1436
1437                                         (*chan)->write_source->mark_capture_start (captrans.capture_val);
1438                                         (*chan)->curr_capture_cnt = 0;
1439
1440                                         have_start = true;
1441                                 }
1442                                 else if (captrans.type == CaptureEnd) {
1443
1444                                         // capture end, the capture_val represents total frames in capture
1445
1446                                         if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1447
1448                                                 // shorten to make the write a perfect fit
1449                                                 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt); 
1450
1451                                                 if (nto_write < to_write) {
1452                                                         ret = 1; // should we?
1453                                                 }
1454                                                 to_write = nto_write;
1455
1456                                                 (*chan)->write_source->mark_capture_end ();
1457                                                 
1458                                                 // increment past this transition, but go no further
1459                                                 ++ti;
1460                                                 break;
1461                                         }
1462                                         else {
1463                                                 // actually ends just beyond this chunk, so force more work
1464                                                 ret = 1;
1465                                                 break;
1466                                         }
1467                                 }
1468                         }
1469
1470                         if (ti > 0) {
1471                                 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1472                         }
1473                 }
1474
1475                 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1476                         error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1477                         return -1;
1478                 }
1479
1480                 (*chan)->capture_buf->increment_read_ptr (to_write);
1481                 (*chan)->curr_capture_cnt += to_write;
1482                 
1483                 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1484                 
1485                         /* we wrote all of vector.len[0] but it wasn't an entire
1486                            disk_io_chunk_frames of data, so arrange for some part 
1487                            of vector.len[1] to be flushed to disk as well.
1488                         */
1489                         
1490                         to_write = min ((nframes_t)(disk_io_chunk_frames - to_write), (nframes_t) vector.len[1]);
1491
1492                         if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1493                                 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1494                                 return -1;
1495                         }
1496
1497                         _write_data_count += (*chan)->write_source->write_data_count();
1498         
1499                         (*chan)->capture_buf->increment_read_ptr (to_write);
1500                         (*chan)->curr_capture_cnt += to_write;
1501                 }
1502         }
1503
1504   out:
1505         return ret;
1506 }
1507
1508 void
1509 AudioDiskstream::transport_stopped (struct tm& when, time_t twhen, bool abort_capture)
1510 {
1511         uint32_t buffer_position;
1512         bool more_work = true;
1513         int err = 0;
1514         boost::shared_ptr<AudioRegion> region;
1515         nframes_t total_capture;
1516         SourceList srcs;
1517         SourceList::iterator src;
1518         ChannelList::iterator chan;
1519         vector<CaptureInfo*>::iterator ci;
1520         boost::shared_ptr<ChannelList> c = channels.reader();
1521         uint32_t n = 0; 
1522         bool mark_write_completed = false;
1523
1524         finish_capture (true, c);
1525
1526         /* butler is already stopped, but there may be work to do 
1527            to flush remaining data to disk.
1528         */
1529
1530         while (more_work && !err) {
1531                 switch (do_flush (Session::TransportContext, true)) {
1532                 case 0:
1533                         more_work = false;
1534                         break;
1535                 case 1:
1536                         break;
1537                 case -1:
1538                         error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1539                         err++;
1540                 }
1541         }
1542
1543         /* XXX is there anything we can do if err != 0 ? */
1544         Glib::Mutex::Lock lm (capture_info_lock);
1545         
1546         if (capture_info.empty()) {
1547                 return;
1548         }
1549
1550         if (abort_capture) {
1551                 
1552                 if (destructive()) {
1553                         goto outout;
1554                 }
1555
1556                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1557
1558                         if ((*chan)->write_source) {
1559                                 
1560                                 (*chan)->write_source->mark_for_remove ();
1561                                 (*chan)->write_source->drop_references ();
1562                                 (*chan)->write_source.reset ();
1563                         }
1564                         
1565                         /* new source set up in "out" below */
1566                 }
1567
1568                 goto out;
1569         } 
1570
1571         for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1572                 total_capture += (*ci)->frames;
1573         }
1574
1575         /* figure out the name for this take */
1576
1577         for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1578
1579                 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1580                 
1581                 if (s) {
1582                         srcs.push_back (s);
1583                         s->update_header (capture_info.front()->start, when, twhen);
1584                         s->set_captured_for (_name);
1585                         s->mark_immutable ();
1586                 }
1587         }
1588
1589         /* destructive tracks have a single, never changing region */
1590
1591         if (destructive()) {
1592
1593                 /* send a signal that any UI can pick up to do the right thing. there is 
1594                    a small problem here in that a UI may need the peak data to be ready
1595                    for the data that was recorded and this isn't interlocked with that
1596                    process. this problem is deferred to the UI.
1597                  */
1598                 
1599                 _playlist->Modified();
1600
1601         } else {
1602
1603                 string whole_file_region_name;
1604                 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1605
1606                 /* Register a new region with the Session that
1607                    describes the entire source. Do this first
1608                    so that any sub-regions will obviously be
1609                    children of this one (later!)
1610                 */
1611                 
1612                 try {
1613                         boost::shared_ptr<Region> rx (RegionFactory::create (srcs, c->front()->write_source->last_capture_start_frame(), total_capture, 
1614                                                                              whole_file_region_name,
1615                                                                              0, AudioRegion::Flag (AudioRegion::DefaultFlags|AudioRegion::Automatic|AudioRegion::WholeFile)));
1616
1617                         region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1618                         region->special_set_position (capture_info.front()->start);
1619                 }
1620                 
1621                 
1622                 catch (failed_constructor& err) {
1623                         error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1624                         /* XXX what now? */
1625                 }
1626                 
1627                 _last_capture_regions.push_back (region);
1628
1629                 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1630                 
1631                 XMLNode &before = _playlist->get_state();
1632                 _playlist->freeze ();
1633                 
1634                 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1635                         
1636                         string region_name;
1637
1638                         _session.region_name (region_name, whole_file_region_name, false);
1639                         
1640                         // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->frames << " add region " << region_name << endl;
1641                         
1642                         try {
1643                                 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, buffer_position, (*ci)->frames, region_name));
1644                                 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1645                         }
1646                         
1647                         catch (failed_constructor& err) {
1648                                 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1649                                 continue; /* XXX is this OK? */
1650                         }
1651                         
1652                         region->GoingAway.connect (bind (mem_fun (*this, &Diskstream::remove_region_from_last_capture), boost::weak_ptr<Region>(region)));
1653                         
1654                         _last_capture_regions.push_back (region);
1655                         
1656                         i_am_the_modifier++;
1657                         _playlist->add_region (region, (*ci)->start);
1658                         i_am_the_modifier--;
1659                         
1660                         buffer_position += (*ci)->frames;
1661                 }
1662
1663                 _playlist->thaw ();
1664                 XMLNode &after = _playlist->get_state();
1665                 _session.add_command (new MementoCommand<Playlist>(*_playlist, &before, &after));
1666         }
1667
1668         mark_write_completed = true;
1669
1670   out:
1671         reset_write_sources (mark_write_completed);
1672
1673   outout:
1674
1675         for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1676                 delete *ci;
1677         }
1678
1679         capture_info.clear ();
1680         capture_start_frame = 0;
1681 }
1682
1683 void
1684 AudioDiskstream::transport_looped (nframes_t transport_frame)
1685 {
1686         if (was_recording) {
1687                 // all we need to do is finish this capture, with modified capture length
1688                 boost::shared_ptr<ChannelList> c = channels.reader();
1689
1690                 // adjust the capture length knowing that the data will be recorded to disk
1691                 // only necessary after the first loop where we're recording
1692                 if (capture_info.size() == 0) {
1693                         capture_captured += _capture_offset;
1694
1695                         if (_alignment_style == ExistingMaterial) {
1696                                 capture_captured += _session.worst_output_latency();
1697                         } else {
1698                                 capture_captured += _roll_delay;
1699                         }
1700                 }
1701
1702                 finish_capture (true, c);
1703
1704                 // the next region will start recording via the normal mechanism
1705                 // we'll set the start position to the current transport pos
1706                 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1707                 capture_start_frame = transport_frame;
1708                 first_recordable_frame = transport_frame; // mild lie
1709                 last_recordable_frame = max_frames;
1710                 was_recording = true;
1711
1712                 if (recordable() && destructive()) {
1713                         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1714                                 
1715                                 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1716                                 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1717                                 
1718                                 if (transvec.len[0] > 0) {
1719                                         transvec.buf[0]->type = CaptureStart;
1720                                         transvec.buf[0]->capture_val = capture_start_frame;
1721                                         (*chan)->capture_transition_buf->increment_write_ptr(1);
1722                                 }
1723                                 else {
1724                                         // bad!
1725                                         fatal << X_("programming error: capture_transition_buf is full on rec loop!  inconceivable!") 
1726                                               << endmsg;
1727                                 }
1728                         }
1729                 }
1730
1731         }
1732 }
1733
1734 void
1735 AudioDiskstream::finish_capture (bool rec_monitors_input, boost::shared_ptr<ChannelList> c)
1736 {
1737         was_recording = false;
1738         
1739         if (capture_captured == 0) {
1740                 return;
1741         }
1742
1743         if (recordable() && destructive()) {
1744                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1745                         
1746                         RingBufferNPT<CaptureTransition>::rw_vector transvec;
1747                         (*chan)->capture_transition_buf->get_write_vector(&transvec);
1748                         
1749                         if (transvec.len[0] > 0) {
1750                                 transvec.buf[0]->type = CaptureEnd;
1751                                 transvec.buf[0]->capture_val = capture_captured;
1752                                 (*chan)->capture_transition_buf->increment_write_ptr(1);
1753                         }
1754                         else {
1755                                 // bad!
1756                                 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record!  inconceivable!")) << endmsg;
1757                         }
1758                 }
1759         }
1760         
1761         
1762         CaptureInfo* ci = new CaptureInfo;
1763         
1764         ci->start =  capture_start_frame;
1765         ci->frames = capture_captured;
1766         
1767         /* XXX theoretical race condition here. Need atomic exchange ? 
1768            However, the circumstances when this is called right 
1769            now (either on record-disable or transport_stopped)
1770            mean that no actual race exists. I think ...
1771            We now have a capture_info_lock, but it is only to be used
1772            to synchronize in the transport_stop and the capture info
1773            accessors, so that invalidation will not occur (both non-realtime).
1774         */
1775
1776         // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1777
1778         capture_info.push_back (ci);
1779         capture_captured = 0;
1780 }
1781
1782 void
1783 AudioDiskstream::set_record_enabled (bool yn)
1784 {
1785         if (!recordable() || !_session.record_enabling_legal() || _io->n_inputs() == 0) {
1786                 return;
1787         }
1788
1789         /* can't rec-enable in destructive mode if transport is before start */
1790
1791         if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1792                 return;
1793         }
1794
1795         if (yn && channels.reader()->front()->source == 0) {
1796
1797                 /* pick up connections not initiated *from* the IO object
1798                    we're associated with.
1799                 */
1800
1801                 get_input_sources ();
1802         }
1803
1804         /* yes, i know that this not proof against race conditions, but its
1805            good enough. i think.
1806         */
1807
1808         if (record_enabled() != yn) {
1809                 if (yn) {
1810                         engage_record_enable ();
1811                 } else {
1812                         disengage_record_enable ();
1813                 }
1814         }
1815 }
1816
1817 void
1818 AudioDiskstream::engage_record_enable ()
1819 {
1820         bool rolling = _session.transport_speed() != 0.0f;
1821         boost::shared_ptr<ChannelList> c = channels.reader();
1822
1823         g_atomic_int_set (&_record_enabled, 1);
1824         capturing_sources.clear ();
1825
1826         if (Config->get_monitoring_model() == HardwareMonitoring) {
1827
1828                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1829                         if ((*chan)->source) {
1830                                 (*chan)->source->ensure_monitor_input (!(Config->get_auto_input() && rolling));
1831                         }
1832                         capturing_sources.push_back ((*chan)->write_source);
1833                 }
1834                 
1835         } else {
1836                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1837                         capturing_sources.push_back ((*chan)->write_source);
1838                 }
1839         }
1840
1841         RecordEnableChanged (); /* EMIT SIGNAL */
1842 }
1843
1844 void
1845 AudioDiskstream::disengage_record_enable ()
1846 {
1847         g_atomic_int_set (&_record_enabled, 0);
1848         boost::shared_ptr<ChannelList> c = channels.reader();
1849         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1850                 if (Config->get_monitoring_model() == HardwareMonitoring) {
1851                         if ((*chan)->source) {
1852                                 (*chan)->source->ensure_monitor_input (false);
1853                         }
1854                 }
1855         }
1856         capturing_sources.clear ();
1857         RecordEnableChanged (); /* EMIT SIGNAL */
1858 }
1859
1860 XMLNode&
1861 AudioDiskstream::get_state ()
1862 {
1863         XMLNode* node = new XMLNode ("AudioDiskstream");
1864         char buf[64] = "";
1865         LocaleGuard lg (X_("POSIX"));
1866         boost::shared_ptr<ChannelList> c = channels.reader();
1867
1868         node->add_property ("flags", enum_2_string (_flags));
1869
1870         snprintf (buf, sizeof(buf), "%zd", c->size());
1871         node->add_property ("channels", buf);
1872
1873         node->add_property ("playlist", _playlist->name());
1874         
1875         snprintf (buf, sizeof(buf), "%.12g", _visible_speed);
1876         node->add_property ("speed", buf);
1877
1878         node->add_property("name", _name);
1879         id().print (buf, sizeof (buf));
1880         node->add_property("id", buf);
1881
1882         if (!capturing_sources.empty() && _session.get_record_enabled()) {
1883
1884                 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1885                 XMLNode* cs_grandchild;
1886
1887                 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1888                         cs_grandchild = new XMLNode (X_("file"));
1889                         cs_grandchild->add_property (X_("path"), (*i)->path());
1890                         cs_child->add_child_nocopy (*cs_grandchild);
1891                 }
1892
1893                 /* store the location where capture will start */
1894
1895                 Location* pi;
1896
1897                 if (Config->get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1898                         snprintf (buf, sizeof (buf), "%" PRIu32, pi->start());
1899                 } else {
1900                         snprintf (buf, sizeof (buf), "%" PRIu32, _session.transport_frame());
1901                 }
1902
1903                 cs_child->add_property (X_("at"), buf);
1904                 node->add_child_nocopy (*cs_child);
1905         }
1906
1907         if (_extra_xml) {
1908                 node->add_child_copy (*_extra_xml);
1909         }
1910
1911         return* node;
1912 }
1913
1914 int
1915 AudioDiskstream::set_state (const XMLNode& node)
1916 {
1917         const XMLProperty* prop;
1918         XMLNodeList nlist = node.children();
1919         XMLNodeIterator niter;
1920         uint32_t nchans = 1;
1921         XMLNode* capture_pending_node = 0;
1922         LocaleGuard lg (X_("POSIX"));
1923
1924         in_set_state = true;
1925
1926         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1927                 if ((*niter)->name() == IO::state_node_name) {
1928                         deprecated_io_node = new XMLNode (**niter);
1929                 }
1930
1931                 if ((*niter)->name() == X_("CapturingSources")) {
1932                         capture_pending_node = *niter;
1933                 }
1934         }
1935
1936         /* prevent write sources from being created */
1937         
1938         in_set_state = true;
1939         
1940         if ((prop = node.property ("name")) != 0) {
1941                 _name = prop->value();
1942         } 
1943
1944         if (deprecated_io_node) {
1945                 if ((prop = deprecated_io_node->property ("id")) != 0) {
1946                         _id = prop->value ();
1947                 }
1948         } else {
1949                 if ((prop = node.property ("id")) != 0) {
1950                         _id = prop->value ();
1951                 }
1952         }
1953
1954         if ((prop = node.property ("flags")) != 0) {
1955                 _flags = Flag (string_2_enum (prop->value(), _flags));
1956         }
1957
1958         if ((prop = node.property ("channels")) != 0) {
1959                 nchans = atoi (prop->value().c_str());
1960         }
1961         
1962         // create necessary extra channels
1963         // we are always constructed with one and we always need one
1964
1965         _n_channels = channels.reader()->size();
1966         
1967         if (nchans > _n_channels) {
1968
1969                 add_channel (nchans - _n_channels);
1970
1971         } else if (nchans < _n_channels) {
1972
1973                 remove_channel (_n_channels - nchans);
1974         }
1975
1976         if ((prop = node.property ("playlist")) == 0) {
1977                 return -1;
1978         }
1979
1980         {
1981                 bool had_playlist = (_playlist != 0);
1982         
1983                 if (find_and_use_playlist (prop->value())) {
1984                         return -1;
1985                 }
1986
1987                 if (!had_playlist) {
1988                         _playlist->set_orig_diskstream_id (_id);
1989                 }
1990                 
1991                 if (!destructive() && capture_pending_node) {
1992                         /* destructive streams have one and only one source per channel,
1993                            and so they never end up in pending capture in any useful
1994                            sense.
1995                         */
1996                         use_pending_capture_data (*capture_pending_node);
1997                 }
1998
1999         }
2000
2001         if ((prop = node.property ("speed")) != 0) {
2002                 double sp = atof (prop->value().c_str());
2003
2004                 if (realtime_set_speed (sp, false)) {
2005                         non_realtime_set_speed ();
2006                 }
2007         }
2008
2009         in_set_state = false;
2010
2011         /* make sure this is clear before we do anything else */
2012
2013         capturing_sources.clear ();
2014
2015         /* write sources are handled when we handle the input set 
2016            up of the IO that owns this DS (::non_realtime_input_change())
2017         */
2018                 
2019         in_set_state = false;
2020
2021         return 0;
2022 }
2023
2024 int
2025 AudioDiskstream::use_new_write_source (uint32_t n)
2026 {
2027         boost::shared_ptr<ChannelList> c = channels.reader();
2028
2029         if (!recordable()) {
2030                 return 1;
2031         }
2032
2033         if (n >= c->size()) {
2034                 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
2035                 return -1;
2036         }
2037
2038         ChannelInfo* chan = (*c)[n];
2039         
2040         if (chan->write_source) {
2041                 chan->write_source->done_with_peakfile_writes ();
2042                 chan->write_source->set_allow_remove_if_empty (true);
2043                 chan->write_source.reset ();
2044         }
2045
2046         try {
2047                 if ((chan->write_source = _session.create_audio_source_for_session (*this, n, destructive())) == 0) {
2048                         throw failed_constructor();
2049                 }
2050         } 
2051
2052         catch (failed_constructor &err) {
2053                 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
2054                 chan->write_source.reset ();
2055                 return -1;
2056         }
2057
2058         /* do not remove destructive files even if they are empty */
2059
2060         chan->write_source->set_allow_remove_if_empty (!destructive());
2061
2062         return 0;
2063 }
2064
2065 void
2066 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool force)
2067 {
2068         ChannelList::iterator chan;
2069         boost::shared_ptr<ChannelList> c = channels.reader();
2070         uint32_t n;
2071
2072         if (!recordable()) {
2073                 return;
2074         }
2075         
2076         capturing_sources.clear ();
2077
2078         for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
2079                 if (!destructive()) {
2080
2081                         if ((*chan)->write_source && mark_write_complete) {
2082                                 (*chan)->write_source->mark_streaming_write_completed ();
2083                         }
2084                         use_new_write_source (n);
2085
2086                         if (record_enabled()) {
2087                                 capturing_sources.push_back ((*chan)->write_source);
2088                         }
2089
2090                 } else {
2091                         if ((*chan)->write_source == 0) {
2092                                 use_new_write_source (n);
2093                         }
2094                 }
2095         }
2096
2097         if (destructive()) {
2098
2099                 /* we now have all our write sources set up, so create the
2100                    playlist's single region.
2101                 */
2102
2103                 if (_playlist->empty()) {
2104                         setup_destructive_playlist ();
2105                 }
2106         }
2107 }
2108
2109 int
2110 AudioDiskstream::rename_write_sources ()
2111 {
2112         ChannelList::iterator chan;
2113         boost::shared_ptr<ChannelList> c = channels.reader();
2114         uint32_t n;
2115
2116         for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
2117                 if ((*chan)->write_source != 0) {
2118                         (*chan)->write_source->set_name (_name, destructive());
2119                         /* XXX what to do if one of them fails ? */
2120                 }
2121         }
2122
2123         return 0;
2124 }
2125
2126 void
2127 AudioDiskstream::set_block_size (nframes_t nframes)
2128 {
2129         if (_session.get_block_size() > speed_buffer_size) {
2130                 speed_buffer_size = _session.get_block_size();
2131                 boost::shared_ptr<ChannelList> c = channels.reader();
2132
2133                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2134                         if ((*chan)->speed_buffer) delete [] (*chan)->speed_buffer;
2135                         (*chan)->speed_buffer = new Sample[speed_buffer_size];
2136                 }
2137         }
2138         allocate_temporary_buffers ();
2139 }
2140
2141 void
2142 AudioDiskstream::allocate_temporary_buffers ()
2143 {
2144         /* make sure the wrap buffer is at least large enough to deal
2145            with the speeds up to 1.2, to allow for micro-variation
2146            when slaving to MTC, SMPTE etc.
2147         */
2148
2149         double sp = max (fabsf (_actual_speed), 1.2f);
2150         nframes_t required_wrap_size = (nframes_t) floor (_session.get_block_size() * sp) + 1;
2151
2152         if (required_wrap_size > wrap_buffer_size) {
2153
2154                 boost::shared_ptr<ChannelList> c = channels.reader();
2155
2156                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2157                         if ((*chan)->playback_wrap_buffer) delete [] (*chan)->playback_wrap_buffer;
2158                         (*chan)->playback_wrap_buffer = new Sample[required_wrap_size]; 
2159                         if ((*chan)->capture_wrap_buffer) delete [] (*chan)->capture_wrap_buffer;
2160                         (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];  
2161                 }
2162
2163                 wrap_buffer_size = required_wrap_size;
2164         }
2165 }
2166
2167 void
2168 AudioDiskstream::monitor_input (bool yn)
2169 {
2170         boost::shared_ptr<ChannelList> c = channels.reader();
2171
2172         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2173                 
2174                 if ((*chan)->source) {
2175                         (*chan)->source->ensure_monitor_input (yn);
2176                 }
2177         }
2178 }
2179
2180 void
2181 AudioDiskstream::set_align_style_from_io ()
2182 {
2183         bool have_physical = false;
2184
2185         if (_io == 0) {
2186                 return;
2187         }
2188
2189         get_input_sources ();
2190         
2191         boost::shared_ptr<ChannelList> c = channels.reader();
2192
2193         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2194                 if ((*chan)->source && (*chan)->source->flags() & JackPortIsPhysical) {
2195                         have_physical = true;
2196                         break;
2197                 }
2198         }
2199
2200         if (have_physical) {
2201                 set_align_style (ExistingMaterial);
2202         } else {
2203                 set_align_style (CaptureTime);
2204         }
2205 }
2206
2207 int
2208 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2209 {
2210         while (how_many--) {
2211                 c->push_back (new ChannelInfo(_session.diskstream_buffer_size(), speed_buffer_size, wrap_buffer_size));
2212         }
2213
2214         _n_channels = c->size();
2215
2216         return 0;
2217 }
2218
2219 int
2220 AudioDiskstream::add_channel (uint32_t how_many)
2221 {
2222         RCUWriter<ChannelList> writer (channels);
2223         boost::shared_ptr<ChannelList> c = writer.get_copy();
2224
2225         return add_channel_to (c, how_many);
2226 }
2227
2228 int
2229 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2230 {
2231         while (--how_many && !c->empty()) {
2232                 delete c->back();
2233                 c->pop_back();
2234         }
2235
2236         _n_channels = c->size();
2237
2238         return 0;
2239 }
2240
2241 int
2242 AudioDiskstream::remove_channel (uint32_t how_many)
2243 {
2244         RCUWriter<ChannelList> writer (channels);
2245         boost::shared_ptr<ChannelList> c = writer.get_copy();
2246         
2247         return remove_channel_from (c, how_many);
2248 }
2249
2250 float
2251 AudioDiskstream::playback_buffer_load () const
2252 {
2253         boost::shared_ptr<ChannelList> c = channels.reader();
2254
2255         return (float) ((double) c->front()->playback_buf->read_space()/
2256                         (double) c->front()->playback_buf->bufsize());
2257 }
2258
2259 float
2260 AudioDiskstream::capture_buffer_load () const
2261 {
2262         boost::shared_ptr<ChannelList> c = channels.reader();
2263
2264         return (float) ((double) c->front()->capture_buf->write_space()/
2265                         (double) c->front()->capture_buf->bufsize());
2266 }
2267
2268 int
2269 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2270 {
2271         const XMLProperty* prop;
2272         XMLNodeList nlist = node.children();
2273         XMLNodeIterator niter;
2274         boost::shared_ptr<AudioFileSource> fs;
2275         boost::shared_ptr<AudioFileSource> first_fs;
2276         SourceList pending_sources;
2277         nframes_t position;
2278
2279         if ((prop = node.property (X_("at"))) == 0) {
2280                 return -1;
2281         }
2282
2283         if (sscanf (prop->value().c_str(), "%" PRIu32, &position) != 1) {
2284                 return -1;
2285         }
2286
2287         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2288                 if ((*niter)->name() == X_("file")) {
2289
2290                         if ((prop = (*niter)->property (X_("path"))) == 0) {
2291                                 continue;
2292                         }
2293
2294                         // This protects sessions from errant CapturingSources in stored sessions
2295                         struct stat sbuf;
2296                         if (stat (prop->value().c_str(), &sbuf)) {
2297                                 continue;
2298                         }
2299
2300                         try {
2301                                 fs = boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createWritable (_session, prop->value(), false, _session.frame_rate()));
2302                         }
2303
2304                         catch (failed_constructor& err) {
2305                                 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2306                                                   _name, prop->value())
2307                                       << endmsg;
2308                                 return -1;
2309                         }
2310
2311                         pending_sources.push_back (fs);
2312                         
2313                         if (first_fs == 0) {
2314                                 first_fs = fs;
2315                         }
2316
2317                         fs->set_captured_for (_name);
2318                 }
2319         }
2320
2321         if (pending_sources.size() == 0) {
2322                 /* nothing can be done */
2323                 return 1;
2324         }
2325
2326         if (pending_sources.size() != _n_channels) {
2327                 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2328                       << endmsg;
2329                 return -1;
2330         }
2331
2332         boost::shared_ptr<AudioRegion> region;
2333         
2334         try {
2335                 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, 0, first_fs->length(),
2336                                                                                           region_name_from_path (first_fs->name(), true), 
2337                                                                                           0, AudioRegion::Flag (AudioRegion::DefaultFlags|AudioRegion::Automatic|AudioRegion::WholeFile)));
2338                 region->special_set_position (0);
2339         }
2340
2341         catch (failed_constructor& err) {
2342                 error << string_compose (_("%1: cannot create whole-file region from pending capture sources"),
2343                                   _name)
2344                       << endmsg;
2345                 
2346                 return -1;
2347         }
2348
2349         try {
2350                 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, 0, first_fs->length(), region_name_from_path (first_fs->name(), true)));
2351         }
2352
2353         catch (failed_constructor& err) {
2354                 error << string_compose (_("%1: cannot create region from pending capture sources"),
2355                                   _name)
2356                       << endmsg;
2357                 
2358                 return -1;
2359         }
2360
2361         _playlist->add_region (region, position);
2362
2363         return 0;
2364 }
2365
2366 int
2367 AudioDiskstream::set_destructive (bool yn)
2368 {
2369         bool bounce_ignored;
2370
2371         if (yn != destructive()) {
2372                 
2373                 if (yn) {
2374                         /* requestor should already have checked this and
2375                            bounced if necessary and desired 
2376                         */
2377                         if (!can_become_destructive (bounce_ignored)) {
2378                                 return -1;
2379                         }
2380                         _flags = Flag (_flags | Destructive);
2381                         use_destructive_playlist ();
2382                 } else {
2383                         _flags = Flag (_flags & ~Destructive);
2384                         reset_write_sources (true, true);
2385                 }
2386         }
2387
2388         return 0;
2389 }
2390
2391 bool
2392 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2393 {
2394         if (!_playlist) {
2395                 requires_bounce = false;
2396                 return false;
2397         }
2398
2399         /* is there only one region ? */
2400
2401         if (_playlist->n_regions() != 1) {
2402                 requires_bounce = true;
2403                 return false;
2404         }
2405
2406         boost::shared_ptr<Region> first = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
2407         assert (first);
2408
2409         /* do the source(s) for the region cover the session start position ? */
2410         
2411         if (first->position() != _session.current_start_frame()) {
2412                 if (first->start() > _session.current_start_frame()) {
2413                         requires_bounce = true;
2414                         return false;
2415                 }
2416         }
2417
2418         /* is the source used by only 1 playlist ? */
2419
2420         boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2421
2422         assert (afirst);
2423
2424         if (afirst->source()->used() > 1) {
2425                 requires_bounce = true; 
2426                 return false;
2427         }
2428
2429         requires_bounce = false;
2430         return true;
2431 }
2432
2433 AudioDiskstream::ChannelInfo::ChannelInfo (nframes_t bufsize, nframes_t speed_size, nframes_t wrap_size)
2434 {
2435         peak_power = 0.0f;
2436         source = 0;
2437         current_capture_buffer = 0;
2438         current_playback_buffer = 0;
2439         curr_capture_cnt = 0;
2440
2441         speed_buffer = new Sample[speed_size];
2442         playback_wrap_buffer = new Sample[wrap_size];
2443         capture_wrap_buffer = new Sample[wrap_size];
2444
2445         playback_buf = new RingBufferNPT<Sample> (bufsize);
2446         capture_buf = new RingBufferNPT<Sample> (bufsize);
2447         capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2448         
2449         /* touch the ringbuffer buffers, which will cause
2450            them to be mapped into locked physical RAM if
2451            we're running with mlockall(). this doesn't do
2452            much if we're not.  
2453         */
2454
2455         memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2456         memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2457         memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2458 }
2459
2460 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2461 {
2462         if (write_source) {
2463                 write_source.reset ();
2464         }
2465                 
2466         if (speed_buffer) {
2467                 delete [] speed_buffer;
2468                 speed_buffer = 0;
2469         }
2470
2471         if (playback_wrap_buffer) {
2472                 delete [] playback_wrap_buffer;
2473                 playback_wrap_buffer = 0;
2474         }
2475
2476         if (capture_wrap_buffer) {
2477                 delete [] capture_wrap_buffer;
2478                 capture_wrap_buffer = 0;
2479         }
2480         
2481         if (playback_buf) {
2482                 delete playback_buf;
2483                 playback_buf = 0;
2484         }
2485
2486         if (capture_buf) {
2487                 delete capture_buf;
2488                 capture_buf = 0;
2489         }
2490
2491         if (capture_transition_buf) {
2492                 delete capture_transition_buf;
2493                 capture_transition_buf = 0;
2494         }
2495 }