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