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