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