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