2 Copyright (C) 2000-2006 Paul Davis
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.
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.
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.
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>
40 #include <ardour/ardour.h>
41 #include <ardour/audioengine.h>
42 #include <ardour/analyser.h>
43 #include <ardour/audio_diskstream.h>
44 #include <ardour/utils.h>
45 #include <ardour/configuration.h>
46 #include <ardour/audiofilesource.h>
47 #include <ardour/send.h>
48 #include <ardour/region_factory.h>
49 #include <ardour/audioplaylist.h>
50 #include <ardour/playlist_factory.h>
51 #include <ardour/cycle_timer.h>
52 #include <ardour/audioregion.h>
53 #include <ardour/audio_port.h>
54 #include <ardour/source_factory.h>
60 using namespace ARDOUR;
63 size_t AudioDiskstream::_working_buffers_size = 0;
64 Sample* AudioDiskstream::_mixdown_buffer = 0;
65 gain_t* AudioDiskstream::_gain_buffer = 0;
67 AudioDiskstream::AudioDiskstream (Session &sess, const string &name, Diskstream::Flag flag)
68 : Diskstream(sess, name, flag)
69 , deprecated_io_node(NULL)
70 , channels (new ChannelList)
72 /* prevent any write sources from being created */
82 AudioDiskstream::AudioDiskstream (Session& sess, const XMLNode& node)
83 : Diskstream(sess, node)
84 , deprecated_io_node(NULL)
85 , channels (new ChannelList)
90 if (set_state (node)) {
92 throw failed_constructor();
98 use_destructive_playlist ();
103 AudioDiskstream::init (Diskstream::Flag f)
107 /* there are no channels at this point, so these
108 two calls just get speed_buffer_size and wrap_buffer
109 size setup without duplicating their code.
112 set_block_size (_session.get_block_size());
113 allocate_temporary_buffers ();
116 assert(_n_channels == ChanCount(DataType::AUDIO, 1));
119 AudioDiskstream::~AudioDiskstream ()
124 RCUWriter<ChannelList> writer (channels);
125 boost::shared_ptr<ChannelList> c = writer.get_copy();
127 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
138 AudioDiskstream::allocate_working_buffers()
140 assert(disk_io_frames() > 0);
142 _working_buffers_size = disk_io_frames();
143 _mixdown_buffer = new Sample[_working_buffers_size];
144 _gain_buffer = new gain_t[_working_buffers_size];
148 AudioDiskstream::free_working_buffers()
150 delete [] _mixdown_buffer;
151 delete [] _gain_buffer;
152 _working_buffers_size = 0;
158 AudioDiskstream::non_realtime_input_change ()
161 Glib::Mutex::Lock lm (state_lock);
163 if (input_change_pending == NoChange) {
168 RCUWriter<ChannelList> writer (channels);
169 boost::shared_ptr<ChannelList> c = writer.get_copy();
171 _n_channels.set(DataType::AUDIO, c->size());
173 if (_io->n_inputs().n_audio() > _n_channels.n_audio()) {
174 add_channel_to (c, _io->n_inputs().n_audio() - _n_channels.n_audio());
175 } else if (_io->n_inputs().n_audio() < _n_channels.n_audio()) {
176 remove_channel_from (c, _n_channels.n_audio() - _io->n_inputs().n_audio());
180 get_input_sources ();
181 set_capture_offset ();
183 if (first_input_change) {
184 set_align_style (_persistent_alignment_style);
185 first_input_change = false;
187 set_align_style_from_io ();
190 input_change_pending = NoChange;
192 /* implicit unlock */
195 /* reset capture files */
197 reset_write_sources (false);
199 /* now refill channel buffers */
201 if (speed() != 1.0f || speed() != -1.0f) {
202 seek ((nframes_t) (_session.transport_frame() * (double) speed()));
204 seek (_session.transport_frame());
209 AudioDiskstream::get_input_sources ()
211 boost::shared_ptr<ChannelList> c = channels.reader();
214 ChannelList::iterator chan;
215 uint32_t ni = _io->n_inputs().n_audio();
216 vector<string> connections;
218 for (n = 0, chan = c->begin(); chan != c->end() && n < ni; ++chan, ++n) {
220 connections.clear ();
222 if (_io->input(n)->get_connections (connections) == 0) {
224 if ((*chan)->source) {
225 // _source->disable_metering ();
231 (*chan)->source = dynamic_cast<AudioPort*>(_session.engine().get_port_by_name (connections[0]) );
237 AudioDiskstream::find_and_use_playlist (const string& name)
239 boost::shared_ptr<AudioPlaylist> playlist;
241 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (_session.playlist_by_name (name))) == 0) {
242 playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, name));
246 error << string_compose(_("AudioDiskstream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
250 return use_playlist (playlist);
254 AudioDiskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
256 assert(boost::dynamic_pointer_cast<AudioPlaylist>(playlist));
258 Diskstream::use_playlist(playlist);
264 AudioDiskstream::use_new_playlist ()
267 boost::shared_ptr<AudioPlaylist> playlist;
269 if (!in_set_state && destructive()) {
274 newname = Playlist::bump_name (_playlist->name(), _session);
276 newname = Playlist::bump_name (_name, _session);
279 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, newname, hidden()))) != 0) {
281 playlist->set_orig_diskstream_id (id());
282 return use_playlist (playlist);
290 AudioDiskstream::use_copy_playlist ()
292 assert(audio_playlist());
298 if (_playlist == 0) {
299 error << string_compose(_("AudioDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
304 boost::shared_ptr<AudioPlaylist> playlist;
306 newname = Playlist::bump_name (_playlist->name(), _session);
308 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist>(PlaylistFactory::create (audio_playlist(), newname))) != 0) {
309 playlist->set_orig_diskstream_id (id());
310 return use_playlist (playlist);
317 AudioDiskstream::setup_destructive_playlist ()
320 boost::shared_ptr<ChannelList> c = channels.reader();
322 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
323 srcs.push_back ((*chan)->write_source);
326 /* a single full-sized region */
328 boost::shared_ptr<Region> region (RegionFactory::create (srcs, 0, max_frames - srcs.front()->natural_position(), _name));
329 _playlist->add_region (region, srcs.front()->natural_position());
333 AudioDiskstream::use_destructive_playlist ()
335 /* this is called from the XML-based constructor or ::set_destructive. when called,
336 we already have a playlist and a region, but we need to
337 set up our sources for write. we use the sources associated
338 with the (presumed single, full-extent) region.
341 boost::shared_ptr<Region> rp = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
344 reset_write_sources (false, true);
348 boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
351 throw failed_constructor();
354 /* be sure to stretch the region out to the maximum length */
356 region->set_length (max_frames - region->position(), this);
359 ChannelList::iterator chan;
360 boost::shared_ptr<ChannelList> c = channels.reader();
362 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
363 (*chan)->write_source = boost::dynamic_pointer_cast<AudioFileSource>(region->source (n));
364 assert((*chan)->write_source);
365 (*chan)->write_source->set_allow_remove_if_empty (false);
367 /* this might be false if we switched modes, so force it */
369 (*chan)->write_source->set_destructive (true);
372 /* the source list will never be reset for a destructive track */
376 AudioDiskstream::check_record_status (nframes_t transport_frame, nframes_t nframes, bool can_record)
378 int possibly_recording;
381 const int transport_rolling = 0x4;
382 const int track_rec_enabled = 0x2;
383 const int global_rec_enabled = 0x1;
385 /* merge together the 3 factors that affect record status, and compute
389 rolling = _session.transport_speed() != 0.0f;
390 possibly_recording = (rolling << 2) | (record_enabled() << 1) | can_record;
391 change = possibly_recording ^ last_possibly_recording;
393 if (possibly_recording == last_possibly_recording) {
399 /* if per-track or global rec-enable turned on while the other was already on, we've started recording */
401 if ((change & track_rec_enabled) && record_enabled() && (!(change & global_rec_enabled) && can_record) ||
402 ((change & global_rec_enabled) && can_record && (!(change & track_rec_enabled) && record_enabled()))) {
404 /* starting to record: compute first+last frames */
406 first_recordable_frame = transport_frame + _capture_offset;
407 last_recordable_frame = max_frames;
408 capture_start_frame = transport_frame;
410 if (!(last_possibly_recording & transport_rolling) && (possibly_recording & transport_rolling)) {
412 /* was stopped, now rolling (and recording) */
414 if (_alignment_style == ExistingMaterial) {
415 first_recordable_frame += _session.worst_output_latency();
417 first_recordable_frame += _roll_delay;
422 /* was rolling, but record state changed */
424 if (_alignment_style == ExistingMaterial) {
426 if (!Config->get_punch_in()) {
428 /* manual punch in happens at the correct transport frame
429 because the user hit a button. but to get alignment correct
430 we have to back up the position of the new region to the
431 appropriate spot given the roll delay.
434 capture_start_frame -= _roll_delay;
436 /* XXX paul notes (august 2005): i don't know why
440 first_recordable_frame += _capture_offset;
444 /* autopunch toggles recording at the precise
445 transport frame, and then the DS waits
446 to start recording for a time that depends
447 on the output latency.
450 first_recordable_frame += _session.worst_output_latency();
455 if (Config->get_punch_in()) {
456 first_recordable_frame += _roll_delay;
458 capture_start_frame -= _roll_delay;
464 if (recordable() && destructive()) {
465 boost::shared_ptr<ChannelList> c = channels.reader();
466 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
468 RingBufferNPT<CaptureTransition>::rw_vector transvec;
469 (*chan)->capture_transition_buf->get_write_vector(&transvec);
471 if (transvec.len[0] > 0) {
472 transvec.buf[0]->type = CaptureStart;
473 transvec.buf[0]->capture_val = capture_start_frame;
474 (*chan)->capture_transition_buf->increment_write_ptr(1);
478 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
484 } else if (!record_enabled() || !can_record) {
488 last_recordable_frame = transport_frame + _capture_offset;
490 if (_alignment_style == ExistingMaterial) {
491 last_recordable_frame += _session.worst_output_latency();
493 last_recordable_frame += _roll_delay;
497 last_possibly_recording = possibly_recording;
501 AudioDiskstream::process (nframes_t transport_frame, nframes_t nframes, nframes_t offset, bool can_record, bool rec_monitors_input)
504 boost::shared_ptr<ChannelList> c = channels.reader();
505 ChannelList::iterator chan;
507 nframes_t rec_offset = 0;
508 nframes_t rec_nframes = 0;
509 bool nominally_recording;
510 bool re = record_enabled ();
511 bool collect_playback = false;
513 /* if we've already processed the frames corresponding to this call,
514 just return. this allows multiple routes that are taking input
515 from this diskstream to call our ::process() method, but have
516 this stuff only happen once. more commonly, it allows both
517 the AudioTrack that is using this AudioDiskstream *and* the Session
518 to call process() without problems.
525 commit_should_unlock = false;
527 if (!_io->active()) {
532 check_record_status (transport_frame, nframes, can_record);
534 nominally_recording = (can_record && re);
541 /* This lock is held until the end of AudioDiskstream::commit, so these two functions
542 must always be called as a pair. The only exception is if this function
543 returns a non-zero value, in which case, ::commit should not be called.
546 // If we can't take the state lock return.
547 if (!state_lock.trylock()) {
550 commit_should_unlock = true;
551 adjust_capture_position = 0;
553 for (chan = c->begin(); chan != c->end(); ++chan) {
554 (*chan)->current_capture_buffer = 0;
555 (*chan)->current_playback_buffer = 0;
558 if (nominally_recording || (_session.get_record_enabled() && Config->get_punch_in())) {
561 // Safeguard against situations where process() goes haywire when autopunching and last_recordable_frame < first_recordable_frame
562 if (last_recordable_frame < first_recordable_frame) {
563 last_recordable_frame = max_frames;
566 ot = coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
573 case OverlapInternal:
574 /* ---------- recrange
577 rec_nframes = nframes;
582 /* |--------| recrange
585 rec_nframes = transport_frame + nframes - first_recordable_frame;
587 rec_offset = first_recordable_frame - transport_frame;
592 /* |--------| recrange
595 rec_nframes = last_recordable_frame - transport_frame;
599 case OverlapExternal:
600 /* |--------| recrange
601 -------------- transrange
603 rec_nframes = last_recordable_frame - first_recordable_frame;
604 rec_offset = first_recordable_frame - transport_frame;
608 if (rec_nframes && !was_recording) {
609 capture_captured = 0;
610 was_recording = true;
615 if (can_record && !_last_capture_regions.empty()) {
616 _last_capture_regions.clear ();
619 if (nominally_recording || rec_nframes) {
621 uint32_t limit = _io->n_inputs ().n_audio();
623 /* one or more ports could already have been removed from _io, but our
624 channel setup hasn't yet been updated. prevent us from trying to
625 use channels that correspond to missing ports. note that the
626 process callback (from which this is called) is always atomic
627 with respect to port removal/addition.
630 for (n = 0, chan = c->begin(); chan != c->end() && n < limit; ++chan, ++n) {
632 ChannelInfo* chaninfo (*chan);
634 chaninfo->capture_buf->get_write_vector (&chaninfo->capture_vector);
636 if (rec_nframes <= chaninfo->capture_vector.len[0]) {
638 chaninfo->current_capture_buffer = chaninfo->capture_vector.buf[0];
640 /* note: grab the entire port buffer, but only copy what we were supposed to for recording, and use
644 AudioPort* const ap = _io->audio_input(n);
646 assert(rec_nframes <= ap->get_audio_buffer().capacity());
647 memcpy (chaninfo->current_capture_buffer, ap->get_audio_buffer().data(rec_nframes, offset + rec_offset), sizeof (Sample) * rec_nframes);
651 nframes_t total = chaninfo->capture_vector.len[0] + chaninfo->capture_vector.len[1];
653 if (rec_nframes > total) {
658 AudioPort* const ap = _io->audio_input(n);
661 Sample* buf = ap->get_audio_buffer().data(nframes, offset);
662 nframes_t first = chaninfo->capture_vector.len[0];
664 memcpy (chaninfo->capture_wrap_buffer, buf, sizeof (Sample) * first);
665 memcpy (chaninfo->capture_vector.buf[0], buf, sizeof (Sample) * first);
666 memcpy (chaninfo->capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
667 memcpy (chaninfo->capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
669 chaninfo->current_capture_buffer = chaninfo->capture_wrap_buffer;
676 finish_capture (rec_monitors_input, c);
683 /* data will be written to disk */
685 if (rec_nframes == nframes && rec_offset == 0) {
687 for (chan = c->begin(); chan != c->end(); ++chan) {
688 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
691 playback_distance = nframes;
696 /* we can't use the capture buffer as the playback buffer, because
697 we recorded only a part of the current process' cycle data
701 collect_playback = true;
704 adjust_capture_position = rec_nframes;
706 } else if (nominally_recording) {
708 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
710 for (chan = c->begin(); chan != c->end(); ++chan) {
711 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
714 playback_distance = nframes;
718 collect_playback = true;
721 if (collect_playback) {
723 /* we're doing playback */
725 nframes_t necessary_samples;
727 /* no varispeed playback if we're recording, because the output .... TBD */
729 if (rec_nframes == 0 && _actual_speed != 1.0f) {
730 necessary_samples = (nframes_t) floor ((nframes * fabs (_actual_speed))) + 1;
732 necessary_samples = nframes;
735 for (chan = c->begin(); chan != c->end(); ++chan) {
736 (*chan)->playback_buf->get_read_vector (&(*chan)->playback_vector);
741 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
743 ChannelInfo* chaninfo (*chan);
745 if (necessary_samples <= chaninfo->playback_vector.len[0]) {
747 chaninfo->current_playback_buffer = chaninfo->playback_vector.buf[0];
750 nframes_t total = chaninfo->playback_vector.len[0] + chaninfo->playback_vector.len[1];
752 if (necessary_samples > total) {
753 cerr << "underrun for " << _name << endl;
759 memcpy ((char *) chaninfo->playback_wrap_buffer, chaninfo->playback_vector.buf[0],
760 chaninfo->playback_vector.len[0] * sizeof (Sample));
761 memcpy (chaninfo->playback_wrap_buffer + chaninfo->playback_vector.len[0], chaninfo->playback_vector.buf[1],
762 (necessary_samples - chaninfo->playback_vector.len[0]) * sizeof (Sample));
764 chaninfo->current_playback_buffer = chaninfo->playback_wrap_buffer;
769 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
771 uint64_t phase = last_phase;
775 // Linearly interpolate into the alt buffer
776 // using 40.24 fixp maths (swh)
778 if (phi != target_phi) {
779 phi_delta = ((int64_t)(target_phi - phi)) / nframes;
784 for (chan = c->begin(); chan != c->end(); ++chan) {
787 ChannelInfo* chaninfo (*chan);
792 for (nframes_t outsample = 0; outsample < nframes; ++outsample) {
794 fr = (phase & 0xFFFFFF) / 16777216.0f;
795 chaninfo->speed_buffer[outsample] =
796 chaninfo->current_playback_buffer[i] * (1.0f - fr) +
797 chaninfo->current_playback_buffer[i+1] * fr;
798 phase += phi + phi_delta;
801 chaninfo->current_playback_buffer = chaninfo->speed_buffer;
804 playback_distance = i; // + 1;
805 last_phase = (phase & 0xFFFFFF);
808 playback_distance = nframes;
822 /* we're exiting with failure, so ::commit will not
823 be called. unlock the state lock.
826 commit_should_unlock = false;
834 AudioDiskstream::commit (nframes_t nframes)
836 bool need_butler = false;
838 if (!_io->active()) {
842 if (_actual_speed < 0.0) {
843 playback_sample -= playback_distance;
845 playback_sample += playback_distance;
848 boost::shared_ptr<ChannelList> c = channels.reader();
849 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
851 (*chan)->playback_buf->increment_read_ptr (playback_distance);
853 if (adjust_capture_position) {
854 (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
858 if (adjust_capture_position != 0) {
859 capture_captured += adjust_capture_position;
860 adjust_capture_position = 0;
864 /*if (_io && _io->active()) {*/
865 need_butler = c->front()->playback_buf->write_space() >= c->front()->playback_buf->bufsize() / 2;
870 /*if (_io && _io->active()) {*/
871 need_butler = c->front()->playback_buf->write_space() >= disk_io_chunk_frames
872 || c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
874 need_butler = c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
878 if (commit_should_unlock) {
888 AudioDiskstream::set_pending_overwrite (bool yn)
890 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
892 pending_overwrite = yn;
894 overwrite_frame = playback_sample;
895 overwrite_offset = channels.reader()->front()->playback_buf->get_read_ptr();
899 AudioDiskstream::overwrite_existing_buffers ()
901 boost::shared_ptr<ChannelList> c = channels.reader();
902 Sample* mixdown_buffer;
905 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
907 overwrite_queued = false;
909 /* assume all are the same size */
910 nframes_t size = c->front()->playback_buf->bufsize();
912 mixdown_buffer = new Sample[size];
913 gain_buffer = new float[size];
915 /* reduce size so that we can fill the buffer correctly. */
921 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
923 start = overwrite_frame;
924 nframes_t cnt = size;
926 /* to fill the buffer without resetting the playback sample, we need to
927 do it one or two chunks (normally two).
929 |----------------------------------------------------------------------|
933 |<- second chunk->||<----------------- first chunk ------------------>|
937 nframes_t to_read = size - overwrite_offset;
939 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, *chan, n, reversed)) {
940 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
941 _id, size, playback_sample) << endmsg;
949 if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer,
950 start, cnt, *chan, n, reversed)) {
951 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
952 _id, size, playback_sample) << endmsg;
961 pending_overwrite = false;
962 delete [] gain_buffer;
963 delete [] mixdown_buffer;
968 AudioDiskstream::seek (nframes_t frame, bool complete_refill)
972 ChannelList::iterator chan;
973 boost::shared_ptr<ChannelList> c = channels.reader();
975 Glib::Mutex::Lock lm (state_lock);
977 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
978 (*chan)->playback_buf->reset ();
979 (*chan)->capture_buf->reset ();
982 /* can't rec-enable in destructive mode if transport is before start */
984 if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
985 disengage_record_enable ();
988 playback_sample = frame;
991 if (complete_refill) {
992 while ((ret = do_refill_with_alloc ()) > 0) ;
994 ret = do_refill_with_alloc ();
1001 AudioDiskstream::can_internal_playback_seek (nframes_t distance)
1003 ChannelList::iterator chan;
1004 boost::shared_ptr<ChannelList> c = channels.reader();
1006 for (chan = c->begin(); chan != c->end(); ++chan) {
1007 if ((*chan)->playback_buf->read_space() < distance) {
1015 AudioDiskstream::internal_playback_seek (nframes_t distance)
1017 ChannelList::iterator chan;
1018 boost::shared_ptr<ChannelList> c = channels.reader();
1020 for (chan = c->begin(); chan != c->end(); ++chan) {
1021 (*chan)->playback_buf->increment_read_ptr (distance);
1024 first_recordable_frame += distance;
1025 playback_sample += distance;
1031 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer, nframes_t& start, nframes_t cnt,
1032 ChannelInfo* channel_info, int channel, bool reversed)
1034 nframes_t this_read = 0;
1035 bool reloop = false;
1036 nframes_t loop_end = 0;
1037 nframes_t loop_start = 0;
1038 nframes_t loop_length = 0;
1039 nframes_t offset = 0;
1042 /* XXX we don't currently play loops in reverse. not sure why */
1046 /* Make the use of a Location atomic for this read operation.
1048 Note: Locations don't get deleted, so all we care about
1049 when I say "atomic" is that we are always pointing to
1050 the same one and using a start/length values obtained
1054 if ((loc = loop_location) != 0) {
1055 loop_start = loc->start();
1056 loop_end = loc->end();
1057 loop_length = loop_end - loop_start;
1060 /* if we are looping, ensure that the first frame we read is at the correct
1061 position within the loop.
1064 if (loc && start >= loop_end) {
1065 //cerr << "start adjusted from " << start;
1066 start = loop_start + ((start - loop_start) % loop_length);
1067 //cerr << "to " << start << endl;
1070 //cerr << "start is " << start << " loopstart: " << loop_start << " loopend: " << loop_end << endl;
1079 /* take any loop into account. we can't read past the end of the loop. */
1081 if (loc && (loop_end - start < cnt)) {
1082 this_read = loop_end - start;
1083 //cerr << "reloop true: thisread: " << this_read << " cnt: " << cnt << endl;
1090 if (this_read == 0) {
1094 this_read = min(cnt,this_read);
1096 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
1097 error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), _id, this_read,
1102 _read_data_count = _playlist->read_data_count();
1106 swap_by_ptr (buf, buf + this_read - 1);
1110 /* if we read to the end of the loop, go back to the beginning */
1120 offset += this_read;
1127 AudioDiskstream::do_refill_with_alloc ()
1129 Sample* mix_buf = new Sample[disk_io_chunk_frames];
1130 float* gain_buf = new float[disk_io_chunk_frames];
1132 int ret = _do_refill(mix_buf, gain_buf);
1141 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer)
1145 RingBufferNPT<Sample>::rw_vector vector;
1146 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1147 nframes_t total_space;
1148 nframes_t zero_fill;
1150 ChannelList::iterator i;
1151 boost::shared_ptr<ChannelList> c = channels.reader();
1158 assert(mixdown_buffer);
1159 assert(gain_buffer);
1166 c->front()->playback_buf->get_write_vector (&vector);
1168 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1172 /* if there are 2+ chunks of disk i/o possible for
1173 this track, let the caller know so that it can arrange
1174 for us to be called again, ASAP.
1177 if (total_space >= (_slaved?3:2) * disk_io_chunk_frames) {
1181 /* if we're running close to normal speed and there isn't enough
1182 space to do disk_io_chunk_frames of I/O, then don't bother.
1184 at higher speeds, just do it because the sync between butler
1185 and audio thread may not be good enough.
1188 if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1192 /* when slaved, don't try to get too close to the read pointer. this
1193 leaves space for the buffer reversal to have something useful to
1197 if (_slaved && total_space < (c->front()->playback_buf->bufsize() / 2)) {
1201 /* never do more than disk_io_chunk_frames worth of disk input per call (limit doesn't apply for memset) */
1203 total_space = min (disk_io_chunk_frames, total_space);
1207 if (file_frame == 0) {
1209 /* at start: nothing to do but fill with silence */
1211 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1213 ChannelInfo* chan (*i);
1214 chan->playback_buf->get_write_vector (&vector);
1215 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1216 if (vector.len[1]) {
1217 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1219 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1224 if (file_frame < total_space) {
1226 /* too close to the start: read what we can,
1227 and then zero fill the rest
1230 zero_fill = total_space - file_frame;
1231 total_space = file_frame;
1241 if (file_frame == max_frames) {
1243 /* at end: nothing to do but fill with silence */
1245 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1247 ChannelInfo* chan (*i);
1248 chan->playback_buf->get_write_vector (&vector);
1249 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1250 if (vector.len[1]) {
1251 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1253 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1258 if (file_frame > max_frames - total_space) {
1260 /* to close to the end: read what we can, and zero fill the rest */
1262 zero_fill = total_space - (max_frames - file_frame);
1263 total_space = max_frames - file_frame;
1270 nframes_t file_frame_tmp = 0;
1272 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1274 ChannelInfo* chan (*i);
1277 nframes_t len1, len2;
1279 chan->playback_buf->get_write_vector (&vector);
1281 if (vector.len[0] > disk_io_chunk_frames) {
1283 /* we're not going to fill the first chunk, so certainly do not bother with the
1284 other part. it won't be connected with the part we do fill, as in:
1286 .... => writable space
1287 ++++ => readable space
1288 ^^^^ => 1 x disk_io_chunk_frames that would be filled
1290 |......|+++++++++++++|...............................|
1295 So, just pretend that the buf1 part isn't there.
1305 file_frame_tmp = file_frame;
1307 buf1 = vector.buf[0];
1308 len1 = vector.len[0];
1309 buf2 = vector.buf[1];
1310 len2 = vector.len[1];
1312 to_read = min (ts, len1);
1313 to_read = min (to_read, disk_io_chunk_frames);
1317 if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1322 chan->playback_buf->increment_write_ptr (to_read);
1326 to_read = min (ts, len2);
1330 /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1331 so read some or all of vector.len[1] as well.
1334 if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1339 chan->playback_buf->increment_write_ptr (to_read);
1348 file_frame = file_frame_tmp;
1355 /** Flush pending data to disk.
1357 * Important note: this function will write *AT MOST* disk_io_chunk_frames
1358 * of data to disk. it will never write more than that. If it writes that
1359 * much and there is more than that waiting to be written, it will return 1,
1360 * otherwise 0 on success or -1 on failure.
1362 * If there is less than disk_io_chunk_frames to be written, no data will be
1363 * written at all unless @a force_flush is true.
1366 AudioDiskstream::do_flush (Session::RunContext context, bool force_flush)
1370 RingBufferNPT<Sample>::rw_vector vector;
1371 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1374 _write_data_count = 0;
1376 transvec.buf[0] = 0;
1377 transvec.buf[1] = 0;
1381 boost::shared_ptr<ChannelList> c = channels.reader();
1382 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1384 (*chan)->capture_buf->get_read_vector (&vector);
1386 total = vector.len[0] + vector.len[1];
1388 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1392 /* if there are 2+ chunks of disk i/o possible for
1393 this track, let the caller know so that it can arrange
1394 for us to be called again, ASAP.
1396 if we are forcing a flush, then if there is* any* extra
1397 work, let the caller know.
1399 if we are no longer recording and there is any extra work,
1400 let the caller know too.
1403 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1407 to_write = min (disk_io_chunk_frames, (nframes_t) vector.len[0]);
1409 // check the transition buffer when recording destructive
1410 // important that we get this after the capture buf
1412 if (destructive()) {
1413 (*chan)->capture_transition_buf->get_read_vector(&transvec);
1414 size_t transcount = transvec.len[0] + transvec.len[1];
1415 bool have_start = false;
1418 for (ti=0; ti < transcount; ++ti) {
1419 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1421 if (captrans.type == CaptureStart) {
1422 // by definition, the first data we got above represents the given capture pos
1424 (*chan)->write_source->mark_capture_start (captrans.capture_val);
1425 (*chan)->curr_capture_cnt = 0;
1429 else if (captrans.type == CaptureEnd) {
1431 // capture end, the capture_val represents total frames in capture
1433 if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1435 // shorten to make the write a perfect fit
1436 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
1438 if (nto_write < to_write) {
1439 ret = 1; // should we?
1441 to_write = nto_write;
1443 (*chan)->write_source->mark_capture_end ();
1445 // increment past this transition, but go no further
1450 // actually ends just beyond this chunk, so force more work
1458 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1462 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1463 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1467 (*chan)->capture_buf->increment_read_ptr (to_write);
1468 (*chan)->curr_capture_cnt += to_write;
1470 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1472 /* we wrote all of vector.len[0] but it wasn't an entire
1473 disk_io_chunk_frames of data, so arrange for some part
1474 of vector.len[1] to be flushed to disk as well.
1477 to_write = min ((nframes_t)(disk_io_chunk_frames - to_write), (nframes_t) vector.len[1]);
1479 if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1480 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1484 _write_data_count += (*chan)->write_source->write_data_count();
1486 (*chan)->capture_buf->increment_read_ptr (to_write);
1487 (*chan)->curr_capture_cnt += to_write;
1496 AudioDiskstream::transport_stopped (struct tm& when, time_t twhen, bool abort_capture)
1498 uint32_t buffer_position;
1499 bool more_work = true;
1501 boost::shared_ptr<AudioRegion> region;
1502 nframes_t total_capture;
1504 SourceList::iterator src;
1505 ChannelList::iterator chan;
1506 vector<CaptureInfo*>::iterator ci;
1507 boost::shared_ptr<ChannelList> c = channels.reader();
1509 bool mark_write_completed = false;
1511 finish_capture (true, c);
1513 /* butler is already stopped, but there may be work to do
1514 to flush remaining data to disk.
1517 while (more_work && !err) {
1518 switch (do_flush (Session::TransportContext, true)) {
1525 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1530 /* XXX is there anything we can do if err != 0 ? */
1531 Glib::Mutex::Lock lm (capture_info_lock);
1533 if (capture_info.empty()) {
1537 if (abort_capture) {
1539 if (destructive()) {
1543 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1545 if ((*chan)->write_source) {
1547 (*chan)->write_source->mark_for_remove ();
1548 (*chan)->write_source->drop_references ();
1549 (*chan)->write_source.reset ();
1552 /* new source set up in "out" below */
1558 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1559 total_capture += (*ci)->frames;
1562 /* figure out the name for this take */
1564 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1566 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1570 s->update_header (capture_info.front()->start, when, twhen);
1571 s->set_captured_for (_name);
1572 s->mark_immutable ();
1573 Analyser::queue_source_for_analysis (s, true);
1577 /* destructive tracks have a single, never changing region */
1579 if (destructive()) {
1581 /* send a signal that any UI can pick up to do the right thing. there is
1582 a small problem here in that a UI may need the peak data to be ready
1583 for the data that was recorded and this isn't interlocked with that
1584 process. this problem is deferred to the UI.
1587 _playlist->Modified();
1591 string whole_file_region_name;
1592 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1594 /* Register a new region with the Session that
1595 describes the entire source. Do this first
1596 so that any sub-regions will obviously be
1597 children of this one (later!)
1601 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, c->front()->write_source->last_capture_start_frame(), total_capture,
1602 whole_file_region_name,
1603 0, AudioRegion::Flag (AudioRegion::DefaultFlags|AudioRegion::Automatic|AudioRegion::WholeFile)));
1605 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1606 region->special_set_position (capture_info.front()->start);
1610 catch (failed_constructor& err) {
1611 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1615 _last_capture_regions.push_back (region);
1617 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1619 XMLNode &before = _playlist->get_state();
1620 _playlist->freeze ();
1622 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1626 _session.region_name (region_name, whole_file_region_name, false);
1628 // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->frames << " add region " << region_name << endl;
1631 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, buffer_position, (*ci)->frames, region_name));
1632 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1635 catch (failed_constructor& err) {
1636 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1637 continue; /* XXX is this OK? */
1640 region->GoingAway.connect (bind (mem_fun (*this, &Diskstream::remove_region_from_last_capture), boost::weak_ptr<Region>(region)));
1642 _last_capture_regions.push_back (region);
1644 i_am_the_modifier++;
1645 _playlist->add_region (region, (*ci)->start);
1646 i_am_the_modifier--;
1648 buffer_position += (*ci)->frames;
1652 XMLNode &after = _playlist->get_state();
1653 _session.add_command (new MementoCommand<Playlist>(*_playlist, &before, &after));
1656 mark_write_completed = true;
1659 reset_write_sources (mark_write_completed);
1663 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1667 capture_info.clear ();
1668 capture_start_frame = 0;
1672 AudioDiskstream::transport_looped (nframes_t transport_frame)
1674 if (was_recording) {
1675 // all we need to do is finish this capture, with modified capture length
1676 boost::shared_ptr<ChannelList> c = channels.reader();
1678 // adjust the capture length knowing that the data will be recorded to disk
1679 // only necessary after the first loop where we're recording
1680 if (capture_info.size() == 0) {
1681 capture_captured += _capture_offset;
1683 if (_alignment_style == ExistingMaterial) {
1684 capture_captured += _session.worst_output_latency();
1686 capture_captured += _roll_delay;
1690 finish_capture (true, c);
1692 // the next region will start recording via the normal mechanism
1693 // we'll set the start position to the current transport pos
1694 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1695 capture_start_frame = transport_frame;
1696 first_recordable_frame = transport_frame; // mild lie
1697 last_recordable_frame = max_frames;
1698 was_recording = true;
1700 if (recordable() && destructive()) {
1701 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1703 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1704 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1706 if (transvec.len[0] > 0) {
1707 transvec.buf[0]->type = CaptureStart;
1708 transvec.buf[0]->capture_val = capture_start_frame;
1709 (*chan)->capture_transition_buf->increment_write_ptr(1);
1713 fatal << X_("programming error: capture_transition_buf is full on rec loop! inconceivable!")
1723 AudioDiskstream::finish_capture (bool rec_monitors_input, boost::shared_ptr<ChannelList> c)
1725 was_recording = false;
1727 if (capture_captured == 0) {
1731 if (recordable() && destructive()) {
1732 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1734 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1735 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1737 if (transvec.len[0] > 0) {
1738 transvec.buf[0]->type = CaptureEnd;
1739 transvec.buf[0]->capture_val = capture_captured;
1740 (*chan)->capture_transition_buf->increment_write_ptr(1);
1744 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1750 CaptureInfo* ci = new CaptureInfo;
1752 ci->start = capture_start_frame;
1753 ci->frames = capture_captured;
1755 /* XXX theoretical race condition here. Need atomic exchange ?
1756 However, the circumstances when this is called right
1757 now (either on record-disable or transport_stopped)
1758 mean that no actual race exists. I think ...
1759 We now have a capture_info_lock, but it is only to be used
1760 to synchronize in the transport_stop and the capture info
1761 accessors, so that invalidation will not occur (both non-realtime).
1764 // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1766 capture_info.push_back (ci);
1767 capture_captured = 0;
1769 /* now we've finished a capture, reset first_recordable_frame for next time */
1770 first_recordable_frame = max_frames;
1774 AudioDiskstream::set_record_enabled (bool yn)
1776 if (!recordable() || !_session.record_enabling_legal() || _io->n_inputs().n_audio() == 0) {
1780 /* can't rec-enable in destructive mode if transport is before start */
1782 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1786 if (yn && channels.reader()->front()->source == 0) {
1788 /* pick up connections not initiated *from* the IO object
1789 we're associated with.
1792 get_input_sources ();
1795 /* yes, i know that this not proof against race conditions, but its
1796 good enough. i think.
1799 if (record_enabled() != yn) {
1801 engage_record_enable ();
1803 disengage_record_enable ();
1809 AudioDiskstream::engage_record_enable ()
1811 bool rolling = _session.transport_speed() != 0.0f;
1812 boost::shared_ptr<ChannelList> c = channels.reader();
1814 g_atomic_int_set (&_record_enabled, 1);
1815 capturing_sources.clear ();
1817 if (Config->get_monitoring_model() == HardwareMonitoring) {
1819 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1820 if ((*chan)->source) {
1821 (*chan)->source->ensure_monitor_input (!(Config->get_auto_input() && rolling));
1823 capturing_sources.push_back ((*chan)->write_source);
1824 (*chan)->write_source->mark_streaming_write_started ();
1828 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1829 capturing_sources.push_back ((*chan)->write_source);
1830 (*chan)->write_source->mark_streaming_write_started ();
1834 RecordEnableChanged (); /* EMIT SIGNAL */
1838 AudioDiskstream::disengage_record_enable ()
1840 g_atomic_int_set (&_record_enabled, 0);
1841 boost::shared_ptr<ChannelList> c = channels.reader();
1842 if (Config->get_monitoring_model() == HardwareMonitoring) {
1843 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1844 if ((*chan)->source) {
1845 (*chan)->source->ensure_monitor_input (false);
1849 capturing_sources.clear ();
1850 RecordEnableChanged (); /* EMIT SIGNAL */
1854 AudioDiskstream::get_state ()
1856 XMLNode* node = new XMLNode ("AudioDiskstream");
1858 LocaleGuard lg (X_("POSIX"));
1859 boost::shared_ptr<ChannelList> c = channels.reader();
1861 node->add_property ("flags", enum_2_string (_flags));
1863 snprintf (buf, sizeof(buf), "%zd", c->size());
1864 node->add_property ("channels", buf);
1866 node->add_property ("playlist", _playlist->name());
1868 snprintf (buf, sizeof(buf), "%.12g", _visible_speed);
1869 node->add_property ("speed", buf);
1871 node->add_property("name", _name);
1872 id().print (buf, sizeof (buf));
1873 node->add_property("id", buf);
1875 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1877 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1878 XMLNode* cs_grandchild;
1880 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1881 cs_grandchild = new XMLNode (X_("file"));
1882 cs_grandchild->add_property (X_("path"), (*i)->path());
1883 cs_child->add_child_nocopy (*cs_grandchild);
1886 /* store the location where capture will start */
1890 if (Config->get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1891 snprintf (buf, sizeof (buf), "%" PRIu32, pi->start());
1893 snprintf (buf, sizeof (buf), "%" PRIu32, _session.transport_frame());
1896 cs_child->add_property (X_("at"), buf);
1897 node->add_child_nocopy (*cs_child);
1901 node->add_child_copy (*_extra_xml);
1908 AudioDiskstream::set_state (const XMLNode& node)
1910 const XMLProperty* prop;
1911 XMLNodeList nlist = node.children();
1912 XMLNodeIterator niter;
1913 uint32_t nchans = 1;
1914 XMLNode* capture_pending_node = 0;
1915 LocaleGuard lg (X_("POSIX"));
1917 in_set_state = true;
1919 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1920 if ((*niter)->name() == IO::state_node_name) {
1921 deprecated_io_node = new XMLNode (**niter);
1924 if ((*niter)->name() == X_("CapturingSources")) {
1925 capture_pending_node = *niter;
1929 /* prevent write sources from being created */
1931 in_set_state = true;
1933 if ((prop = node.property ("name")) != 0) {
1934 _name = prop->value();
1937 if (deprecated_io_node) {
1938 if ((prop = deprecated_io_node->property ("id")) != 0) {
1939 _id = prop->value ();
1942 if ((prop = node.property ("id")) != 0) {
1943 _id = prop->value ();
1947 if ((prop = node.property ("flags")) != 0) {
1948 _flags = Flag (string_2_enum (prop->value(), _flags));
1951 if ((prop = node.property ("channels")) != 0) {
1952 nchans = atoi (prop->value().c_str());
1955 // create necessary extra channels
1956 // we are always constructed with one and we always need one
1958 _n_channels.set(DataType::AUDIO, channels.reader()->size());
1960 if (nchans > _n_channels.n_audio()) {
1962 add_channel (nchans - _n_channels.n_audio());
1963 IO::PortCountChanged(_n_channels);
1965 } else if (nchans < _n_channels.n_audio()) {
1967 remove_channel (_n_channels.n_audio() - nchans);
1970 if ((prop = node.property ("playlist")) == 0) {
1975 bool had_playlist = (_playlist != 0);
1977 if (find_and_use_playlist (prop->value())) {
1981 if (!had_playlist) {
1982 _playlist->set_orig_diskstream_id (_id);
1985 if (!destructive() && capture_pending_node) {
1986 /* destructive streams have one and only one source per channel,
1987 and so they never end up in pending capture in any useful
1990 use_pending_capture_data (*capture_pending_node);
1995 if ((prop = node.property ("speed")) != 0) {
1996 double sp = atof (prop->value().c_str());
1998 if (realtime_set_speed (sp, false)) {
1999 non_realtime_set_speed ();
2003 in_set_state = false;
2005 /* make sure this is clear before we do anything else */
2007 capturing_sources.clear ();
2009 /* write sources are handled when we handle the input set
2010 up of the IO that owns this DS (::non_realtime_input_change())
2017 AudioDiskstream::use_new_write_source (uint32_t n)
2019 boost::shared_ptr<ChannelList> c = channels.reader();
2021 if (!recordable()) {
2025 if (n >= c->size()) {
2026 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
2030 ChannelInfo* chan = (*c)[n];
2032 if (chan->write_source) {
2033 chan->write_source->done_with_peakfile_writes ();
2034 chan->write_source->set_allow_remove_if_empty (true);
2035 chan->write_source.reset ();
2039 if ((chan->write_source = _session.create_audio_source_for_session (*this, n, destructive())) == 0) {
2040 throw failed_constructor();
2044 catch (failed_constructor &err) {
2045 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
2046 chan->write_source.reset ();
2050 /* do not remove destructive files even if they are empty */
2052 chan->write_source->set_allow_remove_if_empty (!destructive());
2058 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool force)
2060 ChannelList::iterator chan;
2061 boost::shared_ptr<ChannelList> c = channels.reader();
2064 if (!recordable()) {
2068 capturing_sources.clear ();
2070 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
2071 if (!destructive()) {
2073 if ((*chan)->write_source && mark_write_complete) {
2074 (*chan)->write_source->mark_streaming_write_completed ();
2076 use_new_write_source (n);
2078 if (record_enabled()) {
2079 capturing_sources.push_back ((*chan)->write_source);
2083 if ((*chan)->write_source == 0) {
2084 use_new_write_source (n);
2089 if (destructive()) {
2091 /* we now have all our write sources set up, so create the
2092 playlist's single region.
2095 if (_playlist->empty()) {
2096 setup_destructive_playlist ();
2102 AudioDiskstream::rename_write_sources ()
2104 ChannelList::iterator chan;
2105 boost::shared_ptr<ChannelList> c = channels.reader();
2108 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
2109 if ((*chan)->write_source != 0) {
2110 (*chan)->write_source->set_source_name (_name, destructive());
2111 /* XXX what to do if one of them fails ? */
2119 AudioDiskstream::set_block_size (nframes_t nframes)
2121 if (_session.get_block_size() > speed_buffer_size) {
2122 speed_buffer_size = _session.get_block_size();
2123 boost::shared_ptr<ChannelList> c = channels.reader();
2125 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2126 if ((*chan)->speed_buffer) delete [] (*chan)->speed_buffer;
2127 (*chan)->speed_buffer = new Sample[speed_buffer_size];
2130 allocate_temporary_buffers ();
2134 AudioDiskstream::allocate_temporary_buffers ()
2136 /* make sure the wrap buffer is at least large enough to deal
2137 with the speeds up to 1.2, to allow for micro-variation
2138 when slaving to MTC, SMPTE etc.
2141 double sp = max (fabsf (_actual_speed), 1.2f);
2142 nframes_t required_wrap_size = (nframes_t) floor (_session.get_block_size() * sp) + 1;
2144 if (required_wrap_size > wrap_buffer_size) {
2146 boost::shared_ptr<ChannelList> c = channels.reader();
2148 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2149 if ((*chan)->playback_wrap_buffer) delete [] (*chan)->playback_wrap_buffer;
2150 (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
2151 if ((*chan)->capture_wrap_buffer) delete [] (*chan)->capture_wrap_buffer;
2152 (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
2155 wrap_buffer_size = required_wrap_size;
2160 AudioDiskstream::monitor_input (bool yn)
2162 boost::shared_ptr<ChannelList> c = channels.reader();
2164 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2166 if ((*chan)->source) {
2167 (*chan)->source->ensure_monitor_input (yn);
2173 AudioDiskstream::set_align_style_from_io ()
2175 bool have_physical = false;
2181 get_input_sources ();
2183 boost::shared_ptr<ChannelList> c = channels.reader();
2185 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2186 if ((*chan)->source && (*chan)->source->flags() & JackPortIsPhysical) {
2187 have_physical = true;
2192 if (have_physical) {
2193 set_align_style (ExistingMaterial);
2195 set_align_style (CaptureTime);
2200 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2202 while (how_many--) {
2203 c->push_back (new ChannelInfo(_session.diskstream_buffer_size(), speed_buffer_size, wrap_buffer_size));
2206 _n_channels.set(DataType::AUDIO, c->size());
2212 AudioDiskstream::add_channel (uint32_t how_many)
2214 RCUWriter<ChannelList> writer (channels);
2215 boost::shared_ptr<ChannelList> c = writer.get_copy();
2217 return add_channel_to (c, how_many);
2221 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2223 while (how_many-- && !c->empty()) {
2228 _n_channels.set(DataType::AUDIO, c->size());
2234 AudioDiskstream::remove_channel (uint32_t how_many)
2236 RCUWriter<ChannelList> writer (channels);
2237 boost::shared_ptr<ChannelList> c = writer.get_copy();
2239 return remove_channel_from (c, how_many);
2243 AudioDiskstream::playback_buffer_load () const
2245 boost::shared_ptr<ChannelList> c = channels.reader();
2247 return (float) ((double) c->front()->playback_buf->read_space()/
2248 (double) c->front()->playback_buf->bufsize());
2252 AudioDiskstream::capture_buffer_load () const
2254 boost::shared_ptr<ChannelList> c = channels.reader();
2256 return (float) ((double) c->front()->capture_buf->write_space()/
2257 (double) c->front()->capture_buf->bufsize());
2261 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2263 const XMLProperty* prop;
2264 XMLNodeList nlist = node.children();
2265 XMLNodeIterator niter;
2266 boost::shared_ptr<AudioFileSource> fs;
2267 boost::shared_ptr<AudioFileSource> first_fs;
2268 SourceList pending_sources;
2271 if ((prop = node.property (X_("at"))) == 0) {
2275 if (sscanf (prop->value().c_str(), "%" PRIu32, &position) != 1) {
2279 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2280 if ((*niter)->name() == X_("file")) {
2282 if ((prop = (*niter)->property (X_("path"))) == 0) {
2286 // This protects sessions from errant CapturingSources in stored sessions
2288 if (stat (prop->value().c_str(), &sbuf)) {
2293 fs = boost::dynamic_pointer_cast<AudioFileSource> (
2294 SourceFactory::createWritable (DataType::AUDIO, _session, prop->value(), false, _session.frame_rate()));
2297 catch (failed_constructor& err) {
2298 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2299 _name, prop->value())
2304 pending_sources.push_back (fs);
2306 if (first_fs == 0) {
2310 fs->set_captured_for (_name);
2314 if (pending_sources.size() == 0) {
2315 /* nothing can be done */
2319 if (pending_sources.size() != _n_channels.n_audio()) {
2320 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2325 boost::shared_ptr<AudioRegion> region;
2328 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, 0, first_fs->length(),
2329 region_name_from_path (first_fs->name(), true),
2330 0, AudioRegion::Flag (AudioRegion::DefaultFlags|AudioRegion::Automatic|AudioRegion::WholeFile)));
2331 region->special_set_position (0);
2334 catch (failed_constructor& err) {
2335 error << string_compose (_("%1: cannot create whole-file region from pending capture sources"),
2343 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, 0, first_fs->length(), region_name_from_path (first_fs->name(), true)));
2346 catch (failed_constructor& err) {
2347 error << string_compose (_("%1: cannot create region from pending capture sources"),
2354 _playlist->add_region (region, position);
2360 AudioDiskstream::set_destructive (bool yn)
2362 bool bounce_ignored;
2364 if (yn != destructive()) {
2367 /* requestor should already have checked this and
2368 bounced if necessary and desired
2370 if (!can_become_destructive (bounce_ignored)) {
2373 _flags = Flag (_flags | Destructive);
2374 use_destructive_playlist ();
2376 _flags = Flag (_flags & ~Destructive);
2377 reset_write_sources (true, true);
2385 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2388 requires_bounce = false;
2392 /* is there only one region ? */
2394 if (_playlist->n_regions() != 1) {
2395 requires_bounce = true;
2399 boost::shared_ptr<Region> first = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
2402 /* do the source(s) for the region cover the session start position ? */
2404 if (first->position() != _session.current_start_frame()) {
2405 if (first->start() > _session.current_start_frame()) {
2406 requires_bounce = true;
2411 /* is the source used by only 1 playlist ? */
2413 boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2417 if (afirst->source()->used() > 1) {
2418 requires_bounce = true;
2422 requires_bounce = false;
2426 AudioDiskstream::ChannelInfo::ChannelInfo (nframes_t bufsize, nframes_t speed_size, nframes_t wrap_size)
2430 current_capture_buffer = 0;
2431 current_playback_buffer = 0;
2432 curr_capture_cnt = 0;
2434 speed_buffer = new Sample[speed_size];
2435 playback_wrap_buffer = new Sample[wrap_size];
2436 capture_wrap_buffer = new Sample[wrap_size];
2438 playback_buf = new RingBufferNPT<Sample> (bufsize);
2439 capture_buf = new RingBufferNPT<Sample> (bufsize);
2440 capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2442 /* touch the ringbuffer buffers, which will cause
2443 them to be mapped into locked physical RAM if
2444 we're running with mlockall(). this doesn't do
2448 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2449 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2450 memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2453 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2456 write_source.reset ();
2460 delete [] speed_buffer;
2464 if (playback_wrap_buffer) {
2465 delete [] playback_wrap_buffer;
2466 playback_wrap_buffer = 0;
2469 if (capture_wrap_buffer) {
2470 delete [] capture_wrap_buffer;
2471 capture_wrap_buffer = 0;
2475 delete playback_buf;
2484 if (capture_transition_buf) {
2485 delete capture_transition_buf;
2486 capture_transition_buf = 0;