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