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