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