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.
33 #include "pbd/error.h"
34 #include "pbd/xml++.h"
35 #include "pbd/memento_command.h"
36 #include "pbd/enumwriter.h"
37 #include "pbd/stateful_diff_command.h"
39 #include "ardour/analyser.h"
40 #include "ardour/audio_buffer.h"
41 #include "ardour/audio_diskstream.h"
42 #include "ardour/audio_port.h"
43 #include "ardour/audioengine.h"
44 #include "ardour/audiofilesource.h"
45 #include "ardour/audioplaylist.h"
46 #include "ardour/audioregion.h"
47 #include "ardour/butler.h"
48 #include "ardour/debug.h"
49 #include "ardour/io.h"
50 #include "ardour/playlist_factory.h"
51 #include "ardour/region_factory.h"
52 #include "ardour/session.h"
53 #include "ardour/session_playlists.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 size_t AudioDiskstream::_working_buffers_size = 0;
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 */
81 AudioDiskstream::AudioDiskstream (Session& sess, const XMLNode& node)
82 : Diskstream(sess, node)
83 , channels (new ChannelList)
88 if (set_state (node, Stateful::loading_state_version)) {
90 throw failed_constructor();
96 use_destructive_playlist ();
101 AudioDiskstream::init ()
103 /* there are no channels at this point, so these
104 two calls just get speed_buffer_size and wrap_buffer
105 size setup without duplicating their code.
108 set_block_size (_session.get_block_size());
109 allocate_temporary_buffers ();
112 AudioDiskstream::~AudioDiskstream ()
114 DEBUG_TRACE (DEBUG::Destruction, string_compose ("Audio Diskstream %1 destructor\n", _name));
117 RCUWriter<ChannelList> writer (channels);
118 boost::shared_ptr<ChannelList> c = writer.get_copy();
120 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
131 AudioDiskstream::allocate_working_buffers()
133 assert(disk_io_frames() > 0);
135 _working_buffers_size = disk_io_frames();
136 _mixdown_buffer = new Sample[_working_buffers_size];
137 _gain_buffer = new gain_t[_working_buffers_size];
141 AudioDiskstream::free_working_buffers()
143 delete [] _mixdown_buffer;
144 delete [] _gain_buffer;
145 _working_buffers_size = 0;
151 AudioDiskstream::non_realtime_input_change ()
154 Glib::Threads::Mutex::Lock lm (state_lock);
156 if (input_change_pending.type == IOChange::NoChange) {
160 if (input_change_pending.type == IOChange::ConfigurationChanged) {
161 RCUWriter<ChannelList> writer (channels);
162 boost::shared_ptr<ChannelList> c = writer.get_copy();
164 _n_channels.set(DataType::AUDIO, c->size());
166 if (_io->n_ports().n_audio() > _n_channels.n_audio()) {
167 add_channel_to (c, _io->n_ports().n_audio() - _n_channels.n_audio());
168 } else if (_io->n_ports().n_audio() < _n_channels.n_audio()) {
169 remove_channel_from (c, _n_channels.n_audio() - _io->n_ports().n_audio());
173 if (input_change_pending.type & IOChange::ConnectionsChanged) {
174 get_input_sources ();
175 set_capture_offset ();
176 set_align_style_from_io ();
179 input_change_pending = IOChange::NoChange;
181 /* implicit unlock */
184 /* reset capture files */
186 reset_write_sources (false);
188 /* now refill channel buffers */
190 if (speed() != 1.0f || speed() != -1.0f) {
191 seek ((framepos_t) (_session.transport_frame() * (double) speed()));
193 seek (_session.transport_frame());
198 AudioDiskstream::non_realtime_locate (framepos_t location)
200 /* now refill channel buffers */
202 if (speed() != 1.0f || speed() != -1.0f) {
203 seek ((framepos_t) (location * (double) speed()));
210 AudioDiskstream::get_input_sources ()
212 boost::shared_ptr<ChannelList> c = channels.reader();
215 ChannelList::iterator chan;
216 uint32_t ni = _io->n_ports().n_audio();
217 vector<string> connections;
219 for (n = 0, chan = c->begin(); chan != c->end() && n < ni; ++chan, ++n) {
221 connections.clear ();
223 if (_io->nth (n)->get_connections (connections) == 0) {
224 if (!(*chan)->source.name.empty()) {
225 // _source->disable_metering ();
227 (*chan)->source.name = string();
229 (*chan)->source.name = connections[0];
235 AudioDiskstream::find_and_use_playlist (const string& name)
237 boost::shared_ptr<AudioPlaylist> playlist;
239 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (_session.playlists->by_name (name))) == 0) {
240 playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, name));
244 error << string_compose(_("AudioDiskstream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
248 return use_playlist (playlist);
252 AudioDiskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
254 assert(boost::dynamic_pointer_cast<AudioPlaylist>(playlist));
256 Diskstream::use_playlist(playlist);
262 AudioDiskstream::use_new_playlist ()
265 boost::shared_ptr<AudioPlaylist> playlist;
267 if (!in_set_state && destructive()) {
272 newname = Playlist::bump_name (_playlist->name(), _session);
274 newname = Playlist::bump_name (_name, _session);
277 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, newname, hidden()))) != 0) {
279 return use_playlist (playlist);
287 AudioDiskstream::use_copy_playlist ()
289 assert(audio_playlist());
295 if (_playlist == 0) {
296 error << string_compose(_("AudioDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
301 boost::shared_ptr<AudioPlaylist> playlist;
303 newname = Playlist::bump_name (_playlist->name(), _session);
305 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist>(PlaylistFactory::create (audio_playlist(), newname))) != 0) {
306 return use_playlist (playlist);
313 AudioDiskstream::setup_destructive_playlist ()
316 boost::shared_ptr<ChannelList> c = channels.reader();
318 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
319 srcs.push_back ((*chan)->write_source);
322 /* a single full-sized region */
324 assert (!srcs.empty ());
327 plist.add (Properties::name, _name.val());
328 plist.add (Properties::start, 0);
329 plist.add (Properties::length, max_framepos - (max_framepos - srcs.front()->natural_position()));
331 boost::shared_ptr<Region> region (RegionFactory::create (srcs, plist));
332 _playlist->add_region (region, srcs.front()->natural_position());
336 AudioDiskstream::use_destructive_playlist ()
338 /* this is called from the XML-based constructor or ::set_destructive. when called,
339 we already have a playlist and a region, but we need to
340 set up our sources for write. we use the sources associated
341 with the (presumed single, full-extent) region.
344 boost::shared_ptr<Region> rp = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
347 reset_write_sources (false, true);
351 boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
354 throw failed_constructor();
357 /* be sure to stretch the region out to the maximum length */
359 region->set_length (max_framepos - region->position());
362 ChannelList::iterator chan;
363 boost::shared_ptr<ChannelList> c = channels.reader();
365 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
366 (*chan)->write_source = boost::dynamic_pointer_cast<AudioFileSource>(region->source (n));
367 assert((*chan)->write_source);
368 (*chan)->write_source->set_allow_remove_if_empty (false);
370 /* this might be false if we switched modes, so force it */
372 (*chan)->write_source->set_destructive (true);
375 /* the source list will never be reset for a destructive track */
379 AudioDiskstream::prepare_record_status(framepos_t capture_start_frame)
381 if (recordable() && destructive()) {
382 boost::shared_ptr<ChannelList> c = channels.reader();
383 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
385 RingBufferNPT<CaptureTransition>::rw_vector transitions;
386 (*chan)->capture_transition_buf->get_write_vector (&transitions);
388 if (transitions.len[0] > 0) {
389 transitions.buf[0]->type = CaptureStart;
390 transitions.buf[0]->capture_val = capture_start_frame;
391 (*chan)->capture_transition_buf->increment_write_ptr(1);
394 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
402 /** Do some record stuff [not described in this comment!]
405 * - Setup playback_distance with the nframes, or nframes adjusted
406 * for current varispeed, if appropriate.
407 * - Setup current_playback_buffer in each ChannelInfo to point to data
408 * that someone can read playback_distance worth of data from.
411 AudioDiskstream::process (BufferSet& bufs, framepos_t transport_frame, pframes_t nframes, framecnt_t& playback_distance, bool need_disk_signal)
414 boost::shared_ptr<ChannelList> c = channels.reader();
415 ChannelList::iterator chan;
416 framecnt_t rec_offset = 0;
417 framecnt_t rec_nframes = 0;
418 bool collect_playback = false;
419 bool can_record = _session.actively_recording ();
421 playback_distance = 0;
423 if (!_io || !_io->active()) {
427 check_record_status (transport_frame, can_record);
433 Glib::Threads::Mutex::Lock sm (state_lock, Glib::Threads::TRY_LOCK);
439 adjust_capture_position = 0;
441 for (chan = c->begin(); chan != c->end(); ++chan) {
442 (*chan)->current_capture_buffer = 0;
443 (*chan)->current_playback_buffer = 0;
446 // Safeguard against situations where process() goes haywire when autopunching
447 // and last_recordable_frame < first_recordable_frame
449 if (last_recordable_frame < first_recordable_frame) {
450 last_recordable_frame = max_framepos;
453 if (record_enabled()) {
455 Evoral::OverlapType ot = Evoral::coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
456 calculate_record_range (ot, transport_frame, nframes, rec_nframes, rec_offset);
458 if (rec_nframes && !was_recording) {
459 capture_captured = 0;
460 was_recording = true;
464 if (can_record && !_last_capture_sources.empty()) {
465 _last_capture_sources.clear ();
470 uint32_t limit = _io->n_ports ().n_audio();
472 /* one or more ports could already have been removed from _io, but our
473 channel setup hasn't yet been updated. prevent us from trying to
474 use channels that correspond to missing ports. note that the
475 process callback (from which this is called) is always atomic
476 with respect to port removal/addition.
479 for (n = 0, chan = c->begin(); chan != c->end() && n < limit; ++chan, ++n) {
481 ChannelInfo* chaninfo (*chan);
483 chaninfo->capture_buf->get_write_vector (&chaninfo->capture_vector);
485 if (rec_nframes <= (framecnt_t) chaninfo->capture_vector.len[0]) {
487 chaninfo->current_capture_buffer = chaninfo->capture_vector.buf[0];
489 /* note: grab the entire port buffer, but only copy what we were supposed to
490 for recording, and use rec_offset
493 boost::shared_ptr<AudioPort> const ap = _io->audio (n);
495 assert(rec_nframes <= (framecnt_t) ap->get_audio_buffer(nframes).capacity());
497 Sample *buf = bufs.get_audio (n).data(rec_offset);
498 memcpy (chaninfo->current_capture_buffer, buf, sizeof (Sample) * rec_nframes);
502 framecnt_t total = chaninfo->capture_vector.len[0] + chaninfo->capture_vector.len[1];
504 if (rec_nframes > total) {
509 boost::shared_ptr<AudioPort> const ap = _io->audio (n);
512 Sample *buf = bufs.get_audio (n).data(rec_offset);
513 framecnt_t first = chaninfo->capture_vector.len[0];
515 memcpy (chaninfo->capture_wrap_buffer, buf, sizeof (Sample) * first);
516 memcpy (chaninfo->capture_vector.buf[0], buf, sizeof (Sample) * first);
517 memcpy (chaninfo->capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
518 memcpy (chaninfo->capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
520 chaninfo->current_capture_buffer = chaninfo->capture_wrap_buffer;
534 /* data will be written to disk */
536 if (rec_nframes == nframes && rec_offset == 0) {
538 for (chan = c->begin(); chan != c->end(); ++chan) {
539 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
542 playback_distance = nframes;
547 /* we can't use the capture buffer as the playback buffer, because
548 we recorded only a part of the current process' cycle data
552 collect_playback = true;
555 adjust_capture_position = rec_nframes;
557 } else if (can_record && record_enabled()) {
559 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
561 for (chan = c->begin(); chan != c->end(); ++chan) {
562 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
565 playback_distance = nframes;
569 collect_playback = true;
572 if ((_track->monitoring_state () & MonitoringDisk) || collect_playback) {
574 /* we're doing playback */
576 framecnt_t necessary_samples;
578 /* no varispeed playback if we're recording, because the output .... TBD */
580 if (rec_nframes == 0 && _actual_speed != 1.0f) {
581 necessary_samples = (framecnt_t) ceil ((nframes * fabs (_actual_speed))) + 2;
583 necessary_samples = nframes;
586 for (chan = c->begin(); chan != c->end(); ++chan) {
587 (*chan)->playback_buf->get_read_vector (&(*chan)->playback_vector);
592 /* Setup current_playback_buffer in each ChannelInfo to point to data that someone
593 can read necessary_samples (== nframes at a transport speed of 1) worth of data
597 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
599 ChannelInfo* chaninfo (*chan);
601 if (necessary_samples <= (framecnt_t) chaninfo->playback_vector.len[0]) {
602 /* There are enough samples in the first part of the ringbuffer */
603 chaninfo->current_playback_buffer = chaninfo->playback_vector.buf[0];
606 framecnt_t total = chaninfo->playback_vector.len[0] + chaninfo->playback_vector.len[1];
608 if (necessary_samples > total) {
609 cerr << _name << " Need " << necessary_samples << " total = " << total << endl;
610 cerr << "underrun for " << _name << endl;
616 /* We have enough samples, but not in one lump. Coalesce the two parts
617 into one in playback_wrap_buffer in our ChannelInfo, and specify that
618 as our current_playback_buffer.
621 assert(wrap_buffer_size >= necessary_samples);
623 /* Copy buf[0] from playback_buf */
624 memcpy ((char *) chaninfo->playback_wrap_buffer,
625 chaninfo->playback_vector.buf[0],
626 chaninfo->playback_vector.len[0] * sizeof (Sample));
628 /* Copy buf[1] from playback_buf */
629 memcpy (chaninfo->playback_wrap_buffer + chaninfo->playback_vector.len[0],
630 chaninfo->playback_vector.buf[1],
631 (necessary_samples - chaninfo->playback_vector.len[0])
634 chaninfo->current_playback_buffer = chaninfo->playback_wrap_buffer;
639 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
641 interpolation.set_speed (_target_speed);
644 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++channel) {
645 ChannelInfo* chaninfo (*chan);
647 playback_distance = interpolation.interpolate (
648 channel, nframes, chaninfo->current_playback_buffer, chaninfo->speed_buffer);
650 chaninfo->current_playback_buffer = chaninfo->speed_buffer;
654 playback_distance = nframes;
657 _speed = _target_speed;
660 if (need_disk_signal) {
662 /* copy data over to buffer set */
664 size_t n_buffers = bufs.count().n_audio();
665 size_t n_chans = c->size();
666 gain_t scaling = 1.0f;
668 if (n_chans > n_buffers) {
669 scaling = ((float) n_buffers)/n_chans;
672 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
674 AudioBuffer& buf (bufs.get_audio (n%n_buffers));
675 ChannelInfo* chaninfo (*chan);
678 if (scaling != 1.0f) {
679 buf.read_from_with_gain (chaninfo->current_playback_buffer, nframes, scaling);
681 buf.read_from (chaninfo->current_playback_buffer, nframes);
684 if (scaling != 1.0f) {
685 buf.accumulate_with_gain_from (chaninfo->current_playback_buffer, nframes, scaling);
687 buf.accumulate_from (chaninfo->current_playback_buffer, nframes);
692 /* leave the MIDI count alone */
693 ChanCount cnt (DataType::AUDIO, n_chans);
694 cnt.set (DataType::MIDI, bufs.count().n_midi());
695 bufs.set_count (cnt);
697 /* extra buffers will already be silent, so leave them alone */
703 /** Update various things including playback_sample, read pointer on each channel's playback_buf
704 * and write pointer on each channel's capture_buf. Also wout whether the butler is needed.
705 * @return true if the butler is required.
708 AudioDiskstream::commit (framecnt_t playback_distance)
710 bool need_butler = false;
712 if (!_io || !_io->active()) {
716 if (_actual_speed < 0.0) {
717 playback_sample -= playback_distance;
719 playback_sample += playback_distance;
722 boost::shared_ptr<ChannelList> c = channels.reader();
723 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
725 (*chan)->playback_buf->increment_read_ptr (playback_distance);
727 if (adjust_capture_position) {
728 (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
732 if (adjust_capture_position != 0) {
733 capture_captured += adjust_capture_position;
734 adjust_capture_position = 0;
742 if (_io && _io->active()) {
743 need_butler = c->front()->playback_buf->write_space() >= c->front()->playback_buf->bufsize() / 2;
748 if (_io && _io->active()) {
749 need_butler = ((framecnt_t) c->front()->playback_buf->write_space() >= disk_io_chunk_frames)
750 || ((framecnt_t) c->front()->capture_buf->read_space() >= disk_io_chunk_frames);
752 need_butler = ((framecnt_t) c->front()->capture_buf->read_space() >= disk_io_chunk_frames);
760 AudioDiskstream::set_pending_overwrite (bool yn)
762 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
764 _pending_overwrite = yn;
766 overwrite_frame = playback_sample;
768 boost::shared_ptr<ChannelList> c = channels.reader ();
770 overwrite_offset = c->front()->playback_buf->get_read_ptr();
775 AudioDiskstream::overwrite_existing_buffers ()
777 boost::shared_ptr<ChannelList> c = channels.reader();
779 _pending_overwrite = false;
783 Sample* mixdown_buffer;
786 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
788 overwrite_queued = false;
790 /* assume all are the same size */
791 framecnt_t size = c->front()->playback_buf->bufsize();
793 mixdown_buffer = new Sample[size];
794 gain_buffer = new float[size];
796 /* reduce size so that we can fill the buffer correctly (ringbuffers
797 can only handle size-1, otherwise they appear to be empty)
804 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
806 start = overwrite_frame;
807 framecnt_t cnt = size;
809 /* to fill the buffer without resetting the playback sample, we need to
810 do it one or two chunks (normally two).
812 |----------------------------------------------------------------------|
816 |<- second chunk->||<----------------- first chunk ------------------>|
820 framecnt_t to_read = size - overwrite_offset;
822 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, n, reversed)) {
823 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
824 id(), size, playback_sample) << endmsg;
832 if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer, start, cnt, n, reversed)) {
833 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
834 id(), size, playback_sample) << endmsg;
843 _pending_overwrite = false;
844 delete [] gain_buffer;
845 delete [] mixdown_buffer;
850 AudioDiskstream::seek (framepos_t frame, bool complete_refill)
854 ChannelList::iterator chan;
855 boost::shared_ptr<ChannelList> c = channels.reader();
857 Glib::Threads::Mutex::Lock lm (state_lock);
859 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
860 (*chan)->playback_buf->reset ();
861 (*chan)->capture_buf->reset ();
864 /* can't rec-enable in destructive mode if transport is before start */
866 if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
867 disengage_record_enable ();
870 playback_sample = frame;
873 if (complete_refill) {
874 while ((ret = do_refill_with_alloc ()) > 0) ;
876 ret = do_refill_with_alloc ();
883 AudioDiskstream::can_internal_playback_seek (framecnt_t distance)
885 ChannelList::iterator chan;
886 boost::shared_ptr<ChannelList> c = channels.reader();
888 for (chan = c->begin(); chan != c->end(); ++chan) {
889 if ((*chan)->playback_buf->read_space() < (size_t) distance) {
897 AudioDiskstream::internal_playback_seek (framecnt_t distance)
899 ChannelList::iterator chan;
900 boost::shared_ptr<ChannelList> c = channels.reader();
902 for (chan = c->begin(); chan != c->end(); ++chan) {
903 (*chan)->playback_buf->increment_read_ptr (distance);
906 if (first_recordable_frame < max_framepos) {
907 first_recordable_frame += distance;
909 playback_sample += distance;
914 /** Read some data for 1 channel from our playlist into a buffer.
915 * @param buf Buffer to write to.
916 * @param start Session frame to start reading from; updated to where we end up
918 * @param cnt Count of samples to read.
919 * @param reversed true if we are running backwards, otherwise false.
922 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer,
923 framepos_t& start, framecnt_t cnt,
924 int channel, bool reversed)
926 framecnt_t this_read = 0;
928 framepos_t loop_end = 0;
929 framepos_t loop_start = 0;
930 framecnt_t offset = 0;
933 /* XXX we don't currently play loops in reverse. not sure why */
937 framecnt_t loop_length = 0;
939 /* Make the use of a Location atomic for this read operation.
941 Note: Locations don't get deleted, so all we care about
942 when I say "atomic" is that we are always pointing to
943 the same one and using a start/length values obtained
947 if ((loc = loop_location) != 0) {
948 loop_start = loc->start();
949 loop_end = loc->end();
950 loop_length = loop_end - loop_start;
953 /* if we are looping, ensure that the first frame we read is at the correct
954 position within the loop.
957 if (loc && start >= loop_end) {
958 start = loop_start + ((start - loop_start) % loop_length);
966 /* We need this while loop in case we hit a loop boundary, in which case our read from
967 the playlist must be split into more than one section.
972 /* take any loop into account. we can't read past the end of the loop. */
974 if (loc && (loop_end - start < cnt)) {
975 this_read = loop_end - start;
982 if (this_read == 0) {
986 this_read = min(cnt,this_read);
988 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
989 error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), id(), this_read,
996 swap_by_ptr (buf, buf + this_read - 1);
1000 /* if we read to the end of the loop, go back to the beginning */
1010 offset += this_read;
1017 AudioDiskstream::do_refill_with_alloc ()
1019 Sample* mix_buf = new Sample[disk_io_chunk_frames];
1020 float* gain_buf = new float[disk_io_chunk_frames];
1022 int ret = _do_refill(mix_buf, gain_buf);
1030 /** Get some more data from disk and put it in our channels' playback_bufs,
1031 * if there is suitable space in them.
1034 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer)
1038 RingBufferNPT<Sample>::rw_vector vector;
1039 bool const reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1040 framecnt_t total_space;
1041 framecnt_t zero_fill;
1043 ChannelList::iterator i;
1044 boost::shared_ptr<ChannelList> c = channels.reader();
1051 assert(mixdown_buffer);
1052 assert(gain_buffer);
1059 c->front()->playback_buf->get_write_vector (&vector);
1061 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1062 /* nowhere to write to */
1066 /* if there are 2+ chunks of disk i/o possible for
1067 this track, let the caller know so that it can arrange
1068 for us to be called again, ASAP.
1071 if (total_space >= (_slaved ? 3 : 2) * disk_io_chunk_frames) {
1075 /* if we're running close to normal speed and there isn't enough
1076 space to do disk_io_chunk_frames of I/O, then don't bother.
1078 at higher speeds, just do it because the sync between butler
1079 and audio thread may not be good enough.
1081 Note: it is a design assumption that disk_io_chunk_frames is smaller
1082 than the playback buffer size, so this check should never trip when
1083 the playback buffer is empty.
1086 if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1090 /* when slaved, don't try to get too close to the read pointer. this
1091 leaves space for the buffer reversal to have something useful to
1095 if (_slaved && total_space < (framecnt_t) (c->front()->playback_buf->bufsize() / 2)) {
1099 /* never do more than disk_io_chunk_frames worth of disk input per call (limit doesn't apply for memset) */
1101 total_space = min (disk_io_chunk_frames, total_space);
1105 if (file_frame == 0) {
1107 /* at start: nothing to do but fill with silence */
1109 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1111 ChannelInfo* chan (*i);
1112 chan->playback_buf->get_write_vector (&vector);
1113 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1114 if (vector.len[1]) {
1115 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1117 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1122 if (file_frame < total_space) {
1124 /* too close to the start: read what we can,
1125 and then zero fill the rest
1128 zero_fill = total_space - file_frame;
1129 total_space = file_frame;
1138 if (file_frame == max_framepos) {
1140 /* at end: nothing to do but fill with silence */
1142 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1144 ChannelInfo* chan (*i);
1145 chan->playback_buf->get_write_vector (&vector);
1146 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1147 if (vector.len[1]) {
1148 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1150 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1155 if (file_frame > max_framepos - total_space) {
1157 /* to close to the end: read what we can, and zero fill the rest */
1159 zero_fill = total_space - (max_framepos - file_frame);
1160 total_space = max_framepos - file_frame;
1167 framepos_t file_frame_tmp = 0;
1169 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1171 ChannelInfo* chan (*i);
1174 framecnt_t len1, len2;
1176 chan->playback_buf->get_write_vector (&vector);
1178 if ((framecnt_t) vector.len[0] > disk_io_chunk_frames) {
1180 /* we're not going to fill the first chunk, so certainly do not bother with the
1181 other part. it won't be connected with the part we do fill, as in:
1183 .... => writable space
1184 ++++ => readable space
1185 ^^^^ => 1 x disk_io_chunk_frames that would be filled
1187 |......|+++++++++++++|...............................|
1192 So, just pretend that the buf1 part isn't there.
1202 file_frame_tmp = file_frame;
1204 buf1 = vector.buf[0];
1205 len1 = vector.len[0];
1206 buf2 = vector.buf[1];
1207 len2 = vector.len[1];
1209 to_read = min (ts, len1);
1210 to_read = min (to_read, disk_io_chunk_frames);
1212 assert (to_read >= 0);
1216 if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1221 chan->playback_buf->increment_write_ptr (to_read);
1225 to_read = min (ts, len2);
1229 /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1230 so read some or all of vector.len[1] as well.
1233 if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1238 chan->playback_buf->increment_write_ptr (to_read);
1242 /* XXX: do something */
1247 file_frame = file_frame_tmp;
1248 assert (file_frame >= 0);
1255 /** Flush pending data to disk.
1257 * Important note: this function will write *AT MOST* disk_io_chunk_frames
1258 * of data to disk. it will never write more than that. If it writes that
1259 * much and there is more than that waiting to be written, it will return 1,
1260 * otherwise 0 on success or -1 on failure.
1262 * If there is less than disk_io_chunk_frames to be written, no data will be
1263 * written at all unless @a force_flush is true.
1266 AudioDiskstream::do_flush (RunContext /*context*/, bool force_flush)
1270 RingBufferNPT<Sample>::rw_vector vector;
1271 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1274 transvec.buf[0] = 0;
1275 transvec.buf[1] = 0;
1279 boost::shared_ptr<ChannelList> c = channels.reader();
1280 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1282 (*chan)->capture_buf->get_read_vector (&vector);
1284 total = vector.len[0] + vector.len[1];
1286 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1290 /* if there are 2+ chunks of disk i/o possible for
1291 this track, let the caller know so that it can arrange
1292 for us to be called again, ASAP.
1294 if we are forcing a flush, then if there is* any* extra
1295 work, let the caller know.
1297 if we are no longer recording and there is any extra work,
1298 let the caller know too.
1301 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1305 to_write = min (disk_io_chunk_frames, (framecnt_t) vector.len[0]);
1307 // check the transition buffer when recording destructive
1308 // important that we get this after the capture buf
1310 if (destructive()) {
1311 (*chan)->capture_transition_buf->get_read_vector(&transvec);
1312 size_t transcount = transvec.len[0] + transvec.len[1];
1315 for (ti=0; ti < transcount; ++ti) {
1316 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1318 if (captrans.type == CaptureStart) {
1319 // by definition, the first data we got above represents the given capture pos
1321 (*chan)->write_source->mark_capture_start (captrans.capture_val);
1322 (*chan)->curr_capture_cnt = 0;
1324 } else if (captrans.type == CaptureEnd) {
1326 // capture end, the capture_val represents total frames in capture
1328 if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1330 // shorten to make the write a perfect fit
1331 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
1333 if (nto_write < to_write) {
1334 ret = 1; // should we?
1336 to_write = nto_write;
1338 (*chan)->write_source->mark_capture_end ();
1340 // increment past this transition, but go no further
1345 // actually ends just beyond this chunk, so force more work
1353 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1357 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1358 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), id()) << endmsg;
1362 (*chan)->capture_buf->increment_read_ptr (to_write);
1363 (*chan)->curr_capture_cnt += to_write;
1365 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1367 /* we wrote all of vector.len[0] but it wasn't an entire
1368 disk_io_chunk_frames of data, so arrange for some part
1369 of vector.len[1] to be flushed to disk as well.
1372 to_write = min ((framecnt_t)(disk_io_chunk_frames - to_write), (framecnt_t) vector.len[1]);
1374 if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1375 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), id()) << endmsg;
1379 (*chan)->capture_buf->increment_read_ptr (to_write);
1380 (*chan)->curr_capture_cnt += to_write;
1389 AudioDiskstream::transport_stopped_wallclock (struct tm& when, time_t twhen, bool abort_capture)
1391 uint32_t buffer_position;
1392 bool more_work = true;
1394 boost::shared_ptr<AudioRegion> region;
1395 framecnt_t total_capture;
1397 SourceList::iterator src;
1398 ChannelList::iterator chan;
1399 vector<CaptureInfo*>::iterator ci;
1400 boost::shared_ptr<ChannelList> c = channels.reader();
1402 bool mark_write_completed = false;
1406 /* butler is already stopped, but there may be work to do
1407 to flush remaining data to disk.
1410 while (more_work && !err) {
1411 switch (do_flush (TransportContext, true)) {
1418 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1423 /* XXX is there anything we can do if err != 0 ? */
1424 Glib::Threads::Mutex::Lock lm (capture_info_lock);
1426 if (capture_info.empty()) {
1430 if (abort_capture) {
1432 if (destructive()) {
1436 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1438 if ((*chan)->write_source) {
1440 (*chan)->write_source->mark_for_remove ();
1441 (*chan)->write_source->drop_references ();
1442 (*chan)->write_source.reset ();
1445 /* new source set up in "out" below */
1451 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1452 total_capture += (*ci)->frames;
1455 /* figure out the name for this take */
1457 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1459 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1463 s->update_header (capture_info.front()->start, when, twhen);
1464 s->set_captured_for (_name.val());
1465 s->mark_immutable ();
1467 if (Config->get_auto_analyse_audio()) {
1468 Analyser::queue_source_for_analysis (s, true);
1473 /* destructive tracks have a single, never changing region */
1475 if (destructive()) {
1477 /* send a signal that any UI can pick up to do the right thing. there is
1478 a small problem here in that a UI may need the peak data to be ready
1479 for the data that was recorded and this isn't interlocked with that
1480 process. this problem is deferred to the UI.
1483 _playlist->LayeringChanged(); // XXX this may not get the UI to do the right thing
1487 string whole_file_region_name;
1488 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1490 /* Register a new region with the Session that
1491 describes the entire source. Do this first
1492 so that any sub-regions will obviously be
1493 children of this one (later!)
1499 plist.add (Properties::start, c->front()->write_source->last_capture_start_frame());
1500 plist.add (Properties::length, total_capture);
1501 plist.add (Properties::name, whole_file_region_name);
1502 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1503 rx->set_automatic (true);
1504 rx->set_whole_file (true);
1506 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1507 region->special_set_position (capture_info.front()->start);
1511 catch (failed_constructor& err) {
1512 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1516 _last_capture_sources.insert (_last_capture_sources.end(), srcs.begin(), srcs.end());
1518 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1520 _playlist->clear_changes ();
1521 _playlist->set_capture_insertion_in_progress (true);
1522 _playlist->freeze ();
1524 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1528 RegionFactory::region_name (region_name, whole_file_region_name, false);
1530 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1 capture start @ %2 length %3 add new region %4\n",
1531 _name, (*ci)->start, (*ci)->frames, region_name));
1537 plist.add (Properties::start, buffer_position);
1538 plist.add (Properties::length, (*ci)->frames);
1539 plist.add (Properties::name, region_name);
1541 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1542 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1545 catch (failed_constructor& err) {
1546 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1547 continue; /* XXX is this OK? */
1550 i_am_the_modifier++;
1552 _playlist->add_region (region, (*ci)->start, 1, non_layered());
1553 _playlist->set_layer (region, DBL_MAX);
1554 i_am_the_modifier--;
1556 buffer_position += (*ci)->frames;
1560 _playlist->set_capture_insertion_in_progress (false);
1561 _session.add_command (new StatefulDiffCommand (_playlist));
1564 mark_write_completed = true;
1567 reset_write_sources (mark_write_completed);
1571 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1575 capture_info.clear ();
1576 capture_start_frame = 0;
1580 AudioDiskstream::transport_looped (framepos_t transport_frame)
1582 if (was_recording) {
1583 // all we need to do is finish this capture, with modified capture length
1584 boost::shared_ptr<ChannelList> c = channels.reader();
1586 // adjust the capture length knowing that the data will be recorded to disk
1587 // only necessary after the first loop where we're recording
1588 if (capture_info.size() == 0) {
1589 capture_captured += _capture_offset;
1591 if (_alignment_style == ExistingMaterial) {
1592 capture_captured += _session.worst_output_latency();
1594 capture_captured += _roll_delay;
1600 // the next region will start recording via the normal mechanism
1601 // we'll set the start position to the current transport pos
1602 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1603 capture_start_frame = transport_frame;
1604 first_recordable_frame = transport_frame; // mild lie
1605 last_recordable_frame = max_framepos;
1606 was_recording = true;
1608 if (recordable() && destructive()) {
1609 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1611 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1612 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1614 if (transvec.len[0] > 0) {
1615 transvec.buf[0]->type = CaptureStart;
1616 transvec.buf[0]->capture_val = capture_start_frame;
1617 (*chan)->capture_transition_buf->increment_write_ptr(1);
1621 fatal << X_("programming error: capture_transition_buf is full on rec loop! inconceivable!")
1631 AudioDiskstream::finish_capture (boost::shared_ptr<ChannelList> c)
1633 was_recording = false;
1634 first_recordable_frame = max_framepos;
1635 last_recordable_frame = max_framepos;
1637 if (capture_captured == 0) {
1641 if (recordable() && destructive()) {
1642 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1644 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1645 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1647 if (transvec.len[0] > 0) {
1648 transvec.buf[0]->type = CaptureEnd;
1649 transvec.buf[0]->capture_val = capture_captured;
1650 (*chan)->capture_transition_buf->increment_write_ptr(1);
1654 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1660 CaptureInfo* ci = new CaptureInfo;
1662 ci->start = capture_start_frame;
1663 ci->frames = capture_captured;
1665 /* XXX theoretical race condition here. Need atomic exchange ?
1666 However, the circumstances when this is called right
1667 now (either on record-disable or transport_stopped)
1668 mean that no actual race exists. I think ...
1669 We now have a capture_info_lock, but it is only to be used
1670 to synchronize in the transport_stop and the capture info
1671 accessors, so that invalidation will not occur (both non-realtime).
1674 // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1676 capture_info.push_back (ci);
1677 capture_captured = 0;
1679 /* now we've finished a capture, reset first_recordable_frame for next time */
1680 first_recordable_frame = max_framepos;
1684 AudioDiskstream::set_record_enabled (bool yn)
1686 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0) {
1690 /* can't rec-enable in destructive mode if transport is before start */
1692 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1696 /* yes, i know that this not proof against race conditions, but its
1697 good enough. i think.
1700 if (record_enabled() != yn) {
1702 engage_record_enable ();
1704 disengage_record_enable ();
1707 RecordEnableChanged (); /* EMIT SIGNAL */
1712 AudioDiskstream::prep_record_enable ()
1714 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0) {
1718 /* can't rec-enable in destructive mode if transport is before start */
1720 if (destructive() && _session.transport_frame() < _session.current_start_frame()) {
1724 bool rolling = _session.transport_speed() != 0.0f;
1725 boost::shared_ptr<ChannelList> c = channels.reader();
1727 capturing_sources.clear ();
1729 if (Config->get_monitoring_model() == HardwareMonitoring) {
1731 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1732 (*chan)->source.request_jack_monitors_input (!(_session.config.get_auto_input() && rolling));
1733 capturing_sources.push_back ((*chan)->write_source);
1734 (*chan)->write_source->mark_streaming_write_started ();
1738 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1739 capturing_sources.push_back ((*chan)->write_source);
1740 (*chan)->write_source->mark_streaming_write_started ();
1748 AudioDiskstream::prep_record_disable ()
1750 boost::shared_ptr<ChannelList> c = channels.reader();
1751 if (Config->get_monitoring_model() == HardwareMonitoring) {
1752 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1753 (*chan)->source.request_jack_monitors_input (false);
1756 capturing_sources.clear ();
1762 AudioDiskstream::get_state ()
1764 XMLNode& node (Diskstream::get_state());
1766 LocaleGuard lg (X_("POSIX"));
1768 boost::shared_ptr<ChannelList> c = channels.reader();
1769 snprintf (buf, sizeof(buf), "%zd", c->size());
1770 node.add_property ("channels", buf);
1772 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1774 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1775 XMLNode* cs_grandchild;
1777 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1778 cs_grandchild = new XMLNode (X_("file"));
1779 cs_grandchild->add_property (X_("path"), (*i)->path());
1780 cs_child->add_child_nocopy (*cs_grandchild);
1783 /* store the location where capture will start */
1787 if (_session.config.get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1788 snprintf (buf, sizeof (buf), "%" PRId64, pi->start());
1790 snprintf (buf, sizeof (buf), "%" PRId64, _session.transport_frame());
1793 cs_child->add_property (X_("at"), buf);
1794 node.add_child_nocopy (*cs_child);
1801 AudioDiskstream::set_state (const XMLNode& node, int version)
1803 const XMLProperty* prop;
1804 XMLNodeList nlist = node.children();
1805 XMLNodeIterator niter;
1806 uint32_t nchans = 1;
1807 XMLNode* capture_pending_node = 0;
1808 LocaleGuard lg (X_("POSIX"));
1810 /* prevent write sources from being created */
1812 in_set_state = true;
1814 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1815 if ((*niter)->name() == IO::state_node_name) {
1816 deprecated_io_node = new XMLNode (**niter);
1819 if ((*niter)->name() == X_("CapturingSources")) {
1820 capture_pending_node = *niter;
1824 if (Diskstream::set_state (node, version)) {
1828 if ((prop = node.property ("channels")) != 0) {
1829 nchans = atoi (prop->value().c_str());
1832 // create necessary extra channels
1833 // we are always constructed with one and we always need one
1835 _n_channels.set(DataType::AUDIO, channels.reader()->size());
1837 if (nchans > _n_channels.n_audio()) {
1839 add_channel (nchans - _n_channels.n_audio());
1840 IO::PortCountChanged(_n_channels);
1842 } else if (nchans < _n_channels.n_audio()) {
1844 remove_channel (_n_channels.n_audio() - nchans);
1849 if (!destructive() && capture_pending_node) {
1850 /* destructive streams have one and only one source per channel,
1851 and so they never end up in pending capture in any useful
1854 use_pending_capture_data (*capture_pending_node);
1857 in_set_state = false;
1859 /* make sure this is clear before we do anything else */
1861 capturing_sources.clear ();
1863 /* write sources are handled when we handle the input set
1864 up of the IO that owns this DS (::non_realtime_input_change())
1871 AudioDiskstream::use_new_write_source (uint32_t n)
1873 boost::shared_ptr<ChannelList> c = channels.reader();
1875 if (!recordable()) {
1879 if (n >= c->size()) {
1880 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
1884 ChannelInfo* chan = (*c)[n];
1887 if ((chan->write_source = _session.create_audio_source_for_session (
1888 n_channels().n_audio(), name(), n, destructive())) == 0) {
1889 throw failed_constructor();
1893 catch (failed_constructor &err) {
1894 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
1895 chan->write_source.reset ();
1899 /* do not remove destructive files even if they are empty */
1901 chan->write_source->set_allow_remove_if_empty (!destructive());
1906 list<boost::shared_ptr<Source> >
1907 AudioDiskstream::steal_write_sources()
1909 /* not possible to steal audio write sources */
1910 list<boost::shared_ptr<Source> > ret;
1915 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool /*force*/)
1917 ChannelList::iterator chan;
1918 boost::shared_ptr<ChannelList> c = channels.reader();
1921 if (!_session.writable() || !recordable()) {
1925 capturing_sources.clear ();
1927 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1929 if (!destructive()) {
1931 if ((*chan)->write_source) {
1933 if (mark_write_complete) {
1934 (*chan)->write_source->mark_streaming_write_completed ();
1935 (*chan)->write_source->done_with_peakfile_writes ();
1938 if ((*chan)->write_source->removable()) {
1939 (*chan)->write_source->mark_for_remove ();
1940 (*chan)->write_source->drop_references ();
1943 (*chan)->write_source.reset ();
1946 use_new_write_source (n);
1948 if (record_enabled()) {
1949 capturing_sources.push_back ((*chan)->write_source);
1954 if ((*chan)->write_source == 0) {
1955 use_new_write_source (n);
1960 if (destructive() && !c->empty ()) {
1962 /* we now have all our write sources set up, so create the
1963 playlist's single region.
1966 if (_playlist->empty()) {
1967 setup_destructive_playlist ();
1973 AudioDiskstream::set_block_size (pframes_t /*nframes*/)
1975 if (_session.get_block_size() > speed_buffer_size) {
1976 speed_buffer_size = _session.get_block_size();
1977 boost::shared_ptr<ChannelList> c = channels.reader();
1979 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1980 if ((*chan)->speed_buffer)
1981 delete [] (*chan)->speed_buffer;
1982 (*chan)->speed_buffer = new Sample[speed_buffer_size];
1985 allocate_temporary_buffers ();
1989 AudioDiskstream::allocate_temporary_buffers ()
1991 /* make sure the wrap buffer is at least large enough to deal
1992 with the speeds up to 1.2, to allow for micro-variation
1993 when slaving to MTC, Timecode etc.
1996 double const sp = max (fabsf (_actual_speed), 1.2f);
1997 framecnt_t required_wrap_size = (framecnt_t) ceil (_session.get_block_size() * sp) + 2;
1999 if (required_wrap_size > wrap_buffer_size) {
2001 boost::shared_ptr<ChannelList> c = channels.reader();
2003 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2004 if ((*chan)->playback_wrap_buffer) {
2005 delete [] (*chan)->playback_wrap_buffer;
2007 (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
2008 if ((*chan)->capture_wrap_buffer) {
2009 delete [] (*chan)->capture_wrap_buffer;
2011 (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
2014 wrap_buffer_size = required_wrap_size;
2019 AudioDiskstream::request_jack_monitors_input (bool yn)
2021 boost::shared_ptr<ChannelList> c = channels.reader();
2023 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2024 (*chan)->source.request_jack_monitors_input (yn);
2029 AudioDiskstream::set_align_style_from_io ()
2031 bool have_physical = false;
2033 if (_alignment_choice != Automatic) {
2041 get_input_sources ();
2043 boost::shared_ptr<ChannelList> c = channels.reader();
2045 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2046 if ((*chan)->source.is_physical ()) {
2047 have_physical = true;
2052 if (have_physical) {
2053 set_align_style (ExistingMaterial);
2055 set_align_style (CaptureTime);
2060 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2062 while (how_many--) {
2063 c->push_back (new ChannelInfo(
2064 _session.butler()->audio_diskstream_playback_buffer_size(),
2065 _session.butler()->audio_diskstream_capture_buffer_size(),
2066 speed_buffer_size, wrap_buffer_size));
2067 interpolation.add_channel_to (
2068 _session.butler()->audio_diskstream_playback_buffer_size(),
2072 _n_channels.set(DataType::AUDIO, c->size());
2078 AudioDiskstream::add_channel (uint32_t how_many)
2080 RCUWriter<ChannelList> writer (channels);
2081 boost::shared_ptr<ChannelList> c = writer.get_copy();
2083 return add_channel_to (c, how_many);
2087 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2089 while (how_many-- && !c->empty()) {
2092 interpolation.remove_channel_from ();
2095 _n_channels.set(DataType::AUDIO, c->size());
2101 AudioDiskstream::remove_channel (uint32_t how_many)
2103 RCUWriter<ChannelList> writer (channels);
2104 boost::shared_ptr<ChannelList> c = writer.get_copy();
2106 return remove_channel_from (c, how_many);
2110 AudioDiskstream::playback_buffer_load () const
2112 boost::shared_ptr<ChannelList> c = channels.reader();
2118 return (float) ((double) c->front()->playback_buf->read_space()/
2119 (double) c->front()->playback_buf->bufsize());
2123 AudioDiskstream::capture_buffer_load () const
2125 boost::shared_ptr<ChannelList> c = channels.reader();
2131 return (float) ((double) c->front()->capture_buf->write_space()/
2132 (double) c->front()->capture_buf->bufsize());
2136 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2138 const XMLProperty* prop;
2139 XMLNodeList nlist = node.children();
2140 XMLNodeIterator niter;
2141 boost::shared_ptr<AudioFileSource> fs;
2142 boost::shared_ptr<AudioFileSource> first_fs;
2143 SourceList pending_sources;
2144 framepos_t position;
2146 if ((prop = node.property (X_("at"))) == 0) {
2150 if (sscanf (prop->value().c_str(), "%" PRIu64, &position) != 1) {
2154 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2155 if ((*niter)->name() == X_("file")) {
2157 if ((prop = (*niter)->property (X_("path"))) == 0) {
2161 // This protects sessions from errant CapturingSources in stored sessions
2163 if (stat (prop->value().c_str(), &sbuf)) {
2168 fs = boost::dynamic_pointer_cast<AudioFileSource> (
2169 SourceFactory::createWritable (
2170 DataType::AUDIO, _session,
2171 prop->value(), false, _session.frame_rate()));
2174 catch (failed_constructor& err) {
2175 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2176 _name, prop->value())
2181 pending_sources.push_back (fs);
2183 if (first_fs == 0) {
2187 fs->set_captured_for (_name.val());
2191 if (pending_sources.size() == 0) {
2192 /* nothing can be done */
2196 if (pending_sources.size() != _n_channels.n_audio()) {
2197 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2202 boost::shared_ptr<AudioRegion> region;
2208 plist.add (Properties::start, 0);
2209 plist.add (Properties::length, first_fs->length (first_fs->timeline_position()));
2210 plist.add (Properties::name, region_name_from_path (first_fs->name(), true));
2212 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, plist));
2214 region->set_automatic (true);
2215 region->set_whole_file (true);
2216 region->special_set_position (0);
2219 catch (failed_constructor& err) {
2220 error << string_compose (
2221 _("%1: cannot create whole-file region from pending capture sources"),
2227 _playlist->add_region (region, position);
2233 AudioDiskstream::set_non_layered (bool yn)
2235 if (yn != non_layered()) {
2238 _flags = Flag (_flags | NonLayered);
2240 _flags = Flag (_flags & ~NonLayered);
2248 AudioDiskstream::set_destructive (bool yn)
2250 if (yn != destructive()) {
2253 bool bounce_ignored;
2254 /* requestor should already have checked this and
2255 bounced if necessary and desired
2257 if (!can_become_destructive (bounce_ignored)) {
2260 _flags = Flag (_flags | Destructive);
2261 use_destructive_playlist ();
2263 _flags = Flag (_flags & ~Destructive);
2264 reset_write_sources (true, true);
2272 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2275 requires_bounce = false;
2279 /* is there only one region ? */
2281 if (_playlist->n_regions() != 1) {
2282 requires_bounce = true;
2286 boost::shared_ptr<Region> first = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
2288 requires_bounce = false;
2292 /* do the source(s) for the region cover the session start position ? */
2294 if (first->position() != _session.current_start_frame()) {
2295 if (first->start() > _session.current_start_frame()) {
2296 requires_bounce = true;
2301 /* is the source used by only 1 playlist ? */
2303 boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2307 if (_session.playlists->source_use_count (afirst->source()) > 1) {
2308 requires_bounce = true;
2312 requires_bounce = false;
2317 AudioDiskstream::adjust_playback_buffering ()
2319 boost::shared_ptr<ChannelList> c = channels.reader();
2321 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2322 (*chan)->resize_playback (_session.butler()->audio_diskstream_playback_buffer_size());
2327 AudioDiskstream::adjust_capture_buffering ()
2329 boost::shared_ptr<ChannelList> c = channels.reader();
2331 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2332 (*chan)->resize_capture (_session.butler()->audio_diskstream_capture_buffer_size());
2337 AudioDiskstream::ChannelSource::is_physical () const
2343 return AudioEngine::instance()->port_is_physical (name);
2347 AudioDiskstream::ChannelSource::request_jack_monitors_input (bool yn) const
2353 return AudioEngine::instance()->request_jack_monitors_input (name, yn);
2356 AudioDiskstream::ChannelInfo::ChannelInfo (framecnt_t playback_bufsize, framecnt_t capture_bufsize, framecnt_t speed_size, framecnt_t wrap_size)
2358 current_capture_buffer = 0;
2359 current_playback_buffer = 0;
2360 curr_capture_cnt = 0;
2362 speed_buffer = new Sample[speed_size];
2363 playback_wrap_buffer = new Sample[wrap_size];
2364 capture_wrap_buffer = new Sample[wrap_size];
2366 playback_buf = new RingBufferNPT<Sample> (playback_bufsize);
2367 capture_buf = new RingBufferNPT<Sample> (capture_bufsize);
2368 capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2370 /* touch the ringbuffer buffers, which will cause
2371 them to be mapped into locked physical RAM if
2372 we're running with mlockall(). this doesn't do
2376 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2377 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2378 memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2382 AudioDiskstream::ChannelInfo::resize_playback (framecnt_t playback_bufsize)
2384 delete playback_buf;
2385 playback_buf = new RingBufferNPT<Sample> (playback_bufsize);
2386 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2390 AudioDiskstream::ChannelInfo::resize_capture (framecnt_t capture_bufsize)
2394 capture_buf = new RingBufferNPT<Sample> (capture_bufsize);
2395 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2398 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2400 write_source.reset ();
2402 delete [] speed_buffer;
2405 delete [] playback_wrap_buffer;
2406 playback_wrap_buffer = 0;
2408 delete [] capture_wrap_buffer;
2409 capture_wrap_buffer = 0;
2411 delete playback_buf;
2417 delete capture_transition_buf;
2418 capture_transition_buf = 0;
2423 AudioDiskstream::set_name (string const & name)
2425 Diskstream::set_name (name);
2427 /* get a new write source so that its name reflects the new diskstream name */
2429 boost::shared_ptr<ChannelList> c = channels.reader();
2430 ChannelList::iterator i;
2433 for (n = 0, i = c->begin(); i != c->end(); ++i, ++n) {
2434 use_new_write_source (n);