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/region_factory.h"
50 #include "ardour/session.h"
51 #include "ardour/session_playlists.h"
52 #include "ardour/source_factory.h"
53 #include "ardour/track.h"
54 #include "ardour/types.h"
55 #include "ardour/utils.h"
61 using namespace ARDOUR;
64 size_t AudioDiskstream::_working_buffers_size = 0;
65 Sample* AudioDiskstream::_mixdown_buffer = 0;
66 gain_t* AudioDiskstream::_gain_buffer = 0;
68 AudioDiskstream::AudioDiskstream (Session &sess, const string &name, Diskstream::Flag flag)
69 : Diskstream(sess, name, flag)
70 , channels (new ChannelList)
72 /* prevent any write sources from being created */
79 AudioDiskstream::AudioDiskstream (Session& sess, const XMLNode& node)
80 : Diskstream(sess, node)
81 , channels (new ChannelList)
86 if (set_state (node, Stateful::loading_state_version)) {
88 throw failed_constructor();
94 use_destructive_playlist ();
99 AudioDiskstream::init ()
101 /* there are no channels at this point, so these
102 two calls just get speed_buffer_size and wrap_buffer
103 size setup without duplicating their code.
106 set_block_size (_session.get_block_size());
107 allocate_temporary_buffers ();
110 AudioDiskstream::~AudioDiskstream ()
112 DEBUG_TRACE (DEBUG::Destruction, string_compose ("Audio Diskstream %1 destructor\n", _name));
115 RCUWriter<ChannelList> writer (channels);
116 boost::shared_ptr<ChannelList> c = writer.get_copy();
118 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
129 AudioDiskstream::allocate_working_buffers()
131 _working_buffers_size = max (disk_write_chunk_frames, disk_read_chunk_frames);
132 _mixdown_buffer = new Sample[_working_buffers_size];
133 _gain_buffer = new gain_t[_working_buffers_size];
137 AudioDiskstream::free_working_buffers()
139 delete [] _mixdown_buffer;
140 delete [] _gain_buffer;
141 _working_buffers_size = 0;
147 AudioDiskstream::non_realtime_input_change ()
149 bool need_write_sources = false;
152 Glib::Threads::Mutex::Lock lm (state_lock);
154 if (input_change_pending.type == IOChange::NoChange) {
158 boost::shared_ptr<ChannelList> cr = channels.reader();
159 if (!cr->empty() && !cr->front()->write_source) {
160 need_write_sources = true;
163 if (input_change_pending.type == IOChange::ConfigurationChanged) {
164 RCUWriter<ChannelList> writer (channels);
165 boost::shared_ptr<ChannelList> c = writer.get_copy();
167 _n_channels.set(DataType::AUDIO, c->size());
169 if (_io->n_ports().n_audio() > _n_channels.n_audio()) {
170 add_channel_to (c, _io->n_ports().n_audio() - _n_channels.n_audio());
171 } else if (_io->n_ports().n_audio() < _n_channels.n_audio()) {
172 remove_channel_from (c, _n_channels.n_audio() - _io->n_ports().n_audio());
175 need_write_sources = true;
178 if (input_change_pending.type & IOChange::ConnectionsChanged) {
179 get_input_sources ();
180 set_capture_offset ();
181 set_align_style_from_io ();
184 input_change_pending = IOChange::NoChange;
186 /* implicit unlock */
189 if (need_write_sources) {
190 reset_write_sources (false);
193 /* now refill channel buffers */
195 if (speed() != 1.0f || speed() != -1.0f) {
196 seek ((framepos_t) (_session.transport_frame() * (double) speed()));
198 seek (_session.transport_frame());
203 AudioDiskstream::non_realtime_locate (framepos_t location)
205 /* now refill channel buffers */
207 if (speed() != 1.0f || speed() != -1.0f) {
208 seek ((framepos_t) (location * (double) speed()));
215 AudioDiskstream::get_input_sources ()
217 boost::shared_ptr<ChannelList> c = channels.reader();
220 ChannelList::iterator chan;
221 uint32_t ni = _io->n_ports().n_audio();
222 vector<string> connections;
224 for (n = 0, chan = c->begin(); chan != c->end() && n < ni; ++chan, ++n) {
226 connections.clear ();
228 if ((_io->nth (n).get()) && (_io->nth (n)->get_connections (connections) == 0)) {
229 if (!(*chan)->source.name.empty()) {
230 // _source->disable_metering ();
232 (*chan)->source.name = string();
234 (*chan)->source.name = connections[0];
240 AudioDiskstream::find_and_use_playlist (const string& name)
242 boost::shared_ptr<AudioPlaylist> playlist;
244 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (_session.playlists->by_name (name))) == 0) {
245 playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, name));
249 error << string_compose(_("AudioDiskstream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
253 return use_playlist (playlist);
257 AudioDiskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
259 assert(boost::dynamic_pointer_cast<AudioPlaylist>(playlist));
261 Diskstream::use_playlist(playlist);
267 AudioDiskstream::use_new_playlist ()
270 boost::shared_ptr<AudioPlaylist> playlist;
272 if (!in_set_state && destructive()) {
277 newname = Playlist::bump_name (_playlist->name(), _session);
279 newname = Playlist::bump_name (_name, _session);
282 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, newname, hidden()))) != 0) {
284 return use_playlist (playlist);
292 AudioDiskstream::use_copy_playlist ()
294 assert(audio_playlist());
300 if (_playlist == 0) {
301 error << string_compose(_("AudioDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
306 boost::shared_ptr<AudioPlaylist> playlist;
308 newname = Playlist::bump_name (_playlist->name(), _session);
310 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist>(PlaylistFactory::create (audio_playlist(), newname))) != 0) {
311 return use_playlist (playlist);
318 AudioDiskstream::setup_destructive_playlist ()
321 boost::shared_ptr<ChannelList> c = channels.reader();
323 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
324 srcs.push_back ((*chan)->write_source);
327 /* a single full-sized region */
329 assert (!srcs.empty ());
332 plist.add (Properties::name, _name.val());
333 plist.add (Properties::start, 0);
334 plist.add (Properties::length, max_framepos - (max_framepos - srcs.front()->natural_position()));
336 boost::shared_ptr<Region> region (RegionFactory::create (srcs, plist));
337 _playlist->add_region (region, srcs.front()->natural_position());
341 AudioDiskstream::use_destructive_playlist ()
343 /* this is called from the XML-based constructor or ::set_destructive. when called,
344 we already have a playlist and a region, but we need to
345 set up our sources for write. we use the sources associated
346 with the (presumed single, full-extent) region.
349 boost::shared_ptr<Region> rp = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
352 reset_write_sources (false, true);
356 boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
359 throw failed_constructor();
362 /* be sure to stretch the region out to the maximum length */
364 region->set_length (max_framepos - region->position());
367 ChannelList::iterator chan;
368 boost::shared_ptr<ChannelList> c = channels.reader();
370 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
371 (*chan)->write_source = boost::dynamic_pointer_cast<AudioFileSource>(region->source (n));
372 assert((*chan)->write_source);
373 (*chan)->write_source->set_allow_remove_if_empty (false);
375 /* this might be false if we switched modes, so force it */
377 (*chan)->write_source->set_destructive (true);
380 /* the source list will never be reset for a destructive track */
384 AudioDiskstream::prepare_record_status(framepos_t capture_start_frame)
386 if (recordable() && destructive()) {
387 boost::shared_ptr<ChannelList> c = channels.reader();
388 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
390 RingBufferNPT<CaptureTransition>::rw_vector transitions;
391 (*chan)->capture_transition_buf->get_write_vector (&transitions);
393 if (transitions.len[0] > 0) {
394 transitions.buf[0]->type = CaptureStart;
395 transitions.buf[0]->capture_val = capture_start_frame;
396 (*chan)->capture_transition_buf->increment_write_ptr(1);
399 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
407 /** Do some record stuff [not described in this comment!]
410 * - Setup playback_distance with the nframes, or nframes adjusted
411 * for current varispeed, if appropriate.
412 * - Setup current_playback_buffer in each ChannelInfo to point to data
413 * that someone can read playback_distance worth of data from.
416 AudioDiskstream::process (BufferSet& bufs, framepos_t transport_frame, pframes_t nframes, framecnt_t& playback_distance, bool need_disk_signal)
419 boost::shared_ptr<ChannelList> c = channels.reader();
420 ChannelList::iterator chan;
421 framecnt_t rec_offset = 0;
422 framecnt_t rec_nframes = 0;
423 bool collect_playback = false;
424 bool can_record = _session.actively_recording ();
426 playback_distance = 0;
428 if (!_io || !_io->active()) {
432 check_record_status (transport_frame, can_record);
438 Glib::Threads::Mutex::Lock sm (state_lock, Glib::Threads::TRY_LOCK);
444 adjust_capture_position = 0;
446 for (chan = c->begin(); chan != c->end(); ++chan) {
447 (*chan)->current_capture_buffer = 0;
448 (*chan)->current_playback_buffer = 0;
451 // Safeguard against situations where process() goes haywire when autopunching
452 // and last_recordable_frame < first_recordable_frame
454 if (last_recordable_frame < first_recordable_frame) {
455 last_recordable_frame = max_framepos;
458 if (record_enabled()) {
460 Evoral::OverlapType ot = Evoral::coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
461 // XXX should this be transport_frame + nframes - 1 ? coverage() expects its parameter ranges to include their end points
462 // XXX also, first_recordable_frame & last_recordable_frame may both be == max_framepos: coverage() will return OverlapNone in that case. Is thak OK?
463 calculate_record_range (ot, transport_frame, nframes, rec_nframes, rec_offset);
465 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1: this time record %2 of %3 frames, offset %4\n", _name, rec_nframes, nframes, rec_offset));
467 if (rec_nframes && !was_recording) {
468 capture_captured = 0;
469 was_recording = true;
473 if (can_record && !_last_capture_sources.empty()) {
474 _last_capture_sources.clear ();
479 uint32_t limit = _io->n_ports ().n_audio();
481 /* one or more ports could already have been removed from _io, but our
482 channel setup hasn't yet been updated. prevent us from trying to
483 use channels that correspond to missing ports. note that the
484 process callback (from which this is called) is always atomic
485 with respect to port removal/addition.
488 for (n = 0, chan = c->begin(); chan != c->end() && n < limit; ++chan, ++n) {
490 ChannelInfo* chaninfo (*chan);
492 chaninfo->capture_buf->get_write_vector (&chaninfo->capture_vector);
494 if (rec_nframes <= (framecnt_t) chaninfo->capture_vector.len[0]) {
496 chaninfo->current_capture_buffer = chaninfo->capture_vector.buf[0];
498 /* note: grab the entire port buffer, but only copy what we were supposed to
499 for recording, and use rec_offset
502 boost::shared_ptr<AudioPort> const ap = _io->audio (n);
504 assert(rec_nframes <= (framecnt_t) ap->get_audio_buffer(nframes).capacity());
506 Sample *buf = bufs.get_audio (n).data(rec_offset);
507 memcpy (chaninfo->current_capture_buffer, buf, sizeof (Sample) * rec_nframes);
511 framecnt_t total = chaninfo->capture_vector.len[0] + chaninfo->capture_vector.len[1];
513 if (rec_nframes > total) {
514 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 overrun in %2, rec_nframes = %3 total space = %4\n",
515 DEBUG_THREAD_SELF, name(), rec_nframes, total));
520 boost::shared_ptr<AudioPort> const ap = _io->audio (n);
523 Sample *buf = bufs.get_audio (n).data(rec_offset);
524 framecnt_t first = chaninfo->capture_vector.len[0];
526 memcpy (chaninfo->capture_wrap_buffer, buf, sizeof (Sample) * first);
527 memcpy (chaninfo->capture_vector.buf[0], buf, sizeof (Sample) * first);
528 memcpy (chaninfo->capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
529 memcpy (chaninfo->capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
531 chaninfo->current_capture_buffer = chaninfo->capture_wrap_buffer;
545 /* data will be written to disk */
547 if (rec_nframes == nframes && rec_offset == 0) {
549 for (chan = c->begin(); chan != c->end(); ++chan) {
550 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
553 playback_distance = nframes;
558 /* we can't use the capture buffer as the playback buffer, because
559 we recorded only a part of the current process' cycle data
563 collect_playback = true;
566 adjust_capture_position = rec_nframes;
568 } else if (can_record && record_enabled()) {
570 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
572 for (chan = c->begin(); chan != c->end(); ++chan) {
573 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
576 playback_distance = nframes;
580 collect_playback = true;
583 if ((_track->monitoring_state () & MonitoringDisk) || collect_playback) {
585 /* we're doing playback */
587 framecnt_t necessary_samples;
589 /* no varispeed playback if we're recording, because the output .... TBD */
591 if (rec_nframes == 0 && _actual_speed != 1.0f) {
592 necessary_samples = (framecnt_t) ceil ((nframes * fabs (_actual_speed))) + 2;
594 necessary_samples = nframes;
597 for (chan = c->begin(); chan != c->end(); ++chan) {
598 (*chan)->playback_buf->get_read_vector (&(*chan)->playback_vector);
603 /* Setup current_playback_buffer in each ChannelInfo to point to data that someone
604 can read necessary_samples (== nframes at a transport speed of 1) worth of data
608 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
610 ChannelInfo* chaninfo (*chan);
612 if (necessary_samples <= (framecnt_t) chaninfo->playback_vector.len[0]) {
613 /* There are enough samples in the first part of the ringbuffer */
614 chaninfo->current_playback_buffer = chaninfo->playback_vector.buf[0];
617 framecnt_t total = chaninfo->playback_vector.len[0] + chaninfo->playback_vector.len[1];
619 if (necessary_samples > total) {
620 cerr << _name << " Need " << necessary_samples << " total = " << total << endl;
621 cerr << "underrun for " << _name << endl;
622 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 underrun in %2, rec_nframes = %3 total space = %4\n",
623 DEBUG_THREAD_SELF, name(), rec_nframes, total));
629 /* We have enough samples, but not in one lump. Coalesce the two parts
630 into one in playback_wrap_buffer in our ChannelInfo, and specify that
631 as our current_playback_buffer.
634 assert(wrap_buffer_size >= necessary_samples);
636 /* Copy buf[0] from playback_buf */
637 memcpy ((char *) chaninfo->playback_wrap_buffer,
638 chaninfo->playback_vector.buf[0],
639 chaninfo->playback_vector.len[0] * sizeof (Sample));
641 /* Copy buf[1] from playback_buf */
642 memcpy (chaninfo->playback_wrap_buffer + chaninfo->playback_vector.len[0],
643 chaninfo->playback_vector.buf[1],
644 (necessary_samples - chaninfo->playback_vector.len[0])
647 chaninfo->current_playback_buffer = chaninfo->playback_wrap_buffer;
652 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
654 interpolation.set_speed (_target_speed);
657 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++channel) {
658 ChannelInfo* chaninfo (*chan);
660 playback_distance = interpolation.interpolate (
661 channel, nframes, chaninfo->current_playback_buffer, chaninfo->speed_buffer);
663 chaninfo->current_playback_buffer = chaninfo->speed_buffer;
667 playback_distance = nframes;
670 _speed = _target_speed;
673 if (need_disk_signal) {
675 /* copy data over to buffer set */
677 size_t n_buffers = bufs.count().n_audio();
678 size_t n_chans = c->size();
679 gain_t scaling = 1.0f;
681 if (n_chans > n_buffers) {
682 scaling = ((float) n_buffers)/n_chans;
685 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
687 AudioBuffer& buf (bufs.get_audio (n%n_buffers));
688 ChannelInfo* chaninfo (*chan);
691 if (scaling != 1.0f) {
692 buf.read_from_with_gain (chaninfo->current_playback_buffer, nframes, scaling);
694 buf.read_from (chaninfo->current_playback_buffer, nframes);
697 if (scaling != 1.0f) {
698 buf.accumulate_with_gain_from (chaninfo->current_playback_buffer, nframes, scaling);
700 buf.accumulate_from (chaninfo->current_playback_buffer, nframes);
705 /* leave the MIDI count alone */
706 ChanCount cnt (DataType::AUDIO, n_chans);
707 cnt.set (DataType::MIDI, bufs.count().n_midi());
708 bufs.set_count (cnt);
710 /* extra buffers will already be silent, so leave them alone */
717 AudioDiskstream::calculate_playback_distance (pframes_t nframes)
719 frameoffset_t playback_distance = nframes;
721 if (record_enabled()) {
722 playback_distance = nframes;
723 } else if (_actual_speed != 1.0f && _actual_speed != -1.0f) {
724 interpolation.set_speed (_target_speed);
725 boost::shared_ptr<ChannelList> c = channels.reader();
727 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++channel) {
728 playback_distance = interpolation.interpolate (channel, nframes, NULL, NULL);
731 playback_distance = nframes;
734 if (_actual_speed < 0.0) {
735 return -playback_distance;
737 return playback_distance;
741 /** Update various things including playback_sample, read pointer on each channel's playback_buf
742 * and write pointer on each channel's capture_buf. Also wout whether the butler is needed.
743 * @return true if the butler is required.
746 AudioDiskstream::commit (framecnt_t playback_distance)
748 bool need_butler = false;
750 if (!_io || !_io->active()) {
754 if (_actual_speed < 0.0) {
755 playback_sample -= playback_distance;
757 playback_sample += playback_distance;
760 boost::shared_ptr<ChannelList> c = channels.reader();
761 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
763 (*chan)->playback_buf->increment_read_ptr (playback_distance);
765 if (adjust_capture_position) {
766 (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
770 if (adjust_capture_position != 0) {
771 capture_captured += adjust_capture_position;
772 adjust_capture_position = 0;
780 if (_io && _io->active()) {
781 need_butler = c->front()->playback_buf->write_space() >= c->front()->playback_buf->bufsize() / 2;
786 if (_io && _io->active()) {
787 need_butler = ((framecnt_t) c->front()->playback_buf->write_space() >= disk_read_chunk_frames)
788 || ((framecnt_t) c->front()->capture_buf->read_space() >= disk_write_chunk_frames);
790 need_butler = ((framecnt_t) c->front()->capture_buf->read_space() >= disk_write_chunk_frames);
798 AudioDiskstream::set_pending_overwrite (bool yn)
800 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
802 _pending_overwrite = yn;
804 overwrite_frame = playback_sample;
806 boost::shared_ptr<ChannelList> c = channels.reader ();
808 overwrite_offset = c->front()->playback_buf->get_read_ptr();
813 AudioDiskstream::overwrite_existing_buffers ()
815 boost::shared_ptr<ChannelList> c = channels.reader();
817 _pending_overwrite = false;
821 Sample* mixdown_buffer;
824 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
826 overwrite_queued = false;
828 /* assume all are the same size */
829 framecnt_t size = c->front()->playback_buf->bufsize();
831 mixdown_buffer = new Sample[size];
832 gain_buffer = new float[size];
834 /* reduce size so that we can fill the buffer correctly (ringbuffers
835 can only handle size-1, otherwise they appear to be empty)
842 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
844 start = overwrite_frame;
845 framecnt_t cnt = size;
847 /* to fill the buffer without resetting the playback sample, we need to
848 do it one or two chunks (normally two).
850 |----------------------------------------------------------------------|
854 |<- second chunk->||<----------------- first chunk ------------------>|
858 framecnt_t to_read = size - overwrite_offset;
860 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, n, reversed)) {
861 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
862 id(), size, playback_sample) << endmsg;
870 if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer, start, cnt, n, reversed)) {
871 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
872 id(), size, playback_sample) << endmsg;
881 _pending_overwrite = false;
882 delete [] gain_buffer;
883 delete [] mixdown_buffer;
888 AudioDiskstream::seek (framepos_t frame, bool complete_refill)
892 ChannelList::iterator chan;
893 boost::shared_ptr<ChannelList> c = channels.reader();
895 Glib::Threads::Mutex::Lock lm (state_lock);
897 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
898 (*chan)->playback_buf->reset ();
899 (*chan)->capture_buf->reset ();
902 /* can't rec-enable in destructive mode if transport is before start */
904 if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
905 disengage_record_enable ();
908 playback_sample = frame;
911 if (complete_refill) {
912 while ((ret = do_refill_with_alloc ()) > 0) ;
914 ret = do_refill_with_alloc ();
921 AudioDiskstream::can_internal_playback_seek (framecnt_t distance)
923 ChannelList::iterator chan;
924 boost::shared_ptr<ChannelList> c = channels.reader();
926 for (chan = c->begin(); chan != c->end(); ++chan) {
927 if ((*chan)->playback_buf->read_space() < (size_t) distance) {
935 AudioDiskstream::internal_playback_seek (framecnt_t distance)
937 ChannelList::iterator chan;
938 boost::shared_ptr<ChannelList> c = channels.reader();
940 for (chan = c->begin(); chan != c->end(); ++chan) {
941 (*chan)->playback_buf->increment_read_ptr (llabs(distance));
944 if (first_recordable_frame < max_framepos) {
945 first_recordable_frame += distance;
947 playback_sample += distance;
952 /** Read some data for 1 channel from our playlist into a buffer.
953 * @param buf Buffer to write to.
954 * @param start Session frame to start reading from; updated to where we end up
956 * @param cnt Count of samples to read.
957 * @param reversed true if we are running backwards, otherwise false.
960 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer,
961 framepos_t& start, framecnt_t cnt,
962 int channel, bool reversed)
964 framecnt_t this_read = 0;
966 framepos_t loop_end = 0;
967 framepos_t loop_start = 0;
968 framecnt_t offset = 0;
971 /* XXX we don't currently play loops in reverse. not sure why */
975 framecnt_t loop_length = 0;
977 /* Make the use of a Location atomic for this read operation.
979 Note: Locations don't get deleted, so all we care about
980 when I say "atomic" is that we are always pointing to
981 the same one and using a start/length values obtained
985 if ((loc = loop_location) != 0) {
986 loop_start = loc->start();
987 loop_end = loc->end();
988 loop_length = loop_end - loop_start;
991 /* if we are looping, ensure that the first frame we read is at the correct
992 position within the loop.
995 if (loc && start >= loop_end) {
996 start = loop_start + ((start - loop_start) % loop_length);
1004 /* We need this while loop in case we hit a loop boundary, in which case our read from
1005 the playlist must be split into more than one section.
1010 /* take any loop into account. we can't read past the end of the loop. */
1012 if (loc && (loop_end - start < cnt)) {
1013 this_read = loop_end - start;
1020 if (this_read == 0) {
1024 this_read = min(cnt,this_read);
1026 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
1027 error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), id(), this_read,
1034 swap_by_ptr (buf, buf + this_read - 1);
1038 /* if we read to the end of the loop, go back to the beginning */
1048 offset += this_read;
1055 AudioDiskstream::do_refill_with_alloc ()
1057 Sample* mix_buf = new Sample[disk_read_chunk_frames];
1058 float* gain_buf = new float[disk_read_chunk_frames];
1060 int ret = _do_refill(mix_buf, gain_buf);
1068 /** Get some more data from disk and put it in our channels' playback_bufs,
1069 * if there is suitable space in them.
1072 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer)
1076 RingBufferNPT<Sample>::rw_vector vector;
1077 bool const reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1078 framecnt_t total_space;
1079 framecnt_t zero_fill;
1081 ChannelList::iterator i;
1082 boost::shared_ptr<ChannelList> c = channels.reader();
1089 assert(mixdown_buffer);
1090 assert(gain_buffer);
1097 c->front()->playback_buf->get_write_vector (&vector);
1099 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1100 /* nowhere to write to */
1104 /* if there are 2+ chunks of disk i/o possible for
1105 this track, let the caller know so that it can arrange
1106 for us to be called again, ASAP.
1109 if (total_space >= (_slaved ? 3 : 2) * disk_read_chunk_frames) {
1113 /* if we're running close to normal speed and there isn't enough
1114 space to do disk_read_chunk_frames of I/O, then don't bother.
1116 at higher speeds, just do it because the sync between butler
1117 and audio thread may not be good enough.
1119 Note: it is a design assumption that disk_read_chunk_frames is smaller
1120 than the playback buffer size, so this check should never trip when
1121 the playback buffer is empty.
1124 if ((total_space < disk_read_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1128 /* when slaved, don't try to get too close to the read pointer. this
1129 leaves space for the buffer reversal to have something useful to
1133 if (_slaved && total_space < (framecnt_t) (c->front()->playback_buf->bufsize() / 2)) {
1137 /* never do more than disk_read_chunk_frames worth of disk input per call (limit doesn't apply for memset) */
1139 total_space = min (disk_read_chunk_frames, total_space);
1143 if (file_frame == 0) {
1145 /* at start: nothing to do but fill with silence */
1147 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1149 ChannelInfo* chan (*i);
1150 chan->playback_buf->get_write_vector (&vector);
1151 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1152 if (vector.len[1]) {
1153 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1155 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1160 if (file_frame < total_space) {
1162 /* too close to the start: read what we can,
1163 and then zero fill the rest
1166 zero_fill = total_space - file_frame;
1167 total_space = file_frame;
1176 if (file_frame == max_framepos) {
1178 /* at end: nothing to do but fill with silence */
1180 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1182 ChannelInfo* chan (*i);
1183 chan->playback_buf->get_write_vector (&vector);
1184 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1185 if (vector.len[1]) {
1186 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1188 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1193 if (file_frame > max_framepos - total_space) {
1195 /* to close to the end: read what we can, and zero fill the rest */
1197 zero_fill = total_space - (max_framepos - file_frame);
1198 total_space = max_framepos - file_frame;
1205 framepos_t file_frame_tmp = 0;
1207 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1209 ChannelInfo* chan (*i);
1212 framecnt_t len1, len2;
1214 chan->playback_buf->get_write_vector (&vector);
1216 if ((framecnt_t) vector.len[0] > disk_read_chunk_frames) {
1218 /* we're not going to fill the first chunk, so certainly do not bother with the
1219 other part. it won't be connected with the part we do fill, as in:
1221 .... => writable space
1222 ++++ => readable space
1223 ^^^^ => 1 x disk_read_chunk_frames that would be filled
1225 |......|+++++++++++++|...............................|
1230 So, just pretend that the buf1 part isn't there.
1240 file_frame_tmp = file_frame;
1242 buf1 = vector.buf[0];
1243 len1 = vector.len[0];
1244 buf2 = vector.buf[1];
1245 len2 = vector.len[1];
1247 to_read = min (ts, len1);
1248 to_read = min (to_read, disk_read_chunk_frames);
1250 assert (to_read >= 0);
1254 if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1259 chan->playback_buf->increment_write_ptr (to_read);
1263 to_read = min (ts, len2);
1267 /* we read all of vector.len[0], but it wasn't an entire disk_read_chunk_frames of data,
1268 so read some or all of vector.len[1] as well.
1271 if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1276 chan->playback_buf->increment_write_ptr (to_read);
1280 /* XXX: do something */
1285 file_frame = file_frame_tmp;
1286 assert (file_frame >= 0);
1293 /** Flush pending data to disk.
1295 * Important note: this function will write *AT MOST* disk_write_chunk_frames
1296 * of data to disk. it will never write more than that. If it writes that
1297 * much and there is more than that waiting to be written, it will return 1,
1298 * otherwise 0 on success or -1 on failure.
1300 * If there is less than disk_write_chunk_frames to be written, no data will be
1301 * written at all unless @a force_flush is true.
1304 AudioDiskstream::do_flush (RunContext /*context*/, bool force_flush)
1308 RingBufferNPT<Sample>::rw_vector vector;
1309 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1312 transvec.buf[0] = 0;
1313 transvec.buf[1] = 0;
1317 boost::shared_ptr<ChannelList> c = channels.reader();
1318 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1320 (*chan)->capture_buf->get_read_vector (&vector);
1322 total = vector.len[0] + vector.len[1];
1324 if (total == 0 || (total < disk_write_chunk_frames && !force_flush && was_recording)) {
1328 /* if there are 2+ chunks of disk i/o possible for
1329 this track, let the caller know so that it can arrange
1330 for us to be called again, ASAP.
1332 if we are forcing a flush, then if there is* any* extra
1333 work, let the caller know.
1335 if we are no longer recording and there is any extra work,
1336 let the caller know too.
1339 if (total >= 2 * disk_write_chunk_frames || ((force_flush || !was_recording) && total > disk_write_chunk_frames)) {
1343 to_write = min (disk_write_chunk_frames, (framecnt_t) vector.len[0]);
1345 // check the transition buffer when recording destructive
1346 // important that we get this after the capture buf
1348 if (destructive()) {
1349 (*chan)->capture_transition_buf->get_read_vector(&transvec);
1350 size_t transcount = transvec.len[0] + transvec.len[1];
1353 for (ti=0; ti < transcount; ++ti) {
1354 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1356 if (captrans.type == CaptureStart) {
1357 // by definition, the first data we got above represents the given capture pos
1359 (*chan)->write_source->mark_capture_start (captrans.capture_val);
1360 (*chan)->curr_capture_cnt = 0;
1362 } else if (captrans.type == CaptureEnd) {
1364 // capture end, the capture_val represents total frames in capture
1366 if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1368 // shorten to make the write a perfect fit
1369 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
1371 if (nto_write < to_write) {
1372 ret = 1; // should we?
1374 to_write = nto_write;
1376 (*chan)->write_source->mark_capture_end ();
1378 // increment past this transition, but go no further
1383 // actually ends just beyond this chunk, so force more work
1391 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1395 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1396 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), id()) << endmsg;
1400 (*chan)->capture_buf->increment_read_ptr (to_write);
1401 (*chan)->curr_capture_cnt += to_write;
1403 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_write_chunk_frames) && !destructive()) {
1405 /* we wrote all of vector.len[0] but it wasn't an entire
1406 disk_write_chunk_frames of data, so arrange for some part
1407 of vector.len[1] to be flushed to disk as well.
1410 to_write = min ((framecnt_t)(disk_write_chunk_frames - to_write), (framecnt_t) vector.len[1]);
1412 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 additional write of %2\n", name(), to_write));
1414 if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1415 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), id()) << endmsg;
1419 (*chan)->capture_buf->increment_read_ptr (to_write);
1420 (*chan)->curr_capture_cnt += to_write;
1429 AudioDiskstream::transport_stopped_wallclock (struct tm& when, time_t twhen, bool abort_capture)
1431 uint32_t buffer_position;
1432 bool more_work = true;
1434 boost::shared_ptr<AudioRegion> region;
1435 framecnt_t total_capture;
1437 SourceList::iterator src;
1438 ChannelList::iterator chan;
1439 vector<CaptureInfo*>::iterator ci;
1440 boost::shared_ptr<ChannelList> c = channels.reader();
1442 bool mark_write_completed = false;
1446 /* butler is already stopped, but there may be work to do
1447 to flush remaining data to disk.
1450 while (more_work && !err) {
1451 switch (do_flush (TransportContext, true)) {
1458 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1463 /* XXX is there anything we can do if err != 0 ? */
1464 Glib::Threads::Mutex::Lock lm (capture_info_lock);
1466 if (capture_info.empty()) {
1470 if (abort_capture) {
1472 if (destructive()) {
1476 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1478 if ((*chan)->write_source) {
1480 (*chan)->write_source->mark_for_remove ();
1481 (*chan)->write_source->drop_references ();
1482 (*chan)->write_source.reset ();
1485 /* new source set up in "out" below */
1491 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1492 total_capture += (*ci)->frames;
1495 /* figure out the name for this take */
1497 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1499 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1503 s->update_header (capture_info.front()->start, when, twhen);
1504 s->set_captured_for (_name.val());
1505 s->mark_immutable ();
1507 if (Config->get_auto_analyse_audio()) {
1508 Analyser::queue_source_for_analysis (s, true);
1513 /* destructive tracks have a single, never changing region */
1515 if (destructive()) {
1517 /* send a signal that any UI can pick up to do the right thing. there is
1518 a small problem here in that a UI may need the peak data to be ready
1519 for the data that was recorded and this isn't interlocked with that
1520 process. this problem is deferred to the UI.
1523 _playlist->LayeringChanged(); // XXX this may not get the UI to do the right thing
1527 string whole_file_region_name;
1528 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1530 /* Register a new region with the Session that
1531 describes the entire source. Do this first
1532 so that any sub-regions will obviously be
1533 children of this one (later!)
1539 plist.add (Properties::start, c->front()->write_source->last_capture_start_frame());
1540 plist.add (Properties::length, total_capture);
1541 plist.add (Properties::name, whole_file_region_name);
1542 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1543 rx->set_automatic (true);
1544 rx->set_whole_file (true);
1546 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1547 region->special_set_position (capture_info.front()->start);
1551 catch (failed_constructor& err) {
1552 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1556 _last_capture_sources.insert (_last_capture_sources.end(), srcs.begin(), srcs.end());
1558 _playlist->clear_changes ();
1559 _playlist->set_capture_insertion_in_progress (true);
1560 _playlist->freeze ();
1562 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1566 RegionFactory::region_name (region_name, whole_file_region_name, false);
1568 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1 capture start @ %2 length %3 add new region %4\n",
1569 _name, (*ci)->start, (*ci)->frames, region_name));
1575 plist.add (Properties::start, buffer_position);
1576 plist.add (Properties::length, (*ci)->frames);
1577 plist.add (Properties::name, region_name);
1579 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1580 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1583 catch (failed_constructor& err) {
1584 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1585 continue; /* XXX is this OK? */
1588 i_am_the_modifier++;
1590 _playlist->add_region (region, (*ci)->start, 1, non_layered());
1591 _playlist->set_layer (region, DBL_MAX);
1592 i_am_the_modifier--;
1594 buffer_position += (*ci)->frames;
1598 _playlist->set_capture_insertion_in_progress (false);
1599 _session.add_command (new StatefulDiffCommand (_playlist));
1602 mark_write_completed = true;
1605 reset_write_sources (mark_write_completed);
1609 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1613 capture_info.clear ();
1614 capture_start_frame = 0;
1618 AudioDiskstream::transport_looped (framepos_t transport_frame)
1620 if (was_recording) {
1621 // all we need to do is finish this capture, with modified capture length
1622 boost::shared_ptr<ChannelList> c = channels.reader();
1624 // adjust the capture length knowing that the data will be recorded to disk
1625 // only necessary after the first loop where we're recording
1626 if (capture_info.size() == 0) {
1627 capture_captured += _capture_offset;
1629 if (_alignment_style == ExistingMaterial) {
1630 capture_captured += _session.worst_output_latency();
1632 capture_captured += _roll_delay;
1638 // the next region will start recording via the normal mechanism
1639 // we'll set the start position to the current transport pos
1640 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1641 capture_start_frame = transport_frame;
1642 first_recordable_frame = transport_frame; // mild lie
1643 last_recordable_frame = max_framepos;
1644 was_recording = true;
1646 if (recordable() && destructive()) {
1647 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1649 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1650 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1652 if (transvec.len[0] > 0) {
1653 transvec.buf[0]->type = CaptureStart;
1654 transvec.buf[0]->capture_val = capture_start_frame;
1655 (*chan)->capture_transition_buf->increment_write_ptr(1);
1659 fatal << X_("programming error: capture_transition_buf is full on rec loop! inconceivable!")
1669 AudioDiskstream::finish_capture (boost::shared_ptr<ChannelList> c)
1671 was_recording = false;
1672 first_recordable_frame = max_framepos;
1673 last_recordable_frame = max_framepos;
1675 if (capture_captured == 0) {
1679 if (recordable() && destructive()) {
1680 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1682 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1683 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1685 if (transvec.len[0] > 0) {
1686 transvec.buf[0]->type = CaptureEnd;
1687 transvec.buf[0]->capture_val = capture_captured;
1688 (*chan)->capture_transition_buf->increment_write_ptr(1);
1692 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1698 CaptureInfo* ci = new CaptureInfo;
1700 ci->start = capture_start_frame;
1701 ci->frames = capture_captured;
1703 /* XXX theoretical race condition here. Need atomic exchange ?
1704 However, the circumstances when this is called right
1705 now (either on record-disable or transport_stopped)
1706 mean that no actual race exists. I think ...
1707 We now have a capture_info_lock, but it is only to be used
1708 to synchronize in the transport_stop and the capture info
1709 accessors, so that invalidation will not occur (both non-realtime).
1712 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("Finish capture, add new CI, %1 + %2\n", ci->start, ci->frames));
1714 capture_info.push_back (ci);
1715 capture_captured = 0;
1717 /* now we've finished a capture, reset first_recordable_frame for next time */
1718 first_recordable_frame = max_framepos;
1722 AudioDiskstream::set_record_enabled (bool yn)
1724 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0) {
1728 /* can't rec-enable in destructive mode if transport is before start */
1730 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1734 /* yes, i know that this not proof against race conditions, but its
1735 good enough. i think.
1738 if (record_enabled() != yn) {
1740 engage_record_enable ();
1742 disengage_record_enable ();
1745 RecordEnableChanged (); /* EMIT SIGNAL */
1750 AudioDiskstream::prep_record_enable ()
1752 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0) {
1756 /* can't rec-enable in destructive mode if transport is before start */
1758 if (destructive() && _session.transport_frame() < _session.current_start_frame()) {
1762 bool rolling = _session.transport_speed() != 0.0f;
1763 boost::shared_ptr<ChannelList> c = channels.reader();
1765 capturing_sources.clear ();
1767 if (Config->get_monitoring_model() == HardwareMonitoring) {
1769 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1770 (*chan)->source.request_input_monitoring (!(_session.config.get_auto_input() && rolling));
1771 capturing_sources.push_back ((*chan)->write_source);
1772 Source::Lock lock((*chan)->write_source->mutex());
1773 (*chan)->write_source->mark_streaming_write_started (lock);
1777 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1778 capturing_sources.push_back ((*chan)->write_source);
1779 Source::Lock lock((*chan)->write_source->mutex());
1780 (*chan)->write_source->mark_streaming_write_started (lock);
1788 AudioDiskstream::prep_record_disable ()
1790 boost::shared_ptr<ChannelList> c = channels.reader();
1791 if (Config->get_monitoring_model() == HardwareMonitoring) {
1792 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1793 (*chan)->source.request_input_monitoring (false);
1796 capturing_sources.clear ();
1802 AudioDiskstream::get_state ()
1804 XMLNode& node (Diskstream::get_state());
1806 LocaleGuard lg (X_("C"));
1808 boost::shared_ptr<ChannelList> c = channels.reader();
1809 snprintf (buf, sizeof(buf), "%u", (unsigned int) c->size());
1810 node.add_property ("channels", buf);
1812 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1814 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1815 XMLNode* cs_grandchild;
1817 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1818 cs_grandchild = new XMLNode (X_("file"));
1819 cs_grandchild->add_property (X_("path"), (*i)->path());
1820 cs_child->add_child_nocopy (*cs_grandchild);
1823 /* store the location where capture will start */
1827 if (_session.config.get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1828 snprintf (buf, sizeof (buf), "%" PRId64, pi->start());
1830 snprintf (buf, sizeof (buf), "%" PRId64, _session.transport_frame());
1833 cs_child->add_property (X_("at"), buf);
1834 node.add_child_nocopy (*cs_child);
1841 AudioDiskstream::set_state (const XMLNode& node, int version)
1843 const XMLProperty* prop;
1844 XMLNodeList nlist = node.children();
1845 XMLNodeIterator niter;
1846 uint32_t nchans = 1;
1847 XMLNode* capture_pending_node = 0;
1848 LocaleGuard lg (X_("C"));
1850 /* prevent write sources from being created */
1852 in_set_state = true;
1854 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1855 if ((*niter)->name() == IO::state_node_name) {
1856 deprecated_io_node = new XMLNode (**niter);
1859 if ((*niter)->name() == X_("CapturingSources")) {
1860 capture_pending_node = *niter;
1864 if (Diskstream::set_state (node, version)) {
1868 if ((prop = node.property ("channels")) != 0) {
1869 nchans = atoi (prop->value().c_str());
1872 // create necessary extra channels
1873 // we are always constructed with one and we always need one
1875 _n_channels.set(DataType::AUDIO, channels.reader()->size());
1877 if (nchans > _n_channels.n_audio()) {
1879 add_channel (nchans - _n_channels.n_audio());
1880 IO::PortCountChanged(_n_channels);
1882 } else if (nchans < _n_channels.n_audio()) {
1884 remove_channel (_n_channels.n_audio() - nchans);
1889 if (!destructive() && capture_pending_node) {
1890 /* destructive streams have one and only one source per channel,
1891 and so they never end up in pending capture in any useful
1894 use_pending_capture_data (*capture_pending_node);
1897 in_set_state = false;
1899 /* make sure this is clear before we do anything else */
1901 capturing_sources.clear ();
1903 /* write sources are handled when we handle the input set
1904 up of the IO that owns this DS (::non_realtime_input_change())
1911 AudioDiskstream::use_new_write_source (uint32_t n)
1913 boost::shared_ptr<ChannelList> c = channels.reader();
1915 if (!recordable()) {
1919 if (n >= c->size()) {
1920 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
1924 ChannelInfo* chan = (*c)[n];
1927 if ((chan->write_source = _session.create_audio_source_for_session (
1928 n_channels().n_audio(), write_source_name(), n, destructive())) == 0) {
1929 throw failed_constructor();
1933 catch (failed_constructor &err) {
1934 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
1935 chan->write_source.reset ();
1939 /* do not remove destructive files even if they are empty */
1941 chan->write_source->set_allow_remove_if_empty (!destructive());
1947 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool /*force*/)
1949 ChannelList::iterator chan;
1950 boost::shared_ptr<ChannelList> c = channels.reader();
1953 if (!_session.writable() || !recordable()) {
1957 capturing_sources.clear ();
1959 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1961 if (!destructive()) {
1963 if ((*chan)->write_source) {
1965 if (mark_write_complete) {
1966 Source::Lock lock((*chan)->write_source->mutex());
1967 (*chan)->write_source->mark_streaming_write_completed (lock);
1968 (*chan)->write_source->done_with_peakfile_writes ();
1971 if ((*chan)->write_source->removable()) {
1972 (*chan)->write_source->mark_for_remove ();
1973 (*chan)->write_source->drop_references ();
1976 (*chan)->write_source.reset ();
1979 use_new_write_source (n);
1981 if (record_enabled()) {
1982 capturing_sources.push_back ((*chan)->write_source);
1987 if ((*chan)->write_source == 0) {
1988 use_new_write_source (n);
1993 if (destructive() && !c->empty ()) {
1995 /* we now have all our write sources set up, so create the
1996 playlist's single region.
1999 if (_playlist->empty()) {
2000 setup_destructive_playlist ();
2006 AudioDiskstream::set_block_size (pframes_t /*nframes*/)
2008 if (_session.get_block_size() > speed_buffer_size) {
2009 speed_buffer_size = _session.get_block_size();
2010 boost::shared_ptr<ChannelList> c = channels.reader();
2012 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2013 if ((*chan)->speed_buffer)
2014 delete [] (*chan)->speed_buffer;
2015 (*chan)->speed_buffer = new Sample[speed_buffer_size];
2018 allocate_temporary_buffers ();
2022 AudioDiskstream::allocate_temporary_buffers ()
2024 /* make sure the wrap buffer is at least large enough to deal
2025 with the speeds up to 1.2, to allow for micro-variation
2026 when slaving to MTC, Timecode etc.
2029 double const sp = max (fabsf (_actual_speed), 1.2f);
2030 framecnt_t required_wrap_size = (framecnt_t) ceil (_session.get_block_size() * sp) + 2;
2032 if (required_wrap_size > wrap_buffer_size) {
2034 boost::shared_ptr<ChannelList> c = channels.reader();
2036 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2037 if ((*chan)->playback_wrap_buffer) {
2038 delete [] (*chan)->playback_wrap_buffer;
2040 (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
2041 if ((*chan)->capture_wrap_buffer) {
2042 delete [] (*chan)->capture_wrap_buffer;
2044 (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
2047 wrap_buffer_size = required_wrap_size;
2052 AudioDiskstream::request_input_monitoring (bool yn)
2054 boost::shared_ptr<ChannelList> c = channels.reader();
2056 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2057 (*chan)->source.request_input_monitoring (yn);
2062 AudioDiskstream::set_align_style_from_io ()
2064 bool have_physical = false;
2066 if (_alignment_choice != Automatic) {
2074 get_input_sources ();
2076 boost::shared_ptr<ChannelList> c = channels.reader();
2078 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2079 if ((*chan)->source.is_physical ()) {
2080 have_physical = true;
2085 if (have_physical) {
2086 set_align_style (ExistingMaterial);
2088 set_align_style (CaptureTime);
2093 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2095 while (how_many--) {
2096 c->push_back (new ChannelInfo(
2097 _session.butler()->audio_diskstream_playback_buffer_size(),
2098 _session.butler()->audio_diskstream_capture_buffer_size(),
2099 speed_buffer_size, wrap_buffer_size));
2100 interpolation.add_channel_to (
2101 _session.butler()->audio_diskstream_playback_buffer_size(),
2105 _n_channels.set(DataType::AUDIO, c->size());
2111 AudioDiskstream::add_channel (uint32_t how_many)
2113 RCUWriter<ChannelList> writer (channels);
2114 boost::shared_ptr<ChannelList> c = writer.get_copy();
2116 return add_channel_to (c, how_many);
2120 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2122 while (how_many-- && !c->empty()) {
2125 interpolation.remove_channel_from ();
2128 _n_channels.set(DataType::AUDIO, c->size());
2134 AudioDiskstream::remove_channel (uint32_t how_many)
2136 RCUWriter<ChannelList> writer (channels);
2137 boost::shared_ptr<ChannelList> c = writer.get_copy();
2139 return remove_channel_from (c, how_many);
2143 AudioDiskstream::playback_buffer_load () const
2145 boost::shared_ptr<ChannelList> c = channels.reader();
2151 return (float) ((double) c->front()->playback_buf->read_space()/
2152 (double) c->front()->playback_buf->bufsize());
2156 AudioDiskstream::capture_buffer_load () const
2158 boost::shared_ptr<ChannelList> c = channels.reader();
2164 return (float) ((double) c->front()->capture_buf->write_space()/
2165 (double) c->front()->capture_buf->bufsize());
2169 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2171 const XMLProperty* prop;
2172 XMLNodeList nlist = node.children();
2173 XMLNodeIterator niter;
2174 boost::shared_ptr<AudioFileSource> fs;
2175 boost::shared_ptr<AudioFileSource> first_fs;
2176 SourceList pending_sources;
2177 framepos_t position;
2179 if ((prop = node.property (X_("at"))) == 0) {
2183 if (sscanf (prop->value().c_str(), "%" PRIu64, &position) != 1) {
2187 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2188 if ((*niter)->name() == X_("file")) {
2190 if ((prop = (*niter)->property (X_("path"))) == 0) {
2194 // This protects sessions from errant CapturingSources in stored sessions
2196 if (stat (prop->value().c_str(), &sbuf)) {
2200 /* XXX as of June 2014, we always record to mono
2201 files. Since this Source is being created as part of
2202 crash recovery, we know that we need the first
2203 channel (the final argument to the SourceFactory
2204 call below). If we ever support non-mono files for
2205 capture, this will need rethinking.
2209 fs = boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createForRecovery (DataType::AUDIO, _session, prop->value(), 0));
2212 catch (failed_constructor& err) {
2213 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2214 _name, prop->value())
2219 pending_sources.push_back (fs);
2221 if (first_fs == 0) {
2225 fs->set_captured_for (_name.val());
2229 if (pending_sources.size() == 0) {
2230 /* nothing can be done */
2234 if (pending_sources.size() != _n_channels.n_audio()) {
2235 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2242 boost::shared_ptr<AudioRegion> wf_region;
2243 boost::shared_ptr<AudioRegion> region;
2245 /* First create the whole file region */
2249 plist.add (Properties::start, 0);
2250 plist.add (Properties::length, first_fs->length (first_fs->timeline_position()));
2251 plist.add (Properties::name, region_name_from_path (first_fs->name(), true));
2253 wf_region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, plist));
2255 wf_region->set_automatic (true);
2256 wf_region->set_whole_file (true);
2257 wf_region->special_set_position (position);
2259 /* Now create a region that isn't the whole file for adding to
2262 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, plist));
2264 _playlist->add_region (region, position);
2267 catch (failed_constructor& err) {
2268 error << string_compose (
2269 _("%1: cannot create whole-file region from pending capture sources"),
2280 AudioDiskstream::set_non_layered (bool yn)
2282 if (yn != non_layered()) {
2285 _flags = Flag (_flags | NonLayered);
2287 _flags = Flag (_flags & ~NonLayered);
2295 AudioDiskstream::set_destructive (bool yn)
2297 if (yn != destructive()) {
2300 bool bounce_ignored;
2301 /* requestor should already have checked this and
2302 bounced if necessary and desired
2304 if (!can_become_destructive (bounce_ignored)) {
2307 _flags = Flag (_flags | Destructive);
2308 use_destructive_playlist ();
2310 _flags = Flag (_flags & ~Destructive);
2311 reset_write_sources (true, true);
2319 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2322 requires_bounce = false;
2326 /* is there only one region ? */
2328 if (_playlist->n_regions() != 1) {
2329 requires_bounce = true;
2333 boost::shared_ptr<Region> first = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
2335 requires_bounce = false;
2339 /* do the source(s) for the region cover the session start position ? */
2341 if (first->position() != _session.current_start_frame()) {
2342 if (first->start() > _session.current_start_frame()) {
2343 requires_bounce = true;
2348 /* is the source used by only 1 playlist ? */
2350 boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2354 if (_session.playlists->source_use_count (afirst->source()) > 1) {
2355 requires_bounce = true;
2359 requires_bounce = false;
2364 AudioDiskstream::adjust_playback_buffering ()
2366 boost::shared_ptr<ChannelList> c = channels.reader();
2368 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2369 (*chan)->resize_playback (_session.butler()->audio_diskstream_playback_buffer_size());
2374 AudioDiskstream::adjust_capture_buffering ()
2376 boost::shared_ptr<ChannelList> c = channels.reader();
2378 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2379 (*chan)->resize_capture (_session.butler()->audio_diskstream_capture_buffer_size());
2384 AudioDiskstream::ChannelSource::is_physical () const
2390 return AudioEngine::instance()->port_is_physical (name);
2394 AudioDiskstream::ChannelSource::request_input_monitoring (bool yn) const
2400 return AudioEngine::instance()->request_input_monitoring (name, yn);
2403 AudioDiskstream::ChannelInfo::ChannelInfo (framecnt_t playback_bufsize, framecnt_t capture_bufsize, framecnt_t speed_size, framecnt_t wrap_size)
2405 current_capture_buffer = 0;
2406 current_playback_buffer = 0;
2407 curr_capture_cnt = 0;
2409 speed_buffer = new Sample[speed_size];
2410 playback_wrap_buffer = new Sample[wrap_size];
2411 capture_wrap_buffer = new Sample[wrap_size];
2413 playback_buf = new RingBufferNPT<Sample> (playback_bufsize);
2414 capture_buf = new RingBufferNPT<Sample> (capture_bufsize);
2415 capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2417 /* touch the ringbuffer buffers, which will cause
2418 them to be mapped into locked physical RAM if
2419 we're running with mlockall(). this doesn't do
2423 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2424 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2425 memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2429 AudioDiskstream::ChannelInfo::resize_playback (framecnt_t playback_bufsize)
2431 delete playback_buf;
2432 playback_buf = new RingBufferNPT<Sample> (playback_bufsize);
2433 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2437 AudioDiskstream::ChannelInfo::resize_capture (framecnt_t capture_bufsize)
2441 capture_buf = new RingBufferNPT<Sample> (capture_bufsize);
2442 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2445 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2447 write_source.reset ();
2449 delete [] speed_buffer;
2452 delete [] playback_wrap_buffer;
2453 playback_wrap_buffer = 0;
2455 delete [] capture_wrap_buffer;
2456 capture_wrap_buffer = 0;
2458 delete playback_buf;
2464 delete capture_transition_buf;
2465 capture_transition_buf = 0;
2470 AudioDiskstream::set_name (string const & name)
2472 if (_name == name) {
2475 Diskstream::set_name (name);
2477 /* get a new write source so that its name reflects the new diskstream name */
2479 boost::shared_ptr<ChannelList> c = channels.reader();
2480 ChannelList::iterator i;
2483 for (n = 0, i = c->begin(); i != c->end(); ++i, ++n) {
2484 use_new_write_source (n);
2491 AudioDiskstream::set_write_source_name (const std::string& str) {
2492 if (_write_source_name == str) {
2496 Diskstream::set_write_source_name (str);
2498 if (_write_source_name == name()) {
2501 boost::shared_ptr<ChannelList> c = channels.reader();
2502 ChannelList::iterator i;
2505 for (n = 0, i = c->begin(); i != c->end(); ++i, ++n) {
2506 use_new_write_source (n);