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