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