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.
30 #include "pbd/gstdio_compat.h"
31 #include "pbd/error.h"
32 #include "pbd/xml++.h"
33 #include "pbd/memento_command.h"
34 #include "pbd/enumwriter.h"
35 #include "pbd/stateful_diff_command.h"
37 #include "ardour/analyser.h"
38 #include "ardour/audio_buffer.h"
39 #include "ardour/audio_diskstream.h"
40 #include "ardour/audio_port.h"
41 #include "ardour/audioengine.h"
42 #include "ardour/audiofilesource.h"
43 #include "ardour/audioplaylist.h"
44 #include "ardour/audioregion.h"
45 #include "ardour/butler.h"
46 #include "ardour/debug.h"
47 #include "ardour/io.h"
48 #include "ardour/playlist_factory.h"
49 #include "ardour/profile.h"
50 #include "ardour/region_factory.h"
51 #include "ardour/session.h"
52 #include "ardour/session_playlists.h"
53 #include "ardour/sndfile_helpers.h"
54 #include "ardour/source_factory.h"
55 #include "ardour/track.h"
56 #include "ardour/types.h"
57 #include "ardour/utils.h"
63 using namespace ARDOUR;
66 Sample* AudioDiskstream::_mixdown_buffer = 0;
67 gain_t* AudioDiskstream::_gain_buffer = 0;
69 AudioDiskstream::AudioDiskstream (Session &sess, const string &name, Diskstream::Flag flag)
70 : Diskstream(sess, name, flag)
71 , channels (new ChannelList)
73 /* prevent any write sources from being created */
79 if (flag & Destructive) {
80 use_destructive_playlist ();
84 AudioDiskstream::AudioDiskstream (Session& sess, const XMLNode& node)
85 : Diskstream(sess, node)
86 , channels (new ChannelList)
91 if (set_state (node, Stateful::loading_state_version)) {
93 throw failed_constructor();
99 use_destructive_playlist ();
104 AudioDiskstream::init ()
106 /* there are no channels at this point, so these
107 two calls just get speed_buffer_size and wrap_buffer
108 size setup without duplicating their code.
111 set_block_size (_session.get_block_size());
112 allocate_temporary_buffers ();
115 AudioDiskstream::~AudioDiskstream ()
117 DEBUG_TRACE (DEBUG::Destruction, string_compose ("Audio Diskstream %1 destructor\n", _name));
120 RCUWriter<ChannelList> writer (channels);
121 boost::shared_ptr<ChannelList> c = writer.get_copy();
123 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
134 AudioDiskstream::allocate_working_buffers()
136 /* with varifill buffer refilling, we compute the read size in bytes (to optimize
137 for disk i/o bandwidth) and then convert back into samples. These buffers
138 need to reflect the maximum size we could use, which is 4MB reads, or 2M samples
139 using 16 bit samples.
141 _mixdown_buffer = new Sample[2*1048576];
142 _gain_buffer = new gain_t[2*1048576];
146 AudioDiskstream::free_working_buffers()
148 delete [] _mixdown_buffer;
149 delete [] _gain_buffer;
155 AudioDiskstream::non_realtime_input_change ()
157 bool need_write_sources = false;
160 Glib::Threads::Mutex::Lock lm (state_lock);
162 if (input_change_pending.type == IOChange::NoChange) {
166 boost::shared_ptr<ChannelList> cr = channels.reader();
167 if (!cr->empty() && !cr->front()->write_source) {
168 need_write_sources = true;
171 if (input_change_pending.type & IOChange::ConfigurationChanged) {
172 RCUWriter<ChannelList> writer (channels);
173 boost::shared_ptr<ChannelList> c = writer.get_copy();
175 _n_channels.set(DataType::AUDIO, c->size());
177 if (_io->n_ports().n_audio() > _n_channels.n_audio()) {
178 add_channel_to (c, _io->n_ports().n_audio() - _n_channels.n_audio());
179 } else if (_io->n_ports().n_audio() < _n_channels.n_audio()) {
180 remove_channel_from (c, _n_channels.n_audio() - _io->n_ports().n_audio());
183 need_write_sources = true;
186 if (input_change_pending.type & IOChange::ConnectionsChanged) {
187 get_input_sources ();
188 set_capture_offset ();
189 set_align_style_from_io ();
192 input_change_pending = IOChange::NoChange;
194 /* implicit unlock */
197 if (need_write_sources) {
198 reset_write_sources (false);
201 /* now refill channel buffers */
203 if (speed() != 1.0f || speed() != -1.0f) {
204 seek ((framepos_t) (_session.transport_frame() * (double) speed()));
206 seek (_session.transport_frame());
211 AudioDiskstream::non_realtime_locate (framepos_t location)
213 /* now refill channel buffers */
215 if (speed() != 1.0f || speed() != -1.0f) {
216 seek ((framepos_t) (location * (double) speed()), true);
218 seek (location, true);
223 AudioDiskstream::get_input_sources ()
225 boost::shared_ptr<ChannelList> c = channels.reader();
228 ChannelList::iterator chan;
229 uint32_t ni = _io->n_ports().n_audio();
230 vector<string> connections;
232 for (n = 0, chan = c->begin(); chan != c->end() && n < ni; ++chan, ++n) {
234 connections.clear ();
236 if ((_io->nth (n).get()) && (_io->nth (n)->get_connections (connections) == 0)) {
237 if (!(*chan)->source.name.empty()) {
238 // _source->disable_metering ();
240 (*chan)->source.name = string();
242 (*chan)->source.name = connections[0];
248 AudioDiskstream::find_and_use_playlist (const string& name)
250 boost::shared_ptr<AudioPlaylist> playlist;
252 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (_session.playlists->by_name (name))) == 0) {
253 playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, name));
257 error << string_compose(_("AudioDiskstream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
261 return use_playlist (playlist);
265 AudioDiskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
267 assert(boost::dynamic_pointer_cast<AudioPlaylist>(playlist));
269 Diskstream::use_playlist(playlist);
275 AudioDiskstream::use_new_playlist ()
278 boost::shared_ptr<AudioPlaylist> playlist;
280 if (!in_set_state && destructive()) {
285 newname = Playlist::bump_name (_playlist->name(), _session);
287 newname = Playlist::bump_name (_name, _session);
290 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, newname, hidden()))) != 0) {
292 return use_playlist (playlist);
300 AudioDiskstream::use_copy_playlist ()
302 assert(audio_playlist());
308 if (_playlist == 0) {
309 error << string_compose(_("AudioDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
314 boost::shared_ptr<AudioPlaylist> playlist;
316 newname = Playlist::bump_name (_playlist->name(), _session);
318 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist>(PlaylistFactory::create (audio_playlist(), newname))) != 0) {
319 return use_playlist (playlist);
326 AudioDiskstream::setup_destructive_playlist ()
329 boost::shared_ptr<ChannelList> c = channels.reader();
331 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
332 srcs.push_back ((*chan)->write_source);
335 /* a single full-sized region */
337 assert (!srcs.empty ());
340 plist.add (Properties::name, _name.val());
341 plist.add (Properties::start, 0);
342 plist.add (Properties::length, max_framepos - srcs.front()->natural_position());
344 boost::shared_ptr<Region> region (RegionFactory::create (srcs, plist));
345 _playlist->add_region (region, srcs.front()->natural_position());
347 /* apply region properties and update write sources */
348 use_destructive_playlist();
352 AudioDiskstream::use_destructive_playlist ()
354 /* this is called from the XML-based constructor or ::set_destructive. when called,
355 we already have a playlist and a region, but we need to
356 set up our sources for write. we use the sources associated
357 with the (presumed single, full-extent) region.
360 boost::shared_ptr<Region> rp;
362 const RegionList& rl (_playlist->region_list().rlist());
364 assert((rl.size() == 1));
370 reset_write_sources (false, true);
374 boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
377 throw failed_constructor();
380 /* be sure to stretch the region out to the maximum length */
382 region->set_length (max_framepos - region->position());
385 ChannelList::iterator chan;
386 boost::shared_ptr<ChannelList> c = channels.reader();
388 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
389 (*chan)->write_source = boost::dynamic_pointer_cast<AudioFileSource>(region->source (n));
390 assert((*chan)->write_source);
391 (*chan)->write_source->set_allow_remove_if_empty (false);
393 /* this might be false if we switched modes, so force it */
395 (*chan)->write_source->set_destructive (true);
398 /* the source list will never be reset for a destructive track */
402 AudioDiskstream::prepare_record_status(framepos_t capture_start_frame)
404 if (recordable() && destructive()) {
405 boost::shared_ptr<ChannelList> c = channels.reader();
406 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
408 RingBufferNPT<CaptureTransition>::rw_vector transitions;
409 (*chan)->capture_transition_buf->get_write_vector (&transitions);
411 if (transitions.len[0] > 0) {
412 transitions.buf[0]->type = CaptureStart;
413 transitions.buf[0]->capture_val = capture_start_frame;
414 (*chan)->capture_transition_buf->increment_write_ptr(1);
417 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
425 /** Do some record stuff [not described in this comment!]
428 * - Setup playback_distance with the nframes, or nframes adjusted
429 * for current varispeed, if appropriate.
430 * - Setup current_playback_buffer in each ChannelInfo to point to data
431 * that someone can read playback_distance worth of data from.
434 AudioDiskstream::process (BufferSet& bufs, framepos_t transport_frame, pframes_t nframes, framecnt_t& playback_distance, bool need_disk_signal)
437 boost::shared_ptr<ChannelList> c = channels.reader();
438 ChannelList::iterator chan;
439 framecnt_t rec_offset = 0;
440 framecnt_t rec_nframes = 0;
441 bool collect_playback = false;
442 bool can_record = _session.actively_recording ();
444 playback_distance = 0;
446 if (!_io || !_io->active()) {
450 check_record_status (transport_frame, can_record);
456 Glib::Threads::Mutex::Lock sm (state_lock, Glib::Threads::TRY_LOCK);
462 adjust_capture_position = 0;
464 for (chan = c->begin(); chan != c->end(); ++chan) {
465 (*chan)->current_capture_buffer = 0;
466 (*chan)->current_playback_buffer = 0;
469 // Safeguard against situations where process() goes haywire when autopunching
470 // and last_recordable_frame < first_recordable_frame
472 if (last_recordable_frame < first_recordable_frame) {
473 last_recordable_frame = max_framepos;
476 if (record_enabled()) {
478 Evoral::OverlapType ot = Evoral::coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
479 // XXX should this be transport_frame + nframes - 1 ? coverage() expects its parameter ranges to include their end points
480 // XXX also, first_recordable_frame & last_recordable_frame may both be == max_framepos: coverage() will return OverlapNone in that case. Is thak OK?
481 calculate_record_range (ot, transport_frame, nframes, rec_nframes, rec_offset);
483 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1: this time record %2 of %3 frames, offset %4\n", _name, rec_nframes, nframes, rec_offset));
485 if (rec_nframes && !was_recording) {
486 capture_captured = 0;
487 was_recording = true;
491 if (can_record && !_last_capture_sources.empty()) {
492 _last_capture_sources.clear ();
497 uint32_t limit = _io->n_ports ().n_audio();
499 /* one or more ports could already have been removed from _io, but our
500 channel setup hasn't yet been updated. prevent us from trying to
501 use channels that correspond to missing ports. note that the
502 process callback (from which this is called) is always atomic
503 with respect to port removal/addition.
506 for (n = 0, chan = c->begin(); chan != c->end() && n < limit; ++chan, ++n) {
508 ChannelInfo* chaninfo (*chan);
510 chaninfo->capture_buf->get_write_vector (&chaninfo->capture_vector);
512 if (rec_nframes <= (framecnt_t) chaninfo->capture_vector.len[0]) {
514 chaninfo->current_capture_buffer = chaninfo->capture_vector.buf[0];
516 /* note: grab the entire port buffer, but only copy what we were supposed to
517 for recording, and use rec_offset
520 boost::shared_ptr<AudioPort> const ap = _io->audio (n);
522 assert(rec_nframes <= (framecnt_t) ap->get_audio_buffer(nframes).capacity());
524 Sample *buf = bufs.get_audio (n).data(rec_offset);
525 memcpy (chaninfo->current_capture_buffer, buf, sizeof (Sample) * rec_nframes);
529 framecnt_t total = chaninfo->capture_vector.len[0] + chaninfo->capture_vector.len[1];
531 if (rec_nframes > total) {
532 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 overrun in %2, rec_nframes = %3 total space = %4\n",
533 DEBUG_THREAD_SELF, name(), rec_nframes, total));
538 boost::shared_ptr<AudioPort> const ap = _io->audio (n);
541 Sample *buf = bufs.get_audio (n).data(rec_offset);
542 framecnt_t first = chaninfo->capture_vector.len[0];
544 memcpy (chaninfo->capture_wrap_buffer, buf, sizeof (Sample) * first);
545 memcpy (chaninfo->capture_vector.buf[0], buf, sizeof (Sample) * first);
546 memcpy (chaninfo->capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
547 memcpy (chaninfo->capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
549 chaninfo->current_capture_buffer = chaninfo->capture_wrap_buffer;
563 /* data will be written to disk */
565 if (rec_nframes == nframes && rec_offset == 0) {
567 for (chan = c->begin(); chan != c->end(); ++chan) {
568 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
571 playback_distance = nframes;
576 /* we can't use the capture buffer as the playback buffer, because
577 we recorded only a part of the current process' cycle data
581 collect_playback = true;
584 adjust_capture_position = rec_nframes;
586 } else if (can_record && record_enabled()) {
588 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
590 for (chan = c->begin(); chan != c->end(); ++chan) {
591 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
594 playback_distance = nframes;
598 collect_playback = true;
601 if ((_track->monitoring_state () & MonitoringDisk) || collect_playback) {
603 /* we're doing playback */
605 framecnt_t necessary_samples;
607 /* no varispeed playback if we're recording, because the output .... TBD */
609 if (rec_nframes == 0 && _actual_speed != 1.0) {
610 necessary_samples = (framecnt_t) ceil ((nframes * fabs (_actual_speed))) + 2;
612 necessary_samples = nframes;
615 for (chan = c->begin(); chan != c->end(); ++chan) {
616 (*chan)->playback_buf->get_read_vector (&(*chan)->playback_vector);
621 /* Setup current_playback_buffer in each ChannelInfo to point to data that someone
622 can read necessary_samples (== nframes at a transport speed of 1) worth of data
626 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
628 ChannelInfo* chaninfo (*chan);
630 if (necessary_samples <= (framecnt_t) chaninfo->playback_vector.len[0]) {
631 /* There are enough samples in the first part of the ringbuffer */
632 chaninfo->current_playback_buffer = chaninfo->playback_vector.buf[0];
635 framecnt_t total = chaninfo->playback_vector.len[0] + chaninfo->playback_vector.len[1];
637 if (necessary_samples > total) {
638 cerr << _name << " Need " << necessary_samples << " total = " << total << endl;
639 cerr << "underrun for " << _name << endl;
640 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 underrun in %2, rec_nframes = %3 total space = %4\n",
641 DEBUG_THREAD_SELF, name(), rec_nframes, total));
647 /* We have enough samples, but not in one lump. Coalesce the two parts
648 into one in playback_wrap_buffer in our ChannelInfo, and specify that
649 as our current_playback_buffer.
652 assert(wrap_buffer_size >= necessary_samples);
654 /* Copy buf[0] from playback_buf */
655 memcpy ((char *) chaninfo->playback_wrap_buffer,
656 chaninfo->playback_vector.buf[0],
657 chaninfo->playback_vector.len[0] * sizeof (Sample));
659 /* Copy buf[1] from playback_buf */
660 memcpy (chaninfo->playback_wrap_buffer + chaninfo->playback_vector.len[0],
661 chaninfo->playback_vector.buf[1],
662 (necessary_samples - chaninfo->playback_vector.len[0])
665 chaninfo->current_playback_buffer = chaninfo->playback_wrap_buffer;
670 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
672 interpolation.set_speed (_target_speed);
675 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++channel) {
676 ChannelInfo* chaninfo (*chan);
678 playback_distance = interpolation.interpolate (
679 channel, nframes, chaninfo->current_playback_buffer, chaninfo->speed_buffer);
681 chaninfo->current_playback_buffer = chaninfo->speed_buffer;
685 playback_distance = nframes;
688 _speed = _target_speed;
691 if (need_disk_signal) {
693 /* copy data over to buffer set */
695 size_t n_buffers = bufs.count().n_audio();
696 size_t n_chans = c->size();
697 gain_t scaling = 1.0f;
699 if (n_chans > n_buffers) {
700 scaling = ((float) n_buffers)/n_chans;
703 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
705 AudioBuffer& buf (bufs.get_audio (n%n_buffers));
706 ChannelInfo* chaninfo (*chan);
709 if (scaling != 1.0f) {
710 buf.read_from_with_gain (chaninfo->current_playback_buffer, nframes, scaling);
712 buf.read_from (chaninfo->current_playback_buffer, nframes);
715 if (scaling != 1.0f) {
716 buf.accumulate_with_gain_from (chaninfo->current_playback_buffer, nframes, scaling);
718 buf.accumulate_from (chaninfo->current_playback_buffer, nframes);
723 /* leave the MIDI count alone */
724 ChanCount cnt (DataType::AUDIO, n_chans);
725 cnt.set (DataType::MIDI, bufs.count().n_midi());
726 bufs.set_count (cnt);
728 /* extra buffers will already be silent, so leave them alone */
735 AudioDiskstream::calculate_playback_distance (pframes_t nframes)
737 frameoffset_t playback_distance = nframes;
739 if (record_enabled()) {
740 playback_distance = nframes;
741 } else if (_actual_speed != 1.0f && _actual_speed != -1.0f) {
742 interpolation.set_speed (_target_speed);
743 boost::shared_ptr<ChannelList> c = channels.reader();
745 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++channel) {
746 playback_distance = interpolation.interpolate (channel, nframes, NULL, NULL);
749 playback_distance = nframes;
752 if (_actual_speed < 0.0) {
753 return -playback_distance;
755 return playback_distance;
759 /** Update various things including playback_sample, read pointer on each channel's playback_buf
760 * and write pointer on each channel's capture_buf. Also wout whether the butler is needed.
761 * @return true if the butler is required.
764 AudioDiskstream::commit (framecnt_t playback_distance)
766 bool need_butler = false;
768 if (!_io || !_io->active()) {
772 if (_actual_speed < 0.0) {
773 playback_sample -= playback_distance;
775 playback_sample += playback_distance;
778 boost::shared_ptr<ChannelList> c = channels.reader();
779 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
781 (*chan)->playback_buf->increment_read_ptr (playback_distance);
783 if (adjust_capture_position) {
784 (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
788 if (adjust_capture_position != 0) {
789 capture_captured += adjust_capture_position;
790 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1 now captured %2 (by %3)\n", name(), capture_captured, adjust_capture_position));
791 adjust_capture_position = 0;
799 if (_io && _io->active()) {
800 need_butler = c->front()->playback_buf->write_space() >= c->front()->playback_buf->bufsize() / 2;
805 if (_io && _io->active()) {
806 need_butler = ((framecnt_t) c->front()->playback_buf->write_space() >= disk_read_chunk_frames)
807 || ((framecnt_t) c->front()->capture_buf->read_space() >= disk_write_chunk_frames);
809 need_butler = ((framecnt_t) c->front()->capture_buf->read_space() >= disk_write_chunk_frames);
817 AudioDiskstream::set_pending_overwrite (bool yn)
819 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
821 _pending_overwrite = yn;
823 overwrite_frame = playback_sample;
825 boost::shared_ptr<ChannelList> c = channels.reader ();
827 overwrite_offset = c->front()->playback_buf->get_read_ptr();
832 AudioDiskstream::overwrite_existing_buffers ()
834 boost::shared_ptr<ChannelList> c = channels.reader();
836 _pending_overwrite = false;
840 Sample* mixdown_buffer;
843 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
845 overwrite_queued = false;
847 /* assume all are the same size */
848 framecnt_t size = c->front()->playback_buf->bufsize();
850 mixdown_buffer = new Sample[size];
851 gain_buffer = new float[size];
853 /* reduce size so that we can fill the buffer correctly (ringbuffers
854 can only handle size-1, otherwise they appear to be empty)
861 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
863 start = overwrite_frame;
864 framecnt_t cnt = size;
866 /* to fill the buffer without resetting the playback sample, we need to
867 do it one or two chunks (normally two).
869 |----------------------------------------------------------------------|
873 |<- second chunk->||<----------------- first chunk ------------------>|
877 framecnt_t to_read = size - overwrite_offset;
879 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, n, reversed)) {
880 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
881 id(), size, playback_sample) << endmsg;
889 if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer, start, cnt, n, reversed)) {
890 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
891 id(), size, playback_sample) << endmsg;
900 _pending_overwrite = false;
901 delete [] gain_buffer;
902 delete [] mixdown_buffer;
907 AudioDiskstream::seek (framepos_t frame, bool complete_refill)
911 ChannelList::iterator chan;
912 boost::shared_ptr<ChannelList> c = channels.reader();
914 Glib::Threads::Mutex::Lock lm (state_lock);
916 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
917 (*chan)->playback_buf->reset ();
918 (*chan)->capture_buf->reset ();
921 /* can't rec-enable in destructive mode if transport is before start */
923 if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
924 disengage_record_enable ();
927 playback_sample = frame;
930 if (complete_refill) {
931 /* call _do_refill() to refill the entire buffer, using
932 the largest reads possible.
934 while ((ret = do_refill_with_alloc (false)) > 0) ;
936 /* call _do_refill() to refill just one chunk, and then
939 ret = do_refill_with_alloc (true);
946 AudioDiskstream::can_internal_playback_seek (framecnt_t distance)
948 ChannelList::iterator chan;
949 boost::shared_ptr<ChannelList> c = channels.reader();
951 for (chan = c->begin(); chan != c->end(); ++chan) {
952 if ((*chan)->playback_buf->read_space() < (size_t) distance) {
960 AudioDiskstream::internal_playback_seek (framecnt_t distance)
962 ChannelList::iterator chan;
963 boost::shared_ptr<ChannelList> c = channels.reader();
965 for (chan = c->begin(); chan != c->end(); ++chan) {
966 (*chan)->playback_buf->increment_read_ptr (::llabs(distance));
969 if (first_recordable_frame < max_framepos) {
970 first_recordable_frame += distance;
972 playback_sample += distance;
977 /** Read some data for 1 channel from our playlist into a buffer.
978 * @param buf Buffer to write to.
979 * @param start Session frame to start reading from; updated to where we end up
981 * @param cnt Count of samples to read.
982 * @param reversed true if we are running backwards, otherwise false.
985 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer,
986 framepos_t& start, framecnt_t cnt,
987 int channel, bool reversed)
989 framecnt_t this_read = 0;
991 framepos_t loop_end = 0;
992 framepos_t loop_start = 0;
993 framecnt_t offset = 0;
996 /* XXX we don't currently play loops in reverse. not sure why */
1000 framecnt_t loop_length = 0;
1002 /* Make the use of a Location atomic for this read operation.
1004 Note: Locations don't get deleted, so all we care about
1005 when I say "atomic" is that we are always pointing to
1006 the same one and using a start/length values obtained
1010 if ((loc = loop_location) != 0) {
1011 loop_start = loc->start();
1012 loop_end = loc->end();
1013 loop_length = loop_end - loop_start;
1016 /* if we are looping, ensure that the first frame we read is at the correct
1017 position within the loop.
1020 if (loc && start >= loop_end) {
1021 start = loop_start + ((start - loop_start) % loop_length);
1030 /* We need this while loop in case we hit a loop boundary, in which case our read from
1031 the playlist must be split into more than one section.
1036 /* take any loop into account. we can't read past the end of the loop. */
1038 if (loc && (loop_end - start < cnt)) {
1039 this_read = loop_end - start;
1046 if (this_read == 0) {
1050 this_read = min(cnt,this_read);
1052 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
1053 error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), id(), this_read,
1060 swap_by_ptr (buf, buf + this_read - 1);
1064 /* if we read to the end of the loop, go back to the beginning */
1074 offset += this_read;
1081 AudioDiskstream::_do_refill_with_alloc (bool partial_fill)
1083 /* We limit disk reads to at most 4MB chunks, which with floating point
1084 samples would be 1M samples. But we might use 16 or 14 bit samples,
1085 in which case 4MB is more samples than that. Therefore size this for
1086 the smallest sample value .. 4MB = 2M samples (16 bit).
1089 Sample* mix_buf = new Sample[2*1048576];
1090 float* gain_buf = new float[2*1048576];
1092 int ret = _do_refill (mix_buf, gain_buf, (partial_fill ? disk_read_chunk_frames : 0));
1100 /** Get some more data from disk and put it in our channels' playback_bufs,
1101 * if there is suitable space in them.
1103 * If fill_level is non-zero, then we will refill the buffer so that there is
1104 * still at least fill_level samples of space left to be filled. This is used
1105 * after locates so that we do not need to wait to fill the entire buffer.
1110 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer, framecnt_t fill_level)
1114 RingBufferNPT<Sample>::rw_vector vector;
1115 bool const reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1116 framecnt_t total_space;
1117 framecnt_t zero_fill;
1119 ChannelList::iterator i;
1120 boost::shared_ptr<ChannelList> c = channels.reader();
1123 /* do not read from disk while session is marked as Loading, to avoid
1124 useless redundant I/O.
1127 if (_session.state_of_the_state() & Session::Loading) {
1135 assert(mixdown_buffer);
1136 assert(gain_buffer);
1143 c->front()->playback_buf->get_write_vector (&vector);
1145 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1146 /* nowhere to write to */
1151 if (fill_level < total_space) {
1152 total_space -= fill_level;
1154 /* we can't do anything with it */
1159 /* if we're running close to normal speed and there isn't enough
1160 space to do disk_read_chunk_frames of I/O, then don't bother.
1162 at higher speeds, just do it because the sync between butler
1163 and audio thread may not be good enough.
1165 Note: it is a design assumption that disk_read_chunk_frames is smaller
1166 than the playback buffer size, so this check should never trip when
1167 the playback buffer is empty.
1170 if ((total_space < disk_read_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1174 /* when slaved, don't try to get too close to the read pointer. this
1175 leaves space for the buffer reversal to have something useful to
1179 if (_slaved && total_space < (framecnt_t) (c->front()->playback_buf->bufsize() / 2)) {
1185 if (file_frame == 0) {
1187 /* at start: nothing to do but fill with silence */
1189 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1191 ChannelInfo* chan (*i);
1192 chan->playback_buf->get_write_vector (&vector);
1193 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1194 if (vector.len[1]) {
1195 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1197 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1202 if (file_frame < total_space) {
1204 /* too close to the start: read what we can,
1205 and then zero fill the rest
1208 zero_fill = total_space - file_frame;
1209 total_space = file_frame;
1218 if (file_frame == max_framepos) {
1220 /* at end: nothing to do but fill with silence */
1222 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1224 ChannelInfo* chan (*i);
1225 chan->playback_buf->get_write_vector (&vector);
1226 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1227 if (vector.len[1]) {
1228 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1230 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1235 if (file_frame > max_framepos - total_space) {
1237 /* to close to the end: read what we can, and zero fill the rest */
1239 zero_fill = total_space - (max_framepos - file_frame);
1240 total_space = max_framepos - file_frame;
1247 framepos_t file_frame_tmp = 0;
1249 /* total_space is in samples. We want to optimize read sizes in various sizes using bytes */
1251 const size_t bits_per_sample = format_data_width (_session.config.get_native_file_data_format());
1252 size_t total_bytes = total_space * bits_per_sample / 8;
1254 /* chunk size range is 256kB to 4MB. Bigger is faster in terms of MB/sec, but bigger chunk size always takes longer
1256 size_t byte_size_for_read = max ((size_t) (256 * 1024), min ((size_t) (4 * 1048576), total_bytes));
1258 /* find nearest (lower) multiple of 16384 */
1260 byte_size_for_read = (byte_size_for_read / 16384) * 16384;
1262 /* now back to samples */
1264 framecnt_t samples_to_read = byte_size_for_read / (bits_per_sample / 8);
1266 //cerr << name() << " will read " << byte_size_for_read << " out of total bytes " << total_bytes << " in buffer of "
1267 // << c->front()->playback_buf->bufsize() * bits_per_sample / 8 << " bps = " << bits_per_sample << endl;
1268 // cerr << name () << " read samples = " << samples_to_read << " out of total space " << total_space << " in buffer of " << c->front()->playback_buf->bufsize() << " samples\n";
1270 // uint64_t before = g_get_monotonic_time ();
1271 // uint64_t elapsed;
1273 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1275 ChannelInfo* chan (*i);
1278 framecnt_t len1, len2;
1280 chan->playback_buf->get_write_vector (&vector);
1282 if ((framecnt_t) vector.len[0] > samples_to_read) {
1284 /* we're not going to fill the first chunk, so certainly do not bother with the
1285 other part. it won't be connected with the part we do fill, as in:
1287 .... => writable space
1288 ++++ => readable space
1289 ^^^^ => 1 x disk_read_chunk_frames that would be filled
1291 |......|+++++++++++++|...............................|
1296 So, just pretend that the buf1 part isn't there.
1306 file_frame_tmp = file_frame;
1308 buf1 = vector.buf[0];
1309 len1 = vector.len[0];
1310 buf2 = vector.buf[1];
1311 len2 = vector.len[1];
1313 to_read = min (ts, len1);
1314 to_read = min (to_read, (framecnt_t) samples_to_read);
1316 assert (to_read >= 0);
1320 if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1325 chan->playback_buf->increment_write_ptr (to_read);
1329 to_read = min (ts, len2);
1333 /* we read all of vector.len[0], but it wasn't the
1334 entire samples_to_read of data, so read some or
1335 all of vector.len[1] as well.
1338 if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1343 chan->playback_buf->increment_write_ptr (to_read);
1347 /* XXX: do something */
1352 // elapsed = g_get_monotonic_time () - before;
1353 // cerr << "\tbandwidth = " << (byte_size_for_read / 1048576.0) / (elapsed/1000000.0) << "MB/sec\n";
1355 file_frame = file_frame_tmp;
1356 assert (file_frame >= 0);
1358 ret = ((total_space - samples_to_read) > disk_read_chunk_frames);
1360 c->front()->playback_buf->get_write_vector (&vector);
1366 /** Flush pending data to disk.
1368 * Important note: this function will write *AT MOST* disk_write_chunk_frames
1369 * of data to disk. it will never write more than that. If it writes that
1370 * much and there is more than that waiting to be written, it will return 1,
1371 * otherwise 0 on success or -1 on failure.
1373 * If there is less than disk_write_chunk_frames to be written, no data will be
1374 * written at all unless @a force_flush is true.
1377 AudioDiskstream::do_flush (RunContext /*context*/, bool force_flush)
1381 RingBufferNPT<Sample>::rw_vector vector;
1382 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1385 transvec.buf[0] = 0;
1386 transvec.buf[1] = 0;
1390 boost::shared_ptr<ChannelList> c = channels.reader();
1391 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1393 (*chan)->capture_buf->get_read_vector (&vector);
1395 total = vector.len[0] + vector.len[1];
1397 if (total == 0 || (total < disk_write_chunk_frames && !force_flush && was_recording)) {
1401 /* if there are 2+ chunks of disk i/o possible for
1402 this track, let the caller know so that it can arrange
1403 for us to be called again, ASAP.
1405 if we are forcing a flush, then if there is* any* extra
1406 work, let the caller know.
1408 if we are no longer recording and there is any extra work,
1409 let the caller know too.
1412 if (total >= 2 * disk_write_chunk_frames || ((force_flush || !was_recording) && total > disk_write_chunk_frames)) {
1416 to_write = min (disk_write_chunk_frames, (framecnt_t) vector.len[0]);
1418 // check the transition buffer when recording destructive
1419 // important that we get this after the capture buf
1421 if (destructive()) {
1422 (*chan)->capture_transition_buf->get_read_vector(&transvec);
1423 size_t transcount = transvec.len[0] + transvec.len[1];
1426 for (ti=0; ti < transcount; ++ti) {
1427 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1429 if (captrans.type == CaptureStart) {
1430 // by definition, the first data we got above represents the given capture pos
1432 (*chan)->write_source->mark_capture_start (captrans.capture_val);
1433 (*chan)->curr_capture_cnt = 0;
1435 } else if (captrans.type == CaptureEnd) {
1437 // capture end, the capture_val represents total frames in capture
1439 if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1441 // shorten to make the write a perfect fit
1442 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
1444 if (nto_write < to_write) {
1445 ret = 1; // should we?
1447 to_write = nto_write;
1449 (*chan)->write_source->mark_capture_end ();
1451 // increment past this transition, but go no further
1456 // actually ends just beyond this chunk, so force more work
1464 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1468 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1469 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), id()) << endmsg;
1473 (*chan)->capture_buf->increment_read_ptr (to_write);
1474 (*chan)->curr_capture_cnt += to_write;
1476 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_write_chunk_frames) && !destructive()) {
1478 /* we wrote all of vector.len[0] but it wasn't an entire
1479 disk_write_chunk_frames of data, so arrange for some part
1480 of vector.len[1] to be flushed to disk as well.
1483 to_write = min ((framecnt_t)(disk_write_chunk_frames - to_write), (framecnt_t) vector.len[1]);
1485 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 additional write of %2\n", name(), to_write));
1487 if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1488 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), id()) << endmsg;
1492 (*chan)->capture_buf->increment_read_ptr (to_write);
1493 (*chan)->curr_capture_cnt += to_write;
1502 AudioDiskstream::transport_stopped_wallclock (struct tm& when, time_t twhen, bool abort_capture)
1504 uint32_t buffer_position;
1505 bool more_work = true;
1507 boost::shared_ptr<AudioRegion> region;
1508 framecnt_t total_capture;
1510 SourceList::iterator src;
1511 ChannelList::iterator chan;
1512 vector<CaptureInfo*>::iterator ci;
1513 boost::shared_ptr<ChannelList> c = channels.reader();
1515 bool mark_write_completed = false;
1519 /* butler is already stopped, but there may be work to do
1520 to flush remaining data to disk.
1523 while (more_work && !err) {
1524 switch (do_flush (TransportContext, true)) {
1531 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1536 /* XXX is there anything we can do if err != 0 ? */
1537 Glib::Threads::Mutex::Lock lm (capture_info_lock);
1539 if (capture_info.empty()) {
1543 if (abort_capture) {
1545 if (destructive()) {
1549 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1551 if ((*chan)->write_source) {
1553 (*chan)->write_source->mark_for_remove ();
1554 (*chan)->write_source->drop_references ();
1555 (*chan)->write_source.reset ();
1558 /* new source set up in "out" below */
1564 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1565 total_capture += (*ci)->frames;
1568 /* figure out the name for this take */
1570 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1572 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1576 s->update_header (capture_info.front()->start, when, twhen);
1577 s->set_captured_for (_name.val());
1578 s->mark_immutable ();
1580 if (Config->get_auto_analyse_audio()) {
1581 Analyser::queue_source_for_analysis (s, true);
1584 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("newly captured source %1 length %2\n", s->path(), s->length (0)));
1588 /* destructive tracks have a single, never changing region */
1590 if (destructive()) {
1592 /* send a signal that any UI can pick up to do the right thing. there is
1593 a small problem here in that a UI may need the peak data to be ready
1594 for the data that was recorded and this isn't interlocked with that
1595 process. this problem is deferred to the UI.
1598 _playlist->LayeringChanged(); // XXX this may not get the UI to do the right thing
1602 string whole_file_region_name;
1603 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1605 /* Register a new region with the Session that
1606 describes the entire source. Do this first
1607 so that any sub-regions will obviously be
1608 children of this one (later!)
1614 plist.add (Properties::start, c->front()->write_source->last_capture_start_frame());
1615 plist.add (Properties::length, total_capture);
1616 plist.add (Properties::name, whole_file_region_name);
1617 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1618 rx->set_automatic (true);
1619 rx->set_whole_file (true);
1621 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1622 region->special_set_position (capture_info.front()->start);
1626 catch (failed_constructor& err) {
1627 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1631 _last_capture_sources.insert (_last_capture_sources.end(), srcs.begin(), srcs.end());
1633 _playlist->clear_changes ();
1634 _playlist->set_capture_insertion_in_progress (true);
1635 _playlist->freeze ();
1637 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1641 RegionFactory::region_name (region_name, whole_file_region_name, false);
1643 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1 capture bufpos %5 start @ %2 length %3 add new region %4\n",
1644 _name, (*ci)->start, (*ci)->frames, region_name, buffer_position));
1650 plist.add (Properties::start, buffer_position);
1651 plist.add (Properties::length, (*ci)->frames);
1652 plist.add (Properties::name, region_name);
1654 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1655 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1658 catch (failed_constructor& err) {
1659 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1660 continue; /* XXX is this OK? */
1663 i_am_the_modifier++;
1665 _playlist->add_region (region, (*ci)->start, 1, non_layered());
1666 _playlist->set_layer (region, DBL_MAX);
1667 i_am_the_modifier--;
1669 buffer_position += (*ci)->frames;
1673 _playlist->set_capture_insertion_in_progress (false);
1674 _session.add_command (new StatefulDiffCommand (_playlist));
1677 mark_write_completed = true;
1680 reset_write_sources (mark_write_completed);
1684 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1688 capture_info.clear ();
1689 capture_start_frame = 0;
1693 AudioDiskstream::transport_looped (framepos_t transport_frame)
1695 if (was_recording) {
1696 // all we need to do is finish this capture, with modified capture length
1697 boost::shared_ptr<ChannelList> c = channels.reader();
1701 // the next region will start recording via the normal mechanism
1702 // we'll set the start position to the current transport pos
1703 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1704 capture_start_frame = transport_frame;
1705 first_recordable_frame = transport_frame; // mild lie
1706 last_recordable_frame = max_framepos;
1707 was_recording = true;
1709 if (recordable() && destructive()) {
1710 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1712 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1713 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1715 if (transvec.len[0] > 0) {
1716 transvec.buf[0]->type = CaptureStart;
1717 transvec.buf[0]->capture_val = capture_start_frame;
1718 (*chan)->capture_transition_buf->increment_write_ptr(1);
1722 fatal << X_("programming error: capture_transition_buf is full on rec loop! inconceivable!")
1732 AudioDiskstream::finish_capture (boost::shared_ptr<ChannelList> c)
1734 was_recording = false;
1735 first_recordable_frame = max_framepos;
1736 last_recordable_frame = max_framepos;
1738 if (capture_captured == 0) {
1742 if (recordable() && destructive()) {
1743 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1745 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1746 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1748 if (transvec.len[0] > 0) {
1749 transvec.buf[0]->type = CaptureEnd;
1750 transvec.buf[0]->capture_val = capture_captured;
1751 (*chan)->capture_transition_buf->increment_write_ptr(1);
1755 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1761 CaptureInfo* ci = new CaptureInfo;
1763 ci->start = capture_start_frame;
1764 ci->frames = capture_captured;
1766 /* XXX theoretical race condition here. Need atomic exchange ?
1767 However, the circumstances when this is called right
1768 now (either on record-disable or transport_stopped)
1769 mean that no actual race exists. I think ...
1770 We now have a capture_info_lock, but it is only to be used
1771 to synchronize in the transport_stop and the capture info
1772 accessors, so that invalidation will not occur (both non-realtime).
1775 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("Finish capture, add new CI, %1 + %2\n", ci->start, ci->frames));
1777 capture_info.push_back (ci);
1778 capture_captured = 0;
1780 /* now we've finished a capture, reset first_recordable_frame for next time */
1781 first_recordable_frame = max_framepos;
1785 AudioDiskstream::set_record_enabled (bool yn)
1787 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0 || record_safe ()) {
1791 /* can't rec-enable in destructive mode if transport is before start */
1793 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1797 /* yes, i know that this not proof against race conditions, but its
1798 good enough. i think.
1801 if (record_enabled() != yn) {
1803 engage_record_enable ();
1805 disengage_record_enable ();
1808 RecordEnableChanged (); /* EMIT SIGNAL */
1813 AudioDiskstream::set_record_safe (bool yn)
1815 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0) {
1819 /* can't rec-safe in destructive mode if transport is before start ????
1822 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1826 /* yes, i know that this not proof against race conditions, but its
1827 good enough. i think.
1830 if (record_safe () != yn) {
1832 engage_record_safe ();
1834 disengage_record_safe ();
1837 RecordSafeChanged (); /* EMIT SIGNAL */
1842 AudioDiskstream::prep_record_enable ()
1844 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0 || record_safe ()) { // REQUIRES REVIEW "|| record_safe ()"
1848 /* can't rec-enable in destructive mode if transport is before start */
1850 if (destructive() && _session.transport_frame() < _session.current_start_frame()) {
1854 bool rolling = _session.transport_speed() != 0.0f;
1855 boost::shared_ptr<ChannelList> c = channels.reader();
1857 capturing_sources.clear ();
1859 if (Config->get_monitoring_model() == HardwareMonitoring) {
1861 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1862 (*chan)->source.request_input_monitoring (!(_session.config.get_auto_input() && rolling));
1863 capturing_sources.push_back ((*chan)->write_source);
1864 Source::Lock lock((*chan)->write_source->mutex());
1865 (*chan)->write_source->mark_streaming_write_started (lock);
1869 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1870 capturing_sources.push_back ((*chan)->write_source);
1871 Source::Lock lock((*chan)->write_source->mutex());
1872 (*chan)->write_source->mark_streaming_write_started (lock);
1880 AudioDiskstream::prep_record_disable ()
1882 boost::shared_ptr<ChannelList> c = channels.reader();
1883 if (Config->get_monitoring_model() == HardwareMonitoring) {
1884 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1885 (*chan)->source.request_input_monitoring (false);
1888 capturing_sources.clear ();
1894 AudioDiskstream::get_state ()
1896 XMLNode& node (Diskstream::get_state());
1900 boost::shared_ptr<ChannelList> c = channels.reader();
1901 snprintf (buf, sizeof(buf), "%u", (unsigned int) c->size());
1902 node.add_property ("channels", buf);
1904 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1906 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1907 XMLNode* cs_grandchild;
1909 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1910 cs_grandchild = new XMLNode (X_("file"));
1911 cs_grandchild->add_property (X_("path"), (*i)->path());
1912 cs_child->add_child_nocopy (*cs_grandchild);
1915 /* store the location where capture will start */
1919 if (_session.config.get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1920 snprintf (buf, sizeof (buf), "%" PRId64, pi->start());
1922 snprintf (buf, sizeof (buf), "%" PRId64, _session.transport_frame());
1925 cs_child->add_property (X_("at"), buf);
1926 node.add_child_nocopy (*cs_child);
1933 AudioDiskstream::set_state (const XMLNode& node, int version)
1935 XMLProperty const * prop;
1936 XMLNodeList nlist = node.children();
1937 XMLNodeIterator niter;
1938 uint32_t nchans = 1;
1939 XMLNode* capture_pending_node = 0;
1942 /* prevent write sources from being created */
1944 in_set_state = true;
1946 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1947 if ((*niter)->name() == IO::state_node_name) {
1948 deprecated_io_node = new XMLNode (**niter);
1951 if ((*niter)->name() == X_("CapturingSources")) {
1952 capture_pending_node = *niter;
1956 if (Diskstream::set_state (node, version)) {
1960 if ((prop = node.property ("channels")) != 0) {
1961 nchans = atoi (prop->value().c_str());
1964 // create necessary extra channels
1965 // we are always constructed with one and we always need one
1967 _n_channels.set(DataType::AUDIO, channels.reader()->size());
1969 if (nchans > _n_channels.n_audio()) {
1971 add_channel (nchans - _n_channels.n_audio());
1972 IO::PortCountChanged(_n_channels);
1974 } else if (nchans < _n_channels.n_audio()) {
1976 remove_channel (_n_channels.n_audio() - nchans);
1981 if (!destructive() && capture_pending_node) {
1982 /* destructive streams have one and only one source per channel,
1983 and so they never end up in pending capture in any useful
1986 use_pending_capture_data (*capture_pending_node);
1989 in_set_state = false;
1991 /* make sure this is clear before we do anything else */
1993 capturing_sources.clear ();
1995 /* write sources are handled when we handle the input set
1996 up of the IO that owns this DS (::non_realtime_input_change())
2003 AudioDiskstream::use_new_write_source (uint32_t n)
2005 boost::shared_ptr<ChannelList> c = channels.reader();
2007 if (!recordable()) {
2011 if (n >= c->size()) {
2012 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
2016 ChannelInfo* chan = (*c)[n];
2019 if ((chan->write_source = _session.create_audio_source_for_session (
2020 n_channels().n_audio(), write_source_name(), n, destructive())) == 0) {
2021 throw failed_constructor();
2025 catch (failed_constructor &err) {
2026 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
2027 chan->write_source.reset ();
2031 /* do not remove destructive files even if they are empty */
2033 chan->write_source->set_allow_remove_if_empty (!destructive());
2039 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool /*force*/)
2041 ChannelList::iterator chan;
2042 boost::shared_ptr<ChannelList> c = channels.reader();
2045 if (!_session.writable() || !recordable()) {
2049 capturing_sources.clear ();
2051 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
2053 if (!destructive()) {
2055 if ((*chan)->write_source) {
2057 if (mark_write_complete) {
2058 Source::Lock lock((*chan)->write_source->mutex());
2059 (*chan)->write_source->mark_streaming_write_completed (lock);
2060 (*chan)->write_source->done_with_peakfile_writes ();
2063 if ((*chan)->write_source->removable()) {
2064 (*chan)->write_source->mark_for_remove ();
2065 (*chan)->write_source->drop_references ();
2068 (*chan)->write_source.reset ();
2071 use_new_write_source (n);
2073 if (record_enabled()) {
2074 capturing_sources.push_back ((*chan)->write_source);
2079 if ((*chan)->write_source == 0) {
2080 use_new_write_source (n);
2085 if (destructive() && !c->empty ()) {
2087 /* we now have all our write sources set up, so create the
2088 playlist's single region.
2091 if (_playlist->empty()) {
2092 setup_destructive_playlist ();
2098 AudioDiskstream::set_block_size (pframes_t /*nframes*/)
2100 if (_session.get_block_size() > speed_buffer_size) {
2101 speed_buffer_size = _session.get_block_size();
2102 boost::shared_ptr<ChannelList> c = channels.reader();
2104 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2105 if ((*chan)->speed_buffer)
2106 delete [] (*chan)->speed_buffer;
2107 (*chan)->speed_buffer = new Sample[speed_buffer_size];
2110 allocate_temporary_buffers ();
2114 AudioDiskstream::allocate_temporary_buffers ()
2116 /* make sure the wrap buffer is at least large enough to deal
2117 with the speeds up to 1.2, to allow for micro-variation
2118 when slaving to MTC, Timecode etc.
2121 double const sp = max (fabs (_actual_speed), 1.2);
2122 framecnt_t required_wrap_size = (framecnt_t) ceil (_session.get_block_size() * sp) + 2;
2124 if (required_wrap_size > wrap_buffer_size) {
2126 boost::shared_ptr<ChannelList> c = channels.reader();
2128 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2129 if ((*chan)->playback_wrap_buffer) {
2130 delete [] (*chan)->playback_wrap_buffer;
2132 (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
2133 if ((*chan)->capture_wrap_buffer) {
2134 delete [] (*chan)->capture_wrap_buffer;
2136 (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
2139 wrap_buffer_size = required_wrap_size;
2144 AudioDiskstream::request_input_monitoring (bool yn)
2146 boost::shared_ptr<ChannelList> c = channels.reader();
2148 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2149 (*chan)->source.request_input_monitoring (yn);
2154 AudioDiskstream::set_align_style_from_io ()
2156 bool have_physical = false;
2158 if (_alignment_choice != Automatic) {
2166 get_input_sources ();
2168 boost::shared_ptr<ChannelList> c = channels.reader();
2170 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2171 if ((*chan)->source.is_physical ()) {
2172 have_physical = true;
2177 if (have_physical) {
2178 set_align_style (ExistingMaterial);
2180 set_align_style (CaptureTime);
2185 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2187 while (how_many--) {
2188 c->push_back (new ChannelInfo(
2189 _session.butler()->audio_diskstream_playback_buffer_size(),
2190 _session.butler()->audio_diskstream_capture_buffer_size(),
2191 speed_buffer_size, wrap_buffer_size));
2192 interpolation.add_channel_to (
2193 _session.butler()->audio_diskstream_playback_buffer_size(),
2197 _n_channels.set(DataType::AUDIO, c->size());
2203 AudioDiskstream::add_channel (uint32_t how_many)
2205 RCUWriter<ChannelList> writer (channels);
2206 boost::shared_ptr<ChannelList> c = writer.get_copy();
2208 return add_channel_to (c, how_many);
2212 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2214 while (how_many-- && !c->empty()) {
2217 interpolation.remove_channel_from ();
2220 _n_channels.set(DataType::AUDIO, c->size());
2226 AudioDiskstream::remove_channel (uint32_t how_many)
2228 RCUWriter<ChannelList> writer (channels);
2229 boost::shared_ptr<ChannelList> c = writer.get_copy();
2231 return remove_channel_from (c, how_many);
2235 AudioDiskstream::playback_buffer_load () const
2237 boost::shared_ptr<ChannelList> c = channels.reader();
2243 return (float) ((double) c->front()->playback_buf->read_space()/
2244 (double) c->front()->playback_buf->bufsize());
2248 AudioDiskstream::capture_buffer_load () const
2250 boost::shared_ptr<ChannelList> c = channels.reader();
2256 return (float) ((double) c->front()->capture_buf->write_space()/
2257 (double) c->front()->capture_buf->bufsize());
2261 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2263 XMLProperty const * prop;
2264 XMLNodeList nlist = node.children();
2265 XMLNodeIterator niter;
2266 boost::shared_ptr<AudioFileSource> fs;
2267 boost::shared_ptr<AudioFileSource> first_fs;
2268 SourceList pending_sources;
2269 framepos_t position;
2271 if ((prop = node.property (X_("at"))) == 0) {
2275 if (sscanf (prop->value().c_str(), "%" PRIu64, &position) != 1) {
2279 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2280 if ((*niter)->name() == X_("file")) {
2282 if ((prop = (*niter)->property (X_("path"))) == 0) {
2286 // This protects sessions from errant CapturingSources in stored sessions
2288 if (g_stat (prop->value().c_str(), &sbuf)) {
2292 /* XXX as of June 2014, we always record to mono
2293 files. Since this Source is being created as part of
2294 crash recovery, we know that we need the first
2295 channel (the final argument to the SourceFactory
2296 call below). If we ever support non-mono files for
2297 capture, this will need rethinking.
2301 fs = boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createForRecovery (DataType::AUDIO, _session, prop->value(), 0));
2304 catch (failed_constructor& err) {
2305 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2306 _name, prop->value())
2311 pending_sources.push_back (fs);
2313 if (first_fs == 0) {
2317 fs->set_captured_for (_name.val());
2321 if (pending_sources.size() == 0) {
2322 /* nothing can be done */
2326 if (pending_sources.size() != _n_channels.n_audio()) {
2327 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2334 boost::shared_ptr<AudioRegion> wf_region;
2335 boost::shared_ptr<AudioRegion> region;
2337 /* First create the whole file region */
2341 plist.add (Properties::start, 0);
2342 plist.add (Properties::length, first_fs->length (first_fs->timeline_position()));
2343 plist.add (Properties::name, region_name_from_path (first_fs->name(), true));
2345 wf_region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, plist));
2347 wf_region->set_automatic (true);
2348 wf_region->set_whole_file (true);
2349 wf_region->special_set_position (position);
2351 /* Now create a region that isn't the whole file for adding to
2354 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, plist));
2356 _playlist->add_region (region, position);
2359 catch (failed_constructor& err) {
2360 error << string_compose (
2361 _("%1: cannot create whole-file region from pending capture sources"),
2372 AudioDiskstream::set_non_layered (bool yn)
2374 if (yn != non_layered()) {
2377 _flags = Flag (_flags | NonLayered);
2379 _flags = Flag (_flags & ~NonLayered);
2387 AudioDiskstream::set_destructive (bool yn)
2389 if (yn != destructive()) {
2392 bool bounce_ignored;
2393 /* requestor should already have checked this and
2394 bounced if necessary and desired
2396 if (!can_become_destructive (bounce_ignored)) {
2399 _flags = Flag (_flags | Destructive);
2400 use_destructive_playlist ();
2402 _flags = Flag (_flags & ~Destructive);
2403 reset_write_sources (true, true);
2411 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2413 if (Profile->get_trx()) {
2418 requires_bounce = false;
2422 /* if no regions are present: easy */
2424 if (_playlist->n_regions() == 0) {
2425 requires_bounce = false;
2429 /* is there only one region ? */
2431 if (_playlist->n_regions() != 1) {
2432 requires_bounce = true;
2436 boost::shared_ptr<Region> first;
2438 const RegionList& rl (_playlist->region_list().rlist());
2439 assert((rl.size() == 1));
2445 requires_bounce = false;
2449 /* do the source(s) for the region cover the session start position ? */
2451 if (first->position() != _session.current_start_frame()) {
2452 // what is the idea here? why start() ??
2453 if (first->start() > _session.current_start_frame()) {
2454 requires_bounce = true;
2459 /* currently RouteTimeAxisView::set_track_mode does not
2460 * implement bounce. Existing regions cannot be converted.
2462 * so let's make sure this region is already set up
2463 * as tape-track (spanning the complete range)
2465 if (first->length() != max_framepos - first->position()) {
2466 requires_bounce = true;
2470 /* is the source used by only 1 playlist ? */
2472 boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2476 if (_session.playlists->source_use_count (afirst->source()) > 1) {
2477 requires_bounce = true;
2481 requires_bounce = false;
2486 AudioDiskstream::adjust_playback_buffering ()
2488 boost::shared_ptr<ChannelList> c = channels.reader();
2490 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2491 (*chan)->resize_playback (_session.butler()->audio_diskstream_playback_buffer_size());
2496 AudioDiskstream::adjust_capture_buffering ()
2498 boost::shared_ptr<ChannelList> c = channels.reader();
2500 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2501 (*chan)->resize_capture (_session.butler()->audio_diskstream_capture_buffer_size());
2506 AudioDiskstream::ChannelSource::is_physical () const
2512 return AudioEngine::instance()->port_is_physical (name);
2516 AudioDiskstream::ChannelSource::request_input_monitoring (bool yn) const
2522 return AudioEngine::instance()->request_input_monitoring (name, yn);
2525 AudioDiskstream::ChannelInfo::ChannelInfo (framecnt_t playback_bufsize, framecnt_t capture_bufsize, framecnt_t speed_size, framecnt_t wrap_size)
2527 current_capture_buffer = 0;
2528 current_playback_buffer = 0;
2529 curr_capture_cnt = 0;
2531 speed_buffer = new Sample[speed_size];
2532 playback_wrap_buffer = new Sample[wrap_size];
2533 capture_wrap_buffer = new Sample[wrap_size];
2535 playback_buf = new RingBufferNPT<Sample> (playback_bufsize);
2536 capture_buf = new RingBufferNPT<Sample> (capture_bufsize);
2537 capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2539 /* touch the ringbuffer buffers, which will cause
2540 them to be mapped into locked physical RAM if
2541 we're running with mlockall(). this doesn't do
2545 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2546 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2547 memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2551 AudioDiskstream::ChannelInfo::resize_playback (framecnt_t playback_bufsize)
2553 delete playback_buf;
2554 playback_buf = new RingBufferNPT<Sample> (playback_bufsize);
2555 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2559 AudioDiskstream::ChannelInfo::resize_capture (framecnt_t capture_bufsize)
2563 capture_buf = new RingBufferNPT<Sample> (capture_bufsize);
2564 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2567 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2570 if (write_source->removable()) {
2571 /* this is a "stub" write source which exists in the
2572 Session source list, but is removable. We must emit
2573 a drop references call because it should not
2574 continue to exist. If we do not do this, then the
2575 Session retains a reference to it, it is not
2576 deleted, and later attempts to create a new source
2577 file will use wierd naming because it already
2580 XXX longer term TO-DO: do not add to session source
2581 list until we write to the source.
2583 write_source->drop_references ();
2587 write_source.reset ();
2589 delete [] speed_buffer;
2592 delete [] playback_wrap_buffer;
2593 playback_wrap_buffer = 0;
2595 delete [] capture_wrap_buffer;
2596 capture_wrap_buffer = 0;
2598 delete playback_buf;
2604 delete capture_transition_buf;
2605 capture_transition_buf = 0;
2610 AudioDiskstream::set_name (string const & name)
2612 if (_name == name) {
2615 Diskstream::set_name (name);
2617 /* get a new write source so that its name reflects the new diskstream name */
2619 boost::shared_ptr<ChannelList> c = channels.reader();
2620 ChannelList::iterator i;
2623 for (n = 0, i = c->begin(); i != c->end(); ++i, ++n) {
2624 use_new_write_source (n);
2631 AudioDiskstream::set_write_source_name (const std::string& str) {
2632 if (_write_source_name == str) {
2636 Diskstream::set_write_source_name (str);
2638 if (_write_source_name == name()) {
2641 boost::shared_ptr<ChannelList> c = channels.reader();
2642 ChannelList::iterator i;
2645 for (n = 0, i = c->begin(); i != c->end(); ++i, ++n) {
2646 use_new_write_source (n);