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