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