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