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