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_property().rlist());
364 /* this can happen when dragging a region onto a tape track */
365 assert((rl.size() == 1));
371 reset_write_sources (false, true);
375 boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
378 throw failed_constructor();
381 /* be sure to stretch the region out to the maximum length (non-musical)*/
383 region->set_length (max_framepos - region->position(), 0);
386 ChannelList::iterator chan;
387 boost::shared_ptr<ChannelList> c = channels.reader();
389 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
390 (*chan)->write_source = boost::dynamic_pointer_cast<AudioFileSource>(region->source (n));
391 assert((*chan)->write_source);
392 (*chan)->write_source->set_allow_remove_if_empty (false);
394 /* this might be false if we switched modes, so force it */
396 #ifdef XXX_OLD_DESTRUCTIVE_API_XXX
397 (*chan)->write_source->set_destructive (true);
399 // should be set when creating the source or loading the state
400 assert ((*chan)->write_source->destructive());
404 /* the source list will never be reset for a destructive track */
408 AudioDiskstream::prepare_record_status(framepos_t capture_start_frame)
410 if (recordable() && destructive()) {
411 boost::shared_ptr<ChannelList> c = channels.reader();
412 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
414 RingBufferNPT<CaptureTransition>::rw_vector transitions;
415 (*chan)->capture_transition_buf->get_write_vector (&transitions);
417 if (transitions.len[0] > 0) {
418 transitions.buf[0]->type = CaptureStart;
419 transitions.buf[0]->capture_val = capture_start_frame;
420 (*chan)->capture_transition_buf->increment_write_ptr(1);
423 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
431 /** Do some record stuff [not described in this comment!]
434 * - Setup playback_distance with the nframes, or nframes adjusted
435 * for current varispeed, if appropriate.
436 * - Setup current_playback_buffer in each ChannelInfo to point to data
437 * that someone can read playback_distance worth of data from.
440 AudioDiskstream::process (BufferSet& bufs, framepos_t transport_frame, pframes_t nframes, framecnt_t& playback_distance, bool need_disk_signal)
443 boost::shared_ptr<ChannelList> c = channels.reader();
444 ChannelList::iterator chan;
445 framecnt_t rec_offset = 0;
446 framecnt_t rec_nframes = 0;
447 bool collect_playback = false;
448 bool can_record = _session.actively_recording ();
450 playback_distance = 0;
452 if (!_io || !_io->active()) {
456 check_record_status (transport_frame, can_record);
462 Glib::Threads::Mutex::Lock sm (state_lock, Glib::Threads::TRY_LOCK);
468 adjust_capture_position = 0;
470 for (chan = c->begin(); chan != c->end(); ++chan) {
471 (*chan)->current_capture_buffer = 0;
472 (*chan)->current_playback_buffer = 0;
475 // Safeguard against situations where process() goes haywire when autopunching
476 // and last_recordable_frame < first_recordable_frame
478 if (last_recordable_frame < first_recordable_frame) {
479 last_recordable_frame = max_framepos;
482 if (record_enabled()) {
484 Evoral::OverlapType ot = Evoral::coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
485 // XXX should this be transport_frame + nframes - 1 ? coverage() expects its parameter ranges to include their end points
486 // XXX also, first_recordable_frame & last_recordable_frame may both be == max_framepos: coverage() will return OverlapNone in that case. Is thak OK?
487 calculate_record_range (ot, transport_frame, nframes, rec_nframes, rec_offset);
489 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1: this time record %2 of %3 frames, offset %4\n", _name, rec_nframes, nframes, rec_offset));
491 if (rec_nframes && !was_recording) {
492 capture_captured = 0;
493 was_recording = true;
497 if (can_record && !_last_capture_sources.empty()) {
498 _last_capture_sources.clear ();
503 uint32_t limit = _io->n_ports ().n_audio();
505 /* one or more ports could already have been removed from _io, but our
506 channel setup hasn't yet been updated. prevent us from trying to
507 use channels that correspond to missing ports. note that the
508 process callback (from which this is called) is always atomic
509 with respect to port removal/addition.
512 for (n = 0, chan = c->begin(); chan != c->end() && n < limit; ++chan, ++n) {
514 ChannelInfo* chaninfo (*chan);
516 chaninfo->capture_buf->get_write_vector (&chaninfo->capture_vector);
518 if (rec_nframes <= (framecnt_t) chaninfo->capture_vector.len[0]) {
520 chaninfo->current_capture_buffer = chaninfo->capture_vector.buf[0];
522 /* note: grab the entire port buffer, but only copy what we were supposed to
523 for recording, and use rec_offset
526 boost::shared_ptr<AudioPort> const ap = _io->audio (n);
528 assert(rec_nframes <= (framecnt_t) ap->get_audio_buffer(nframes).capacity());
530 Sample *buf = bufs.get_audio (n).data(rec_offset);
531 memcpy (chaninfo->current_capture_buffer, buf, sizeof (Sample) * rec_nframes);
535 framecnt_t total = chaninfo->capture_vector.len[0] + chaninfo->capture_vector.len[1];
537 if (rec_nframes > total) {
538 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 overrun in %2, rec_nframes = %3 total space = %4\n",
539 DEBUG_THREAD_SELF, name(), rec_nframes, total));
544 boost::shared_ptr<AudioPort> const ap = _io->audio (n);
547 Sample *buf = bufs.get_audio (n).data(rec_offset);
548 framecnt_t first = chaninfo->capture_vector.len[0];
550 memcpy (chaninfo->capture_wrap_buffer, buf, sizeof (Sample) * first);
551 memcpy (chaninfo->capture_vector.buf[0], buf, sizeof (Sample) * first);
552 memcpy (chaninfo->capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
553 memcpy (chaninfo->capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
555 chaninfo->current_capture_buffer = chaninfo->capture_wrap_buffer;
569 /* data will be written to disk */
571 if (rec_nframes == nframes && rec_offset == 0) {
573 for (chan = c->begin(); chan != c->end(); ++chan) {
574 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
577 playback_distance = nframes;
582 /* we can't use the capture buffer as the playback buffer, because
583 we recorded only a part of the current process' cycle data
587 collect_playback = true;
590 adjust_capture_position = rec_nframes;
592 } else if (can_record && record_enabled()) {
594 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
596 for (chan = c->begin(); chan != c->end(); ++chan) {
597 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
600 playback_distance = nframes;
604 collect_playback = true;
607 if ((_track->monitoring_state () & MonitoringDisk) || collect_playback) {
609 /* we're doing playback */
611 framecnt_t necessary_samples;
613 /* no varispeed playback if we're recording, because the output .... TBD */
615 if (rec_nframes == 0 && _actual_speed != 1.0) {
616 necessary_samples = (framecnt_t) ceil ((nframes * fabs (_actual_speed))) + 2;
618 necessary_samples = nframes;
621 for (chan = c->begin(); chan != c->end(); ++chan) {
622 (*chan)->playback_buf->get_read_vector (&(*chan)->playback_vector);
627 /* Setup current_playback_buffer in each ChannelInfo to point to data that someone
628 can read necessary_samples (== nframes at a transport speed of 1) worth of data
632 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
634 ChannelInfo* chaninfo (*chan);
636 if (necessary_samples <= (framecnt_t) chaninfo->playback_vector.len[0]) {
637 /* There are enough samples in the first part of the ringbuffer */
638 chaninfo->current_playback_buffer = chaninfo->playback_vector.buf[0];
641 framecnt_t total = chaninfo->playback_vector.len[0] + chaninfo->playback_vector.len[1];
643 if (necessary_samples > total) {
644 cerr << _name << " Need " << necessary_samples << " total = " << total << endl;
645 cerr << "underrun for " << _name << endl;
646 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 underrun in %2, rec_nframes = %3 total space = %4\n",
647 DEBUG_THREAD_SELF, name(), rec_nframes, total));
653 /* We have enough samples, but not in one lump. Coalesce the two parts
654 into one in playback_wrap_buffer in our ChannelInfo, and specify that
655 as our current_playback_buffer.
658 assert(wrap_buffer_size >= necessary_samples);
660 /* Copy buf[0] from playback_buf */
661 memcpy ((char *) chaninfo->playback_wrap_buffer,
662 chaninfo->playback_vector.buf[0],
663 chaninfo->playback_vector.len[0] * sizeof (Sample));
665 /* Copy buf[1] from playback_buf */
666 memcpy (chaninfo->playback_wrap_buffer + chaninfo->playback_vector.len[0],
667 chaninfo->playback_vector.buf[1],
668 (necessary_samples - chaninfo->playback_vector.len[0])
671 chaninfo->current_playback_buffer = chaninfo->playback_wrap_buffer;
676 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
678 interpolation.set_speed (_target_speed);
681 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++channel) {
682 ChannelInfo* chaninfo (*chan);
684 playback_distance = interpolation.interpolate (
685 channel, nframes, chaninfo->current_playback_buffer, chaninfo->speed_buffer);
687 chaninfo->current_playback_buffer = chaninfo->speed_buffer;
691 playback_distance = nframes;
694 _speed = _target_speed;
697 if (need_disk_signal) {
699 /* copy data over to buffer set */
701 size_t n_buffers = bufs.count().n_audio();
702 size_t n_chans = c->size();
703 gain_t scaling = 1.0f;
705 if (n_chans > n_buffers) {
706 scaling = ((float) n_buffers)/n_chans;
709 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
711 AudioBuffer& buf (bufs.get_audio (n%n_buffers));
712 ChannelInfo* chaninfo (*chan);
715 if (scaling != 1.0f) {
716 buf.read_from_with_gain (chaninfo->current_playback_buffer, nframes, scaling);
718 buf.read_from (chaninfo->current_playback_buffer, nframes);
721 if (scaling != 1.0f) {
722 buf.accumulate_with_gain_from (chaninfo->current_playback_buffer, nframes, scaling);
724 buf.accumulate_from (chaninfo->current_playback_buffer, nframes);
729 /* leave the MIDI count alone */
730 ChanCount cnt (DataType::AUDIO, n_chans);
731 cnt.set (DataType::MIDI, bufs.count().n_midi());
732 bufs.set_count (cnt);
734 /* extra buffers will already be silent, so leave them alone */
741 AudioDiskstream::calculate_playback_distance (pframes_t nframes)
743 frameoffset_t playback_distance = nframes;
745 if (record_enabled()) {
746 playback_distance = nframes;
747 } else if (_actual_speed != 1.0f && _actual_speed != -1.0f) {
748 interpolation.set_speed (_target_speed);
749 boost::shared_ptr<ChannelList> c = channels.reader();
751 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++channel) {
752 playback_distance = interpolation.interpolate (channel, nframes, NULL, NULL);
755 playback_distance = nframes;
758 if (_actual_speed < 0.0) {
759 return -playback_distance;
761 return playback_distance;
765 /** Update various things including playback_sample, read pointer on each channel's playback_buf
766 * and write pointer on each channel's capture_buf. Also wout whether the butler is needed.
767 * @return true if the butler is required.
770 AudioDiskstream::commit (framecnt_t playback_distance)
772 bool need_butler = false;
774 if (!_io || !_io->active()) {
778 if (_actual_speed < 0.0) {
779 playback_sample -= playback_distance;
781 playback_sample += playback_distance;
784 boost::shared_ptr<ChannelList> c = channels.reader();
785 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
787 (*chan)->playback_buf->increment_read_ptr (playback_distance);
789 if (adjust_capture_position) {
790 (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
794 if (adjust_capture_position != 0) {
795 capture_captured += adjust_capture_position;
796 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1 now captured %2 (by %3)\n", name(), capture_captured, adjust_capture_position));
797 adjust_capture_position = 0;
805 if (_io && _io->active()) {
806 need_butler = c->front()->playback_buf->write_space() >= c->front()->playback_buf->bufsize() / 2;
811 if (_io && _io->active()) {
812 need_butler = ((framecnt_t) c->front()->playback_buf->write_space() >= disk_read_chunk_frames)
813 || ((framecnt_t) c->front()->capture_buf->read_space() >= disk_write_chunk_frames);
815 need_butler = ((framecnt_t) c->front()->capture_buf->read_space() >= disk_write_chunk_frames);
823 AudioDiskstream::set_pending_overwrite (bool yn)
825 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
827 _pending_overwrite = yn;
829 overwrite_frame = playback_sample;
831 boost::shared_ptr<ChannelList> c = channels.reader ();
833 overwrite_offset = c->front()->playback_buf->get_read_ptr();
838 AudioDiskstream::overwrite_existing_buffers ()
840 boost::shared_ptr<ChannelList> c = channels.reader();
842 _pending_overwrite = false;
846 Sample* mixdown_buffer;
849 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
851 overwrite_queued = false;
853 /* assume all are the same size */
854 framecnt_t size = c->front()->playback_buf->bufsize();
856 mixdown_buffer = new Sample[size];
857 gain_buffer = new float[size];
859 /* reduce size so that we can fill the buffer correctly (ringbuffers
860 can only handle size-1, otherwise they appear to be empty)
867 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
869 start = overwrite_frame;
870 framecnt_t cnt = size;
872 /* to fill the buffer without resetting the playback sample, we need to
873 do it one or two chunks (normally two).
875 |----------------------------------------------------------------------|
879 |<- second chunk->||<----------------- first chunk ------------------>|
883 framecnt_t to_read = size - overwrite_offset;
885 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, n, reversed)) {
886 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
887 id(), size, playback_sample) << endmsg;
895 if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer, start, cnt, n, reversed)) {
896 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
897 id(), size, playback_sample) << endmsg;
906 _pending_overwrite = false;
907 delete [] gain_buffer;
908 delete [] mixdown_buffer;
913 AudioDiskstream::seek (framepos_t frame, bool complete_refill)
917 ChannelList::iterator chan;
918 boost::shared_ptr<ChannelList> c = channels.reader();
920 Glib::Threads::Mutex::Lock lm (state_lock);
922 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
923 (*chan)->playback_buf->reset ();
924 (*chan)->capture_buf->reset ();
927 /* can't rec-enable in destructive mode if transport is before start */
929 if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
930 disengage_record_enable ();
933 playback_sample = frame;
936 if (complete_refill) {
937 /* call _do_refill() to refill the entire buffer, using
938 the largest reads possible.
940 while ((ret = do_refill_with_alloc (false)) > 0) ;
942 /* call _do_refill() to refill just one chunk, and then
945 ret = do_refill_with_alloc (true);
952 AudioDiskstream::can_internal_playback_seek (framecnt_t distance)
954 ChannelList::iterator chan;
955 boost::shared_ptr<ChannelList> c = channels.reader();
957 for (chan = c->begin(); chan != c->end(); ++chan) {
958 if ((*chan)->playback_buf->read_space() < (size_t) distance) {
966 AudioDiskstream::internal_playback_seek (framecnt_t distance)
968 ChannelList::iterator chan;
969 boost::shared_ptr<ChannelList> c = channels.reader();
971 for (chan = c->begin(); chan != c->end(); ++chan) {
972 (*chan)->playback_buf->increment_read_ptr (::llabs(distance));
975 if (first_recordable_frame < max_framepos) {
976 first_recordable_frame += distance;
978 playback_sample += distance;
983 /** Read some data for 1 channel from our playlist into a buffer.
984 * @param buf Buffer to write to.
985 * @param start Session frame to start reading from; updated to where we end up
987 * @param cnt Count of samples to read.
988 * @param reversed true if we are running backwards, otherwise false.
991 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer,
992 framepos_t& start, framecnt_t cnt,
993 int channel, bool reversed)
995 framecnt_t this_read = 0;
997 framepos_t loop_end = 0;
998 framepos_t loop_start = 0;
999 framecnt_t offset = 0;
1002 /* XXX we don't currently play loops in reverse. not sure why */
1006 framecnt_t loop_length = 0;
1008 /* Make the use of a Location atomic for this read operation.
1010 Note: Locations don't get deleted, so all we care about
1011 when I say "atomic" is that we are always pointing to
1012 the same one and using a start/length values obtained
1016 if ((loc = loop_location) != 0) {
1017 loop_start = loc->start();
1018 loop_end = loc->end();
1019 loop_length = loop_end - loop_start;
1022 /* if we are looping, ensure that the first frame we read is at the correct
1023 position within the loop.
1026 if (loc && start >= loop_end) {
1027 start = loop_start + ((start - loop_start) % loop_length);
1036 /* We need this while loop in case we hit a loop boundary, in which case our read from
1037 the playlist must be split into more than one section.
1042 /* take any loop into account. we can't read past the end of the loop. */
1044 if (loc && (loop_end - start < cnt)) {
1045 this_read = loop_end - start;
1052 if (this_read == 0) {
1056 this_read = min(cnt,this_read);
1058 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
1059 error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), id(), this_read,
1066 swap_by_ptr (buf, buf + this_read - 1);
1070 /* if we read to the end of the loop, go back to the beginning */
1080 offset += this_read;
1087 AudioDiskstream::_do_refill_with_alloc (bool partial_fill)
1089 /* We limit disk reads to at most 4MB chunks, which with floating point
1090 samples would be 1M samples. But we might use 16 or 14 bit samples,
1091 in which case 4MB is more samples than that. Therefore size this for
1092 the smallest sample value .. 4MB = 2M samples (16 bit).
1095 Sample* mix_buf = new Sample[2*1048576];
1096 float* gain_buf = new float[2*1048576];
1098 int ret = _do_refill (mix_buf, gain_buf, (partial_fill ? disk_read_chunk_frames : 0));
1106 /** Get some more data from disk and put it in our channels' playback_bufs,
1107 * if there is suitable space in them.
1109 * If fill_level is non-zero, then we will refill the buffer so that there is
1110 * still at least fill_level samples of space left to be filled. This is used
1111 * after locates so that we do not need to wait to fill the entire buffer.
1116 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer, framecnt_t fill_level)
1120 RingBufferNPT<Sample>::rw_vector vector;
1121 bool const reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1122 framecnt_t total_space;
1123 framecnt_t zero_fill;
1125 ChannelList::iterator i;
1126 boost::shared_ptr<ChannelList> c = channels.reader();
1129 /* do not read from disk while session is marked as Loading, to avoid
1130 useless redundant I/O.
1133 if (_session.state_of_the_state() & Session::Loading) {
1141 assert(mixdown_buffer);
1142 assert(gain_buffer);
1149 c->front()->playback_buf->get_write_vector (&vector);
1151 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1152 /* nowhere to write to */
1157 if (fill_level < total_space) {
1158 total_space -= fill_level;
1160 /* we can't do anything with it */
1165 /* if we're running close to normal speed and there isn't enough
1166 space to do disk_read_chunk_frames of I/O, then don't bother.
1168 at higher speeds, just do it because the sync between butler
1169 and audio thread may not be good enough.
1171 Note: it is a design assumption that disk_read_chunk_frames is smaller
1172 than the playback buffer size, so this check should never trip when
1173 the playback buffer is empty.
1176 if ((total_space < disk_read_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1180 /* when slaved, don't try to get too close to the read pointer. this
1181 leaves space for the buffer reversal to have something useful to
1185 if (_slaved && total_space < (framecnt_t) (c->front()->playback_buf->bufsize() / 2)) {
1191 if (file_frame == 0) {
1193 /* at start: 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 < total_space) {
1210 /* too close to the start: read what we can,
1211 and then zero fill the rest
1214 zero_fill = total_space - file_frame;
1215 total_space = file_frame;
1224 if (file_frame == max_framepos) {
1226 /* at end: nothing to do but fill with silence */
1228 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1230 ChannelInfo* chan (*i);
1231 chan->playback_buf->get_write_vector (&vector);
1232 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1233 if (vector.len[1]) {
1234 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1236 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1241 if (file_frame > max_framepos - total_space) {
1243 /* to close to the end: read what we can, and zero fill the rest */
1245 zero_fill = total_space - (max_framepos - file_frame);
1246 total_space = max_framepos - file_frame;
1253 framepos_t file_frame_tmp = 0;
1255 /* total_space is in samples. We want to optimize read sizes in various sizes using bytes */
1257 const size_t bits_per_sample = format_data_width (_session.config.get_native_file_data_format());
1258 size_t total_bytes = total_space * bits_per_sample / 8;
1260 /* chunk size range is 256kB to 4MB. Bigger is faster in terms of MB/sec, but bigger chunk size always takes longer
1262 size_t byte_size_for_read = max ((size_t) (256 * 1024), min ((size_t) (4 * 1048576), total_bytes));
1264 /* find nearest (lower) multiple of 16384 */
1266 byte_size_for_read = (byte_size_for_read / 16384) * 16384;
1268 /* now back to samples */
1270 framecnt_t samples_to_read = byte_size_for_read / (bits_per_sample / 8);
1272 //cerr << name() << " will read " << byte_size_for_read << " out of total bytes " << total_bytes << " in buffer of "
1273 // << c->front()->playback_buf->bufsize() * bits_per_sample / 8 << " bps = " << bits_per_sample << endl;
1274 // cerr << name () << " read samples = " << samples_to_read << " out of total space " << total_space << " in buffer of " << c->front()->playback_buf->bufsize() << " samples\n";
1276 // uint64_t before = g_get_monotonic_time ();
1277 // uint64_t elapsed;
1279 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1281 ChannelInfo* chan (*i);
1284 framecnt_t len1, len2;
1286 chan->playback_buf->get_write_vector (&vector);
1288 if ((framecnt_t) vector.len[0] > samples_to_read) {
1290 /* we're not going to fill the first chunk, so certainly do not bother with the
1291 other part. it won't be connected with the part we do fill, as in:
1293 .... => writable space
1294 ++++ => readable space
1295 ^^^^ => 1 x disk_read_chunk_frames that would be filled
1297 |......|+++++++++++++|...............................|
1302 So, just pretend that the buf1 part isn't there.
1312 file_frame_tmp = file_frame;
1314 buf1 = vector.buf[0];
1315 len1 = vector.len[0];
1316 buf2 = vector.buf[1];
1317 len2 = vector.len[1];
1319 to_read = min (ts, len1);
1320 to_read = min (to_read, (framecnt_t) samples_to_read);
1322 assert (to_read >= 0);
1326 if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1331 chan->playback_buf->increment_write_ptr (to_read);
1335 to_read = min (ts, len2);
1339 /* we read all of vector.len[0], but it wasn't the
1340 entire samples_to_read of data, so read some or
1341 all of vector.len[1] as well.
1344 if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1349 chan->playback_buf->increment_write_ptr (to_read);
1353 /* XXX: do something */
1358 // elapsed = g_get_monotonic_time () - before;
1359 // cerr << "\tbandwidth = " << (byte_size_for_read / 1048576.0) / (elapsed/1000000.0) << "MB/sec\n";
1361 file_frame = file_frame_tmp;
1362 assert (file_frame >= 0);
1364 ret = ((total_space - samples_to_read) > disk_read_chunk_frames);
1366 c->front()->playback_buf->get_write_vector (&vector);
1372 /** Flush pending data to disk.
1374 * Important note: this function will write *AT MOST* disk_write_chunk_frames
1375 * of data to disk. it will never write more than that. If it writes that
1376 * much and there is more than that waiting to be written, it will return 1,
1377 * otherwise 0 on success or -1 on failure.
1379 * If there is less than disk_write_chunk_frames to be written, no data will be
1380 * written at all unless @a force_flush is true.
1383 AudioDiskstream::do_flush (RunContext /*context*/, bool force_flush)
1387 RingBufferNPT<Sample>::rw_vector vector;
1388 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1391 transvec.buf[0] = 0;
1392 transvec.buf[1] = 0;
1396 boost::shared_ptr<ChannelList> c = channels.reader();
1397 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1399 (*chan)->capture_buf->get_read_vector (&vector);
1401 total = vector.len[0] + vector.len[1];
1403 if (total == 0 || (total < disk_write_chunk_frames && !force_flush && was_recording)) {
1407 /* if there are 2+ chunks of disk i/o possible for
1408 this track, let the caller know so that it can arrange
1409 for us to be called again, ASAP.
1411 if we are forcing a flush, then if there is* any* extra
1412 work, let the caller know.
1414 if we are no longer recording and there is any extra work,
1415 let the caller know too.
1418 if (total >= 2 * disk_write_chunk_frames || ((force_flush || !was_recording) && total > disk_write_chunk_frames)) {
1422 to_write = min (disk_write_chunk_frames, (framecnt_t) vector.len[0]);
1424 // check the transition buffer when recording destructive
1425 // important that we get this after the capture buf
1427 if (destructive()) {
1428 (*chan)->capture_transition_buf->get_read_vector(&transvec);
1429 size_t transcount = transvec.len[0] + transvec.len[1];
1432 for (ti=0; ti < transcount; ++ti) {
1433 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1435 if (captrans.type == CaptureStart) {
1436 // by definition, the first data we got above represents the given capture pos
1438 (*chan)->write_source->mark_capture_start (captrans.capture_val);
1439 (*chan)->curr_capture_cnt = 0;
1441 } else if (captrans.type == CaptureEnd) {
1443 // capture end, the capture_val represents total frames in capture
1445 if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1447 // shorten to make the write a perfect fit
1448 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
1450 if (nto_write < to_write) {
1451 ret = 1; // should we?
1453 to_write = nto_write;
1455 (*chan)->write_source->mark_capture_end ();
1457 // increment past this transition, but go no further
1462 // actually ends just beyond this chunk, so force more work
1470 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1474 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1475 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), id()) << endmsg;
1479 (*chan)->capture_buf->increment_read_ptr (to_write);
1480 (*chan)->curr_capture_cnt += to_write;
1482 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_write_chunk_frames) && !destructive()) {
1484 /* we wrote all of vector.len[0] but it wasn't an entire
1485 disk_write_chunk_frames of data, so arrange for some part
1486 of vector.len[1] to be flushed to disk as well.
1489 to_write = min ((framecnt_t)(disk_write_chunk_frames - to_write), (framecnt_t) vector.len[1]);
1491 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 additional write of %2\n", name(), to_write));
1493 if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1494 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), id()) << endmsg;
1498 (*chan)->capture_buf->increment_read_ptr (to_write);
1499 (*chan)->curr_capture_cnt += to_write;
1508 AudioDiskstream::transport_stopped_wallclock (struct tm& when, time_t twhen, bool abort_capture)
1510 uint32_t buffer_position;
1511 bool more_work = true;
1513 boost::shared_ptr<AudioRegion> region;
1514 framecnt_t total_capture;
1516 SourceList::iterator src;
1517 ChannelList::iterator chan;
1518 vector<CaptureInfo*>::iterator ci;
1519 boost::shared_ptr<ChannelList> c = channels.reader();
1521 bool mark_write_completed = false;
1525 /* butler is already stopped, but there may be work to do
1526 to flush remaining data to disk.
1529 while (more_work && !err) {
1530 switch (do_flush (TransportContext, true)) {
1537 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1542 /* XXX is there anything we can do if err != 0 ? */
1543 Glib::Threads::Mutex::Lock lm (capture_info_lock);
1545 if (capture_info.empty()) {
1549 if (abort_capture) {
1551 if (destructive()) {
1555 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1557 if ((*chan)->write_source) {
1559 (*chan)->write_source->mark_for_remove ();
1560 (*chan)->write_source->drop_references ();
1561 (*chan)->write_source.reset ();
1564 /* new source set up in "out" below */
1570 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1571 total_capture += (*ci)->frames;
1574 /* figure out the name for this take */
1576 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1578 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1582 s->update_header (capture_info.front()->start, when, twhen);
1583 s->set_captured_for (_name.val());
1584 s->mark_immutable ();
1586 if (Config->get_auto_analyse_audio()) {
1587 Analyser::queue_source_for_analysis (s, true);
1590 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("newly captured source %1 length %2\n", s->path(), s->length (0)));
1594 /* destructive tracks have a single, never changing region */
1596 if (destructive()) {
1598 /* send a signal that any UI can pick up to do the right thing. there is
1599 a small problem here in that a UI may need the peak data to be ready
1600 for the data that was recorded and this isn't interlocked with that
1601 process. this problem is deferred to the UI.
1604 _playlist->LayeringChanged(); // XXX this may not get the UI to do the right thing
1608 string whole_file_region_name;
1609 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1611 /* Register a new region with the Session that
1612 describes the entire source. Do this first
1613 so that any sub-regions will obviously be
1614 children of this one (later!)
1620 plist.add (Properties::start, c->front()->write_source->last_capture_start_frame());
1621 plist.add (Properties::length, total_capture);
1622 plist.add (Properties::name, whole_file_region_name);
1623 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1624 rx->set_automatic (true);
1625 rx->set_whole_file (true);
1627 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1628 region->special_set_position (capture_info.front()->start);
1632 catch (failed_constructor& err) {
1633 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1637 _last_capture_sources.insert (_last_capture_sources.end(), srcs.begin(), srcs.end());
1639 _playlist->clear_changes ();
1640 _playlist->set_capture_insertion_in_progress (true);
1641 _playlist->freeze ();
1643 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1647 RegionFactory::region_name (region_name, whole_file_region_name, false);
1649 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1 capture bufpos %5 start @ %2 length %3 add new region %4\n",
1650 _name, (*ci)->start, (*ci)->frames, region_name, buffer_position));
1656 plist.add (Properties::start, buffer_position);
1657 plist.add (Properties::length, (*ci)->frames);
1658 plist.add (Properties::name, region_name);
1660 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1661 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1664 catch (failed_constructor& err) {
1665 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1666 continue; /* XXX is this OK? */
1669 i_am_the_modifier++;
1671 _playlist->add_region (region, (*ci)->start, 1, non_layered());
1672 _playlist->set_layer (region, DBL_MAX);
1673 i_am_the_modifier--;
1675 buffer_position += (*ci)->frames;
1679 _playlist->set_capture_insertion_in_progress (false);
1680 _session.add_command (new StatefulDiffCommand (_playlist));
1683 mark_write_completed = true;
1686 reset_write_sources (mark_write_completed);
1690 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1694 capture_info.clear ();
1695 capture_start_frame = 0;
1699 AudioDiskstream::transport_looped (framepos_t transport_frame)
1701 if (was_recording) {
1702 // all we need to do is finish this capture, with modified capture length
1703 boost::shared_ptr<ChannelList> c = channels.reader();
1707 // the next region will start recording via the normal mechanism
1708 // we'll set the start position to the current transport pos
1709 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1710 capture_start_frame = transport_frame;
1711 first_recordable_frame = transport_frame; // mild lie
1712 last_recordable_frame = max_framepos;
1713 was_recording = true;
1715 if (recordable() && destructive()) {
1716 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1718 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1719 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1721 if (transvec.len[0] > 0) {
1722 transvec.buf[0]->type = CaptureStart;
1723 transvec.buf[0]->capture_val = capture_start_frame;
1724 (*chan)->capture_transition_buf->increment_write_ptr(1);
1728 fatal << X_("programming error: capture_transition_buf is full on rec loop! inconceivable!")
1738 AudioDiskstream::finish_capture (boost::shared_ptr<ChannelList> c)
1740 was_recording = false;
1741 first_recordable_frame = max_framepos;
1742 last_recordable_frame = max_framepos;
1744 if (capture_captured == 0) {
1748 if (recordable() && destructive()) {
1749 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1751 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1752 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1754 if (transvec.len[0] > 0) {
1755 transvec.buf[0]->type = CaptureEnd;
1756 transvec.buf[0]->capture_val = capture_captured;
1757 (*chan)->capture_transition_buf->increment_write_ptr(1);
1761 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1767 CaptureInfo* ci = new CaptureInfo;
1769 ci->start = capture_start_frame;
1770 ci->frames = capture_captured;
1772 /* XXX theoretical race condition here. Need atomic exchange ?
1773 However, the circumstances when this is called right
1774 now (either on record-disable or transport_stopped)
1775 mean that no actual race exists. I think ...
1776 We now have a capture_info_lock, but it is only to be used
1777 to synchronize in the transport_stop and the capture info
1778 accessors, so that invalidation will not occur (both non-realtime).
1781 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("Finish capture, add new CI, %1 + %2\n", ci->start, ci->frames));
1783 capture_info.push_back (ci);
1784 capture_captured = 0;
1786 /* now we've finished a capture, reset first_recordable_frame for next time */
1787 first_recordable_frame = max_framepos;
1791 AudioDiskstream::set_record_enabled (bool yn)
1793 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0 || record_safe ()) {
1797 /* can't rec-enable in destructive mode if transport is before start */
1799 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1803 /* yes, i know that this not proof against race conditions, but its
1804 good enough. i think.
1807 if (record_enabled() != yn) {
1809 engage_record_enable ();
1811 disengage_record_enable ();
1814 RecordEnableChanged (); /* EMIT SIGNAL */
1819 AudioDiskstream::set_record_safe (bool yn)
1821 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0) {
1825 /* can't rec-safe in destructive mode if transport is before start ????
1828 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1832 /* yes, i know that this not proof against race conditions, but its
1833 good enough. i think.
1836 if (record_safe () != yn) {
1838 engage_record_safe ();
1840 disengage_record_safe ();
1843 RecordSafeChanged (); /* EMIT SIGNAL */
1848 AudioDiskstream::prep_record_enable ()
1850 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0 || record_safe ()) { // REQUIRES REVIEW "|| record_safe ()"
1854 /* can't rec-enable in destructive mode if transport is before start */
1856 if (destructive() && _session.transport_frame() < _session.current_start_frame()) {
1860 bool rolling = _session.transport_speed() != 0.0f;
1861 boost::shared_ptr<ChannelList> c = channels.reader();
1863 capturing_sources.clear ();
1865 if (Config->get_monitoring_model() == HardwareMonitoring) {
1867 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1868 (*chan)->source.request_input_monitoring (!(_session.config.get_auto_input() && rolling));
1869 capturing_sources.push_back ((*chan)->write_source);
1870 Source::Lock lock((*chan)->write_source->mutex());
1871 (*chan)->write_source->mark_streaming_write_started (lock);
1875 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1876 capturing_sources.push_back ((*chan)->write_source);
1877 Source::Lock lock((*chan)->write_source->mutex());
1878 (*chan)->write_source->mark_streaming_write_started (lock);
1886 AudioDiskstream::prep_record_disable ()
1888 boost::shared_ptr<ChannelList> c = channels.reader();
1889 if (Config->get_monitoring_model() == HardwareMonitoring) {
1890 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1891 (*chan)->source.request_input_monitoring (false);
1894 capturing_sources.clear ();
1900 AudioDiskstream::get_state ()
1902 XMLNode& node (Diskstream::get_state());
1906 boost::shared_ptr<ChannelList> c = channels.reader();
1907 snprintf (buf, sizeof(buf), "%u", (unsigned int) c->size());
1908 node.add_property ("channels", buf);
1910 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1912 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1913 XMLNode* cs_grandchild;
1915 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1916 cs_grandchild = new XMLNode (X_("file"));
1917 cs_grandchild->add_property (X_("path"), (*i)->path());
1918 cs_child->add_child_nocopy (*cs_grandchild);
1921 /* store the location where capture will start */
1925 if (_session.config.get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1926 snprintf (buf, sizeof (buf), "%" PRId64, pi->start());
1928 snprintf (buf, sizeof (buf), "%" PRId64, _session.transport_frame());
1931 cs_child->add_property (X_("at"), buf);
1932 node.add_child_nocopy (*cs_child);
1939 AudioDiskstream::set_state (const XMLNode& node, int version)
1941 XMLProperty const * prop;
1942 XMLNodeList nlist = node.children();
1943 XMLNodeIterator niter;
1944 uint32_t nchans = 1;
1945 XMLNode* capture_pending_node = 0;
1948 /* prevent write sources from being created */
1950 in_set_state = true;
1952 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1953 if ((*niter)->name() == IO::state_node_name) {
1954 deprecated_io_node = new XMLNode (**niter);
1957 if ((*niter)->name() == X_("CapturingSources")) {
1958 capture_pending_node = *niter;
1962 if (Diskstream::set_state (node, version)) {
1966 if ((prop = node.property ("channels")) != 0) {
1967 nchans = atoi (prop->value().c_str());
1970 // create necessary extra channels
1971 // we are always constructed with one and we always need one
1973 _n_channels.set(DataType::AUDIO, channels.reader()->size());
1975 if (nchans > _n_channels.n_audio()) {
1977 add_channel (nchans - _n_channels.n_audio());
1978 IO::PortCountChanged(_n_channels);
1980 } else if (nchans < _n_channels.n_audio()) {
1982 remove_channel (_n_channels.n_audio() - nchans);
1987 if (!destructive() && capture_pending_node) {
1988 /* destructive streams have one and only one source per channel,
1989 and so they never end up in pending capture in any useful
1992 use_pending_capture_data (*capture_pending_node);
1995 in_set_state = false;
1997 /* make sure this is clear before we do anything else */
1999 capturing_sources.clear ();
2001 /* write sources are handled when we handle the input set
2002 up of the IO that owns this DS (::non_realtime_input_change())
2009 AudioDiskstream::use_new_write_source (uint32_t n)
2011 boost::shared_ptr<ChannelList> c = channels.reader();
2013 if (!recordable()) {
2017 if (n >= c->size()) {
2018 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
2022 ChannelInfo* chan = (*c)[n];
2025 if ((chan->write_source = _session.create_audio_source_for_session (
2026 n_channels().n_audio(), write_source_name(), n, destructive())) == 0) {
2027 throw failed_constructor();
2031 catch (failed_constructor &err) {
2032 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
2033 chan->write_source.reset ();
2037 /* do not remove destructive files even if they are empty */
2039 chan->write_source->set_allow_remove_if_empty (!destructive());
2045 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool /*force*/)
2047 ChannelList::iterator chan;
2048 boost::shared_ptr<ChannelList> c = channels.reader();
2051 if (!_session.writable() || !recordable()) {
2055 capturing_sources.clear ();
2057 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
2059 if (!destructive()) {
2061 if ((*chan)->write_source) {
2063 if (mark_write_complete) {
2064 Source::Lock lock((*chan)->write_source->mutex());
2065 (*chan)->write_source->mark_streaming_write_completed (lock);
2066 (*chan)->write_source->done_with_peakfile_writes ();
2069 if ((*chan)->write_source->removable()) {
2070 (*chan)->write_source->mark_for_remove ();
2071 (*chan)->write_source->drop_references ();
2074 (*chan)->write_source.reset ();
2077 use_new_write_source (n);
2079 if (record_enabled()) {
2080 capturing_sources.push_back ((*chan)->write_source);
2085 if ((*chan)->write_source == 0) {
2086 use_new_write_source (n);
2091 if (destructive() && !c->empty ()) {
2093 /* we now have all our write sources set up, so create the
2094 playlist's single region.
2097 if (_playlist->empty()) {
2098 setup_destructive_playlist ();
2104 AudioDiskstream::set_block_size (pframes_t /*nframes*/)
2106 if (_session.get_block_size() > speed_buffer_size) {
2107 speed_buffer_size = _session.get_block_size();
2108 boost::shared_ptr<ChannelList> c = channels.reader();
2110 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2111 if ((*chan)->speed_buffer)
2112 delete [] (*chan)->speed_buffer;
2113 (*chan)->speed_buffer = new Sample[speed_buffer_size];
2116 allocate_temporary_buffers ();
2120 AudioDiskstream::allocate_temporary_buffers ()
2122 /* make sure the wrap buffer is at least large enough to deal
2123 with the speeds up to 1.2, to allow for micro-variation
2124 when slaving to MTC, Timecode etc.
2127 double const sp = max (fabs (_actual_speed), 1.2);
2128 framecnt_t required_wrap_size = (framecnt_t) ceil (_session.get_block_size() * sp) + 2;
2130 if (required_wrap_size > wrap_buffer_size) {
2132 boost::shared_ptr<ChannelList> c = channels.reader();
2134 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2135 if ((*chan)->playback_wrap_buffer) {
2136 delete [] (*chan)->playback_wrap_buffer;
2138 (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
2139 if ((*chan)->capture_wrap_buffer) {
2140 delete [] (*chan)->capture_wrap_buffer;
2142 (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
2145 wrap_buffer_size = required_wrap_size;
2150 AudioDiskstream::request_input_monitoring (bool yn)
2152 boost::shared_ptr<ChannelList> c = channels.reader();
2154 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2155 (*chan)->source.request_input_monitoring (yn);
2160 AudioDiskstream::set_align_style_from_io ()
2162 bool have_physical = false;
2164 if (_alignment_choice != Automatic) {
2172 get_input_sources ();
2174 boost::shared_ptr<ChannelList> c = channels.reader();
2176 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2177 if ((*chan)->source.is_physical ()) {
2178 have_physical = true;
2184 // compensate for latency when bouncing from master or mixbus.
2185 // we need to use "ExistingMaterial" to pick up the master bus' latency
2186 // see also Route::direct_feeds_according_to_reality
2188 ios.push_back (_io);
2189 if (_session.master_out() && ios.fed_by (_session.master_out()->output())) {
2190 have_physical = true;
2192 for (uint32_t n = 0; n < NUM_MIXBUSES && !have_physical; ++n) {
2193 if (_session.get_mixbus (n) && ios.fed_by (_session.get_mixbus(n)->output())) {
2194 have_physical = true;
2199 if (have_physical) {
2200 set_align_style (ExistingMaterial);
2202 set_align_style (CaptureTime);
2207 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2209 while (how_many--) {
2210 c->push_back (new ChannelInfo(
2211 _session.butler()->audio_diskstream_playback_buffer_size(),
2212 _session.butler()->audio_diskstream_capture_buffer_size(),
2213 speed_buffer_size, wrap_buffer_size));
2214 interpolation.add_channel_to (
2215 _session.butler()->audio_diskstream_playback_buffer_size(),
2219 _n_channels.set(DataType::AUDIO, c->size());
2225 AudioDiskstream::add_channel (uint32_t how_many)
2227 RCUWriter<ChannelList> writer (channels);
2228 boost::shared_ptr<ChannelList> c = writer.get_copy();
2230 return add_channel_to (c, how_many);
2234 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2236 while (how_many-- && !c->empty()) {
2239 interpolation.remove_channel_from ();
2242 _n_channels.set(DataType::AUDIO, c->size());
2248 AudioDiskstream::remove_channel (uint32_t how_many)
2250 RCUWriter<ChannelList> writer (channels);
2251 boost::shared_ptr<ChannelList> c = writer.get_copy();
2253 return remove_channel_from (c, how_many);
2257 AudioDiskstream::playback_buffer_load () const
2259 boost::shared_ptr<ChannelList> c = channels.reader();
2265 return (float) ((double) c->front()->playback_buf->read_space()/
2266 (double) c->front()->playback_buf->bufsize());
2270 AudioDiskstream::capture_buffer_load () const
2272 boost::shared_ptr<ChannelList> c = channels.reader();
2278 return (float) ((double) c->front()->capture_buf->write_space()/
2279 (double) c->front()->capture_buf->bufsize());
2283 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2285 XMLProperty const * prop;
2286 XMLNodeList nlist = node.children();
2287 XMLNodeIterator niter;
2288 boost::shared_ptr<AudioFileSource> fs;
2289 boost::shared_ptr<AudioFileSource> first_fs;
2290 SourceList pending_sources;
2291 framepos_t position;
2293 if ((prop = node.property (X_("at"))) == 0) {
2297 if (sscanf (prop->value().c_str(), "%" PRIu64, &position) != 1) {
2301 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2302 if ((*niter)->name() == X_("file")) {
2304 if ((prop = (*niter)->property (X_("path"))) == 0) {
2308 // This protects sessions from errant CapturingSources in stored sessions
2310 if (g_stat (prop->value().c_str(), &sbuf)) {
2314 /* XXX as of June 2014, we always record to mono
2315 files. Since this Source is being created as part of
2316 crash recovery, we know that we need the first
2317 channel (the final argument to the SourceFactory
2318 call below). If we ever support non-mono files for
2319 capture, this will need rethinking.
2323 fs = boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createForRecovery (DataType::AUDIO, _session, prop->value(), 0));
2326 catch (failed_constructor& err) {
2327 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2328 _name, prop->value())
2333 pending_sources.push_back (fs);
2335 if (first_fs == 0) {
2339 fs->set_captured_for (_name.val());
2343 if (pending_sources.size() == 0) {
2344 /* nothing can be done */
2348 if (pending_sources.size() != _n_channels.n_audio()) {
2349 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2356 boost::shared_ptr<AudioRegion> wf_region;
2357 boost::shared_ptr<AudioRegion> region;
2359 /* First create the whole file region */
2363 plist.add (Properties::start, 0);
2364 plist.add (Properties::length, first_fs->length (first_fs->timeline_position()));
2365 plist.add (Properties::name, region_name_from_path (first_fs->name(), true));
2367 wf_region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, plist));
2369 wf_region->set_automatic (true);
2370 wf_region->set_whole_file (true);
2371 wf_region->special_set_position (position);
2373 /* Now create a region that isn't the whole file for adding to
2376 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, plist));
2378 _playlist->add_region (region, position);
2381 catch (failed_constructor& err) {
2382 error << string_compose (
2383 _("%1: cannot create whole-file region from pending capture sources"),
2393 #ifdef XXX_OLD_DESTRUCTIVE_API_XXX
2395 AudioDiskstream::set_non_layered (bool yn)
2397 if (yn != non_layered()) {
2400 _flags = Flag (_flags | NonLayered);
2402 _flags = Flag (_flags & ~NonLayered);
2410 AudioDiskstream::set_destructive (bool yn)
2412 if (yn != destructive()) {
2415 bool bounce_ignored;
2416 /* requestor should already have checked this and
2417 bounced if necessary and desired
2419 if (!can_become_destructive (bounce_ignored)) {
2422 _flags = Flag (_flags | Destructive);
2423 use_destructive_playlist ();
2425 _flags = Flag (_flags & ~Destructive);
2426 reset_write_sources (true, true);
2434 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2436 if (Profile->get_trx()) {
2441 requires_bounce = false;
2445 /* if no regions are present: easy */
2447 if (_playlist->n_regions() == 0) {
2448 requires_bounce = false;
2452 /* is there only one region ? */
2454 if (_playlist->n_regions() != 1) {
2455 requires_bounce = true;
2459 boost::shared_ptr<Region> first;
2461 const RegionList& rl (_playlist->region_list_property().rlist());
2462 assert((rl.size() == 1));
2468 requires_bounce = false;
2472 /* do the source(s) for the region cover the session start position ? */
2474 if (first->position() != _session.current_start_frame()) {
2475 // what is the idea here? why start() ??
2476 if (first->start() > _session.current_start_frame()) {
2477 requires_bounce = true;
2482 /* currently RouteTimeAxisView::set_track_mode does not
2483 * implement bounce. Existing regions cannot be converted.
2485 * so let's make sure this region is already set up
2486 * as tape-track (spanning the complete range)
2488 if (first->length() != max_framepos - first->position()) {
2489 requires_bounce = true;
2493 /* is the source used by only 1 playlist ? */
2495 boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2499 if (_session.playlists->source_use_count (afirst->source()) > 1) {
2500 requires_bounce = true;
2504 requires_bounce = false;
2510 AudioDiskstream::adjust_playback_buffering ()
2512 boost::shared_ptr<ChannelList> c = channels.reader();
2514 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2515 (*chan)->resize_playback (_session.butler()->audio_diskstream_playback_buffer_size());
2520 AudioDiskstream::adjust_capture_buffering ()
2522 boost::shared_ptr<ChannelList> c = channels.reader();
2524 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2525 (*chan)->resize_capture (_session.butler()->audio_diskstream_capture_buffer_size());
2530 AudioDiskstream::ChannelSource::is_physical () const
2536 return AudioEngine::instance()->port_is_physical (name);
2540 AudioDiskstream::ChannelSource::request_input_monitoring (bool yn) const
2546 return AudioEngine::instance()->request_input_monitoring (name, yn);
2549 AudioDiskstream::ChannelInfo::ChannelInfo (framecnt_t playback_bufsize, framecnt_t capture_bufsize, framecnt_t speed_size, framecnt_t wrap_size)
2551 current_capture_buffer = 0;
2552 current_playback_buffer = 0;
2553 curr_capture_cnt = 0;
2555 speed_buffer = new Sample[speed_size];
2556 playback_wrap_buffer = new Sample[wrap_size];
2557 capture_wrap_buffer = new Sample[wrap_size];
2559 playback_buf = new RingBufferNPT<Sample> (playback_bufsize);
2560 capture_buf = new RingBufferNPT<Sample> (capture_bufsize);
2561 capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2563 /* touch the ringbuffer buffers, which will cause
2564 them to be mapped into locked physical RAM if
2565 we're running with mlockall(). this doesn't do
2569 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2570 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2571 memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2575 AudioDiskstream::ChannelInfo::resize_playback (framecnt_t playback_bufsize)
2577 delete playback_buf;
2578 playback_buf = new RingBufferNPT<Sample> (playback_bufsize);
2579 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2583 AudioDiskstream::ChannelInfo::resize_capture (framecnt_t capture_bufsize)
2587 capture_buf = new RingBufferNPT<Sample> (capture_bufsize);
2588 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2591 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2594 if (write_source->removable()) {
2595 /* this is a "stub" write source which exists in the
2596 Session source list, but is removable. We must emit
2597 a drop references call because it should not
2598 continue to exist. If we do not do this, then the
2599 Session retains a reference to it, it is not
2600 deleted, and later attempts to create a new source
2601 file will use wierd naming because it already
2604 XXX longer term TO-DO: do not add to session source
2605 list until we write to the source.
2607 write_source->drop_references ();
2611 write_source.reset ();
2613 delete [] speed_buffer;
2616 delete [] playback_wrap_buffer;
2617 playback_wrap_buffer = 0;
2619 delete [] capture_wrap_buffer;
2620 capture_wrap_buffer = 0;
2622 delete playback_buf;
2628 delete capture_transition_buf;
2629 capture_transition_buf = 0;
2634 AudioDiskstream::set_name (string const & name)
2636 if (_name == name) {
2639 Diskstream::set_name (name);
2641 /* get a new write source so that its name reflects the new diskstream name */
2643 boost::shared_ptr<ChannelList> c = channels.reader();
2644 ChannelList::iterator i;
2647 for (n = 0, i = c->begin(); i != c->end(); ++i, ++n) {
2648 use_new_write_source (n);
2655 AudioDiskstream::set_write_source_name (const std::string& str) {
2656 if (_write_source_name == str) {
2660 Diskstream::set_write_source_name (str);
2662 if (_write_source_name == name()) {
2665 boost::shared_ptr<ChannelList> c = channels.reader();
2666 ChannelList::iterator i;
2669 for (n = 0, i = c->begin(); i != c->end(); ++i, ++n) {
2670 use_new_write_source (n);