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