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