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