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