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 */
78 if (flag & Destructive) {
79 use_destructive_playlist ();
83 AudioDiskstream::AudioDiskstream (Session& sess, const XMLNode& node)
84 : Diskstream(sess, node)
85 , channels (new ChannelList)
90 if (set_state (node, Stateful::loading_state_version)) {
92 throw failed_constructor();
98 use_destructive_playlist ();
103 AudioDiskstream::init ()
105 /* there are no channels at this point, so these
106 two calls just get speed_buffer_size and wrap_buffer
107 size setup without duplicating their code.
110 set_block_size (_session.get_block_size());
111 allocate_temporary_buffers ();
114 AudioDiskstream::~AudioDiskstream ()
116 DEBUG_TRACE (DEBUG::Destruction, string_compose ("Audio Diskstream %1 destructor\n", _name));
119 RCUWriter<ChannelList> writer (channels);
120 boost::shared_ptr<ChannelList> c = writer.get_copy();
122 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
133 AudioDiskstream::allocate_working_buffers()
135 _working_buffers_size = max (disk_write_chunk_frames, disk_read_chunk_frames);
136 _mixdown_buffer = new Sample[_working_buffers_size];
137 _gain_buffer = new gain_t[_working_buffers_size];
141 AudioDiskstream::free_working_buffers()
143 delete [] _mixdown_buffer;
144 delete [] _gain_buffer;
145 _working_buffers_size = 0;
151 AudioDiskstream::non_realtime_input_change ()
153 bool need_write_sources = false;
156 Glib::Threads::Mutex::Lock lm (state_lock);
158 if (input_change_pending.type == IOChange::NoChange) {
162 boost::shared_ptr<ChannelList> cr = channels.reader();
163 if (!cr->empty() && !cr->front()->write_source) {
164 need_write_sources = true;
167 if (input_change_pending.type == IOChange::ConfigurationChanged) {
168 RCUWriter<ChannelList> writer (channels);
169 boost::shared_ptr<ChannelList> c = writer.get_copy();
171 _n_channels.set(DataType::AUDIO, c->size());
173 if (_io->n_ports().n_audio() > _n_channels.n_audio()) {
174 add_channel_to (c, _io->n_ports().n_audio() - _n_channels.n_audio());
175 } else if (_io->n_ports().n_audio() < _n_channels.n_audio()) {
176 remove_channel_from (c, _n_channels.n_audio() - _io->n_ports().n_audio());
179 need_write_sources = true;
182 if (input_change_pending.type & IOChange::ConnectionsChanged) {
183 get_input_sources ();
184 set_capture_offset ();
185 set_align_style_from_io ();
188 input_change_pending = IOChange::NoChange;
190 /* implicit unlock */
193 if (need_write_sources) {
194 reset_write_sources (false);
197 /* now refill channel buffers */
199 if (speed() != 1.0f || speed() != -1.0f) {
200 seek ((framepos_t) (_session.transport_frame() * (double) speed()));
202 seek (_session.transport_frame());
207 AudioDiskstream::non_realtime_locate (framepos_t location)
209 /* now refill channel buffers */
211 if (speed() != 1.0f || speed() != -1.0f) {
212 seek ((framepos_t) (location * (double) speed()));
219 AudioDiskstream::get_input_sources ()
221 boost::shared_ptr<ChannelList> c = channels.reader();
224 ChannelList::iterator chan;
225 uint32_t ni = _io->n_ports().n_audio();
226 vector<string> connections;
228 for (n = 0, chan = c->begin(); chan != c->end() && n < ni; ++chan, ++n) {
230 connections.clear ();
232 if ((_io->nth (n).get()) && (_io->nth (n)->get_connections (connections) == 0)) {
233 if (!(*chan)->source.name.empty()) {
234 // _source->disable_metering ();
236 (*chan)->source.name = string();
238 (*chan)->source.name = connections[0];
244 AudioDiskstream::find_and_use_playlist (const string& name)
246 boost::shared_ptr<AudioPlaylist> playlist;
248 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (_session.playlists->by_name (name))) == 0) {
249 playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, name));
253 error << string_compose(_("AudioDiskstream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
257 return use_playlist (playlist);
261 AudioDiskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
263 assert(boost::dynamic_pointer_cast<AudioPlaylist>(playlist));
265 Diskstream::use_playlist(playlist);
271 AudioDiskstream::use_new_playlist ()
274 boost::shared_ptr<AudioPlaylist> playlist;
276 if (!in_set_state && destructive()) {
281 newname = Playlist::bump_name (_playlist->name(), _session);
283 newname = Playlist::bump_name (_name, _session);
286 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, newname, hidden()))) != 0) {
288 return use_playlist (playlist);
296 AudioDiskstream::use_copy_playlist ()
298 assert(audio_playlist());
304 if (_playlist == 0) {
305 error << string_compose(_("AudioDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
310 boost::shared_ptr<AudioPlaylist> playlist;
312 newname = Playlist::bump_name (_playlist->name(), _session);
314 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist>(PlaylistFactory::create (audio_playlist(), newname))) != 0) {
315 return use_playlist (playlist);
322 AudioDiskstream::setup_destructive_playlist ()
325 boost::shared_ptr<ChannelList> c = channels.reader();
327 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
328 srcs.push_back ((*chan)->write_source);
331 /* a single full-sized region */
333 assert (!srcs.empty ());
336 plist.add (Properties::name, _name.val());
337 plist.add (Properties::start, 0);
338 plist.add (Properties::length, max_framepos - srcs.front()->natural_position());
340 boost::shared_ptr<Region> region (RegionFactory::create (srcs, plist));
341 _playlist->add_region (region, srcs.front()->natural_position());
343 /* apply region properties and update write sources */
344 use_destructive_playlist();
348 AudioDiskstream::use_destructive_playlist ()
350 /* this is called from the XML-based constructor or ::set_destructive. when called,
351 we already have a playlist and a region, but we need to
352 set up our sources for write. we use the sources associated
353 with the (presumed single, full-extent) region.
356 boost::shared_ptr<Region> rp;
358 const RegionList& rl (_playlist->region_list().rlist());
360 assert((rl.size() == 1));
366 reset_write_sources (false, true);
370 boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
373 throw failed_constructor();
376 /* be sure to stretch the region out to the maximum length */
378 region->set_length (max_framepos - region->position());
381 ChannelList::iterator chan;
382 boost::shared_ptr<ChannelList> c = channels.reader();
384 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
385 (*chan)->write_source = boost::dynamic_pointer_cast<AudioFileSource>(region->source (n));
386 assert((*chan)->write_source);
387 (*chan)->write_source->set_allow_remove_if_empty (false);
389 /* this might be false if we switched modes, so force it */
391 (*chan)->write_source->set_destructive (true);
394 /* the source list will never be reset for a destructive track */
398 AudioDiskstream::prepare_record_status(framepos_t capture_start_frame)
400 if (recordable() && destructive()) {
401 boost::shared_ptr<ChannelList> c = channels.reader();
402 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
404 RingBufferNPT<CaptureTransition>::rw_vector transitions;
405 (*chan)->capture_transition_buf->get_write_vector (&transitions);
407 if (transitions.len[0] > 0) {
408 transitions.buf[0]->type = CaptureStart;
409 transitions.buf[0]->capture_val = capture_start_frame;
410 (*chan)->capture_transition_buf->increment_write_ptr(1);
413 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
421 /** Do some record stuff [not described in this comment!]
424 * - Setup playback_distance with the nframes, or nframes adjusted
425 * for current varispeed, if appropriate.
426 * - Setup current_playback_buffer in each ChannelInfo to point to data
427 * that someone can read playback_distance worth of data from.
430 AudioDiskstream::process (BufferSet& bufs, framepos_t transport_frame, pframes_t nframes, framecnt_t& playback_distance, bool need_disk_signal)
433 boost::shared_ptr<ChannelList> c = channels.reader();
434 ChannelList::iterator chan;
435 framecnt_t rec_offset = 0;
436 framecnt_t rec_nframes = 0;
437 bool collect_playback = false;
438 bool can_record = _session.actively_recording ();
440 playback_distance = 0;
442 if (!_io || !_io->active()) {
446 check_record_status (transport_frame, can_record);
452 Glib::Threads::Mutex::Lock sm (state_lock, Glib::Threads::TRY_LOCK);
458 adjust_capture_position = 0;
460 for (chan = c->begin(); chan != c->end(); ++chan) {
461 (*chan)->current_capture_buffer = 0;
462 (*chan)->current_playback_buffer = 0;
465 // Safeguard against situations where process() goes haywire when autopunching
466 // and last_recordable_frame < first_recordable_frame
468 if (last_recordable_frame < first_recordable_frame) {
469 last_recordable_frame = max_framepos;
472 if (record_enabled()) {
474 Evoral::OverlapType ot = Evoral::coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
475 // XXX should this be transport_frame + nframes - 1 ? coverage() expects its parameter ranges to include their end points
476 // XXX also, first_recordable_frame & last_recordable_frame may both be == max_framepos: coverage() will return OverlapNone in that case. Is thak OK?
477 calculate_record_range (ot, transport_frame, nframes, rec_nframes, rec_offset);
479 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1: this time record %2 of %3 frames, offset %4\n", _name, rec_nframes, nframes, rec_offset));
481 if (rec_nframes && !was_recording) {
482 capture_captured = 0;
483 was_recording = true;
487 if (can_record && !_last_capture_sources.empty()) {
488 _last_capture_sources.clear ();
493 uint32_t limit = _io->n_ports ().n_audio();
495 /* one or more ports could already have been removed from _io, but our
496 channel setup hasn't yet been updated. prevent us from trying to
497 use channels that correspond to missing ports. note that the
498 process callback (from which this is called) is always atomic
499 with respect to port removal/addition.
502 for (n = 0, chan = c->begin(); chan != c->end() && n < limit; ++chan, ++n) {
504 ChannelInfo* chaninfo (*chan);
506 chaninfo->capture_buf->get_write_vector (&chaninfo->capture_vector);
508 if (rec_nframes <= (framecnt_t) chaninfo->capture_vector.len[0]) {
510 chaninfo->current_capture_buffer = chaninfo->capture_vector.buf[0];
512 /* note: grab the entire port buffer, but only copy what we were supposed to
513 for recording, and use rec_offset
516 boost::shared_ptr<AudioPort> const ap = _io->audio (n);
518 assert(rec_nframes <= (framecnt_t) ap->get_audio_buffer(nframes).capacity());
520 Sample *buf = bufs.get_audio (n).data(rec_offset);
521 memcpy (chaninfo->current_capture_buffer, buf, sizeof (Sample) * rec_nframes);
525 framecnt_t total = chaninfo->capture_vector.len[0] + chaninfo->capture_vector.len[1];
527 if (rec_nframes > total) {
528 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 overrun in %2, rec_nframes = %3 total space = %4\n",
529 DEBUG_THREAD_SELF, name(), rec_nframes, total));
534 boost::shared_ptr<AudioPort> const ap = _io->audio (n);
537 Sample *buf = bufs.get_audio (n).data(rec_offset);
538 framecnt_t first = chaninfo->capture_vector.len[0];
540 memcpy (chaninfo->capture_wrap_buffer, buf, sizeof (Sample) * first);
541 memcpy (chaninfo->capture_vector.buf[0], buf, sizeof (Sample) * first);
542 memcpy (chaninfo->capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
543 memcpy (chaninfo->capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
545 chaninfo->current_capture_buffer = chaninfo->capture_wrap_buffer;
559 /* data will be written to disk */
561 if (rec_nframes == nframes && rec_offset == 0) {
563 for (chan = c->begin(); chan != c->end(); ++chan) {
564 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
567 playback_distance = nframes;
572 /* we can't use the capture buffer as the playback buffer, because
573 we recorded only a part of the current process' cycle data
577 collect_playback = true;
580 adjust_capture_position = rec_nframes;
582 } else if (can_record && record_enabled()) {
584 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
586 for (chan = c->begin(); chan != c->end(); ++chan) {
587 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
590 playback_distance = nframes;
594 collect_playback = true;
597 if ((_track->monitoring_state () & MonitoringDisk) || collect_playback) {
599 /* we're doing playback */
601 framecnt_t necessary_samples;
603 /* no varispeed playback if we're recording, because the output .... TBD */
605 if (rec_nframes == 0 && _actual_speed != 1.0f) {
606 necessary_samples = (framecnt_t) ceil ((nframes * fabs (_actual_speed))) + 2;
608 necessary_samples = nframes;
611 for (chan = c->begin(); chan != c->end(); ++chan) {
612 (*chan)->playback_buf->get_read_vector (&(*chan)->playback_vector);
617 /* Setup current_playback_buffer in each ChannelInfo to point to data that someone
618 can read necessary_samples (== nframes at a transport speed of 1) worth of data
622 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
624 ChannelInfo* chaninfo (*chan);
626 if (necessary_samples <= (framecnt_t) chaninfo->playback_vector.len[0]) {
627 /* There are enough samples in the first part of the ringbuffer */
628 chaninfo->current_playback_buffer = chaninfo->playback_vector.buf[0];
631 framecnt_t total = chaninfo->playback_vector.len[0] + chaninfo->playback_vector.len[1];
633 if (necessary_samples > total) {
634 cerr << _name << " Need " << necessary_samples << " total = " << total << endl;
635 cerr << "underrun for " << _name << endl;
636 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 underrun in %2, rec_nframes = %3 total space = %4\n",
637 DEBUG_THREAD_SELF, name(), rec_nframes, total));
643 /* We have enough samples, but not in one lump. Coalesce the two parts
644 into one in playback_wrap_buffer in our ChannelInfo, and specify that
645 as our current_playback_buffer.
648 assert(wrap_buffer_size >= necessary_samples);
650 /* Copy buf[0] from playback_buf */
651 memcpy ((char *) chaninfo->playback_wrap_buffer,
652 chaninfo->playback_vector.buf[0],
653 chaninfo->playback_vector.len[0] * sizeof (Sample));
655 /* Copy buf[1] from playback_buf */
656 memcpy (chaninfo->playback_wrap_buffer + chaninfo->playback_vector.len[0],
657 chaninfo->playback_vector.buf[1],
658 (necessary_samples - chaninfo->playback_vector.len[0])
661 chaninfo->current_playback_buffer = chaninfo->playback_wrap_buffer;
666 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
668 interpolation.set_speed (_target_speed);
671 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++channel) {
672 ChannelInfo* chaninfo (*chan);
674 playback_distance = interpolation.interpolate (
675 channel, nframes, chaninfo->current_playback_buffer, chaninfo->speed_buffer);
677 chaninfo->current_playback_buffer = chaninfo->speed_buffer;
681 playback_distance = nframes;
684 _speed = _target_speed;
687 if (need_disk_signal) {
689 /* copy data over to buffer set */
691 size_t n_buffers = bufs.count().n_audio();
692 size_t n_chans = c->size();
693 gain_t scaling = 1.0f;
695 if (n_chans > n_buffers) {
696 scaling = ((float) n_buffers)/n_chans;
699 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
701 AudioBuffer& buf (bufs.get_audio (n%n_buffers));
702 ChannelInfo* chaninfo (*chan);
705 if (scaling != 1.0f) {
706 buf.read_from_with_gain (chaninfo->current_playback_buffer, nframes, scaling);
708 buf.read_from (chaninfo->current_playback_buffer, nframes);
711 if (scaling != 1.0f) {
712 buf.accumulate_with_gain_from (chaninfo->current_playback_buffer, nframes, scaling);
714 buf.accumulate_from (chaninfo->current_playback_buffer, nframes);
719 /* leave the MIDI count alone */
720 ChanCount cnt (DataType::AUDIO, n_chans);
721 cnt.set (DataType::MIDI, bufs.count().n_midi());
722 bufs.set_count (cnt);
724 /* extra buffers will already be silent, so leave them alone */
731 AudioDiskstream::calculate_playback_distance (pframes_t nframes)
733 frameoffset_t playback_distance = nframes;
735 if (record_enabled()) {
736 playback_distance = nframes;
737 } else if (_actual_speed != 1.0f && _actual_speed != -1.0f) {
738 interpolation.set_speed (_target_speed);
739 boost::shared_ptr<ChannelList> c = channels.reader();
741 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++channel) {
742 playback_distance = interpolation.interpolate (channel, nframes, NULL, NULL);
745 playback_distance = nframes;
748 if (_actual_speed < 0.0) {
749 return -playback_distance;
751 return playback_distance;
755 /** Update various things including playback_sample, read pointer on each channel's playback_buf
756 * and write pointer on each channel's capture_buf. Also wout whether the butler is needed.
757 * @return true if the butler is required.
760 AudioDiskstream::commit (framecnt_t playback_distance)
762 bool need_butler = false;
764 if (!_io || !_io->active()) {
768 if (_actual_speed < 0.0) {
769 playback_sample -= playback_distance;
771 playback_sample += playback_distance;
774 boost::shared_ptr<ChannelList> c = channels.reader();
775 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
777 (*chan)->playback_buf->increment_read_ptr (playback_distance);
779 if (adjust_capture_position) {
780 (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
784 if (adjust_capture_position != 0) {
785 capture_captured += adjust_capture_position;
786 adjust_capture_position = 0;
794 if (_io && _io->active()) {
795 need_butler = c->front()->playback_buf->write_space() >= c->front()->playback_buf->bufsize() / 2;
800 if (_io && _io->active()) {
801 need_butler = ((framecnt_t) c->front()->playback_buf->write_space() >= disk_read_chunk_frames)
802 || ((framecnt_t) c->front()->capture_buf->read_space() >= disk_write_chunk_frames);
804 need_butler = ((framecnt_t) c->front()->capture_buf->read_space() >= disk_write_chunk_frames);
812 AudioDiskstream::set_pending_overwrite (bool yn)
814 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
816 _pending_overwrite = yn;
818 overwrite_frame = playback_sample;
820 boost::shared_ptr<ChannelList> c = channels.reader ();
822 overwrite_offset = c->front()->playback_buf->get_read_ptr();
827 AudioDiskstream::overwrite_existing_buffers ()
829 boost::shared_ptr<ChannelList> c = channels.reader();
831 _pending_overwrite = false;
835 Sample* mixdown_buffer;
838 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
840 overwrite_queued = false;
842 /* assume all are the same size */
843 framecnt_t size = c->front()->playback_buf->bufsize();
845 mixdown_buffer = new Sample[size];
846 gain_buffer = new float[size];
848 /* reduce size so that we can fill the buffer correctly (ringbuffers
849 can only handle size-1, otherwise they appear to be empty)
856 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
858 start = overwrite_frame;
859 framecnt_t cnt = size;
861 /* to fill the buffer without resetting the playback sample, we need to
862 do it one or two chunks (normally two).
864 |----------------------------------------------------------------------|
868 |<- second chunk->||<----------------- first chunk ------------------>|
872 framecnt_t to_read = size - overwrite_offset;
874 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, n, reversed)) {
875 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
876 id(), size, playback_sample) << endmsg;
884 if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer, start, cnt, n, reversed)) {
885 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
886 id(), size, playback_sample) << endmsg;
895 _pending_overwrite = false;
896 delete [] gain_buffer;
897 delete [] mixdown_buffer;
902 AudioDiskstream::seek (framepos_t frame, bool complete_refill)
906 ChannelList::iterator chan;
907 boost::shared_ptr<ChannelList> c = channels.reader();
909 Glib::Threads::Mutex::Lock lm (state_lock);
911 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
912 (*chan)->playback_buf->reset ();
913 (*chan)->capture_buf->reset ();
916 /* can't rec-enable in destructive mode if transport is before start */
918 if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
919 disengage_record_enable ();
922 playback_sample = frame;
925 if (complete_refill) {
926 while ((ret = do_refill_with_alloc ()) > 0) ;
928 ret = do_refill_with_alloc ();
935 AudioDiskstream::can_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 if ((*chan)->playback_buf->read_space() < (size_t) distance) {
949 AudioDiskstream::internal_playback_seek (framecnt_t distance)
951 ChannelList::iterator chan;
952 boost::shared_ptr<ChannelList> c = channels.reader();
954 for (chan = c->begin(); chan != c->end(); ++chan) {
955 (*chan)->playback_buf->increment_read_ptr (llabs(distance));
958 if (first_recordable_frame < max_framepos) {
959 first_recordable_frame += distance;
961 playback_sample += distance;
966 /** Read some data for 1 channel from our playlist into a buffer.
967 * @param buf Buffer to write to.
968 * @param start Session frame to start reading from; updated to where we end up
970 * @param cnt Count of samples to read.
971 * @param reversed true if we are running backwards, otherwise false.
974 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer,
975 framepos_t& start, framecnt_t cnt,
976 int channel, bool reversed)
978 framecnt_t this_read = 0;
980 framepos_t loop_end = 0;
981 framepos_t loop_start = 0;
982 framecnt_t offset = 0;
985 /* XXX we don't currently play loops in reverse. not sure why */
989 framecnt_t loop_length = 0;
991 /* Make the use of a Location atomic for this read operation.
993 Note: Locations don't get deleted, so all we care about
994 when I say "atomic" is that we are always pointing to
995 the same one and using a start/length values obtained
999 if ((loc = loop_location) != 0) {
1000 loop_start = loc->start();
1001 loop_end = loc->end();
1002 loop_length = loop_end - loop_start;
1005 /* if we are looping, ensure that the first frame we read is at the correct
1006 position within the loop.
1009 if (loc && start >= loop_end) {
1010 start = loop_start + ((start - loop_start) % loop_length);
1019 /* We need this while loop in case we hit a loop boundary, in which case our read from
1020 the playlist must be split into more than one section.
1025 /* take any loop into account. we can't read past the end of the loop. */
1027 if (loc && (loop_end - start < cnt)) {
1028 this_read = loop_end - start;
1035 if (this_read == 0) {
1039 this_read = min(cnt,this_read);
1041 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
1042 error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), id(), this_read,
1049 swap_by_ptr (buf, buf + this_read - 1);
1053 /* if we read to the end of the loop, go back to the beginning */
1063 offset += this_read;
1070 AudioDiskstream::do_refill_with_alloc ()
1072 Sample* mix_buf = new Sample[disk_read_chunk_frames];
1073 float* gain_buf = new float[disk_read_chunk_frames];
1075 int ret = _do_refill(mix_buf, gain_buf);
1083 /** Get some more data from disk and put it in our channels' playback_bufs,
1084 * if there is suitable space in them.
1087 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer)
1091 RingBufferNPT<Sample>::rw_vector vector;
1092 bool const reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1093 framecnt_t total_space;
1094 framecnt_t zero_fill;
1096 ChannelList::iterator i;
1097 boost::shared_ptr<ChannelList> c = channels.reader();
1104 assert(mixdown_buffer);
1105 assert(gain_buffer);
1112 c->front()->playback_buf->get_write_vector (&vector);
1114 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1115 /* nowhere to write to */
1119 /* if there are 2+ chunks of disk i/o possible for
1120 this track, let the caller know so that it can arrange
1121 for us to be called again, ASAP.
1124 if (total_space >= (_slaved ? 3 : 2) * disk_read_chunk_frames) {
1128 /* if we're running close to normal speed and there isn't enough
1129 space to do disk_read_chunk_frames of I/O, then don't bother.
1131 at higher speeds, just do it because the sync between butler
1132 and audio thread may not be good enough.
1134 Note: it is a design assumption that disk_read_chunk_frames is smaller
1135 than the playback buffer size, so this check should never trip when
1136 the playback buffer is empty.
1139 if ((total_space < disk_read_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1143 /* when slaved, don't try to get too close to the read pointer. this
1144 leaves space for the buffer reversal to have something useful to
1148 if (_slaved && total_space < (framecnt_t) (c->front()->playback_buf->bufsize() / 2)) {
1152 /* never do more than disk_read_chunk_frames worth of disk input per call (limit doesn't apply for memset) */
1154 total_space = min (disk_read_chunk_frames, total_space);
1158 if (file_frame == 0) {
1160 /* at start: nothing to do but fill with silence */
1162 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1164 ChannelInfo* chan (*i);
1165 chan->playback_buf->get_write_vector (&vector);
1166 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1167 if (vector.len[1]) {
1168 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1170 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1175 if (file_frame < total_space) {
1177 /* too close to the start: read what we can,
1178 and then zero fill the rest
1181 zero_fill = total_space - file_frame;
1182 total_space = file_frame;
1191 if (file_frame == max_framepos) {
1193 /* at end: nothing to do but fill with silence */
1195 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1197 ChannelInfo* chan (*i);
1198 chan->playback_buf->get_write_vector (&vector);
1199 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1200 if (vector.len[1]) {
1201 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1203 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1208 if (file_frame > max_framepos - total_space) {
1210 /* to close to the end: read what we can, and zero fill the rest */
1212 zero_fill = total_space - (max_framepos - file_frame);
1213 total_space = max_framepos - file_frame;
1220 framepos_t file_frame_tmp = 0;
1222 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1224 ChannelInfo* chan (*i);
1227 framecnt_t len1, len2;
1229 chan->playback_buf->get_write_vector (&vector);
1231 if ((framecnt_t) vector.len[0] > disk_read_chunk_frames) {
1233 /* we're not going to fill the first chunk, so certainly do not bother with the
1234 other part. it won't be connected with the part we do fill, as in:
1236 .... => writable space
1237 ++++ => readable space
1238 ^^^^ => 1 x disk_read_chunk_frames that would be filled
1240 |......|+++++++++++++|...............................|
1245 So, just pretend that the buf1 part isn't there.
1255 file_frame_tmp = file_frame;
1257 buf1 = vector.buf[0];
1258 len1 = vector.len[0];
1259 buf2 = vector.buf[1];
1260 len2 = vector.len[1];
1262 to_read = min (ts, len1);
1263 to_read = min (to_read, disk_read_chunk_frames);
1265 assert (to_read >= 0);
1269 if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1274 chan->playback_buf->increment_write_ptr (to_read);
1278 to_read = min (ts, len2);
1282 /* we read all of vector.len[0], but it wasn't an entire disk_read_chunk_frames of data,
1283 so read some or all of vector.len[1] as well.
1286 if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1291 chan->playback_buf->increment_write_ptr (to_read);
1295 /* XXX: do something */
1300 file_frame = file_frame_tmp;
1301 assert (file_frame >= 0);
1308 /** Flush pending data to disk.
1310 * Important note: this function will write *AT MOST* disk_write_chunk_frames
1311 * of data to disk. it will never write more than that. If it writes that
1312 * much and there is more than that waiting to be written, it will return 1,
1313 * otherwise 0 on success or -1 on failure.
1315 * If there is less than disk_write_chunk_frames to be written, no data will be
1316 * written at all unless @a force_flush is true.
1319 AudioDiskstream::do_flush (RunContext /*context*/, bool force_flush)
1323 RingBufferNPT<Sample>::rw_vector vector;
1324 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1327 transvec.buf[0] = 0;
1328 transvec.buf[1] = 0;
1332 boost::shared_ptr<ChannelList> c = channels.reader();
1333 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1335 (*chan)->capture_buf->get_read_vector (&vector);
1337 total = vector.len[0] + vector.len[1];
1339 if (total == 0 || (total < disk_write_chunk_frames && !force_flush && was_recording)) {
1343 /* if there are 2+ chunks of disk i/o possible for
1344 this track, let the caller know so that it can arrange
1345 for us to be called again, ASAP.
1347 if we are forcing a flush, then if there is* any* extra
1348 work, let the caller know.
1350 if we are no longer recording and there is any extra work,
1351 let the caller know too.
1354 if (total >= 2 * disk_write_chunk_frames || ((force_flush || !was_recording) && total > disk_write_chunk_frames)) {
1358 to_write = min (disk_write_chunk_frames, (framecnt_t) vector.len[0]);
1360 // check the transition buffer when recording destructive
1361 // important that we get this after the capture buf
1363 if (destructive()) {
1364 (*chan)->capture_transition_buf->get_read_vector(&transvec);
1365 size_t transcount = transvec.len[0] + transvec.len[1];
1368 for (ti=0; ti < transcount; ++ti) {
1369 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1371 if (captrans.type == CaptureStart) {
1372 // by definition, the first data we got above represents the given capture pos
1374 (*chan)->write_source->mark_capture_start (captrans.capture_val);
1375 (*chan)->curr_capture_cnt = 0;
1377 } else if (captrans.type == CaptureEnd) {
1379 // capture end, the capture_val represents total frames in capture
1381 if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1383 // shorten to make the write a perfect fit
1384 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
1386 if (nto_write < to_write) {
1387 ret = 1; // should we?
1389 to_write = nto_write;
1391 (*chan)->write_source->mark_capture_end ();
1393 // increment past this transition, but go no further
1398 // actually ends just beyond this chunk, so force more work
1406 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1410 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1411 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), id()) << endmsg;
1415 (*chan)->capture_buf->increment_read_ptr (to_write);
1416 (*chan)->curr_capture_cnt += to_write;
1418 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_write_chunk_frames) && !destructive()) {
1420 /* we wrote all of vector.len[0] but it wasn't an entire
1421 disk_write_chunk_frames of data, so arrange for some part
1422 of vector.len[1] to be flushed to disk as well.
1425 to_write = min ((framecnt_t)(disk_write_chunk_frames - to_write), (framecnt_t) vector.len[1]);
1427 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 additional write of %2\n", name(), to_write));
1429 if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1430 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), id()) << endmsg;
1434 (*chan)->capture_buf->increment_read_ptr (to_write);
1435 (*chan)->curr_capture_cnt += to_write;
1444 AudioDiskstream::transport_stopped_wallclock (struct tm& when, time_t twhen, bool abort_capture)
1446 uint32_t buffer_position;
1447 bool more_work = true;
1449 boost::shared_ptr<AudioRegion> region;
1450 framecnt_t total_capture;
1452 SourceList::iterator src;
1453 ChannelList::iterator chan;
1454 vector<CaptureInfo*>::iterator ci;
1455 boost::shared_ptr<ChannelList> c = channels.reader();
1457 bool mark_write_completed = false;
1461 /* butler is already stopped, but there may be work to do
1462 to flush remaining data to disk.
1465 while (more_work && !err) {
1466 switch (do_flush (TransportContext, true)) {
1473 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1478 /* XXX is there anything we can do if err != 0 ? */
1479 Glib::Threads::Mutex::Lock lm (capture_info_lock);
1481 if (capture_info.empty()) {
1485 if (abort_capture) {
1487 if (destructive()) {
1491 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1493 if ((*chan)->write_source) {
1495 (*chan)->write_source->mark_for_remove ();
1496 (*chan)->write_source->drop_references ();
1497 (*chan)->write_source.reset ();
1500 /* new source set up in "out" below */
1506 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1507 total_capture += (*ci)->frames;
1510 /* figure out the name for this take */
1512 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1514 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1518 s->update_header (capture_info.front()->start, when, twhen);
1519 s->set_captured_for (_name.val());
1520 s->mark_immutable ();
1522 if (Config->get_auto_analyse_audio()) {
1523 Analyser::queue_source_for_analysis (s, true);
1528 /* destructive tracks have a single, never changing region */
1530 if (destructive()) {
1532 /* send a signal that any UI can pick up to do the right thing. there is
1533 a small problem here in that a UI may need the peak data to be ready
1534 for the data that was recorded and this isn't interlocked with that
1535 process. this problem is deferred to the UI.
1538 _playlist->LayeringChanged(); // XXX this may not get the UI to do the right thing
1542 string whole_file_region_name;
1543 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1545 /* Register a new region with the Session that
1546 describes the entire source. Do this first
1547 so that any sub-regions will obviously be
1548 children of this one (later!)
1554 plist.add (Properties::start, c->front()->write_source->last_capture_start_frame());
1555 plist.add (Properties::length, total_capture);
1556 plist.add (Properties::name, whole_file_region_name);
1557 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1558 rx->set_automatic (true);
1559 rx->set_whole_file (true);
1561 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1562 region->special_set_position (capture_info.front()->start);
1566 catch (failed_constructor& err) {
1567 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1571 _last_capture_sources.insert (_last_capture_sources.end(), srcs.begin(), srcs.end());
1573 _playlist->clear_changes ();
1574 _playlist->set_capture_insertion_in_progress (true);
1575 _playlist->freeze ();
1577 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1581 RegionFactory::region_name (region_name, whole_file_region_name, false);
1583 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1 capture start @ %2 length %3 add new region %4\n",
1584 _name, (*ci)->start, (*ci)->frames, region_name));
1590 plist.add (Properties::start, buffer_position);
1591 plist.add (Properties::length, (*ci)->frames);
1592 plist.add (Properties::name, region_name);
1594 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1595 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1598 catch (failed_constructor& err) {
1599 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1600 continue; /* XXX is this OK? */
1603 i_am_the_modifier++;
1605 _playlist->add_region (region, (*ci)->start, 1, non_layered());
1606 _playlist->set_layer (region, DBL_MAX);
1607 i_am_the_modifier--;
1609 buffer_position += (*ci)->frames;
1613 _playlist->set_capture_insertion_in_progress (false);
1614 _session.add_command (new StatefulDiffCommand (_playlist));
1617 mark_write_completed = true;
1620 reset_write_sources (mark_write_completed);
1624 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1628 capture_info.clear ();
1629 capture_start_frame = 0;
1633 AudioDiskstream::transport_looped (framepos_t transport_frame)
1635 if (was_recording) {
1636 // all we need to do is finish this capture, with modified capture length
1637 boost::shared_ptr<ChannelList> c = channels.reader();
1639 // adjust the capture length knowing that the data will be recorded to disk
1640 // only necessary after the first loop where we're recording
1641 if (capture_info.size() == 0) {
1642 capture_captured += _capture_offset;
1644 if (_alignment_style == ExistingMaterial) {
1645 capture_captured += _session.worst_output_latency();
1647 capture_captured += _roll_delay;
1653 // the next region will start recording via the normal mechanism
1654 // we'll set the start position to the current transport pos
1655 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1656 capture_start_frame = transport_frame;
1657 first_recordable_frame = transport_frame; // mild lie
1658 last_recordable_frame = max_framepos;
1659 was_recording = true;
1661 if (recordable() && destructive()) {
1662 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1664 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1665 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1667 if (transvec.len[0] > 0) {
1668 transvec.buf[0]->type = CaptureStart;
1669 transvec.buf[0]->capture_val = capture_start_frame;
1670 (*chan)->capture_transition_buf->increment_write_ptr(1);
1674 fatal << X_("programming error: capture_transition_buf is full on rec loop! inconceivable!")
1684 AudioDiskstream::finish_capture (boost::shared_ptr<ChannelList> c)
1686 was_recording = false;
1687 first_recordable_frame = max_framepos;
1688 last_recordable_frame = max_framepos;
1690 if (capture_captured == 0) {
1694 if (recordable() && destructive()) {
1695 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1697 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1698 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1700 if (transvec.len[0] > 0) {
1701 transvec.buf[0]->type = CaptureEnd;
1702 transvec.buf[0]->capture_val = capture_captured;
1703 (*chan)->capture_transition_buf->increment_write_ptr(1);
1707 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1713 CaptureInfo* ci = new CaptureInfo;
1715 ci->start = capture_start_frame;
1716 ci->frames = capture_captured;
1718 /* XXX theoretical race condition here. Need atomic exchange ?
1719 However, the circumstances when this is called right
1720 now (either on record-disable or transport_stopped)
1721 mean that no actual race exists. I think ...
1722 We now have a capture_info_lock, but it is only to be used
1723 to synchronize in the transport_stop and the capture info
1724 accessors, so that invalidation will not occur (both non-realtime).
1727 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("Finish capture, add new CI, %1 + %2\n", ci->start, ci->frames));
1729 capture_info.push_back (ci);
1730 capture_captured = 0;
1732 /* now we've finished a capture, reset first_recordable_frame for next time */
1733 first_recordable_frame = max_framepos;
1737 AudioDiskstream::set_record_enabled (bool yn)
1739 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0 || record_safe ()) {
1743 /* can't rec-enable in destructive mode if transport is before start */
1745 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1749 /* yes, i know that this not proof against race conditions, but its
1750 good enough. i think.
1753 if (record_enabled() != yn) {
1755 engage_record_enable ();
1757 disengage_record_enable ();
1760 RecordEnableChanged (); /* EMIT SIGNAL */
1765 AudioDiskstream::set_record_safe (bool yn)
1767 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0) {
1771 /* can't rec-safe in destructive mode if transport is before start ????
1774 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1778 /* yes, i know that this not proof against race conditions, but its
1779 good enough. i think.
1782 if (record_safe () != yn) {
1784 engage_record_safe ();
1786 disengage_record_safe ();
1789 RecordSafeChanged (); /* EMIT SIGNAL */
1794 AudioDiskstream::prep_record_enable ()
1796 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0 || record_safe ()) { // REQUIRES REVIEW "|| record_safe ()"
1800 /* can't rec-enable in destructive mode if transport is before start */
1802 if (destructive() && _session.transport_frame() < _session.current_start_frame()) {
1806 bool rolling = _session.transport_speed() != 0.0f;
1807 boost::shared_ptr<ChannelList> c = channels.reader();
1809 capturing_sources.clear ();
1811 if (Config->get_monitoring_model() == HardwareMonitoring) {
1813 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1814 (*chan)->source.request_input_monitoring (!(_session.config.get_auto_input() && rolling));
1815 capturing_sources.push_back ((*chan)->write_source);
1816 Source::Lock lock((*chan)->write_source->mutex());
1817 (*chan)->write_source->mark_streaming_write_started (lock);
1821 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1822 capturing_sources.push_back ((*chan)->write_source);
1823 Source::Lock lock((*chan)->write_source->mutex());
1824 (*chan)->write_source->mark_streaming_write_started (lock);
1832 AudioDiskstream::prep_record_disable ()
1834 boost::shared_ptr<ChannelList> c = channels.reader();
1835 if (Config->get_monitoring_model() == HardwareMonitoring) {
1836 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1837 (*chan)->source.request_input_monitoring (false);
1840 capturing_sources.clear ();
1846 AudioDiskstream::get_state ()
1848 XMLNode& node (Diskstream::get_state());
1850 LocaleGuard lg (X_("C"));
1852 boost::shared_ptr<ChannelList> c = channels.reader();
1853 snprintf (buf, sizeof(buf), "%u", (unsigned int) c->size());
1854 node.add_property ("channels", buf);
1856 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1858 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1859 XMLNode* cs_grandchild;
1861 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1862 cs_grandchild = new XMLNode (X_("file"));
1863 cs_grandchild->add_property (X_("path"), (*i)->path());
1864 cs_child->add_child_nocopy (*cs_grandchild);
1867 /* store the location where capture will start */
1871 if (_session.config.get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1872 snprintf (buf, sizeof (buf), "%" PRId64, pi->start());
1874 snprintf (buf, sizeof (buf), "%" PRId64, _session.transport_frame());
1877 cs_child->add_property (X_("at"), buf);
1878 node.add_child_nocopy (*cs_child);
1885 AudioDiskstream::set_state (const XMLNode& node, int version)
1887 const XMLProperty* prop;
1888 XMLNodeList nlist = node.children();
1889 XMLNodeIterator niter;
1890 uint32_t nchans = 1;
1891 XMLNode* capture_pending_node = 0;
1892 LocaleGuard lg (X_("C"));
1894 /* prevent write sources from being created */
1896 in_set_state = true;
1898 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1899 if ((*niter)->name() == IO::state_node_name) {
1900 deprecated_io_node = new XMLNode (**niter);
1903 if ((*niter)->name() == X_("CapturingSources")) {
1904 capture_pending_node = *niter;
1908 if (Diskstream::set_state (node, version)) {
1912 if ((prop = node.property ("channels")) != 0) {
1913 nchans = atoi (prop->value().c_str());
1916 // create necessary extra channels
1917 // we are always constructed with one and we always need one
1919 _n_channels.set(DataType::AUDIO, channels.reader()->size());
1921 if (nchans > _n_channels.n_audio()) {
1923 add_channel (nchans - _n_channels.n_audio());
1924 IO::PortCountChanged(_n_channels);
1926 } else if (nchans < _n_channels.n_audio()) {
1928 remove_channel (_n_channels.n_audio() - nchans);
1933 if (!destructive() && capture_pending_node) {
1934 /* destructive streams have one and only one source per channel,
1935 and so they never end up in pending capture in any useful
1938 use_pending_capture_data (*capture_pending_node);
1941 in_set_state = false;
1943 /* make sure this is clear before we do anything else */
1945 capturing_sources.clear ();
1947 /* write sources are handled when we handle the input set
1948 up of the IO that owns this DS (::non_realtime_input_change())
1955 AudioDiskstream::use_new_write_source (uint32_t n)
1957 boost::shared_ptr<ChannelList> c = channels.reader();
1959 if (!recordable()) {
1963 if (n >= c->size()) {
1964 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
1968 ChannelInfo* chan = (*c)[n];
1971 if ((chan->write_source = _session.create_audio_source_for_session (
1972 n_channels().n_audio(), write_source_name(), n, destructive())) == 0) {
1973 throw failed_constructor();
1977 catch (failed_constructor &err) {
1978 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
1979 chan->write_source.reset ();
1983 /* do not remove destructive files even if they are empty */
1985 chan->write_source->set_allow_remove_if_empty (!destructive());
1991 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool /*force*/)
1993 ChannelList::iterator chan;
1994 boost::shared_ptr<ChannelList> c = channels.reader();
1997 if (!_session.writable() || !recordable()) {
2001 capturing_sources.clear ();
2003 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
2005 if (!destructive()) {
2007 if ((*chan)->write_source) {
2009 if (mark_write_complete) {
2010 Source::Lock lock((*chan)->write_source->mutex());
2011 (*chan)->write_source->mark_streaming_write_completed (lock);
2012 (*chan)->write_source->done_with_peakfile_writes ();
2015 if ((*chan)->write_source->removable()) {
2016 (*chan)->write_source->mark_for_remove ();
2017 (*chan)->write_source->drop_references ();
2020 (*chan)->write_source.reset ();
2023 use_new_write_source (n);
2025 if (record_enabled()) {
2026 capturing_sources.push_back ((*chan)->write_source);
2031 if ((*chan)->write_source == 0) {
2032 use_new_write_source (n);
2037 if (destructive() && !c->empty ()) {
2039 /* we now have all our write sources set up, so create the
2040 playlist's single region.
2043 if (_playlist->empty()) {
2044 setup_destructive_playlist ();
2050 AudioDiskstream::set_block_size (pframes_t /*nframes*/)
2052 if (_session.get_block_size() > speed_buffer_size) {
2053 speed_buffer_size = _session.get_block_size();
2054 boost::shared_ptr<ChannelList> c = channels.reader();
2056 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2057 if ((*chan)->speed_buffer)
2058 delete [] (*chan)->speed_buffer;
2059 (*chan)->speed_buffer = new Sample[speed_buffer_size];
2062 allocate_temporary_buffers ();
2066 AudioDiskstream::allocate_temporary_buffers ()
2068 /* make sure the wrap buffer is at least large enough to deal
2069 with the speeds up to 1.2, to allow for micro-variation
2070 when slaving to MTC, Timecode etc.
2073 double const sp = max (fabsf (_actual_speed), 1.2f);
2074 framecnt_t required_wrap_size = (framecnt_t) ceil (_session.get_block_size() * sp) + 2;
2076 if (required_wrap_size > wrap_buffer_size) {
2078 boost::shared_ptr<ChannelList> c = channels.reader();
2080 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2081 if ((*chan)->playback_wrap_buffer) {
2082 delete [] (*chan)->playback_wrap_buffer;
2084 (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
2085 if ((*chan)->capture_wrap_buffer) {
2086 delete [] (*chan)->capture_wrap_buffer;
2088 (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
2091 wrap_buffer_size = required_wrap_size;
2096 AudioDiskstream::request_input_monitoring (bool yn)
2098 boost::shared_ptr<ChannelList> c = channels.reader();
2100 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2101 (*chan)->source.request_input_monitoring (yn);
2106 AudioDiskstream::set_align_style_from_io ()
2108 bool have_physical = false;
2110 if (_alignment_choice != Automatic) {
2118 get_input_sources ();
2120 boost::shared_ptr<ChannelList> c = channels.reader();
2122 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2123 if ((*chan)->source.is_physical ()) {
2124 have_physical = true;
2129 if (have_physical) {
2130 set_align_style (ExistingMaterial);
2132 set_align_style (CaptureTime);
2137 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2139 while (how_many--) {
2140 c->push_back (new ChannelInfo(
2141 _session.butler()->audio_diskstream_playback_buffer_size(),
2142 _session.butler()->audio_diskstream_capture_buffer_size(),
2143 speed_buffer_size, wrap_buffer_size));
2144 interpolation.add_channel_to (
2145 _session.butler()->audio_diskstream_playback_buffer_size(),
2149 _n_channels.set(DataType::AUDIO, c->size());
2155 AudioDiskstream::add_channel (uint32_t how_many)
2157 RCUWriter<ChannelList> writer (channels);
2158 boost::shared_ptr<ChannelList> c = writer.get_copy();
2160 return add_channel_to (c, how_many);
2164 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2166 while (how_many-- && !c->empty()) {
2169 interpolation.remove_channel_from ();
2172 _n_channels.set(DataType::AUDIO, c->size());
2178 AudioDiskstream::remove_channel (uint32_t how_many)
2180 RCUWriter<ChannelList> writer (channels);
2181 boost::shared_ptr<ChannelList> c = writer.get_copy();
2183 return remove_channel_from (c, how_many);
2187 AudioDiskstream::playback_buffer_load () const
2189 boost::shared_ptr<ChannelList> c = channels.reader();
2195 return (float) ((double) c->front()->playback_buf->read_space()/
2196 (double) c->front()->playback_buf->bufsize());
2200 AudioDiskstream::capture_buffer_load () const
2202 boost::shared_ptr<ChannelList> c = channels.reader();
2208 return (float) ((double) c->front()->capture_buf->write_space()/
2209 (double) c->front()->capture_buf->bufsize());
2213 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2215 const XMLProperty* prop;
2216 XMLNodeList nlist = node.children();
2217 XMLNodeIterator niter;
2218 boost::shared_ptr<AudioFileSource> fs;
2219 boost::shared_ptr<AudioFileSource> first_fs;
2220 SourceList pending_sources;
2221 framepos_t position;
2223 if ((prop = node.property (X_("at"))) == 0) {
2227 if (sscanf (prop->value().c_str(), "%" PRIu64, &position) != 1) {
2231 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2232 if ((*niter)->name() == X_("file")) {
2234 if ((prop = (*niter)->property (X_("path"))) == 0) {
2238 // This protects sessions from errant CapturingSources in stored sessions
2240 if (stat (prop->value().c_str(), &sbuf)) {
2244 /* XXX as of June 2014, we always record to mono
2245 files. Since this Source is being created as part of
2246 crash recovery, we know that we need the first
2247 channel (the final argument to the SourceFactory
2248 call below). If we ever support non-mono files for
2249 capture, this will need rethinking.
2253 fs = boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createForRecovery (DataType::AUDIO, _session, prop->value(), 0));
2256 catch (failed_constructor& err) {
2257 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2258 _name, prop->value())
2263 pending_sources.push_back (fs);
2265 if (first_fs == 0) {
2269 fs->set_captured_for (_name.val());
2273 if (pending_sources.size() == 0) {
2274 /* nothing can be done */
2278 if (pending_sources.size() != _n_channels.n_audio()) {
2279 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2286 boost::shared_ptr<AudioRegion> wf_region;
2287 boost::shared_ptr<AudioRegion> region;
2289 /* First create the whole file region */
2293 plist.add (Properties::start, 0);
2294 plist.add (Properties::length, first_fs->length (first_fs->timeline_position()));
2295 plist.add (Properties::name, region_name_from_path (first_fs->name(), true));
2297 wf_region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, plist));
2299 wf_region->set_automatic (true);
2300 wf_region->set_whole_file (true);
2301 wf_region->special_set_position (position);
2303 /* Now create a region that isn't the whole file for adding to
2306 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, plist));
2308 _playlist->add_region (region, position);
2311 catch (failed_constructor& err) {
2312 error << string_compose (
2313 _("%1: cannot create whole-file region from pending capture sources"),
2324 AudioDiskstream::set_non_layered (bool yn)
2326 if (yn != non_layered()) {
2329 _flags = Flag (_flags | NonLayered);
2331 _flags = Flag (_flags & ~NonLayered);
2339 AudioDiskstream::set_destructive (bool yn)
2341 if (yn != destructive()) {
2344 bool bounce_ignored;
2345 /* requestor should already have checked this and
2346 bounced if necessary and desired
2348 if (!can_become_destructive (bounce_ignored)) {
2351 _flags = Flag (_flags | Destructive);
2352 use_destructive_playlist ();
2354 _flags = Flag (_flags & ~Destructive);
2355 reset_write_sources (true, true);
2363 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2366 requires_bounce = false;
2370 /* if no regions are present: easy */
2372 if (_playlist->n_regions() == 0) {
2373 requires_bounce = false;
2377 /* is there only one region ? */
2379 if (_playlist->n_regions() != 1) {
2380 requires_bounce = true;
2384 boost::shared_ptr<Region> first;
2386 const RegionList& rl (_playlist->region_list().rlist());
2387 assert((rl.size() == 1));
2393 requires_bounce = false;
2397 /* do the source(s) for the region cover the session start position ? */
2399 if (first->position() != _session.current_start_frame()) {
2400 // what is the idea here? why start() ??
2401 if (first->start() > _session.current_start_frame()) {
2402 requires_bounce = true;
2407 /* currently RouteTimeAxisView::set_track_mode does not
2408 * implement bounce. Existing regions cannot be converted.
2410 * so let's make sure this region is already set up
2411 * as tape-track (spanning the complete range)
2413 if (first->length() != max_framepos - first->position()) {
2414 requires_bounce = true;
2418 /* is the source used by only 1 playlist ? */
2420 boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2424 if (_session.playlists->source_use_count (afirst->source()) > 1) {
2425 requires_bounce = true;
2429 requires_bounce = false;
2434 AudioDiskstream::adjust_playback_buffering ()
2436 boost::shared_ptr<ChannelList> c = channels.reader();
2438 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2439 (*chan)->resize_playback (_session.butler()->audio_diskstream_playback_buffer_size());
2444 AudioDiskstream::adjust_capture_buffering ()
2446 boost::shared_ptr<ChannelList> c = channels.reader();
2448 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2449 (*chan)->resize_capture (_session.butler()->audio_diskstream_capture_buffer_size());
2454 AudioDiskstream::ChannelSource::is_physical () const
2460 return AudioEngine::instance()->port_is_physical (name);
2464 AudioDiskstream::ChannelSource::request_input_monitoring (bool yn) const
2470 return AudioEngine::instance()->request_input_monitoring (name, yn);
2473 AudioDiskstream::ChannelInfo::ChannelInfo (framecnt_t playback_bufsize, framecnt_t capture_bufsize, framecnt_t speed_size, framecnt_t wrap_size)
2475 current_capture_buffer = 0;
2476 current_playback_buffer = 0;
2477 curr_capture_cnt = 0;
2479 speed_buffer = new Sample[speed_size];
2480 playback_wrap_buffer = new Sample[wrap_size];
2481 capture_wrap_buffer = new Sample[wrap_size];
2483 playback_buf = new RingBufferNPT<Sample> (playback_bufsize);
2484 capture_buf = new RingBufferNPT<Sample> (capture_bufsize);
2485 capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2487 /* touch the ringbuffer buffers, which will cause
2488 them to be mapped into locked physical RAM if
2489 we're running with mlockall(). this doesn't do
2493 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2494 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2495 memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2499 AudioDiskstream::ChannelInfo::resize_playback (framecnt_t playback_bufsize)
2501 delete playback_buf;
2502 playback_buf = new RingBufferNPT<Sample> (playback_bufsize);
2503 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2507 AudioDiskstream::ChannelInfo::resize_capture (framecnt_t capture_bufsize)
2511 capture_buf = new RingBufferNPT<Sample> (capture_bufsize);
2512 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2515 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2518 if (write_source->removable()) {
2519 /* this is a "stub" write source which exists in the
2520 Session source list, but is removable. We must emit
2521 a drop references call because it should not
2522 continue to exist. If we do not do this, then the
2523 Session retains a reference to it, it is not
2524 deleted, and later attempts to create a new source
2525 file will use wierd naming because it already
2528 XXX longer term TO-DO: do not add to session source
2529 list until we write to the source.
2531 write_source->drop_references ();
2535 write_source.reset ();
2537 delete [] speed_buffer;
2540 delete [] playback_wrap_buffer;
2541 playback_wrap_buffer = 0;
2543 delete [] capture_wrap_buffer;
2544 capture_wrap_buffer = 0;
2546 delete playback_buf;
2552 delete capture_transition_buf;
2553 capture_transition_buf = 0;
2558 AudioDiskstream::set_name (string const & name)
2560 if (_name == name) {
2563 Diskstream::set_name (name);
2565 /* get a new write source so that its name reflects the new diskstream name */
2567 boost::shared_ptr<ChannelList> c = channels.reader();
2568 ChannelList::iterator i;
2571 for (n = 0, i = c->begin(); i != c->end(); ++i, ++n) {
2572 use_new_write_source (n);
2579 AudioDiskstream::set_write_source_name (const std::string& str) {
2580 if (_write_source_name == str) {
2584 Diskstream::set_write_source_name (str);
2586 if (_write_source_name == name()) {
2589 boost::shared_ptr<ChannelList> c = channels.reader();
2590 ChannelList::iterator i;
2593 for (n = 0, i = c->begin(); i != c->end(); ++i, ++n) {
2594 use_new_write_source (n);