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