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