2 Copyright (C) 2000-2006 Paul Davis
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
31 #include <pbd/gstdio_compat.h>
32 #include "pbd/error.h"
33 #include "pbd/xml++.h"
34 #include "pbd/memento_command.h"
35 #include "pbd/enumwriter.h"
36 #include "pbd/stateful_diff_command.h"
38 #include "ardour/analyser.h"
39 #include "ardour/audio_buffer.h"
40 #include "ardour/audio_diskstream.h"
41 #include "ardour/audio_port.h"
42 #include "ardour/audioengine.h"
43 #include "ardour/audiofilesource.h"
44 #include "ardour/audioplaylist.h"
45 #include "ardour/audioregion.h"
46 #include "ardour/butler.h"
47 #include "ardour/debug.h"
48 #include "ardour/io.h"
49 #include "ardour/playlist_factory.h"
50 #include "ardour/profile.h"
51 #include "ardour/region_factory.h"
52 #include "ardour/session.h"
53 #include "ardour/session_playlists.h"
54 #include "ardour/sndfile_helpers.h"
55 #include "ardour/source_factory.h"
56 #include "ardour/track.h"
57 #include "ardour/types.h"
58 #include "ardour/utils.h"
64 using namespace ARDOUR;
67 Sample* AudioDiskstream::_mixdown_buffer = 0;
68 gain_t* AudioDiskstream::_gain_buffer = 0;
70 AudioDiskstream::AudioDiskstream (Session &sess, const string &name, Diskstream::Flag flag)
71 : Diskstream(sess, name, flag)
72 , channels (new ChannelList)
74 /* prevent any write sources from being created */
80 if (flag & Destructive) {
81 use_destructive_playlist ();
85 AudioDiskstream::AudioDiskstream (Session& sess, const XMLNode& node)
86 : Diskstream(sess, node)
87 , channels (new ChannelList)
92 if (set_state (node, Stateful::loading_state_version)) {
94 throw failed_constructor();
100 use_destructive_playlist ();
105 AudioDiskstream::init ()
107 /* there are no channels at this point, so these
108 two calls just get speed_buffer_size and wrap_buffer
109 size setup without duplicating their code.
112 set_block_size (_session.get_block_size());
113 allocate_temporary_buffers ();
116 AudioDiskstream::~AudioDiskstream ()
118 DEBUG_TRACE (DEBUG::Destruction, string_compose ("Audio Diskstream %1 destructor\n", _name));
121 RCUWriter<ChannelList> writer (channels);
122 boost::shared_ptr<ChannelList> c = writer.get_copy();
124 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
135 AudioDiskstream::allocate_working_buffers()
137 /* with varifill buffer refilling, we compute the read size in bytes (to optimize
138 for disk i/o bandwidth) and then convert back into samples. These buffers
139 need to reflect the maximum size we could use, which is 4MB reads, or 2M samples
140 using 16 bit samples.
142 _mixdown_buffer = new Sample[2*1048576];
143 _gain_buffer = new gain_t[2*1048576];
147 AudioDiskstream::free_working_buffers()
149 delete [] _mixdown_buffer;
150 delete [] _gain_buffer;
156 AudioDiskstream::non_realtime_input_change ()
158 bool need_write_sources = false;
161 Glib::Threads::Mutex::Lock lm (state_lock);
163 if (input_change_pending.type == IOChange::NoChange) {
167 boost::shared_ptr<ChannelList> cr = channels.reader();
168 if (!cr->empty() && !cr->front()->write_source) {
169 need_write_sources = true;
172 if (input_change_pending.type == IOChange::ConfigurationChanged) {
173 RCUWriter<ChannelList> writer (channels);
174 boost::shared_ptr<ChannelList> c = writer.get_copy();
176 _n_channels.set(DataType::AUDIO, c->size());
178 if (_io->n_ports().n_audio() > _n_channels.n_audio()) {
179 add_channel_to (c, _io->n_ports().n_audio() - _n_channels.n_audio());
180 } else if (_io->n_ports().n_audio() < _n_channels.n_audio()) {
181 remove_channel_from (c, _n_channels.n_audio() - _io->n_ports().n_audio());
184 need_write_sources = true;
187 if (input_change_pending.type & IOChange::ConnectionsChanged) {
188 get_input_sources ();
189 set_capture_offset ();
190 set_align_style_from_io ();
193 input_change_pending = IOChange::NoChange;
195 /* implicit unlock */
198 if (need_write_sources) {
199 reset_write_sources (false);
202 /* now refill channel buffers */
204 if (speed() != 1.0f || speed() != -1.0f) {
205 seek ((framepos_t) (_session.transport_frame() * (double) speed()));
207 seek (_session.transport_frame());
212 AudioDiskstream::non_realtime_locate (framepos_t location)
214 /* now refill channel buffers */
216 if (speed() != 1.0f || speed() != -1.0f) {
217 seek ((framepos_t) (location * (double) speed()), true);
219 seek (location, true);
224 AudioDiskstream::get_input_sources ()
226 boost::shared_ptr<ChannelList> c = channels.reader();
229 ChannelList::iterator chan;
230 uint32_t ni = _io->n_ports().n_audio();
231 vector<string> connections;
233 for (n = 0, chan = c->begin(); chan != c->end() && n < ni; ++chan, ++n) {
235 connections.clear ();
237 if ((_io->nth (n).get()) && (_io->nth (n)->get_connections (connections) == 0)) {
238 if (!(*chan)->source.name.empty()) {
239 // _source->disable_metering ();
241 (*chan)->source.name = string();
243 (*chan)->source.name = connections[0];
249 AudioDiskstream::find_and_use_playlist (const string& name)
251 boost::shared_ptr<AudioPlaylist> playlist;
253 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (_session.playlists->by_name (name))) == 0) {
254 playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, name));
258 error << string_compose(_("AudioDiskstream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
262 return use_playlist (playlist);
266 AudioDiskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
268 assert(boost::dynamic_pointer_cast<AudioPlaylist>(playlist));
270 Diskstream::use_playlist(playlist);
276 AudioDiskstream::use_new_playlist ()
279 boost::shared_ptr<AudioPlaylist> playlist;
281 if (!in_set_state && destructive()) {
286 newname = Playlist::bump_name (_playlist->name(), _session);
288 newname = Playlist::bump_name (_name, _session);
291 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, newname, hidden()))) != 0) {
293 return use_playlist (playlist);
301 AudioDiskstream::use_copy_playlist ()
303 assert(audio_playlist());
309 if (_playlist == 0) {
310 error << string_compose(_("AudioDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
315 boost::shared_ptr<AudioPlaylist> playlist;
317 newname = Playlist::bump_name (_playlist->name(), _session);
319 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist>(PlaylistFactory::create (audio_playlist(), newname))) != 0) {
320 return use_playlist (playlist);
327 AudioDiskstream::setup_destructive_playlist ()
330 boost::shared_ptr<ChannelList> c = channels.reader();
332 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
333 srcs.push_back ((*chan)->write_source);
336 /* a single full-sized region */
338 assert (!srcs.empty ());
341 plist.add (Properties::name, _name.val());
342 plist.add (Properties::start, 0);
343 plist.add (Properties::length, max_framepos - srcs.front()->natural_position());
345 boost::shared_ptr<Region> region (RegionFactory::create (srcs, plist));
346 _playlist->add_region (region, srcs.front()->natural_position());
348 /* apply region properties and update write sources */
349 use_destructive_playlist();
353 AudioDiskstream::use_destructive_playlist ()
355 /* this is called from the XML-based constructor or ::set_destructive. when called,
356 we already have a playlist and a region, but we need to
357 set up our sources for write. we use the sources associated
358 with the (presumed single, full-extent) region.
361 boost::shared_ptr<Region> rp;
363 const RegionList& rl (_playlist->region_list().rlist());
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 */
383 region->set_length (max_framepos - region->position());
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 (*chan)->write_source->set_destructive (true);
399 /* the source list will never be reset for a destructive track */
403 AudioDiskstream::prepare_record_status(framepos_t capture_start_frame)
405 if (recordable() && destructive()) {
406 boost::shared_ptr<ChannelList> c = channels.reader();
407 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
409 RingBufferNPT<CaptureTransition>::rw_vector transitions;
410 (*chan)->capture_transition_buf->get_write_vector (&transitions);
412 if (transitions.len[0] > 0) {
413 transitions.buf[0]->type = CaptureStart;
414 transitions.buf[0]->capture_val = capture_start_frame;
415 (*chan)->capture_transition_buf->increment_write_ptr(1);
418 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
426 /** Do some record stuff [not described in this comment!]
429 * - Setup playback_distance with the nframes, or nframes adjusted
430 * for current varispeed, if appropriate.
431 * - Setup current_playback_buffer in each ChannelInfo to point to data
432 * that someone can read playback_distance worth of data from.
435 AudioDiskstream::process (BufferSet& bufs, framepos_t transport_frame, pframes_t nframes, framecnt_t& playback_distance, bool need_disk_signal)
438 boost::shared_ptr<ChannelList> c = channels.reader();
439 ChannelList::iterator chan;
440 framecnt_t rec_offset = 0;
441 framecnt_t rec_nframes = 0;
442 bool collect_playback = false;
443 bool can_record = _session.actively_recording ();
445 playback_distance = 0;
447 if (!_io || !_io->active()) {
451 check_record_status (transport_frame, can_record);
457 Glib::Threads::Mutex::Lock sm (state_lock, Glib::Threads::TRY_LOCK);
463 adjust_capture_position = 0;
465 for (chan = c->begin(); chan != c->end(); ++chan) {
466 (*chan)->current_capture_buffer = 0;
467 (*chan)->current_playback_buffer = 0;
470 // Safeguard against situations where process() goes haywire when autopunching
471 // and last_recordable_frame < first_recordable_frame
473 if (last_recordable_frame < first_recordable_frame) {
474 last_recordable_frame = max_framepos;
477 if (record_enabled()) {
479 Evoral::OverlapType ot = Evoral::coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
480 // XXX should this be transport_frame + nframes - 1 ? coverage() expects its parameter ranges to include their end points
481 // XXX also, first_recordable_frame & last_recordable_frame may both be == max_framepos: coverage() will return OverlapNone in that case. Is thak OK?
482 calculate_record_range (ot, transport_frame, nframes, rec_nframes, rec_offset);
484 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1: this time record %2 of %3 frames, offset %4\n", _name, rec_nframes, nframes, rec_offset));
486 if (rec_nframes && !was_recording) {
487 capture_captured = 0;
488 was_recording = true;
492 if (can_record && !_last_capture_sources.empty()) {
493 _last_capture_sources.clear ();
498 uint32_t limit = _io->n_ports ().n_audio();
500 /* one or more ports could already have been removed from _io, but our
501 channel setup hasn't yet been updated. prevent us from trying to
502 use channels that correspond to missing ports. note that the
503 process callback (from which this is called) is always atomic
504 with respect to port removal/addition.
507 for (n = 0, chan = c->begin(); chan != c->end() && n < limit; ++chan, ++n) {
509 ChannelInfo* chaninfo (*chan);
511 chaninfo->capture_buf->get_write_vector (&chaninfo->capture_vector);
513 if (rec_nframes <= (framecnt_t) chaninfo->capture_vector.len[0]) {
515 chaninfo->current_capture_buffer = chaninfo->capture_vector.buf[0];
517 /* note: grab the entire port buffer, but only copy what we were supposed to
518 for recording, and use rec_offset
521 boost::shared_ptr<AudioPort> const ap = _io->audio (n);
523 assert(rec_nframes <= (framecnt_t) ap->get_audio_buffer(nframes).capacity());
525 Sample *buf = bufs.get_audio (n).data(rec_offset);
526 memcpy (chaninfo->current_capture_buffer, buf, sizeof (Sample) * rec_nframes);
530 framecnt_t total = chaninfo->capture_vector.len[0] + chaninfo->capture_vector.len[1];
532 if (rec_nframes > total) {
533 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 overrun in %2, rec_nframes = %3 total space = %4\n",
534 DEBUG_THREAD_SELF, name(), rec_nframes, total));
539 boost::shared_ptr<AudioPort> const ap = _io->audio (n);
542 Sample *buf = bufs.get_audio (n).data(rec_offset);
543 framecnt_t first = chaninfo->capture_vector.len[0];
545 memcpy (chaninfo->capture_wrap_buffer, buf, sizeof (Sample) * first);
546 memcpy (chaninfo->capture_vector.buf[0], buf, sizeof (Sample) * first);
547 memcpy (chaninfo->capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
548 memcpy (chaninfo->capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
550 chaninfo->current_capture_buffer = chaninfo->capture_wrap_buffer;
564 /* data will be written to disk */
566 if (rec_nframes == nframes && rec_offset == 0) {
568 for (chan = c->begin(); chan != c->end(); ++chan) {
569 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
572 playback_distance = nframes;
577 /* we can't use the capture buffer as the playback buffer, because
578 we recorded only a part of the current process' cycle data
582 collect_playback = true;
585 adjust_capture_position = rec_nframes;
587 } else if (can_record && record_enabled()) {
589 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
591 for (chan = c->begin(); chan != c->end(); ++chan) {
592 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
595 playback_distance = nframes;
599 collect_playback = true;
602 if ((_track->monitoring_state () & MonitoringDisk) || collect_playback) {
604 /* we're doing playback */
606 framecnt_t necessary_samples;
608 /* no varispeed playback if we're recording, because the output .... TBD */
610 if (rec_nframes == 0 && _actual_speed != 1.0) {
611 necessary_samples = (framecnt_t) ceil ((nframes * fabs (_actual_speed))) + 2;
613 necessary_samples = nframes;
616 for (chan = c->begin(); chan != c->end(); ++chan) {
617 (*chan)->playback_buf->get_read_vector (&(*chan)->playback_vector);
622 /* Setup current_playback_buffer in each ChannelInfo to point to data that someone
623 can read necessary_samples (== nframes at a transport speed of 1) worth of data
627 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
629 ChannelInfo* chaninfo (*chan);
631 if (necessary_samples <= (framecnt_t) chaninfo->playback_vector.len[0]) {
632 /* There are enough samples in the first part of the ringbuffer */
633 chaninfo->current_playback_buffer = chaninfo->playback_vector.buf[0];
636 framecnt_t total = chaninfo->playback_vector.len[0] + chaninfo->playback_vector.len[1];
638 if (necessary_samples > total) {
639 cerr << _name << " Need " << necessary_samples << " total = " << total << endl;
640 cerr << "underrun for " << _name << endl;
641 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 underrun in %2, rec_nframes = %3 total space = %4\n",
642 DEBUG_THREAD_SELF, name(), rec_nframes, total));
648 /* We have enough samples, but not in one lump. Coalesce the two parts
649 into one in playback_wrap_buffer in our ChannelInfo, and specify that
650 as our current_playback_buffer.
653 assert(wrap_buffer_size >= necessary_samples);
655 /* Copy buf[0] from playback_buf */
656 memcpy ((char *) chaninfo->playback_wrap_buffer,
657 chaninfo->playback_vector.buf[0],
658 chaninfo->playback_vector.len[0] * sizeof (Sample));
660 /* Copy buf[1] from playback_buf */
661 memcpy (chaninfo->playback_wrap_buffer + chaninfo->playback_vector.len[0],
662 chaninfo->playback_vector.buf[1],
663 (necessary_samples - chaninfo->playback_vector.len[0])
666 chaninfo->current_playback_buffer = chaninfo->playback_wrap_buffer;
671 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
673 interpolation.set_speed (_target_speed);
676 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++channel) {
677 ChannelInfo* chaninfo (*chan);
679 playback_distance = interpolation.interpolate (
680 channel, nframes, chaninfo->current_playback_buffer, chaninfo->speed_buffer);
682 chaninfo->current_playback_buffer = chaninfo->speed_buffer;
686 playback_distance = nframes;
689 _speed = _target_speed;
692 if (need_disk_signal) {
694 /* copy data over to buffer set */
696 size_t n_buffers = bufs.count().n_audio();
697 size_t n_chans = c->size();
698 gain_t scaling = 1.0f;
700 if (n_chans > n_buffers) {
701 scaling = ((float) n_buffers)/n_chans;
704 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
706 AudioBuffer& buf (bufs.get_audio (n%n_buffers));
707 ChannelInfo* chaninfo (*chan);
710 if (scaling != 1.0f) {
711 buf.read_from_with_gain (chaninfo->current_playback_buffer, nframes, scaling);
713 buf.read_from (chaninfo->current_playback_buffer, nframes);
716 if (scaling != 1.0f) {
717 buf.accumulate_with_gain_from (chaninfo->current_playback_buffer, nframes, scaling);
719 buf.accumulate_from (chaninfo->current_playback_buffer, nframes);
724 /* leave the MIDI count alone */
725 ChanCount cnt (DataType::AUDIO, n_chans);
726 cnt.set (DataType::MIDI, bufs.count().n_midi());
727 bufs.set_count (cnt);
729 /* extra buffers will already be silent, so leave them alone */
736 AudioDiskstream::calculate_playback_distance (pframes_t nframes)
738 frameoffset_t playback_distance = nframes;
740 if (record_enabled()) {
741 playback_distance = nframes;
742 } else if (_actual_speed != 1.0f && _actual_speed != -1.0f) {
743 interpolation.set_speed (_target_speed);
744 boost::shared_ptr<ChannelList> c = channels.reader();
746 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++channel) {
747 playback_distance = interpolation.interpolate (channel, nframes, NULL, NULL);
750 playback_distance = nframes;
753 if (_actual_speed < 0.0) {
754 return -playback_distance;
756 return playback_distance;
760 /** Update various things including playback_sample, read pointer on each channel's playback_buf
761 * and write pointer on each channel's capture_buf. Also wout whether the butler is needed.
762 * @return true if the butler is required.
765 AudioDiskstream::commit (framecnt_t playback_distance)
767 bool need_butler = false;
769 if (!_io || !_io->active()) {
773 if (_actual_speed < 0.0) {
774 playback_sample -= playback_distance;
776 playback_sample += playback_distance;
779 boost::shared_ptr<ChannelList> c = channels.reader();
780 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
782 (*chan)->playback_buf->increment_read_ptr (playback_distance);
784 if (adjust_capture_position) {
785 (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
789 if (adjust_capture_position != 0) {
790 capture_captured += adjust_capture_position;
791 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1 now captured %2 (by %3)\n", name(), capture_captured, adjust_capture_position));
792 adjust_capture_position = 0;
800 if (_io && _io->active()) {
801 need_butler = c->front()->playback_buf->write_space() >= c->front()->playback_buf->bufsize() / 2;
806 if (_io && _io->active()) {
807 need_butler = ((framecnt_t) c->front()->playback_buf->write_space() >= disk_read_chunk_frames)
808 || ((framecnt_t) c->front()->capture_buf->read_space() >= disk_write_chunk_frames);
810 need_butler = ((framecnt_t) c->front()->capture_buf->read_space() >= disk_write_chunk_frames);
818 AudioDiskstream::set_pending_overwrite (bool yn)
820 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
822 _pending_overwrite = yn;
824 overwrite_frame = playback_sample;
826 boost::shared_ptr<ChannelList> c = channels.reader ();
828 overwrite_offset = c->front()->playback_buf->get_read_ptr();
833 AudioDiskstream::overwrite_existing_buffers ()
835 boost::shared_ptr<ChannelList> c = channels.reader();
837 _pending_overwrite = false;
841 Sample* mixdown_buffer;
844 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
846 overwrite_queued = false;
848 /* assume all are the same size */
849 framecnt_t size = c->front()->playback_buf->bufsize();
851 mixdown_buffer = new Sample[size];
852 gain_buffer = new float[size];
854 /* reduce size so that we can fill the buffer correctly (ringbuffers
855 can only handle size-1, otherwise they appear to be empty)
862 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
864 start = overwrite_frame;
865 framecnt_t cnt = size;
867 /* to fill the buffer without resetting the playback sample, we need to
868 do it one or two chunks (normally two).
870 |----------------------------------------------------------------------|
874 |<- second chunk->||<----------------- first chunk ------------------>|
878 framecnt_t to_read = size - overwrite_offset;
880 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, n, reversed)) {
881 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
882 id(), size, playback_sample) << endmsg;
890 if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer, start, cnt, n, reversed)) {
891 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
892 id(), size, playback_sample) << endmsg;
901 _pending_overwrite = false;
902 delete [] gain_buffer;
903 delete [] mixdown_buffer;
908 AudioDiskstream::seek (framepos_t frame, bool complete_refill)
912 ChannelList::iterator chan;
913 boost::shared_ptr<ChannelList> c = channels.reader();
915 Glib::Threads::Mutex::Lock lm (state_lock);
917 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
918 (*chan)->playback_buf->reset ();
919 (*chan)->capture_buf->reset ();
922 /* can't rec-enable in destructive mode if transport is before start */
924 if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
925 disengage_record_enable ();
928 playback_sample = frame;
931 if (complete_refill) {
932 /* call _do_refill() to refill the entire buffer, using
933 the largest reads possible.
935 while ((ret = do_refill_with_alloc (false)) > 0) ;
937 /* call _do_refill() to refill just one chunk, and then
940 ret = do_refill_with_alloc (true);
947 AudioDiskstream::can_internal_playback_seek (framecnt_t distance)
949 ChannelList::iterator chan;
950 boost::shared_ptr<ChannelList> c = channels.reader();
952 for (chan = c->begin(); chan != c->end(); ++chan) {
953 if ((*chan)->playback_buf->read_space() < (size_t) distance) {
961 AudioDiskstream::internal_playback_seek (framecnt_t distance)
963 ChannelList::iterator chan;
964 boost::shared_ptr<ChannelList> c = channels.reader();
966 for (chan = c->begin(); chan != c->end(); ++chan) {
967 (*chan)->playback_buf->increment_read_ptr (::llabs(distance));
970 if (first_recordable_frame < max_framepos) {
971 first_recordable_frame += distance;
973 playback_sample += distance;
978 /** Read some data for 1 channel from our playlist into a buffer.
979 * @param buf Buffer to write to.
980 * @param start Session frame to start reading from; updated to where we end up
982 * @param cnt Count of samples to read.
983 * @param reversed true if we are running backwards, otherwise false.
986 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer,
987 framepos_t& start, framecnt_t cnt,
988 int channel, bool reversed)
990 framecnt_t this_read = 0;
992 framepos_t loop_end = 0;
993 framepos_t loop_start = 0;
994 framecnt_t offset = 0;
997 /* XXX we don't currently play loops in reverse. not sure why */
1001 framecnt_t loop_length = 0;
1003 /* Make the use of a Location atomic for this read operation.
1005 Note: Locations don't get deleted, so all we care about
1006 when I say "atomic" is that we are always pointing to
1007 the same one and using a start/length values obtained
1011 if ((loc = loop_location) != 0) {
1012 loop_start = loc->start();
1013 loop_end = loc->end();
1014 loop_length = loop_end - loop_start;
1017 /* if we are looping, ensure that the first frame we read is at the correct
1018 position within the loop.
1021 if (loc && start >= loop_end) {
1022 start = loop_start + ((start - loop_start) % loop_length);
1031 /* We need this while loop in case we hit a loop boundary, in which case our read from
1032 the playlist must be split into more than one section.
1037 /* take any loop into account. we can't read past the end of the loop. */
1039 if (loc && (loop_end - start < cnt)) {
1040 this_read = loop_end - start;
1047 if (this_read == 0) {
1051 this_read = min(cnt,this_read);
1053 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
1054 error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), id(), this_read,
1061 swap_by_ptr (buf, buf + this_read - 1);
1065 /* if we read to the end of the loop, go back to the beginning */
1075 offset += this_read;
1082 AudioDiskstream::_do_refill_with_alloc (bool partial_fill)
1084 /* We limit disk reads to at most 4MB chunks, which with floating point
1085 samples would be 1M samples. But we might use 16 or 14 bit samples,
1086 in which case 4MB is more samples than that. Therefore size this for
1087 the smallest sample value .. 4MB = 2M samples (16 bit).
1090 Sample* mix_buf = new Sample[2*1048576];
1091 float* gain_buf = new float[2*1048576];
1093 int ret = _do_refill (mix_buf, gain_buf, (partial_fill ? disk_read_chunk_frames : 0));
1101 /** Get some more data from disk and put it in our channels' playback_bufs,
1102 * if there is suitable space in them.
1104 * If fill_level is non-zero, then we will refill the buffer so that there is
1105 * still at least fill_level samples of space left to be filled. This is used
1106 * after locates so that we do not need to wait to fill the entire buffer.
1111 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer, framecnt_t fill_level)
1115 RingBufferNPT<Sample>::rw_vector vector;
1116 bool const reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1117 framecnt_t total_space;
1118 framecnt_t zero_fill;
1120 ChannelList::iterator i;
1121 boost::shared_ptr<ChannelList> c = channels.reader();
1124 /* do not read from disk while session is marked as Loading, to avoid
1125 useless redundant I/O.
1128 if (_session.state_of_the_state() & Session::Loading) {
1136 assert(mixdown_buffer);
1137 assert(gain_buffer);
1144 c->front()->playback_buf->get_write_vector (&vector);
1146 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1147 /* nowhere to write to */
1152 if (fill_level < total_space) {
1153 total_space -= fill_level;
1155 /* we can't do anything with it */
1160 /* if we're running close to normal speed and there isn't enough
1161 space to do disk_read_chunk_frames of I/O, then don't bother.
1163 at higher speeds, just do it because the sync between butler
1164 and audio thread may not be good enough.
1166 Note: it is a design assumption that disk_read_chunk_frames is smaller
1167 than the playback buffer size, so this check should never trip when
1168 the playback buffer is empty.
1171 if ((total_space < disk_read_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1175 /* when slaved, don't try to get too close to the read pointer. this
1176 leaves space for the buffer reversal to have something useful to
1180 if (_slaved && total_space < (framecnt_t) (c->front()->playback_buf->bufsize() / 2)) {
1186 if (file_frame == 0) {
1188 /* at start: nothing to do but fill with silence */
1190 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1192 ChannelInfo* chan (*i);
1193 chan->playback_buf->get_write_vector (&vector);
1194 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1195 if (vector.len[1]) {
1196 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1198 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1203 if (file_frame < total_space) {
1205 /* too close to the start: read what we can,
1206 and then zero fill the rest
1209 zero_fill = total_space - file_frame;
1210 total_space = file_frame;
1219 if (file_frame == max_framepos) {
1221 /* at end: nothing to do but fill with silence */
1223 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1225 ChannelInfo* chan (*i);
1226 chan->playback_buf->get_write_vector (&vector);
1227 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1228 if (vector.len[1]) {
1229 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1231 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1236 if (file_frame > max_framepos - total_space) {
1238 /* to close to the end: read what we can, and zero fill the rest */
1240 zero_fill = total_space - (max_framepos - file_frame);
1241 total_space = max_framepos - file_frame;
1248 framepos_t file_frame_tmp = 0;
1250 /* total_space is in samples. We want to optimize read sizes in various sizes using bytes */
1252 const size_t bits_per_sample = format_data_width (_session.config.get_native_file_data_format());
1253 size_t total_bytes = total_space * bits_per_sample / 8;
1255 /* chunk size range is 256kB to 4MB. Bigger is faster in terms of MB/sec, but bigger chunk size always takes longer
1257 size_t byte_size_for_read = max ((size_t) (256 * 1024), min ((size_t) (4 * 1048576), total_bytes));
1259 /* find nearest (lower) multiple of 16384 */
1261 byte_size_for_read = (byte_size_for_read / 16384) * 16384;
1263 /* now back to samples */
1265 framecnt_t samples_to_read = byte_size_for_read / (bits_per_sample / 8);
1267 //cerr << name() << " will read " << byte_size_for_read << " out of total bytes " << total_bytes << " in buffer of "
1268 // << c->front()->playback_buf->bufsize() * bits_per_sample / 8 << " bps = " << bits_per_sample << endl;
1269 // cerr << name () << " read samples = " << samples_to_read << " out of total space " << total_space << " in buffer of " << c->front()->playback_buf->bufsize() << " samples\n";
1271 // uint64_t before = g_get_monotonic_time ();
1272 // uint64_t elapsed;
1274 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1276 ChannelInfo* chan (*i);
1279 framecnt_t len1, len2;
1281 chan->playback_buf->get_write_vector (&vector);
1283 if ((framecnt_t) vector.len[0] > samples_to_read) {
1285 /* we're not going to fill the first chunk, so certainly do not bother with the
1286 other part. it won't be connected with the part we do fill, as in:
1288 .... => writable space
1289 ++++ => readable space
1290 ^^^^ => 1 x disk_read_chunk_frames that would be filled
1292 |......|+++++++++++++|...............................|
1297 So, just pretend that the buf1 part isn't there.
1307 file_frame_tmp = file_frame;
1309 buf1 = vector.buf[0];
1310 len1 = vector.len[0];
1311 buf2 = vector.buf[1];
1312 len2 = vector.len[1];
1314 to_read = min (ts, len1);
1315 to_read = min (to_read, (framecnt_t) samples_to_read);
1317 assert (to_read >= 0);
1321 if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1326 chan->playback_buf->increment_write_ptr (to_read);
1330 to_read = min (ts, len2);
1334 /* we read all of vector.len[0], but it wasn't the
1335 entire samples_to_read of data, so read some or
1336 all of vector.len[1] as well.
1339 if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1344 chan->playback_buf->increment_write_ptr (to_read);
1348 /* XXX: do something */
1353 // elapsed = g_get_monotonic_time () - before;
1354 // cerr << "\tbandwidth = " << (byte_size_for_read / 1048576.0) / (elapsed/1000000.0) << "MB/sec\n";
1356 file_frame = file_frame_tmp;
1357 assert (file_frame >= 0);
1359 ret = ((total_space - samples_to_read) > disk_read_chunk_frames);
1361 c->front()->playback_buf->get_write_vector (&vector);
1367 /** Flush pending data to disk.
1369 * Important note: this function will write *AT MOST* disk_write_chunk_frames
1370 * of data to disk. it will never write more than that. If it writes that
1371 * much and there is more than that waiting to be written, it will return 1,
1372 * otherwise 0 on success or -1 on failure.
1374 * If there is less than disk_write_chunk_frames to be written, no data will be
1375 * written at all unless @a force_flush is true.
1378 AudioDiskstream::do_flush (RunContext /*context*/, bool force_flush)
1382 RingBufferNPT<Sample>::rw_vector vector;
1383 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1386 transvec.buf[0] = 0;
1387 transvec.buf[1] = 0;
1391 boost::shared_ptr<ChannelList> c = channels.reader();
1392 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1394 (*chan)->capture_buf->get_read_vector (&vector);
1396 total = vector.len[0] + vector.len[1];
1398 if (total == 0 || (total < disk_write_chunk_frames && !force_flush && was_recording)) {
1402 /* if there are 2+ chunks of disk i/o possible for
1403 this track, let the caller know so that it can arrange
1404 for us to be called again, ASAP.
1406 if we are forcing a flush, then if there is* any* extra
1407 work, let the caller know.
1409 if we are no longer recording and there is any extra work,
1410 let the caller know too.
1413 if (total >= 2 * disk_write_chunk_frames || ((force_flush || !was_recording) && total > disk_write_chunk_frames)) {
1417 to_write = min (disk_write_chunk_frames, (framecnt_t) vector.len[0]);
1419 // check the transition buffer when recording destructive
1420 // important that we get this after the capture buf
1422 if (destructive()) {
1423 (*chan)->capture_transition_buf->get_read_vector(&transvec);
1424 size_t transcount = transvec.len[0] + transvec.len[1];
1427 for (ti=0; ti < transcount; ++ti) {
1428 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1430 if (captrans.type == CaptureStart) {
1431 // by definition, the first data we got above represents the given capture pos
1433 (*chan)->write_source->mark_capture_start (captrans.capture_val);
1434 (*chan)->curr_capture_cnt = 0;
1436 } else if (captrans.type == CaptureEnd) {
1438 // capture end, the capture_val represents total frames in capture
1440 if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1442 // shorten to make the write a perfect fit
1443 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
1445 if (nto_write < to_write) {
1446 ret = 1; // should we?
1448 to_write = nto_write;
1450 (*chan)->write_source->mark_capture_end ();
1452 // increment past this transition, but go no further
1457 // actually ends just beyond this chunk, so force more work
1465 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1469 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1470 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), id()) << endmsg;
1474 (*chan)->capture_buf->increment_read_ptr (to_write);
1475 (*chan)->curr_capture_cnt += to_write;
1477 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_write_chunk_frames) && !destructive()) {
1479 /* we wrote all of vector.len[0] but it wasn't an entire
1480 disk_write_chunk_frames of data, so arrange for some part
1481 of vector.len[1] to be flushed to disk as well.
1484 to_write = min ((framecnt_t)(disk_write_chunk_frames - to_write), (framecnt_t) vector.len[1]);
1486 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 additional write of %2\n", name(), to_write));
1488 if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1489 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), id()) << endmsg;
1493 (*chan)->capture_buf->increment_read_ptr (to_write);
1494 (*chan)->curr_capture_cnt += to_write;
1503 AudioDiskstream::transport_stopped_wallclock (struct tm& when, time_t twhen, bool abort_capture)
1505 uint32_t buffer_position;
1506 bool more_work = true;
1508 boost::shared_ptr<AudioRegion> region;
1509 framecnt_t total_capture;
1511 SourceList::iterator src;
1512 ChannelList::iterator chan;
1513 vector<CaptureInfo*>::iterator ci;
1514 boost::shared_ptr<ChannelList> c = channels.reader();
1516 bool mark_write_completed = false;
1520 /* butler is already stopped, but there may be work to do
1521 to flush remaining data to disk.
1524 while (more_work && !err) {
1525 switch (do_flush (TransportContext, true)) {
1532 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1537 /* XXX is there anything we can do if err != 0 ? */
1538 Glib::Threads::Mutex::Lock lm (capture_info_lock);
1540 if (capture_info.empty()) {
1544 if (abort_capture) {
1546 if (destructive()) {
1550 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1552 if ((*chan)->write_source) {
1554 (*chan)->write_source->mark_for_remove ();
1555 (*chan)->write_source->drop_references ();
1556 (*chan)->write_source.reset ();
1559 /* new source set up in "out" below */
1565 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1566 total_capture += (*ci)->frames;
1569 /* figure out the name for this take */
1571 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1573 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1577 s->update_header (capture_info.front()->start, when, twhen);
1578 s->set_captured_for (_name.val());
1579 s->mark_immutable ();
1581 if (Config->get_auto_analyse_audio()) {
1582 Analyser::queue_source_for_analysis (s, true);
1585 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("newly captured source %1 length %2\n", s->path(), s->length (0)));
1589 /* destructive tracks have a single, never changing region */
1591 if (destructive()) {
1593 /* send a signal that any UI can pick up to do the right thing. there is
1594 a small problem here in that a UI may need the peak data to be ready
1595 for the data that was recorded and this isn't interlocked with that
1596 process. this problem is deferred to the UI.
1599 _playlist->LayeringChanged(); // XXX this may not get the UI to do the right thing
1603 string whole_file_region_name;
1604 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1606 /* Register a new region with the Session that
1607 describes the entire source. Do this first
1608 so that any sub-regions will obviously be
1609 children of this one (later!)
1615 plist.add (Properties::start, c->front()->write_source->last_capture_start_frame());
1616 plist.add (Properties::length, total_capture);
1617 plist.add (Properties::name, whole_file_region_name);
1618 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1619 rx->set_automatic (true);
1620 rx->set_whole_file (true);
1622 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1623 region->special_set_position (capture_info.front()->start);
1627 catch (failed_constructor& err) {
1628 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1632 _last_capture_sources.insert (_last_capture_sources.end(), srcs.begin(), srcs.end());
1634 _playlist->clear_changes ();
1635 _playlist->set_capture_insertion_in_progress (true);
1636 _playlist->freeze ();
1638 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1642 RegionFactory::region_name (region_name, whole_file_region_name, false);
1644 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1 capture bufpos %5 start @ %2 length %3 add new region %4\n",
1645 _name, (*ci)->start, (*ci)->frames, region_name, buffer_position));
1651 plist.add (Properties::start, buffer_position);
1652 plist.add (Properties::length, (*ci)->frames);
1653 plist.add (Properties::name, region_name);
1655 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1656 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1659 catch (failed_constructor& err) {
1660 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1661 continue; /* XXX is this OK? */
1664 i_am_the_modifier++;
1666 _playlist->add_region (region, (*ci)->start, 1, non_layered());
1667 _playlist->set_layer (region, DBL_MAX);
1668 i_am_the_modifier--;
1670 buffer_position += (*ci)->frames;
1674 _playlist->set_capture_insertion_in_progress (false);
1675 _session.add_command (new StatefulDiffCommand (_playlist));
1678 mark_write_completed = true;
1681 reset_write_sources (mark_write_completed);
1685 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1689 capture_info.clear ();
1690 capture_start_frame = 0;
1694 AudioDiskstream::transport_looped (framepos_t transport_frame)
1696 if (was_recording) {
1697 // all we need to do is finish this capture, with modified capture length
1698 boost::shared_ptr<ChannelList> c = channels.reader();
1702 // the next region will start recording via the normal mechanism
1703 // we'll set the start position to the current transport pos
1704 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1705 capture_start_frame = transport_frame;
1706 first_recordable_frame = transport_frame; // mild lie
1707 last_recordable_frame = max_framepos;
1708 was_recording = true;
1710 if (recordable() && destructive()) {
1711 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1713 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1714 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1716 if (transvec.len[0] > 0) {
1717 transvec.buf[0]->type = CaptureStart;
1718 transvec.buf[0]->capture_val = capture_start_frame;
1719 (*chan)->capture_transition_buf->increment_write_ptr(1);
1723 fatal << X_("programming error: capture_transition_buf is full on rec loop! inconceivable!")
1733 AudioDiskstream::finish_capture (boost::shared_ptr<ChannelList> c)
1735 was_recording = false;
1736 first_recordable_frame = max_framepos;
1737 last_recordable_frame = max_framepos;
1739 if (capture_captured == 0) {
1743 if (recordable() && destructive()) {
1744 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1746 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1747 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1749 if (transvec.len[0] > 0) {
1750 transvec.buf[0]->type = CaptureEnd;
1751 transvec.buf[0]->capture_val = capture_captured;
1752 (*chan)->capture_transition_buf->increment_write_ptr(1);
1756 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1762 CaptureInfo* ci = new CaptureInfo;
1764 ci->start = capture_start_frame;
1765 ci->frames = capture_captured;
1767 /* XXX theoretical race condition here. Need atomic exchange ?
1768 However, the circumstances when this is called right
1769 now (either on record-disable or transport_stopped)
1770 mean that no actual race exists. I think ...
1771 We now have a capture_info_lock, but it is only to be used
1772 to synchronize in the transport_stop and the capture info
1773 accessors, so that invalidation will not occur (both non-realtime).
1776 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("Finish capture, add new CI, %1 + %2\n", ci->start, ci->frames));
1778 capture_info.push_back (ci);
1779 capture_captured = 0;
1781 /* now we've finished a capture, reset first_recordable_frame for next time */
1782 first_recordable_frame = max_framepos;
1786 AudioDiskstream::set_record_enabled (bool yn)
1788 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0 || record_safe ()) {
1792 /* can't rec-enable in destructive mode if transport is before start */
1794 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1798 /* yes, i know that this not proof against race conditions, but its
1799 good enough. i think.
1802 if (record_enabled() != yn) {
1804 engage_record_enable ();
1806 disengage_record_enable ();
1809 RecordEnableChanged (); /* EMIT SIGNAL */
1814 AudioDiskstream::set_record_safe (bool yn)
1816 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0) {
1820 /* can't rec-safe in destructive mode if transport is before start ????
1823 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1827 /* yes, i know that this not proof against race conditions, but its
1828 good enough. i think.
1831 if (record_safe () != yn) {
1833 engage_record_safe ();
1835 disengage_record_safe ();
1838 RecordSafeChanged (); /* EMIT SIGNAL */
1843 AudioDiskstream::prep_record_enable ()
1845 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0 || record_safe ()) { // REQUIRES REVIEW "|| record_safe ()"
1849 /* can't rec-enable in destructive mode if transport is before start */
1851 if (destructive() && _session.transport_frame() < _session.current_start_frame()) {
1855 bool rolling = _session.transport_speed() != 0.0f;
1856 boost::shared_ptr<ChannelList> c = channels.reader();
1858 capturing_sources.clear ();
1860 if (Config->get_monitoring_model() == HardwareMonitoring) {
1862 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1863 (*chan)->source.request_input_monitoring (!(_session.config.get_auto_input() && rolling));
1864 capturing_sources.push_back ((*chan)->write_source);
1865 Source::Lock lock((*chan)->write_source->mutex());
1866 (*chan)->write_source->mark_streaming_write_started (lock);
1870 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1871 capturing_sources.push_back ((*chan)->write_source);
1872 Source::Lock lock((*chan)->write_source->mutex());
1873 (*chan)->write_source->mark_streaming_write_started (lock);
1881 AudioDiskstream::prep_record_disable ()
1883 boost::shared_ptr<ChannelList> c = channels.reader();
1884 if (Config->get_monitoring_model() == HardwareMonitoring) {
1885 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1886 (*chan)->source.request_input_monitoring (false);
1889 capturing_sources.clear ();
1895 AudioDiskstream::get_state ()
1897 XMLNode& node (Diskstream::get_state());
1899 LocaleGuard lg (X_("C"));
1901 boost::shared_ptr<ChannelList> c = channels.reader();
1902 snprintf (buf, sizeof(buf), "%u", (unsigned int) c->size());
1903 node.add_property ("channels", buf);
1905 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1907 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1908 XMLNode* cs_grandchild;
1910 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1911 cs_grandchild = new XMLNode (X_("file"));
1912 cs_grandchild->add_property (X_("path"), (*i)->path());
1913 cs_child->add_child_nocopy (*cs_grandchild);
1916 /* store the location where capture will start */
1920 if (_session.config.get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1921 snprintf (buf, sizeof (buf), "%" PRId64, pi->start());
1923 snprintf (buf, sizeof (buf), "%" PRId64, _session.transport_frame());
1926 cs_child->add_property (X_("at"), buf);
1927 node.add_child_nocopy (*cs_child);
1934 AudioDiskstream::set_state (const XMLNode& node, int version)
1936 const XMLProperty* prop;
1937 XMLNodeList nlist = node.children();
1938 XMLNodeIterator niter;
1939 uint32_t nchans = 1;
1940 XMLNode* capture_pending_node = 0;
1941 LocaleGuard lg (X_("C"));
1943 /* prevent write sources from being created */
1945 in_set_state = true;
1947 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1948 if ((*niter)->name() == IO::state_node_name) {
1949 deprecated_io_node = new XMLNode (**niter);
1952 if ((*niter)->name() == X_("CapturingSources")) {
1953 capture_pending_node = *niter;
1957 if (Diskstream::set_state (node, version)) {
1961 if ((prop = node.property ("channels")) != 0) {
1962 nchans = atoi (prop->value().c_str());
1965 // create necessary extra channels
1966 // we are always constructed with one and we always need one
1968 _n_channels.set(DataType::AUDIO, channels.reader()->size());
1970 if (nchans > _n_channels.n_audio()) {
1972 add_channel (nchans - _n_channels.n_audio());
1973 IO::PortCountChanged(_n_channels);
1975 } else if (nchans < _n_channels.n_audio()) {
1977 remove_channel (_n_channels.n_audio() - nchans);
1982 if (!destructive() && capture_pending_node) {
1983 /* destructive streams have one and only one source per channel,
1984 and so they never end up in pending capture in any useful
1987 use_pending_capture_data (*capture_pending_node);
1990 in_set_state = false;
1992 /* make sure this is clear before we do anything else */
1994 capturing_sources.clear ();
1996 /* write sources are handled when we handle the input set
1997 up of the IO that owns this DS (::non_realtime_input_change())
2004 AudioDiskstream::use_new_write_source (uint32_t n)
2006 boost::shared_ptr<ChannelList> c = channels.reader();
2008 if (!recordable()) {
2012 if (n >= c->size()) {
2013 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
2017 ChannelInfo* chan = (*c)[n];
2020 if ((chan->write_source = _session.create_audio_source_for_session (
2021 n_channels().n_audio(), write_source_name(), n, destructive())) == 0) {
2022 throw failed_constructor();
2026 catch (failed_constructor &err) {
2027 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
2028 chan->write_source.reset ();
2032 /* do not remove destructive files even if they are empty */
2034 chan->write_source->set_allow_remove_if_empty (!destructive());
2040 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool /*force*/)
2042 ChannelList::iterator chan;
2043 boost::shared_ptr<ChannelList> c = channels.reader();
2046 if (!_session.writable() || !recordable()) {
2050 capturing_sources.clear ();
2052 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
2054 if (!destructive()) {
2056 if ((*chan)->write_source) {
2058 if (mark_write_complete) {
2059 Source::Lock lock((*chan)->write_source->mutex());
2060 (*chan)->write_source->mark_streaming_write_completed (lock);
2061 (*chan)->write_source->done_with_peakfile_writes ();
2064 if ((*chan)->write_source->removable()) {
2065 (*chan)->write_source->mark_for_remove ();
2066 (*chan)->write_source->drop_references ();
2069 (*chan)->write_source.reset ();
2072 use_new_write_source (n);
2074 if (record_enabled()) {
2075 capturing_sources.push_back ((*chan)->write_source);
2080 if ((*chan)->write_source == 0) {
2081 use_new_write_source (n);
2086 if (destructive() && !c->empty ()) {
2088 /* we now have all our write sources set up, so create the
2089 playlist's single region.
2092 if (_playlist->empty()) {
2093 setup_destructive_playlist ();
2099 AudioDiskstream::set_block_size (pframes_t /*nframes*/)
2101 if (_session.get_block_size() > speed_buffer_size) {
2102 speed_buffer_size = _session.get_block_size();
2103 boost::shared_ptr<ChannelList> c = channels.reader();
2105 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2106 if ((*chan)->speed_buffer)
2107 delete [] (*chan)->speed_buffer;
2108 (*chan)->speed_buffer = new Sample[speed_buffer_size];
2111 allocate_temporary_buffers ();
2115 AudioDiskstream::allocate_temporary_buffers ()
2117 /* make sure the wrap buffer is at least large enough to deal
2118 with the speeds up to 1.2, to allow for micro-variation
2119 when slaving to MTC, Timecode etc.
2122 double const sp = max (fabs (_actual_speed), 1.2);
2123 framecnt_t required_wrap_size = (framecnt_t) ceil (_session.get_block_size() * sp) + 2;
2125 if (required_wrap_size > wrap_buffer_size) {
2127 boost::shared_ptr<ChannelList> c = channels.reader();
2129 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2130 if ((*chan)->playback_wrap_buffer) {
2131 delete [] (*chan)->playback_wrap_buffer;
2133 (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
2134 if ((*chan)->capture_wrap_buffer) {
2135 delete [] (*chan)->capture_wrap_buffer;
2137 (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
2140 wrap_buffer_size = required_wrap_size;
2145 AudioDiskstream::request_input_monitoring (bool yn)
2147 boost::shared_ptr<ChannelList> c = channels.reader();
2149 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2150 (*chan)->source.request_input_monitoring (yn);
2155 AudioDiskstream::set_align_style_from_io ()
2157 bool have_physical = false;
2159 if (_alignment_choice != Automatic) {
2167 get_input_sources ();
2169 boost::shared_ptr<ChannelList> c = channels.reader();
2171 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2172 if ((*chan)->source.is_physical ()) {
2173 have_physical = true;
2178 if (have_physical) {
2179 set_align_style (ExistingMaterial);
2181 set_align_style (CaptureTime);
2186 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2188 while (how_many--) {
2189 c->push_back (new ChannelInfo(
2190 _session.butler()->audio_diskstream_playback_buffer_size(),
2191 _session.butler()->audio_diskstream_capture_buffer_size(),
2192 speed_buffer_size, wrap_buffer_size));
2193 interpolation.add_channel_to (
2194 _session.butler()->audio_diskstream_playback_buffer_size(),
2198 _n_channels.set(DataType::AUDIO, c->size());
2204 AudioDiskstream::add_channel (uint32_t how_many)
2206 RCUWriter<ChannelList> writer (channels);
2207 boost::shared_ptr<ChannelList> c = writer.get_copy();
2209 return add_channel_to (c, how_many);
2213 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2215 while (how_many-- && !c->empty()) {
2218 interpolation.remove_channel_from ();
2221 _n_channels.set(DataType::AUDIO, c->size());
2227 AudioDiskstream::remove_channel (uint32_t how_many)
2229 RCUWriter<ChannelList> writer (channels);
2230 boost::shared_ptr<ChannelList> c = writer.get_copy();
2232 return remove_channel_from (c, how_many);
2236 AudioDiskstream::playback_buffer_load () const
2238 boost::shared_ptr<ChannelList> c = channels.reader();
2244 return (float) ((double) c->front()->playback_buf->read_space()/
2245 (double) c->front()->playback_buf->bufsize());
2249 AudioDiskstream::capture_buffer_load () const
2251 boost::shared_ptr<ChannelList> c = channels.reader();
2257 return (float) ((double) c->front()->capture_buf->write_space()/
2258 (double) c->front()->capture_buf->bufsize());
2262 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2264 const XMLProperty* prop;
2265 XMLNodeList nlist = node.children();
2266 XMLNodeIterator niter;
2267 boost::shared_ptr<AudioFileSource> fs;
2268 boost::shared_ptr<AudioFileSource> first_fs;
2269 SourceList pending_sources;
2270 framepos_t position;
2272 if ((prop = node.property (X_("at"))) == 0) {
2276 if (sscanf (prop->value().c_str(), "%" PRIu64, &position) != 1) {
2280 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2281 if ((*niter)->name() == X_("file")) {
2283 if ((prop = (*niter)->property (X_("path"))) == 0) {
2287 // This protects sessions from errant CapturingSources in stored sessions
2289 if (g_stat (prop->value().c_str(), &sbuf)) {
2293 /* XXX as of June 2014, we always record to mono
2294 files. Since this Source is being created as part of
2295 crash recovery, we know that we need the first
2296 channel (the final argument to the SourceFactory
2297 call below). If we ever support non-mono files for
2298 capture, this will need rethinking.
2302 fs = boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createForRecovery (DataType::AUDIO, _session, prop->value(), 0));
2305 catch (failed_constructor& err) {
2306 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2307 _name, prop->value())
2312 pending_sources.push_back (fs);
2314 if (first_fs == 0) {
2318 fs->set_captured_for (_name.val());
2322 if (pending_sources.size() == 0) {
2323 /* nothing can be done */
2327 if (pending_sources.size() != _n_channels.n_audio()) {
2328 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2335 boost::shared_ptr<AudioRegion> wf_region;
2336 boost::shared_ptr<AudioRegion> region;
2338 /* First create the whole file region */
2342 plist.add (Properties::start, 0);
2343 plist.add (Properties::length, first_fs->length (first_fs->timeline_position()));
2344 plist.add (Properties::name, region_name_from_path (first_fs->name(), true));
2346 wf_region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, plist));
2348 wf_region->set_automatic (true);
2349 wf_region->set_whole_file (true);
2350 wf_region->special_set_position (position);
2352 /* Now create a region that isn't the whole file for adding to
2355 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, plist));
2357 _playlist->add_region (region, position);
2360 catch (failed_constructor& err) {
2361 error << string_compose (
2362 _("%1: cannot create whole-file region from pending capture sources"),
2373 AudioDiskstream::set_non_layered (bool yn)
2375 if (yn != non_layered()) {
2378 _flags = Flag (_flags | NonLayered);
2380 _flags = Flag (_flags & ~NonLayered);
2388 AudioDiskstream::set_destructive (bool yn)
2390 if (yn != destructive()) {
2393 bool bounce_ignored;
2394 /* requestor should already have checked this and
2395 bounced if necessary and desired
2397 if (!can_become_destructive (bounce_ignored)) {
2400 _flags = Flag (_flags | Destructive);
2401 use_destructive_playlist ();
2403 _flags = Flag (_flags & ~Destructive);
2404 reset_write_sources (true, true);
2412 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2414 if (Profile->get_trx()) {
2419 requires_bounce = false;
2423 /* if no regions are present: easy */
2425 if (_playlist->n_regions() == 0) {
2426 requires_bounce = false;
2430 /* is there only one region ? */
2432 if (_playlist->n_regions() != 1) {
2433 requires_bounce = true;
2437 boost::shared_ptr<Region> first;
2439 const RegionList& rl (_playlist->region_list().rlist());
2440 assert((rl.size() == 1));
2446 requires_bounce = false;
2450 /* do the source(s) for the region cover the session start position ? */
2452 if (first->position() != _session.current_start_frame()) {
2453 // what is the idea here? why start() ??
2454 if (first->start() > _session.current_start_frame()) {
2455 requires_bounce = true;
2460 /* currently RouteTimeAxisView::set_track_mode does not
2461 * implement bounce. Existing regions cannot be converted.
2463 * so let's make sure this region is already set up
2464 * as tape-track (spanning the complete range)
2466 if (first->length() != max_framepos - first->position()) {
2467 requires_bounce = true;
2471 /* is the source used by only 1 playlist ? */
2473 boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2477 if (_session.playlists->source_use_count (afirst->source()) > 1) {
2478 requires_bounce = true;
2482 requires_bounce = false;
2487 AudioDiskstream::adjust_playback_buffering ()
2489 boost::shared_ptr<ChannelList> c = channels.reader();
2491 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2492 (*chan)->resize_playback (_session.butler()->audio_diskstream_playback_buffer_size());
2497 AudioDiskstream::adjust_capture_buffering ()
2499 boost::shared_ptr<ChannelList> c = channels.reader();
2501 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2502 (*chan)->resize_capture (_session.butler()->audio_diskstream_capture_buffer_size());
2507 AudioDiskstream::ChannelSource::is_physical () const
2513 return AudioEngine::instance()->port_is_physical (name);
2517 AudioDiskstream::ChannelSource::request_input_monitoring (bool yn) const
2523 return AudioEngine::instance()->request_input_monitoring (name, yn);
2526 AudioDiskstream::ChannelInfo::ChannelInfo (framecnt_t playback_bufsize, framecnt_t capture_bufsize, framecnt_t speed_size, framecnt_t wrap_size)
2528 current_capture_buffer = 0;
2529 current_playback_buffer = 0;
2530 curr_capture_cnt = 0;
2532 speed_buffer = new Sample[speed_size];
2533 playback_wrap_buffer = new Sample[wrap_size];
2534 capture_wrap_buffer = new Sample[wrap_size];
2536 playback_buf = new RingBufferNPT<Sample> (playback_bufsize);
2537 capture_buf = new RingBufferNPT<Sample> (capture_bufsize);
2538 capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2540 /* touch the ringbuffer buffers, which will cause
2541 them to be mapped into locked physical RAM if
2542 we're running with mlockall(). this doesn't do
2546 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2547 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2548 memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2552 AudioDiskstream::ChannelInfo::resize_playback (framecnt_t playback_bufsize)
2554 delete playback_buf;
2555 playback_buf = new RingBufferNPT<Sample> (playback_bufsize);
2556 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2560 AudioDiskstream::ChannelInfo::resize_capture (framecnt_t capture_bufsize)
2564 capture_buf = new RingBufferNPT<Sample> (capture_bufsize);
2565 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2568 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2571 if (write_source->removable()) {
2572 /* this is a "stub" write source which exists in the
2573 Session source list, but is removable. We must emit
2574 a drop references call because it should not
2575 continue to exist. If we do not do this, then the
2576 Session retains a reference to it, it is not
2577 deleted, and later attempts to create a new source
2578 file will use wierd naming because it already
2581 XXX longer term TO-DO: do not add to session source
2582 list until we write to the source.
2584 write_source->drop_references ();
2588 write_source.reset ();
2590 delete [] speed_buffer;
2593 delete [] playback_wrap_buffer;
2594 playback_wrap_buffer = 0;
2596 delete [] capture_wrap_buffer;
2597 capture_wrap_buffer = 0;
2599 delete playback_buf;
2605 delete capture_transition_buf;
2606 capture_transition_buf = 0;
2611 AudioDiskstream::set_name (string const & name)
2613 if (_name == name) {
2616 Diskstream::set_name (name);
2618 /* get a new write source so that its name reflects the new diskstream name */
2620 boost::shared_ptr<ChannelList> c = channels.reader();
2621 ChannelList::iterator i;
2624 for (n = 0, i = c->begin(); i != c->end(); ++i, ++n) {
2625 use_new_write_source (n);
2632 AudioDiskstream::set_write_source_name (const std::string& str) {
2633 if (_write_source_name == str) {
2637 Diskstream::set_write_source_name (str);
2639 if (_write_source_name == name()) {
2642 boost::shared_ptr<ChannelList> c = channels.reader();
2643 ChannelList::iterator i;
2646 for (n = 0, i = c->begin(); i != c->end(); ++i, ++n) {
2647 use_new_write_source (n);