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