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.
31 #include "pbd/error.h"
32 #include "pbd/xml++.h"
33 #include "pbd/memento_command.h"
34 #include "pbd/enumwriter.h"
35 #include "pbd/stateful_diff_command.h"
37 #include "ardour/analyser.h"
38 #include "ardour/audio_buffer.h"
39 #include "ardour/audio_diskstream.h"
40 #include "ardour/audio_port.h"
41 #include "ardour/audioengine.h"
42 #include "ardour/audiofilesource.h"
43 #include "ardour/audioplaylist.h"
44 #include "ardour/audioregion.h"
45 #include "ardour/butler.h"
46 #include "ardour/debug.h"
47 #include "ardour/io.h"
48 #include "ardour/playlist_factory.h"
49 #include "ardour/profile.h"
50 #include "ardour/region_factory.h"
51 #include "ardour/session.h"
52 #include "ardour/session_playlists.h"
53 #include "ardour/sndfile_helpers.h"
54 #include "ardour/source_factory.h"
55 #include "ardour/track.h"
56 #include "ardour/types.h"
57 #include "ardour/utils.h"
63 using namespace ARDOUR;
66 size_t AudioDiskstream::_working_buffers_size = 0;
67 Sample* AudioDiskstream::_mixdown_buffer = 0;
68 gain_t* AudioDiskstream::_gain_buffer = 0;
70 AudioDiskstream::AudioDiskstream (Session &sess, const string &name, Diskstream::Flag flag)
71 : Diskstream(sess, name, flag)
72 , channels (new ChannelList)
74 /* prevent any write sources from being created */
80 if (flag & Destructive) {
81 use_destructive_playlist ();
85 AudioDiskstream::AudioDiskstream (Session& sess, const XMLNode& node)
86 : Diskstream(sess, node)
87 , channels (new ChannelList)
92 if (set_state (node, Stateful::loading_state_version)) {
94 throw failed_constructor();
100 use_destructive_playlist ();
105 AudioDiskstream::init ()
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 AudioDiskstream::~AudioDiskstream ()
118 DEBUG_TRACE (DEBUG::Destruction, string_compose ("Audio Diskstream %1 destructor\n", _name));
121 RCUWriter<ChannelList> writer (channels);
122 boost::shared_ptr<ChannelList> c = writer.get_copy();
124 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
135 AudioDiskstream::allocate_working_buffers()
137 _working_buffers_size = max (disk_write_chunk_frames, disk_read_chunk_frames);
138 _mixdown_buffer = new Sample[_working_buffers_size];
139 _gain_buffer = new gain_t[_working_buffers_size];
143 AudioDiskstream::free_working_buffers()
145 delete [] _mixdown_buffer;
146 delete [] _gain_buffer;
147 _working_buffers_size = 0;
153 AudioDiskstream::non_realtime_input_change ()
155 bool need_write_sources = false;
158 Glib::Threads::Mutex::Lock lm (state_lock);
160 if (input_change_pending.type == IOChange::NoChange) {
164 boost::shared_ptr<ChannelList> cr = channels.reader();
165 if (!cr->empty() && !cr->front()->write_source) {
166 need_write_sources = true;
169 if (input_change_pending.type == IOChange::ConfigurationChanged) {
170 RCUWriter<ChannelList> writer (channels);
171 boost::shared_ptr<ChannelList> c = writer.get_copy();
173 _n_channels.set(DataType::AUDIO, c->size());
175 if (_io->n_ports().n_audio() > _n_channels.n_audio()) {
176 add_channel_to (c, _io->n_ports().n_audio() - _n_channels.n_audio());
177 } else if (_io->n_ports().n_audio() < _n_channels.n_audio()) {
178 remove_channel_from (c, _n_channels.n_audio() - _io->n_ports().n_audio());
181 need_write_sources = true;
184 if (input_change_pending.type & IOChange::ConnectionsChanged) {
185 get_input_sources ();
186 set_capture_offset ();
187 set_align_style_from_io ();
190 input_change_pending = IOChange::NoChange;
192 /* implicit unlock */
195 if (need_write_sources) {
196 reset_write_sources (false);
199 /* now refill channel buffers */
201 if (speed() != 1.0f || speed() != -1.0f) {
202 seek ((framepos_t) (_session.transport_frame() * (double) speed()));
204 seek (_session.transport_frame());
209 AudioDiskstream::non_realtime_locate (framepos_t location)
211 /* now refill channel buffers */
213 if (speed() != 1.0f || speed() != -1.0f) {
214 seek ((framepos_t) (location * (double) speed()));
221 AudioDiskstream::get_input_sources ()
223 boost::shared_ptr<ChannelList> c = channels.reader();
226 ChannelList::iterator chan;
227 uint32_t ni = _io->n_ports().n_audio();
228 vector<string> connections;
230 for (n = 0, chan = c->begin(); chan != c->end() && n < ni; ++chan, ++n) {
232 connections.clear ();
234 if ((_io->nth (n).get()) && (_io->nth (n)->get_connections (connections) == 0)) {
235 if (!(*chan)->source.name.empty()) {
236 // _source->disable_metering ();
238 (*chan)->source.name = string();
240 (*chan)->source.name = connections[0];
246 AudioDiskstream::find_and_use_playlist (const string& name)
248 boost::shared_ptr<AudioPlaylist> playlist;
250 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (_session.playlists->by_name (name))) == 0) {
251 playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, name));
255 error << string_compose(_("AudioDiskstream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
259 return use_playlist (playlist);
263 AudioDiskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
265 assert(boost::dynamic_pointer_cast<AudioPlaylist>(playlist));
267 Diskstream::use_playlist(playlist);
273 AudioDiskstream::use_new_playlist ()
276 boost::shared_ptr<AudioPlaylist> playlist;
278 if (!in_set_state && destructive()) {
283 newname = Playlist::bump_name (_playlist->name(), _session);
285 newname = Playlist::bump_name (_name, _session);
288 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, newname, hidden()))) != 0) {
290 return use_playlist (playlist);
298 AudioDiskstream::use_copy_playlist ()
300 assert(audio_playlist());
306 if (_playlist == 0) {
307 error << string_compose(_("AudioDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
312 boost::shared_ptr<AudioPlaylist> playlist;
314 newname = Playlist::bump_name (_playlist->name(), _session);
316 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist>(PlaylistFactory::create (audio_playlist(), newname))) != 0) {
317 return use_playlist (playlist);
324 AudioDiskstream::setup_destructive_playlist ()
327 boost::shared_ptr<ChannelList> c = channels.reader();
329 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
330 srcs.push_back ((*chan)->write_source);
333 /* a single full-sized region */
335 assert (!srcs.empty ());
338 plist.add (Properties::name, _name.val());
339 plist.add (Properties::start, 0);
340 plist.add (Properties::length, max_framepos - srcs.front()->natural_position());
342 boost::shared_ptr<Region> region (RegionFactory::create (srcs, plist));
343 _playlist->add_region (region, srcs.front()->natural_position());
345 /* apply region properties and update write sources */
346 use_destructive_playlist();
350 AudioDiskstream::use_destructive_playlist ()
352 /* this is called from the XML-based constructor or ::set_destructive. when called,
353 we already have a playlist and a region, but we need to
354 set up our sources for write. we use the sources associated
355 with the (presumed single, full-extent) region.
358 boost::shared_ptr<Region> rp;
360 const RegionList& rl (_playlist->region_list().rlist());
362 assert((rl.size() == 1));
368 reset_write_sources (false, true);
372 boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
375 throw failed_constructor();
378 /* be sure to stretch the region out to the maximum length */
380 region->set_length (max_framepos - region->position());
383 ChannelList::iterator chan;
384 boost::shared_ptr<ChannelList> c = channels.reader();
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);
391 /* this might be false if we switched modes, so force it */
393 (*chan)->write_source->set_destructive (true);
396 /* the source list will never be reset for a destructive track */
400 AudioDiskstream::prepare_record_status(framepos_t capture_start_frame)
402 if (recordable() && destructive()) {
403 boost::shared_ptr<ChannelList> c = channels.reader();
404 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
406 RingBufferNPT<CaptureTransition>::rw_vector transitions;
407 (*chan)->capture_transition_buf->get_write_vector (&transitions);
409 if (transitions.len[0] > 0) {
410 transitions.buf[0]->type = CaptureStart;
411 transitions.buf[0]->capture_val = capture_start_frame;
412 (*chan)->capture_transition_buf->increment_write_ptr(1);
415 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
423 /** Do some record stuff [not described in this comment!]
426 * - Setup playback_distance with the nframes, or nframes adjusted
427 * for current varispeed, if appropriate.
428 * - Setup current_playback_buffer in each ChannelInfo to point to data
429 * that someone can read playback_distance worth of data from.
432 AudioDiskstream::process (BufferSet& bufs, framepos_t transport_frame, pframes_t nframes, framecnt_t& playback_distance, bool need_disk_signal)
435 boost::shared_ptr<ChannelList> c = channels.reader();
436 ChannelList::iterator chan;
437 framecnt_t rec_offset = 0;
438 framecnt_t rec_nframes = 0;
439 bool collect_playback = false;
440 bool can_record = _session.actively_recording ();
442 playback_distance = 0;
444 if (!_io || !_io->active()) {
448 check_record_status (transport_frame, can_record);
454 Glib::Threads::Mutex::Lock sm (state_lock, Glib::Threads::TRY_LOCK);
460 adjust_capture_position = 0;
462 for (chan = c->begin(); chan != c->end(); ++chan) {
463 (*chan)->current_capture_buffer = 0;
464 (*chan)->current_playback_buffer = 0;
467 // Safeguard against situations where process() goes haywire when autopunching
468 // and last_recordable_frame < first_recordable_frame
470 if (last_recordable_frame < first_recordable_frame) {
471 last_recordable_frame = max_framepos;
474 if (record_enabled()) {
476 Evoral::OverlapType ot = Evoral::coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
477 // XXX should this be transport_frame + nframes - 1 ? coverage() expects its parameter ranges to include their end points
478 // XXX also, first_recordable_frame & last_recordable_frame may both be == max_framepos: coverage() will return OverlapNone in that case. Is thak OK?
479 calculate_record_range (ot, transport_frame, nframes, rec_nframes, rec_offset);
481 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1: this time record %2 of %3 frames, offset %4\n", _name, rec_nframes, nframes, rec_offset));
483 if (rec_nframes && !was_recording) {
484 capture_captured = 0;
485 was_recording = true;
489 if (can_record && !_last_capture_sources.empty()) {
490 _last_capture_sources.clear ();
495 uint32_t limit = _io->n_ports ().n_audio();
497 /* one or more ports could already have been removed from _io, but our
498 channel setup hasn't yet been updated. prevent us from trying to
499 use channels that correspond to missing ports. note that the
500 process callback (from which this is called) is always atomic
501 with respect to port removal/addition.
504 for (n = 0, chan = c->begin(); chan != c->end() && n < limit; ++chan, ++n) {
506 ChannelInfo* chaninfo (*chan);
508 chaninfo->capture_buf->get_write_vector (&chaninfo->capture_vector);
510 if (rec_nframes <= (framecnt_t) chaninfo->capture_vector.len[0]) {
512 chaninfo->current_capture_buffer = chaninfo->capture_vector.buf[0];
514 /* note: grab the entire port buffer, but only copy what we were supposed to
515 for recording, and use rec_offset
518 boost::shared_ptr<AudioPort> const ap = _io->audio (n);
520 assert(rec_nframes <= (framecnt_t) ap->get_audio_buffer(nframes).capacity());
522 Sample *buf = bufs.get_audio (n).data(rec_offset);
523 memcpy (chaninfo->current_capture_buffer, buf, sizeof (Sample) * rec_nframes);
527 framecnt_t total = chaninfo->capture_vector.len[0] + chaninfo->capture_vector.len[1];
529 if (rec_nframes > total) {
530 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 overrun in %2, rec_nframes = %3 total space = %4\n",
531 DEBUG_THREAD_SELF, name(), rec_nframes, total));
536 boost::shared_ptr<AudioPort> const ap = _io->audio (n);
539 Sample *buf = bufs.get_audio (n).data(rec_offset);
540 framecnt_t first = chaninfo->capture_vector.len[0];
542 memcpy (chaninfo->capture_wrap_buffer, buf, sizeof (Sample) * first);
543 memcpy (chaninfo->capture_vector.buf[0], buf, sizeof (Sample) * first);
544 memcpy (chaninfo->capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
545 memcpy (chaninfo->capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
547 chaninfo->current_capture_buffer = chaninfo->capture_wrap_buffer;
561 /* data will be written to disk */
563 if (rec_nframes == nframes && rec_offset == 0) {
565 for (chan = c->begin(); chan != c->end(); ++chan) {
566 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
569 playback_distance = nframes;
574 /* we can't use the capture buffer as the playback buffer, because
575 we recorded only a part of the current process' cycle data
579 collect_playback = true;
582 adjust_capture_position = rec_nframes;
584 } else if (can_record && record_enabled()) {
586 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
588 for (chan = c->begin(); chan != c->end(); ++chan) {
589 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
592 playback_distance = nframes;
596 collect_playback = true;
599 if ((_track->monitoring_state () & MonitoringDisk) || collect_playback) {
601 /* we're doing playback */
603 framecnt_t necessary_samples;
605 /* no varispeed playback if we're recording, because the output .... TBD */
607 if (rec_nframes == 0 && _actual_speed != 1.0f) {
608 necessary_samples = (framecnt_t) ceil ((nframes * fabs (_actual_speed))) + 2;
610 necessary_samples = nframes;
613 for (chan = c->begin(); chan != c->end(); ++chan) {
614 (*chan)->playback_buf->get_read_vector (&(*chan)->playback_vector);
619 /* Setup current_playback_buffer in each ChannelInfo to point to data that someone
620 can read necessary_samples (== nframes at a transport speed of 1) worth of data
624 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
626 ChannelInfo* chaninfo (*chan);
628 if (necessary_samples <= (framecnt_t) chaninfo->playback_vector.len[0]) {
629 /* There are enough samples in the first part of the ringbuffer */
630 chaninfo->current_playback_buffer = chaninfo->playback_vector.buf[0];
633 framecnt_t total = chaninfo->playback_vector.len[0] + chaninfo->playback_vector.len[1];
635 if (necessary_samples > total) {
636 cerr << _name << " Need " << necessary_samples << " total = " << total << endl;
637 cerr << "underrun for " << _name << endl;
638 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 underrun in %2, rec_nframes = %3 total space = %4\n",
639 DEBUG_THREAD_SELF, name(), rec_nframes, total));
645 /* We have enough samples, but not in one lump. Coalesce the two parts
646 into one in playback_wrap_buffer in our ChannelInfo, and specify that
647 as our current_playback_buffer.
650 assert(wrap_buffer_size >= necessary_samples);
652 /* Copy buf[0] from playback_buf */
653 memcpy ((char *) chaninfo->playback_wrap_buffer,
654 chaninfo->playback_vector.buf[0],
655 chaninfo->playback_vector.len[0] * sizeof (Sample));
657 /* Copy buf[1] from playback_buf */
658 memcpy (chaninfo->playback_wrap_buffer + chaninfo->playback_vector.len[0],
659 chaninfo->playback_vector.buf[1],
660 (necessary_samples - chaninfo->playback_vector.len[0])
663 chaninfo->current_playback_buffer = chaninfo->playback_wrap_buffer;
668 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
670 interpolation.set_speed (_target_speed);
673 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++channel) {
674 ChannelInfo* chaninfo (*chan);
676 playback_distance = interpolation.interpolate (
677 channel, nframes, chaninfo->current_playback_buffer, chaninfo->speed_buffer);
679 chaninfo->current_playback_buffer = chaninfo->speed_buffer;
683 playback_distance = nframes;
686 _speed = _target_speed;
689 if (need_disk_signal) {
691 /* copy data over to buffer set */
693 size_t n_buffers = bufs.count().n_audio();
694 size_t n_chans = c->size();
695 gain_t scaling = 1.0f;
697 if (n_chans > n_buffers) {
698 scaling = ((float) n_buffers)/n_chans;
701 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
703 AudioBuffer& buf (bufs.get_audio (n%n_buffers));
704 ChannelInfo* chaninfo (*chan);
707 if (scaling != 1.0f) {
708 buf.read_from_with_gain (chaninfo->current_playback_buffer, nframes, scaling);
710 buf.read_from (chaninfo->current_playback_buffer, nframes);
713 if (scaling != 1.0f) {
714 buf.accumulate_with_gain_from (chaninfo->current_playback_buffer, nframes, scaling);
716 buf.accumulate_from (chaninfo->current_playback_buffer, nframes);
721 /* leave the MIDI count alone */
722 ChanCount cnt (DataType::AUDIO, n_chans);
723 cnt.set (DataType::MIDI, bufs.count().n_midi());
724 bufs.set_count (cnt);
726 /* extra buffers will already be silent, so leave them alone */
733 AudioDiskstream::calculate_playback_distance (pframes_t nframes)
735 frameoffset_t playback_distance = nframes;
737 if (record_enabled()) {
738 playback_distance = nframes;
739 } else if (_actual_speed != 1.0f && _actual_speed != -1.0f) {
740 interpolation.set_speed (_target_speed);
741 boost::shared_ptr<ChannelList> c = channels.reader();
743 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++channel) {
744 playback_distance = interpolation.interpolate (channel, nframes, NULL, NULL);
747 playback_distance = nframes;
750 if (_actual_speed < 0.0) {
751 return -playback_distance;
753 return playback_distance;
757 /** Update various things including playback_sample, read pointer on each channel's playback_buf
758 * and write pointer on each channel's capture_buf. Also wout whether the butler is needed.
759 * @return true if the butler is required.
762 AudioDiskstream::commit (framecnt_t playback_distance)
764 bool need_butler = false;
766 if (!_io || !_io->active()) {
770 if (_actual_speed < 0.0) {
771 playback_sample -= playback_distance;
773 playback_sample += playback_distance;
776 boost::shared_ptr<ChannelList> c = channels.reader();
777 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
779 (*chan)->playback_buf->increment_read_ptr (playback_distance);
781 if (adjust_capture_position) {
782 (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
786 if (adjust_capture_position != 0) {
787 capture_captured += adjust_capture_position;
788 adjust_capture_position = 0;
796 if (_io && _io->active()) {
797 need_butler = c->front()->playback_buf->write_space() >= c->front()->playback_buf->bufsize() / 2;
802 if (_io && _io->active()) {
803 need_butler = ((framecnt_t) c->front()->playback_buf->write_space() >= disk_read_chunk_frames)
804 || ((framecnt_t) c->front()->capture_buf->read_space() >= disk_write_chunk_frames);
806 need_butler = ((framecnt_t) c->front()->capture_buf->read_space() >= disk_write_chunk_frames);
814 AudioDiskstream::set_pending_overwrite (bool yn)
816 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
818 _pending_overwrite = yn;
820 overwrite_frame = playback_sample;
822 boost::shared_ptr<ChannelList> c = channels.reader ();
824 overwrite_offset = c->front()->playback_buf->get_read_ptr();
829 AudioDiskstream::overwrite_existing_buffers ()
831 boost::shared_ptr<ChannelList> c = channels.reader();
833 _pending_overwrite = false;
837 Sample* mixdown_buffer;
840 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
842 overwrite_queued = false;
844 /* assume all are the same size */
845 framecnt_t size = c->front()->playback_buf->bufsize();
847 mixdown_buffer = new Sample[size];
848 gain_buffer = new float[size];
850 /* reduce size so that we can fill the buffer correctly (ringbuffers
851 can only handle size-1, otherwise they appear to be empty)
858 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
860 start = overwrite_frame;
861 framecnt_t cnt = size;
863 /* to fill the buffer without resetting the playback sample, we need to
864 do it one or two chunks (normally two).
866 |----------------------------------------------------------------------|
870 |<- second chunk->||<----------------- first chunk ------------------>|
874 framecnt_t to_read = size - overwrite_offset;
876 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, n, reversed)) {
877 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
878 id(), size, playback_sample) << endmsg;
886 if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer, start, cnt, n, reversed)) {
887 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
888 id(), size, playback_sample) << endmsg;
897 _pending_overwrite = false;
898 delete [] gain_buffer;
899 delete [] mixdown_buffer;
904 AudioDiskstream::seek (framepos_t frame, bool complete_refill)
908 ChannelList::iterator chan;
909 boost::shared_ptr<ChannelList> c = channels.reader();
911 Glib::Threads::Mutex::Lock lm (state_lock);
913 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
914 (*chan)->playback_buf->reset ();
915 (*chan)->capture_buf->reset ();
918 /* can't rec-enable in destructive mode if transport is before start */
920 if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
921 disengage_record_enable ();
924 playback_sample = frame;
927 if (complete_refill) {
928 /* call _do_refill() to refill the entire buffer, using
929 the largest reads possible.
931 while ((ret = do_refill_with_alloc (false)) > 0) ;
933 /* call _do_refill() to refill just one chunk, and then
936 ret = do_refill_with_alloc (true);
943 AudioDiskstream::can_internal_playback_seek (framecnt_t distance)
945 ChannelList::iterator chan;
946 boost::shared_ptr<ChannelList> c = channels.reader();
948 for (chan = c->begin(); chan != c->end(); ++chan) {
949 if ((*chan)->playback_buf->read_space() < (size_t) distance) {
957 AudioDiskstream::internal_playback_seek (framecnt_t distance)
959 ChannelList::iterator chan;
960 boost::shared_ptr<ChannelList> c = channels.reader();
962 for (chan = c->begin(); chan != c->end(); ++chan) {
963 (*chan)->playback_buf->increment_read_ptr (llabs(distance));
966 if (first_recordable_frame < max_framepos) {
967 first_recordable_frame += distance;
969 playback_sample += distance;
974 /** Read some data for 1 channel from our playlist into a buffer.
975 * @param buf Buffer to write to.
976 * @param start Session frame to start reading from; updated to where we end up
978 * @param cnt Count of samples to read.
979 * @param reversed true if we are running backwards, otherwise false.
982 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer,
983 framepos_t& start, framecnt_t cnt,
984 int channel, bool reversed)
986 framecnt_t this_read = 0;
988 framepos_t loop_end = 0;
989 framepos_t loop_start = 0;
990 framecnt_t offset = 0;
993 /* XXX we don't currently play loops in reverse. not sure why */
997 framecnt_t loop_length = 0;
999 /* Make the use of a Location atomic for this read operation.
1001 Note: Locations don't get deleted, so all we care about
1002 when I say "atomic" is that we are always pointing to
1003 the same one and using a start/length values obtained
1007 if ((loc = loop_location) != 0) {
1008 loop_start = loc->start();
1009 loop_end = loc->end();
1010 loop_length = loop_end - loop_start;
1013 /* if we are looping, ensure that the first frame we read is at the correct
1014 position within the loop.
1017 if (loc && start >= loop_end) {
1018 start = loop_start + ((start - loop_start) % loop_length);
1027 /* We need this while loop in case we hit a loop boundary, in which case our read from
1028 the playlist must be split into more than one section.
1033 /* take any loop into account. we can't read past the end of the loop. */
1035 if (loc && (loop_end - start < cnt)) {
1036 this_read = loop_end - start;
1043 if (this_read == 0) {
1047 this_read = min(cnt,this_read);
1049 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
1050 error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), id(), this_read,
1057 swap_by_ptr (buf, buf + this_read - 1);
1061 /* if we read to the end of the loop, go back to the beginning */
1071 offset += this_read;
1078 AudioDiskstream::_do_refill_with_alloc (bool partial_fill)
1080 Sample* mix_buf = new Sample[1048576];
1081 float* gain_buf = new float[1048576];
1083 int ret = _do_refill (mix_buf, gain_buf, (partial_fill ? disk_read_chunk_frames : 0));
1091 /** Get some more data from disk and put it in our channels' playback_bufs,
1092 * if there is suitable space in them.
1094 * If fill_level is non-zero, then we will refill the buffer so that there is
1095 * still at least fill_level samples of space left to be filled. This is used
1096 * after locates so that we do not need to wait to fill the entire buffer.
1101 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer, framecnt_t fill_level)
1105 RingBufferNPT<Sample>::rw_vector vector;
1106 bool const reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1107 framecnt_t total_space;
1108 framecnt_t zero_fill;
1110 ChannelList::iterator i;
1111 boost::shared_ptr<ChannelList> c = channels.reader();
1114 /* do not read from disk while session is marked as Loading, to avoid
1115 useless redundant I/O.
1118 if (_session.state_of_the_state() & Session::Loading) {
1126 assert(mixdown_buffer);
1127 assert(gain_buffer);
1134 c->front()->playback_buf->get_write_vector (&vector);
1136 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1137 /* nowhere to write to */
1142 if (fill_level < total_space) {
1143 cerr << name() << " adjust total space of " << total_space << " to leave " << fill_level << " to still refill\n";
1144 if (fill_level < 0) {
1145 PBD::stacktrace (cerr, 20);
1147 total_space -= fill_level;
1149 /* we can't do anything with it */
1154 /* if we're running close to normal speed and there isn't enough
1155 space to do disk_read_chunk_frames of I/O, then don't bother.
1157 at higher speeds, just do it because the sync between butler
1158 and audio thread may not be good enough.
1160 Note: it is a design assumption that disk_read_chunk_frames is smaller
1161 than the playback buffer size, so this check should never trip when
1162 the playback buffer is empty.
1165 if ((total_space < disk_read_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1169 /* when slaved, don't try to get too close to the read pointer. this
1170 leaves space for the buffer reversal to have something useful to
1174 if (_slaved && total_space < (framecnt_t) (c->front()->playback_buf->bufsize() / 2)) {
1180 if (file_frame == 0) {
1182 /* at start: nothing to do but fill with silence */
1184 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1186 ChannelInfo* chan (*i);
1187 chan->playback_buf->get_write_vector (&vector);
1188 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1189 if (vector.len[1]) {
1190 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1192 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1197 if (file_frame < total_space) {
1199 /* too close to the start: read what we can,
1200 and then zero fill the rest
1203 zero_fill = total_space - file_frame;
1204 total_space = file_frame;
1213 if (file_frame == max_framepos) {
1215 /* at end: nothing to do but fill with silence */
1217 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1219 ChannelInfo* chan (*i);
1220 chan->playback_buf->get_write_vector (&vector);
1221 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1222 if (vector.len[1]) {
1223 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1225 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1230 if (file_frame > max_framepos - total_space) {
1232 /* to close to the end: read what we can, and zero fill the rest */
1234 zero_fill = total_space - (max_framepos - file_frame);
1235 total_space = max_framepos - file_frame;
1242 framepos_t file_frame_tmp = 0;
1244 /* total_space is in samples. We want to optimize read sizes in various sizes using bytes */
1246 const size_t bits_per_sample = sndfile_data_width (_session.config.get_native_file_data_format());
1247 size_t total_bytes = total_space * bits_per_sample / 8;
1249 /* chunk size range is 256kB to 4MB. Bigger is faster in terms of MB/sec, but bigger chunk size always takes longer
1251 size_t byte_size_for_read = max ((size_t) (256 * 1024), min ((size_t) (4 * 1048576), total_bytes));
1253 /* find nearest (lower) multiple of 16384 */
1255 byte_size_for_read = (byte_size_for_read / 16384) * 16384;
1257 /* now back to samples */
1259 framecnt_t samples_to_read = byte_size_for_read / (bits_per_sample / 8);
1261 //cerr << name() << " will read " << byte_size_for_read << " out of total bytes " << total_bytes << " in buffer of "
1262 // << c->front()->playback_buf->bufsize() * bits_per_sample / 8 << " bps = " << bits_per_sample << endl;
1263 cerr << name () << " read samples = " << samples_to_read << " out of total space " << total_space << " in buffer of " << c->front()->playback_buf->bufsize() << " samples\n";
1265 uint64_t before = g_get_monotonic_time ();
1268 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1270 ChannelInfo* chan (*i);
1273 framecnt_t len1, len2;
1275 chan->playback_buf->get_write_vector (&vector);
1277 if ((framecnt_t) vector.len[0] > samples_to_read) {
1279 /* we're not going to fill the first chunk, so certainly do not bother with the
1280 other part. it won't be connected with the part we do fill, as in:
1282 .... => writable space
1283 ++++ => readable space
1284 ^^^^ => 1 x disk_read_chunk_frames that would be filled
1286 |......|+++++++++++++|...............................|
1291 So, just pretend that the buf1 part isn't there.
1301 file_frame_tmp = file_frame;
1303 buf1 = vector.buf[0];
1304 len1 = vector.len[0];
1305 buf2 = vector.buf[1];
1306 len2 = vector.len[1];
1308 to_read = min (ts, len1);
1309 to_read = min (to_read, (framecnt_t) samples_to_read);
1311 assert (to_read >= 0);
1315 if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1320 chan->playback_buf->increment_write_ptr (to_read);
1324 to_read = min (ts, len2);
1328 /* we read all of vector.len[0], but it wasn't the
1329 entire samples_to_read of data, so read some or
1330 all of vector.len[1] as well.
1333 if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1338 chan->playback_buf->increment_write_ptr (to_read);
1342 /* XXX: do something */
1347 elapsed = g_get_monotonic_time () - before;
1348 cerr << "\tbandwidth = " << (byte_size_for_read / 1048576.0) / (elapsed/1000000.0) << "MB/sec\n";
1350 file_frame = file_frame_tmp;
1351 assert (file_frame >= 0);
1353 ret = ((total_space - samples_to_read) > disk_read_chunk_frames);
1355 c->front()->playback_buf->get_write_vector (&vector);
1361 /** Flush pending data to disk.
1363 * Important note: this function will write *AT MOST* disk_write_chunk_frames
1364 * of data to disk. it will never write more than that. If it writes that
1365 * much and there is more than that waiting to be written, it will return 1,
1366 * otherwise 0 on success or -1 on failure.
1368 * If there is less than disk_write_chunk_frames to be written, no data will be
1369 * written at all unless @a force_flush is true.
1372 AudioDiskstream::do_flush (RunContext /*context*/, bool force_flush)
1376 RingBufferNPT<Sample>::rw_vector vector;
1377 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1380 transvec.buf[0] = 0;
1381 transvec.buf[1] = 0;
1385 boost::shared_ptr<ChannelList> c = channels.reader();
1386 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1388 (*chan)->capture_buf->get_read_vector (&vector);
1390 total = vector.len[0] + vector.len[1];
1392 if (total == 0 || (total < disk_write_chunk_frames && !force_flush && was_recording)) {
1396 /* if there are 2+ chunks of disk i/o possible for
1397 this track, let the caller know so that it can arrange
1398 for us to be called again, ASAP.
1400 if we are forcing a flush, then if there is* any* extra
1401 work, let the caller know.
1403 if we are no longer recording and there is any extra work,
1404 let the caller know too.
1407 if (total >= 2 * disk_write_chunk_frames || ((force_flush || !was_recording) && total > disk_write_chunk_frames)) {
1411 to_write = min (disk_write_chunk_frames, (framecnt_t) vector.len[0]);
1413 // check the transition buffer when recording destructive
1414 // important that we get this after the capture buf
1416 if (destructive()) {
1417 (*chan)->capture_transition_buf->get_read_vector(&transvec);
1418 size_t transcount = transvec.len[0] + transvec.len[1];
1421 for (ti=0; ti < transcount; ++ti) {
1422 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1424 if (captrans.type == CaptureStart) {
1425 // by definition, the first data we got above represents the given capture pos
1427 (*chan)->write_source->mark_capture_start (captrans.capture_val);
1428 (*chan)->curr_capture_cnt = 0;
1430 } else if (captrans.type == CaptureEnd) {
1432 // capture end, the capture_val represents total frames in capture
1434 if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1436 // shorten to make the write a perfect fit
1437 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
1439 if (nto_write < to_write) {
1440 ret = 1; // should we?
1442 to_write = nto_write;
1444 (*chan)->write_source->mark_capture_end ();
1446 // increment past this transition, but go no further
1451 // actually ends just beyond this chunk, so force more work
1459 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1463 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1464 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), id()) << endmsg;
1468 (*chan)->capture_buf->increment_read_ptr (to_write);
1469 (*chan)->curr_capture_cnt += to_write;
1471 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_write_chunk_frames) && !destructive()) {
1473 /* we wrote all of vector.len[0] but it wasn't an entire
1474 disk_write_chunk_frames of data, so arrange for some part
1475 of vector.len[1] to be flushed to disk as well.
1478 to_write = min ((framecnt_t)(disk_write_chunk_frames - to_write), (framecnt_t) vector.len[1]);
1480 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 additional write of %2\n", name(), to_write));
1482 if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1483 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), id()) << endmsg;
1487 (*chan)->capture_buf->increment_read_ptr (to_write);
1488 (*chan)->curr_capture_cnt += to_write;
1497 AudioDiskstream::transport_stopped_wallclock (struct tm& when, time_t twhen, bool abort_capture)
1499 uint32_t buffer_position;
1500 bool more_work = true;
1502 boost::shared_ptr<AudioRegion> region;
1503 framecnt_t total_capture;
1505 SourceList::iterator src;
1506 ChannelList::iterator chan;
1507 vector<CaptureInfo*>::iterator ci;
1508 boost::shared_ptr<ChannelList> c = channels.reader();
1510 bool mark_write_completed = false;
1514 /* butler is already stopped, but there may be work to do
1515 to flush remaining data to disk.
1518 while (more_work && !err) {
1519 switch (do_flush (TransportContext, true)) {
1526 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1531 /* XXX is there anything we can do if err != 0 ? */
1532 Glib::Threads::Mutex::Lock lm (capture_info_lock);
1534 if (capture_info.empty()) {
1538 if (abort_capture) {
1540 if (destructive()) {
1544 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1546 if ((*chan)->write_source) {
1548 (*chan)->write_source->mark_for_remove ();
1549 (*chan)->write_source->drop_references ();
1550 (*chan)->write_source.reset ();
1553 /* new source set up in "out" below */
1559 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1560 total_capture += (*ci)->frames;
1563 /* figure out the name for this take */
1565 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1567 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1571 s->update_header (capture_info.front()->start, when, twhen);
1572 s->set_captured_for (_name.val());
1573 s->mark_immutable ();
1575 if (Config->get_auto_analyse_audio()) {
1576 Analyser::queue_source_for_analysis (s, true);
1581 /* destructive tracks have a single, never changing region */
1583 if (destructive()) {
1585 /* send a signal that any UI can pick up to do the right thing. there is
1586 a small problem here in that a UI may need the peak data to be ready
1587 for the data that was recorded and this isn't interlocked with that
1588 process. this problem is deferred to the UI.
1591 _playlist->LayeringChanged(); // XXX this may not get the UI to do the right thing
1595 string whole_file_region_name;
1596 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1598 /* Register a new region with the Session that
1599 describes the entire source. Do this first
1600 so that any sub-regions will obviously be
1601 children of this one (later!)
1607 plist.add (Properties::start, c->front()->write_source->last_capture_start_frame());
1608 plist.add (Properties::length, total_capture);
1609 plist.add (Properties::name, whole_file_region_name);
1610 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1611 rx->set_automatic (true);
1612 rx->set_whole_file (true);
1614 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1615 region->special_set_position (capture_info.front()->start);
1619 catch (failed_constructor& err) {
1620 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1624 _last_capture_sources.insert (_last_capture_sources.end(), srcs.begin(), srcs.end());
1626 _playlist->clear_changes ();
1627 _playlist->set_capture_insertion_in_progress (true);
1628 _playlist->freeze ();
1630 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1634 RegionFactory::region_name (region_name, whole_file_region_name, false);
1636 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1 capture start @ %2 length %3 add new region %4\n",
1637 _name, (*ci)->start, (*ci)->frames, region_name));
1643 plist.add (Properties::start, buffer_position);
1644 plist.add (Properties::length, (*ci)->frames);
1645 plist.add (Properties::name, region_name);
1647 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1648 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1651 catch (failed_constructor& err) {
1652 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1653 continue; /* XXX is this OK? */
1656 i_am_the_modifier++;
1658 _playlist->add_region (region, (*ci)->start, 1, non_layered());
1659 _playlist->set_layer (region, DBL_MAX);
1660 i_am_the_modifier--;
1662 buffer_position += (*ci)->frames;
1666 _playlist->set_capture_insertion_in_progress (false);
1667 _session.add_command (new StatefulDiffCommand (_playlist));
1670 mark_write_completed = true;
1673 reset_write_sources (mark_write_completed);
1677 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1681 capture_info.clear ();
1682 capture_start_frame = 0;
1686 AudioDiskstream::transport_looped (framepos_t transport_frame)
1688 if (was_recording) {
1689 // all we need to do is finish this capture, with modified capture length
1690 boost::shared_ptr<ChannelList> c = channels.reader();
1692 // adjust the capture length knowing that the data will be recorded to disk
1693 // only necessary after the first loop where we're recording
1694 if (capture_info.size() == 0) {
1695 capture_captured += _capture_offset;
1697 if (_alignment_style == ExistingMaterial) {
1698 capture_captured += _session.worst_output_latency();
1700 capture_captured += _roll_delay;
1706 // the next region will start recording via the normal mechanism
1707 // we'll set the start position to the current transport pos
1708 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1709 capture_start_frame = transport_frame;
1710 first_recordable_frame = transport_frame; // mild lie
1711 last_recordable_frame = max_framepos;
1712 was_recording = true;
1714 if (recordable() && destructive()) {
1715 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1717 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1718 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1720 if (transvec.len[0] > 0) {
1721 transvec.buf[0]->type = CaptureStart;
1722 transvec.buf[0]->capture_val = capture_start_frame;
1723 (*chan)->capture_transition_buf->increment_write_ptr(1);
1727 fatal << X_("programming error: capture_transition_buf is full on rec loop! inconceivable!")
1737 AudioDiskstream::finish_capture (boost::shared_ptr<ChannelList> c)
1739 was_recording = false;
1740 first_recordable_frame = max_framepos;
1741 last_recordable_frame = max_framepos;
1743 if (capture_captured == 0) {
1747 if (recordable() && destructive()) {
1748 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1750 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1751 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1753 if (transvec.len[0] > 0) {
1754 transvec.buf[0]->type = CaptureEnd;
1755 transvec.buf[0]->capture_val = capture_captured;
1756 (*chan)->capture_transition_buf->increment_write_ptr(1);
1760 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1766 CaptureInfo* ci = new CaptureInfo;
1768 ci->start = capture_start_frame;
1769 ci->frames = capture_captured;
1771 /* XXX theoretical race condition here. Need atomic exchange ?
1772 However, the circumstances when this is called right
1773 now (either on record-disable or transport_stopped)
1774 mean that no actual race exists. I think ...
1775 We now have a capture_info_lock, but it is only to be used
1776 to synchronize in the transport_stop and the capture info
1777 accessors, so that invalidation will not occur (both non-realtime).
1780 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("Finish capture, add new CI, %1 + %2\n", ci->start, ci->frames));
1782 capture_info.push_back (ci);
1783 capture_captured = 0;
1785 /* now we've finished a capture, reset first_recordable_frame for next time */
1786 first_recordable_frame = max_framepos;
1790 AudioDiskstream::set_record_enabled (bool yn)
1792 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0 || record_safe ()) {
1796 /* can't rec-enable in destructive mode if transport is before start */
1798 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1802 /* yes, i know that this not proof against race conditions, but its
1803 good enough. i think.
1806 if (record_enabled() != yn) {
1808 engage_record_enable ();
1810 disengage_record_enable ();
1813 RecordEnableChanged (); /* EMIT SIGNAL */
1818 AudioDiskstream::set_record_safe (bool yn)
1820 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0) {
1824 /* can't rec-safe in destructive mode if transport is before start ????
1827 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1831 /* yes, i know that this not proof against race conditions, but its
1832 good enough. i think.
1835 if (record_safe () != yn) {
1837 engage_record_safe ();
1839 disengage_record_safe ();
1842 RecordSafeChanged (); /* EMIT SIGNAL */
1847 AudioDiskstream::prep_record_enable ()
1849 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0 || record_safe ()) { // REQUIRES REVIEW "|| record_safe ()"
1853 /* can't rec-enable in destructive mode if transport is before start */
1855 if (destructive() && _session.transport_frame() < _session.current_start_frame()) {
1859 bool rolling = _session.transport_speed() != 0.0f;
1860 boost::shared_ptr<ChannelList> c = channels.reader();
1862 capturing_sources.clear ();
1864 if (Config->get_monitoring_model() == HardwareMonitoring) {
1866 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1867 (*chan)->source.request_input_monitoring (!(_session.config.get_auto_input() && rolling));
1868 capturing_sources.push_back ((*chan)->write_source);
1869 Source::Lock lock((*chan)->write_source->mutex());
1870 (*chan)->write_source->mark_streaming_write_started (lock);
1874 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1875 capturing_sources.push_back ((*chan)->write_source);
1876 Source::Lock lock((*chan)->write_source->mutex());
1877 (*chan)->write_source->mark_streaming_write_started (lock);
1885 AudioDiskstream::prep_record_disable ()
1887 boost::shared_ptr<ChannelList> c = channels.reader();
1888 if (Config->get_monitoring_model() == HardwareMonitoring) {
1889 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1890 (*chan)->source.request_input_monitoring (false);
1893 capturing_sources.clear ();
1899 AudioDiskstream::get_state ()
1901 XMLNode& node (Diskstream::get_state());
1903 LocaleGuard lg (X_("C"));
1905 boost::shared_ptr<ChannelList> c = channels.reader();
1906 snprintf (buf, sizeof(buf), "%u", (unsigned int) c->size());
1907 node.add_property ("channels", buf);
1909 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1911 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1912 XMLNode* cs_grandchild;
1914 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1915 cs_grandchild = new XMLNode (X_("file"));
1916 cs_grandchild->add_property (X_("path"), (*i)->path());
1917 cs_child->add_child_nocopy (*cs_grandchild);
1920 /* store the location where capture will start */
1924 if (_session.config.get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1925 snprintf (buf, sizeof (buf), "%" PRId64, pi->start());
1927 snprintf (buf, sizeof (buf), "%" PRId64, _session.transport_frame());
1930 cs_child->add_property (X_("at"), buf);
1931 node.add_child_nocopy (*cs_child);
1938 AudioDiskstream::set_state (const XMLNode& node, int version)
1940 const XMLProperty* prop;
1941 XMLNodeList nlist = node.children();
1942 XMLNodeIterator niter;
1943 uint32_t nchans = 1;
1944 XMLNode* capture_pending_node = 0;
1945 LocaleGuard lg (X_("C"));
1947 /* prevent write sources from being created */
1949 in_set_state = true;
1951 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1952 if ((*niter)->name() == IO::state_node_name) {
1953 deprecated_io_node = new XMLNode (**niter);
1956 if ((*niter)->name() == X_("CapturingSources")) {
1957 capture_pending_node = *niter;
1961 if (Diskstream::set_state (node, version)) {
1965 if ((prop = node.property ("channels")) != 0) {
1966 nchans = atoi (prop->value().c_str());
1969 // create necessary extra channels
1970 // we are always constructed with one and we always need one
1972 _n_channels.set(DataType::AUDIO, channels.reader()->size());
1974 if (nchans > _n_channels.n_audio()) {
1976 add_channel (nchans - _n_channels.n_audio());
1977 IO::PortCountChanged(_n_channels);
1979 } else if (nchans < _n_channels.n_audio()) {
1981 remove_channel (_n_channels.n_audio() - nchans);
1986 if (!destructive() && capture_pending_node) {
1987 /* destructive streams have one and only one source per channel,
1988 and so they never end up in pending capture in any useful
1991 use_pending_capture_data (*capture_pending_node);
1994 in_set_state = false;
1996 /* make sure this is clear before we do anything else */
1998 capturing_sources.clear ();
2000 /* write sources are handled when we handle the input set
2001 up of the IO that owns this DS (::non_realtime_input_change())
2008 AudioDiskstream::use_new_write_source (uint32_t n)
2010 boost::shared_ptr<ChannelList> c = channels.reader();
2012 if (!recordable()) {
2016 if (n >= c->size()) {
2017 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
2021 ChannelInfo* chan = (*c)[n];
2024 if ((chan->write_source = _session.create_audio_source_for_session (
2025 n_channels().n_audio(), write_source_name(), n, destructive())) == 0) {
2026 throw failed_constructor();
2030 catch (failed_constructor &err) {
2031 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
2032 chan->write_source.reset ();
2036 /* do not remove destructive files even if they are empty */
2038 chan->write_source->set_allow_remove_if_empty (!destructive());
2044 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool /*force*/)
2046 ChannelList::iterator chan;
2047 boost::shared_ptr<ChannelList> c = channels.reader();
2050 if (!_session.writable() || !recordable()) {
2054 capturing_sources.clear ();
2056 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
2058 if (!destructive()) {
2060 if ((*chan)->write_source) {
2062 if (mark_write_complete) {
2063 Source::Lock lock((*chan)->write_source->mutex());
2064 (*chan)->write_source->mark_streaming_write_completed (lock);
2065 (*chan)->write_source->done_with_peakfile_writes ();
2068 if ((*chan)->write_source->removable()) {
2069 (*chan)->write_source->mark_for_remove ();
2070 (*chan)->write_source->drop_references ();
2073 (*chan)->write_source.reset ();
2076 use_new_write_source (n);
2078 if (record_enabled()) {
2079 capturing_sources.push_back ((*chan)->write_source);
2084 if ((*chan)->write_source == 0) {
2085 use_new_write_source (n);
2090 if (destructive() && !c->empty ()) {
2092 /* we now have all our write sources set up, so create the
2093 playlist's single region.
2096 if (_playlist->empty()) {
2097 setup_destructive_playlist ();
2103 AudioDiskstream::set_block_size (pframes_t /*nframes*/)
2105 if (_session.get_block_size() > speed_buffer_size) {
2106 speed_buffer_size = _session.get_block_size();
2107 boost::shared_ptr<ChannelList> c = channels.reader();
2109 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2110 if ((*chan)->speed_buffer)
2111 delete [] (*chan)->speed_buffer;
2112 (*chan)->speed_buffer = new Sample[speed_buffer_size];
2115 allocate_temporary_buffers ();
2119 AudioDiskstream::allocate_temporary_buffers ()
2121 /* make sure the wrap buffer is at least large enough to deal
2122 with the speeds up to 1.2, to allow for micro-variation
2123 when slaving to MTC, Timecode etc.
2126 double const sp = max (fabsf (_actual_speed), 1.2f);
2127 framecnt_t required_wrap_size = (framecnt_t) ceil (_session.get_block_size() * sp) + 2;
2129 if (required_wrap_size > wrap_buffer_size) {
2131 boost::shared_ptr<ChannelList> c = channels.reader();
2133 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2134 if ((*chan)->playback_wrap_buffer) {
2135 delete [] (*chan)->playback_wrap_buffer;
2137 (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
2138 if ((*chan)->capture_wrap_buffer) {
2139 delete [] (*chan)->capture_wrap_buffer;
2141 (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
2144 wrap_buffer_size = required_wrap_size;
2149 AudioDiskstream::request_input_monitoring (bool yn)
2151 boost::shared_ptr<ChannelList> c = channels.reader();
2153 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2154 (*chan)->source.request_input_monitoring (yn);
2159 AudioDiskstream::set_align_style_from_io ()
2161 bool have_physical = false;
2163 if (_alignment_choice != Automatic) {
2171 get_input_sources ();
2173 boost::shared_ptr<ChannelList> c = channels.reader();
2175 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2176 if ((*chan)->source.is_physical ()) {
2177 have_physical = true;
2182 if (have_physical) {
2183 set_align_style (ExistingMaterial);
2185 set_align_style (CaptureTime);
2190 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2192 while (how_many--) {
2193 c->push_back (new ChannelInfo(
2194 _session.butler()->audio_diskstream_playback_buffer_size(),
2195 _session.butler()->audio_diskstream_capture_buffer_size(),
2196 speed_buffer_size, wrap_buffer_size));
2197 interpolation.add_channel_to (
2198 _session.butler()->audio_diskstream_playback_buffer_size(),
2202 _n_channels.set(DataType::AUDIO, c->size());
2208 AudioDiskstream::add_channel (uint32_t how_many)
2210 RCUWriter<ChannelList> writer (channels);
2211 boost::shared_ptr<ChannelList> c = writer.get_copy();
2213 return add_channel_to (c, how_many);
2217 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2219 while (how_many-- && !c->empty()) {
2222 interpolation.remove_channel_from ();
2225 _n_channels.set(DataType::AUDIO, c->size());
2231 AudioDiskstream::remove_channel (uint32_t how_many)
2233 RCUWriter<ChannelList> writer (channels);
2234 boost::shared_ptr<ChannelList> c = writer.get_copy();
2236 return remove_channel_from (c, how_many);
2240 AudioDiskstream::playback_buffer_load () const
2242 boost::shared_ptr<ChannelList> c = channels.reader();
2248 return (float) ((double) c->front()->playback_buf->read_space()/
2249 (double) c->front()->playback_buf->bufsize());
2253 AudioDiskstream::capture_buffer_load () const
2255 boost::shared_ptr<ChannelList> c = channels.reader();
2261 return (float) ((double) c->front()->capture_buf->write_space()/
2262 (double) c->front()->capture_buf->bufsize());
2266 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2268 const XMLProperty* prop;
2269 XMLNodeList nlist = node.children();
2270 XMLNodeIterator niter;
2271 boost::shared_ptr<AudioFileSource> fs;
2272 boost::shared_ptr<AudioFileSource> first_fs;
2273 SourceList pending_sources;
2274 framepos_t position;
2276 if ((prop = node.property (X_("at"))) == 0) {
2280 if (sscanf (prop->value().c_str(), "%" PRIu64, &position) != 1) {
2284 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2285 if ((*niter)->name() == X_("file")) {
2287 if ((prop = (*niter)->property (X_("path"))) == 0) {
2291 // This protects sessions from errant CapturingSources in stored sessions
2293 if (stat (prop->value().c_str(), &sbuf)) {
2297 /* XXX as of June 2014, we always record to mono
2298 files. Since this Source is being created as part of
2299 crash recovery, we know that we need the first
2300 channel (the final argument to the SourceFactory
2301 call below). If we ever support non-mono files for
2302 capture, this will need rethinking.
2306 fs = boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createForRecovery (DataType::AUDIO, _session, prop->value(), 0));
2309 catch (failed_constructor& err) {
2310 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2311 _name, prop->value())
2316 pending_sources.push_back (fs);
2318 if (first_fs == 0) {
2322 fs->set_captured_for (_name.val());
2326 if (pending_sources.size() == 0) {
2327 /* nothing can be done */
2331 if (pending_sources.size() != _n_channels.n_audio()) {
2332 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2339 boost::shared_ptr<AudioRegion> wf_region;
2340 boost::shared_ptr<AudioRegion> region;
2342 /* First create the whole file region */
2346 plist.add (Properties::start, 0);
2347 plist.add (Properties::length, first_fs->length (first_fs->timeline_position()));
2348 plist.add (Properties::name, region_name_from_path (first_fs->name(), true));
2350 wf_region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, plist));
2352 wf_region->set_automatic (true);
2353 wf_region->set_whole_file (true);
2354 wf_region->special_set_position (position);
2356 /* Now create a region that isn't the whole file for adding to
2359 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, plist));
2361 _playlist->add_region (region, position);
2364 catch (failed_constructor& err) {
2365 error << string_compose (
2366 _("%1: cannot create whole-file region from pending capture sources"),
2377 AudioDiskstream::set_non_layered (bool yn)
2379 if (yn != non_layered()) {
2382 _flags = Flag (_flags | NonLayered);
2384 _flags = Flag (_flags & ~NonLayered);
2392 AudioDiskstream::set_destructive (bool yn)
2394 if (yn != destructive()) {
2397 bool bounce_ignored;
2398 /* requestor should already have checked this and
2399 bounced if necessary and desired
2401 if (!can_become_destructive (bounce_ignored)) {
2404 _flags = Flag (_flags | Destructive);
2405 use_destructive_playlist ();
2407 _flags = Flag (_flags & ~Destructive);
2408 reset_write_sources (true, true);
2416 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2418 if (Profile->get_trx()) {
2423 requires_bounce = false;
2427 /* if no regions are present: easy */
2429 if (_playlist->n_regions() == 0) {
2430 requires_bounce = false;
2434 /* is there only one region ? */
2436 if (_playlist->n_regions() != 1) {
2437 requires_bounce = true;
2441 boost::shared_ptr<Region> first;
2443 const RegionList& rl (_playlist->region_list().rlist());
2444 assert((rl.size() == 1));
2450 requires_bounce = false;
2454 /* do the source(s) for the region cover the session start position ? */
2456 if (first->position() != _session.current_start_frame()) {
2457 // what is the idea here? why start() ??
2458 if (first->start() > _session.current_start_frame()) {
2459 requires_bounce = true;
2464 /* currently RouteTimeAxisView::set_track_mode does not
2465 * implement bounce. Existing regions cannot be converted.
2467 * so let's make sure this region is already set up
2468 * as tape-track (spanning the complete range)
2470 if (first->length() != max_framepos - first->position()) {
2471 requires_bounce = true;
2475 /* is the source used by only 1 playlist ? */
2477 boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2481 if (_session.playlists->source_use_count (afirst->source()) > 1) {
2482 requires_bounce = true;
2486 requires_bounce = false;
2491 AudioDiskstream::adjust_playback_buffering ()
2493 boost::shared_ptr<ChannelList> c = channels.reader();
2495 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2496 (*chan)->resize_playback (_session.butler()->audio_diskstream_playback_buffer_size());
2501 AudioDiskstream::adjust_capture_buffering ()
2503 boost::shared_ptr<ChannelList> c = channels.reader();
2505 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2506 (*chan)->resize_capture (_session.butler()->audio_diskstream_capture_buffer_size());
2511 AudioDiskstream::ChannelSource::is_physical () const
2517 return AudioEngine::instance()->port_is_physical (name);
2521 AudioDiskstream::ChannelSource::request_input_monitoring (bool yn) const
2527 return AudioEngine::instance()->request_input_monitoring (name, yn);
2530 AudioDiskstream::ChannelInfo::ChannelInfo (framecnt_t playback_bufsize, framecnt_t capture_bufsize, framecnt_t speed_size, framecnt_t wrap_size)
2532 current_capture_buffer = 0;
2533 current_playback_buffer = 0;
2534 curr_capture_cnt = 0;
2536 speed_buffer = new Sample[speed_size];
2537 playback_wrap_buffer = new Sample[wrap_size];
2538 capture_wrap_buffer = new Sample[wrap_size];
2540 playback_buf = new RingBufferNPT<Sample> (playback_bufsize);
2541 capture_buf = new RingBufferNPT<Sample> (capture_bufsize);
2542 capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2544 /* touch the ringbuffer buffers, which will cause
2545 them to be mapped into locked physical RAM if
2546 we're running with mlockall(). this doesn't do
2550 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2551 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2552 memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2556 AudioDiskstream::ChannelInfo::resize_playback (framecnt_t playback_bufsize)
2558 delete playback_buf;
2559 playback_buf = new RingBufferNPT<Sample> (playback_bufsize);
2560 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2564 AudioDiskstream::ChannelInfo::resize_capture (framecnt_t capture_bufsize)
2568 capture_buf = new RingBufferNPT<Sample> (capture_bufsize);
2569 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2572 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2575 if (write_source->removable()) {
2576 /* this is a "stub" write source which exists in the
2577 Session source list, but is removable. We must emit
2578 a drop references call because it should not
2579 continue to exist. If we do not do this, then the
2580 Session retains a reference to it, it is not
2581 deleted, and later attempts to create a new source
2582 file will use wierd naming because it already
2585 XXX longer term TO-DO: do not add to session source
2586 list until we write to the source.
2588 write_source->drop_references ();
2592 write_source.reset ();
2594 delete [] speed_buffer;
2597 delete [] playback_wrap_buffer;
2598 playback_wrap_buffer = 0;
2600 delete [] capture_wrap_buffer;
2601 capture_wrap_buffer = 0;
2603 delete playback_buf;
2609 delete capture_transition_buf;
2610 capture_transition_buf = 0;
2615 AudioDiskstream::set_name (string const & name)
2617 if (_name == name) {
2620 Diskstream::set_name (name);
2622 /* get a new write source so that its name reflects the new diskstream name */
2624 boost::shared_ptr<ChannelList> c = channels.reader();
2625 ChannelList::iterator i;
2628 for (n = 0, i = c->begin(); i != c->end(); ++i, ++n) {
2629 use_new_write_source (n);
2636 AudioDiskstream::set_write_source_name (const std::string& str) {
2637 if (_write_source_name == str) {
2641 Diskstream::set_write_source_name (str);
2643 if (_write_source_name == name()) {
2646 boost::shared_ptr<ChannelList> c = channels.reader();
2647 ChannelList::iterator i;
2650 for (n = 0, i = c->begin(); i != c->end(); ++i, ++n) {
2651 use_new_write_source (n);