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