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