2 Copyright (C) 2000-2006 Paul Davis
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
31 #include "pbd/error.h"
32 #include "pbd/xml++.h"
33 #include "pbd/memento_command.h"
34 #include "pbd/enumwriter.h"
35 #include "pbd/stateful_diff_command.h"
37 #include "ardour/analyser.h"
38 #include "ardour/audio_buffer.h"
39 #include "ardour/audio_diskstream.h"
40 #include "ardour/audio_port.h"
41 #include "ardour/audioengine.h"
42 #include "ardour/audiofilesource.h"
43 #include "ardour/audioplaylist.h"
44 #include "ardour/audioregion.h"
45 #include "ardour/butler.h"
46 #include "ardour/debug.h"
47 #include "ardour/io.h"
48 #include "ardour/playlist_factory.h"
49 #include "ardour/region_factory.h"
50 #include "ardour/session.h"
51 #include "ardour/session_playlists.h"
52 #include "ardour/source_factory.h"
53 #include "ardour/track.h"
54 #include "ardour/types.h"
55 #include "ardour/utils.h"
61 using namespace ARDOUR;
64 size_t AudioDiskstream::_working_buffers_size = 0;
65 Sample* AudioDiskstream::_mixdown_buffer = 0;
66 gain_t* AudioDiskstream::_gain_buffer = 0;
68 AudioDiskstream::AudioDiskstream (Session &sess, const string &name, Diskstream::Flag flag)
69 : Diskstream(sess, name, flag)
70 , channels (new ChannelList)
72 /* prevent any write sources from being created */
79 AudioDiskstream::AudioDiskstream (Session& sess, const XMLNode& node)
80 : Diskstream(sess, node)
81 , channels (new ChannelList)
86 if (set_state (node, Stateful::loading_state_version)) {
88 throw failed_constructor();
94 use_destructive_playlist ();
99 AudioDiskstream::init ()
101 /* there are no channels at this point, so these
102 two calls just get speed_buffer_size and wrap_buffer
103 size setup without duplicating their code.
106 set_block_size (_session.get_block_size());
107 allocate_temporary_buffers ();
110 AudioDiskstream::~AudioDiskstream ()
112 DEBUG_TRACE (DEBUG::Destruction, string_compose ("Audio Diskstream %1 destructor\n", _name));
115 RCUWriter<ChannelList> writer (channels);
116 boost::shared_ptr<ChannelList> c = writer.get_copy();
118 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
129 AudioDiskstream::allocate_working_buffers()
131 assert(disk_io_frames() > 0);
133 _working_buffers_size = disk_io_frames();
134 _mixdown_buffer = new Sample[_working_buffers_size];
135 _gain_buffer = new gain_t[_working_buffers_size];
139 AudioDiskstream::free_working_buffers()
141 delete [] _mixdown_buffer;
142 delete [] _gain_buffer;
143 _working_buffers_size = 0;
149 AudioDiskstream::non_realtime_input_change ()
151 bool need_write_sources = false;
154 Glib::Threads::Mutex::Lock lm (state_lock);
156 if (input_change_pending.type == IOChange::NoChange) {
160 boost::shared_ptr<ChannelList> cr = channels.reader();
161 if (!cr->empty() && !cr->front()->write_source) {
162 need_write_sources = true;
165 if (input_change_pending.type == IOChange::ConfigurationChanged) {
166 RCUWriter<ChannelList> writer (channels);
167 boost::shared_ptr<ChannelList> c = writer.get_copy();
169 _n_channels.set(DataType::AUDIO, c->size());
171 if (_io->n_ports().n_audio() > _n_channels.n_audio()) {
172 add_channel_to (c, _io->n_ports().n_audio() - _n_channels.n_audio());
173 } else if (_io->n_ports().n_audio() < _n_channels.n_audio()) {
174 remove_channel_from (c, _n_channels.n_audio() - _io->n_ports().n_audio());
177 need_write_sources = true;
180 if (input_change_pending.type & IOChange::ConnectionsChanged) {
181 get_input_sources ();
182 set_capture_offset ();
183 set_align_style_from_io ();
186 input_change_pending = IOChange::NoChange;
188 /* implicit unlock */
191 if (need_write_sources) {
192 reset_write_sources (false);
195 /* now refill channel buffers */
197 if (speed() != 1.0f || speed() != -1.0f) {
198 seek ((framepos_t) (_session.transport_frame() * (double) speed()));
200 seek (_session.transport_frame());
205 AudioDiskstream::non_realtime_locate (framepos_t location)
207 /* now refill channel buffers */
209 if (speed() != 1.0f || speed() != -1.0f) {
210 seek ((framepos_t) (location * (double) speed()));
217 AudioDiskstream::get_input_sources ()
219 boost::shared_ptr<ChannelList> c = channels.reader();
222 ChannelList::iterator chan;
223 uint32_t ni = _io->n_ports().n_audio();
224 vector<string> connections;
226 for (n = 0, chan = c->begin(); chan != c->end() && n < ni; ++chan, ++n) {
228 connections.clear ();
230 if (_io->nth (n)->get_connections (connections) == 0) {
231 if (!(*chan)->source.name.empty()) {
232 // _source->disable_metering ();
234 (*chan)->source.name = string();
236 (*chan)->source.name = connections[0];
242 AudioDiskstream::find_and_use_playlist (const string& name)
244 boost::shared_ptr<AudioPlaylist> playlist;
246 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (_session.playlists->by_name (name))) == 0) {
247 playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, name));
251 error << string_compose(_("AudioDiskstream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
255 return use_playlist (playlist);
259 AudioDiskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
261 assert(boost::dynamic_pointer_cast<AudioPlaylist>(playlist));
263 Diskstream::use_playlist(playlist);
269 AudioDiskstream::use_new_playlist ()
272 boost::shared_ptr<AudioPlaylist> playlist;
274 if (!in_set_state && destructive()) {
279 newname = Playlist::bump_name (_playlist->name(), _session);
281 newname = Playlist::bump_name (_name, _session);
284 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, newname, hidden()))) != 0) {
286 return use_playlist (playlist);
294 AudioDiskstream::use_copy_playlist ()
296 assert(audio_playlist());
302 if (_playlist == 0) {
303 error << string_compose(_("AudioDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
308 boost::shared_ptr<AudioPlaylist> playlist;
310 newname = Playlist::bump_name (_playlist->name(), _session);
312 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist>(PlaylistFactory::create (audio_playlist(), newname))) != 0) {
313 return use_playlist (playlist);
320 AudioDiskstream::setup_destructive_playlist ()
323 boost::shared_ptr<ChannelList> c = channels.reader();
325 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
326 srcs.push_back ((*chan)->write_source);
329 /* a single full-sized region */
331 assert (!srcs.empty ());
334 plist.add (Properties::name, _name.val());
335 plist.add (Properties::start, 0);
336 plist.add (Properties::length, max_framepos - (max_framepos - srcs.front()->natural_position()));
338 boost::shared_ptr<Region> region (RegionFactory::create (srcs, plist));
339 _playlist->add_region (region, srcs.front()->natural_position());
343 AudioDiskstream::use_destructive_playlist ()
345 /* this is called from the XML-based constructor or ::set_destructive. when called,
346 we already have a playlist and a region, but we need to
347 set up our sources for write. we use the sources associated
348 with the (presumed single, full-extent) region.
351 boost::shared_ptr<Region> rp = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
354 reset_write_sources (false, true);
358 boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
361 throw failed_constructor();
364 /* be sure to stretch the region out to the maximum length */
366 region->set_length (max_framepos - region->position());
369 ChannelList::iterator chan;
370 boost::shared_ptr<ChannelList> c = channels.reader();
372 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
373 (*chan)->write_source = boost::dynamic_pointer_cast<AudioFileSource>(region->source (n));
374 assert((*chan)->write_source);
375 (*chan)->write_source->set_allow_remove_if_empty (false);
377 /* this might be false if we switched modes, so force it */
379 (*chan)->write_source->set_destructive (true);
382 /* the source list will never be reset for a destructive track */
386 AudioDiskstream::prepare_record_status(framepos_t capture_start_frame)
388 if (recordable() && destructive()) {
389 boost::shared_ptr<ChannelList> c = channels.reader();
390 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
392 RingBufferNPT<CaptureTransition>::rw_vector transitions;
393 (*chan)->capture_transition_buf->get_write_vector (&transitions);
395 if (transitions.len[0] > 0) {
396 transitions.buf[0]->type = CaptureStart;
397 transitions.buf[0]->capture_val = capture_start_frame;
398 (*chan)->capture_transition_buf->increment_write_ptr(1);
401 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
409 /** Do some record stuff [not described in this comment!]
412 * - Setup playback_distance with the nframes, or nframes adjusted
413 * for current varispeed, if appropriate.
414 * - Setup current_playback_buffer in each ChannelInfo to point to data
415 * that someone can read playback_distance worth of data from.
418 AudioDiskstream::process (BufferSet& bufs, framepos_t transport_frame, pframes_t nframes, framecnt_t& playback_distance, bool need_disk_signal)
421 boost::shared_ptr<ChannelList> c = channels.reader();
422 ChannelList::iterator chan;
423 framecnt_t rec_offset = 0;
424 framecnt_t rec_nframes = 0;
425 bool collect_playback = false;
426 bool can_record = _session.actively_recording ();
428 playback_distance = 0;
430 if (!_io || !_io->active()) {
434 check_record_status (transport_frame, can_record);
440 Glib::Threads::Mutex::Lock sm (state_lock, Glib::Threads::TRY_LOCK);
446 adjust_capture_position = 0;
448 for (chan = c->begin(); chan != c->end(); ++chan) {
449 (*chan)->current_capture_buffer = 0;
450 (*chan)->current_playback_buffer = 0;
453 // Safeguard against situations where process() goes haywire when autopunching
454 // and last_recordable_frame < first_recordable_frame
456 if (last_recordable_frame < first_recordable_frame) {
457 last_recordable_frame = max_framepos;
460 if (record_enabled()) {
462 Evoral::OverlapType ot = Evoral::coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
463 calculate_record_range (ot, transport_frame, nframes, rec_nframes, rec_offset);
465 if (rec_nframes && !was_recording) {
466 capture_captured = 0;
467 was_recording = true;
471 if (can_record && !_last_capture_sources.empty()) {
472 _last_capture_sources.clear ();
477 uint32_t limit = _io->n_ports ().n_audio();
479 /* one or more ports could already have been removed from _io, but our
480 channel setup hasn't yet been updated. prevent us from trying to
481 use channels that correspond to missing ports. note that the
482 process callback (from which this is called) is always atomic
483 with respect to port removal/addition.
486 for (n = 0, chan = c->begin(); chan != c->end() && n < limit; ++chan, ++n) {
488 ChannelInfo* chaninfo (*chan);
490 chaninfo->capture_buf->get_write_vector (&chaninfo->capture_vector);
492 if (rec_nframes <= (framecnt_t) chaninfo->capture_vector.len[0]) {
494 chaninfo->current_capture_buffer = chaninfo->capture_vector.buf[0];
496 /* note: grab the entire port buffer, but only copy what we were supposed to
497 for recording, and use rec_offset
500 boost::shared_ptr<AudioPort> const ap = _io->audio (n);
502 assert(rec_nframes <= (framecnt_t) ap->get_audio_buffer(nframes).capacity());
504 Sample *buf = bufs.get_audio (n).data(rec_offset);
505 memcpy (chaninfo->current_capture_buffer, buf, sizeof (Sample) * rec_nframes);
509 framecnt_t total = chaninfo->capture_vector.len[0] + chaninfo->capture_vector.len[1];
511 if (rec_nframes > total) {
516 boost::shared_ptr<AudioPort> const ap = _io->audio (n);
519 Sample *buf = bufs.get_audio (n).data(rec_offset);
520 framecnt_t first = chaninfo->capture_vector.len[0];
522 memcpy (chaninfo->capture_wrap_buffer, buf, sizeof (Sample) * first);
523 memcpy (chaninfo->capture_vector.buf[0], buf, sizeof (Sample) * first);
524 memcpy (chaninfo->capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
525 memcpy (chaninfo->capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
527 chaninfo->current_capture_buffer = chaninfo->capture_wrap_buffer;
541 /* data will be written to disk */
543 if (rec_nframes == nframes && rec_offset == 0) {
545 for (chan = c->begin(); chan != c->end(); ++chan) {
546 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
549 playback_distance = nframes;
554 /* we can't use the capture buffer as the playback buffer, because
555 we recorded only a part of the current process' cycle data
559 collect_playback = true;
562 adjust_capture_position = rec_nframes;
564 } else if (can_record && record_enabled()) {
566 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
568 for (chan = c->begin(); chan != c->end(); ++chan) {
569 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
572 playback_distance = nframes;
576 collect_playback = true;
579 if ((_track->monitoring_state () & MonitoringDisk) || collect_playback) {
581 /* we're doing playback */
583 framecnt_t necessary_samples;
585 /* no varispeed playback if we're recording, because the output .... TBD */
587 if (rec_nframes == 0 && _actual_speed != 1.0f) {
588 necessary_samples = (framecnt_t) ceil ((nframes * fabs (_actual_speed))) + 2;
590 necessary_samples = nframes;
593 for (chan = c->begin(); chan != c->end(); ++chan) {
594 (*chan)->playback_buf->get_read_vector (&(*chan)->playback_vector);
599 /* Setup current_playback_buffer in each ChannelInfo to point to data that someone
600 can read necessary_samples (== nframes at a transport speed of 1) worth of data
604 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
606 ChannelInfo* chaninfo (*chan);
608 if (necessary_samples <= (framecnt_t) chaninfo->playback_vector.len[0]) {
609 /* There are enough samples in the first part of the ringbuffer */
610 chaninfo->current_playback_buffer = chaninfo->playback_vector.buf[0];
613 framecnt_t total = chaninfo->playback_vector.len[0] + chaninfo->playback_vector.len[1];
615 if (necessary_samples > total) {
616 cerr << _name << " Need " << necessary_samples << " total = " << total << endl;
617 cerr << "underrun for " << _name << endl;
623 /* We have enough samples, but not in one lump. Coalesce the two parts
624 into one in playback_wrap_buffer in our ChannelInfo, and specify that
625 as our current_playback_buffer.
628 assert(wrap_buffer_size >= necessary_samples);
630 /* Copy buf[0] from playback_buf */
631 memcpy ((char *) chaninfo->playback_wrap_buffer,
632 chaninfo->playback_vector.buf[0],
633 chaninfo->playback_vector.len[0] * sizeof (Sample));
635 /* Copy buf[1] from playback_buf */
636 memcpy (chaninfo->playback_wrap_buffer + chaninfo->playback_vector.len[0],
637 chaninfo->playback_vector.buf[1],
638 (necessary_samples - chaninfo->playback_vector.len[0])
641 chaninfo->current_playback_buffer = chaninfo->playback_wrap_buffer;
646 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
648 interpolation.set_speed (_target_speed);
651 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++channel) {
652 ChannelInfo* chaninfo (*chan);
654 playback_distance = interpolation.interpolate (
655 channel, nframes, chaninfo->current_playback_buffer, chaninfo->speed_buffer);
657 chaninfo->current_playback_buffer = chaninfo->speed_buffer;
661 playback_distance = nframes;
664 _speed = _target_speed;
667 if (need_disk_signal) {
669 /* copy data over to buffer set */
671 size_t n_buffers = bufs.count().n_audio();
672 size_t n_chans = c->size();
673 gain_t scaling = 1.0f;
675 if (n_chans > n_buffers) {
676 scaling = ((float) n_buffers)/n_chans;
679 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
681 AudioBuffer& buf (bufs.get_audio (n%n_buffers));
682 ChannelInfo* chaninfo (*chan);
685 if (scaling != 1.0f) {
686 buf.read_from_with_gain (chaninfo->current_playback_buffer, nframes, scaling);
688 buf.read_from (chaninfo->current_playback_buffer, nframes);
691 if (scaling != 1.0f) {
692 buf.accumulate_with_gain_from (chaninfo->current_playback_buffer, nframes, scaling);
694 buf.accumulate_from (chaninfo->current_playback_buffer, nframes);
699 /* leave the MIDI count alone */
700 ChanCount cnt (DataType::AUDIO, n_chans);
701 cnt.set (DataType::MIDI, bufs.count().n_midi());
702 bufs.set_count (cnt);
704 /* extra buffers will already be silent, so leave them alone */
711 AudioDiskstream::calculate_playback_distance (pframes_t nframes)
713 frameoffset_t playback_distance = nframes;
715 if (record_enabled()) {
716 playback_distance = nframes;
717 } else if (_actual_speed != 1.0f && _actual_speed != -1.0f) {
718 interpolation.set_speed (_target_speed);
719 boost::shared_ptr<ChannelList> c = channels.reader();
721 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++channel) {
722 playback_distance = interpolation.interpolate (channel, nframes, NULL, NULL);
725 playback_distance = nframes;
728 if (_actual_speed < 0.0) {
729 return -playback_distance;
731 return playback_distance;
735 /** Update various things including playback_sample, read pointer on each channel's playback_buf
736 * and write pointer on each channel's capture_buf. Also wout whether the butler is needed.
737 * @return true if the butler is required.
740 AudioDiskstream::commit (framecnt_t playback_distance)
742 bool need_butler = false;
744 if (!_io || !_io->active()) {
748 if (_actual_speed < 0.0) {
749 playback_sample -= playback_distance;
751 playback_sample += playback_distance;
754 boost::shared_ptr<ChannelList> c = channels.reader();
755 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
757 (*chan)->playback_buf->increment_read_ptr (playback_distance);
759 if (adjust_capture_position) {
760 (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
764 if (adjust_capture_position != 0) {
765 capture_captured += adjust_capture_position;
766 adjust_capture_position = 0;
774 if (_io && _io->active()) {
775 need_butler = c->front()->playback_buf->write_space() >= c->front()->playback_buf->bufsize() / 2;
780 if (_io && _io->active()) {
781 need_butler = ((framecnt_t) c->front()->playback_buf->write_space() >= disk_io_chunk_frames)
782 || ((framecnt_t) c->front()->capture_buf->read_space() >= disk_io_chunk_frames);
784 need_butler = ((framecnt_t) c->front()->capture_buf->read_space() >= disk_io_chunk_frames);
792 AudioDiskstream::set_pending_overwrite (bool yn)
794 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
796 _pending_overwrite = yn;
798 overwrite_frame = playback_sample;
800 boost::shared_ptr<ChannelList> c = channels.reader ();
802 overwrite_offset = c->front()->playback_buf->get_read_ptr();
807 AudioDiskstream::overwrite_existing_buffers ()
809 boost::shared_ptr<ChannelList> c = channels.reader();
811 _pending_overwrite = false;
815 Sample* mixdown_buffer;
818 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
820 overwrite_queued = false;
822 /* assume all are the same size */
823 framecnt_t size = c->front()->playback_buf->bufsize();
825 mixdown_buffer = new Sample[size];
826 gain_buffer = new float[size];
828 /* reduce size so that we can fill the buffer correctly (ringbuffers
829 can only handle size-1, otherwise they appear to be empty)
836 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
838 start = overwrite_frame;
839 framecnt_t cnt = size;
841 /* to fill the buffer without resetting the playback sample, we need to
842 do it one or two chunks (normally two).
844 |----------------------------------------------------------------------|
848 |<- second chunk->||<----------------- first chunk ------------------>|
852 framecnt_t to_read = size - overwrite_offset;
854 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, n, reversed)) {
855 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
856 id(), size, playback_sample) << endmsg;
864 if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer, start, cnt, n, reversed)) {
865 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
866 id(), size, playback_sample) << endmsg;
875 _pending_overwrite = false;
876 delete [] gain_buffer;
877 delete [] mixdown_buffer;
882 AudioDiskstream::seek (framepos_t frame, bool complete_refill)
886 ChannelList::iterator chan;
887 boost::shared_ptr<ChannelList> c = channels.reader();
889 Glib::Threads::Mutex::Lock lm (state_lock);
891 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
892 (*chan)->playback_buf->reset ();
893 (*chan)->capture_buf->reset ();
896 /* can't rec-enable in destructive mode if transport is before start */
898 if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
899 disengage_record_enable ();
902 playback_sample = frame;
905 if (complete_refill) {
906 while ((ret = do_refill_with_alloc ()) > 0) ;
908 ret = do_refill_with_alloc ();
915 AudioDiskstream::can_internal_playback_seek (framecnt_t distance)
917 ChannelList::iterator chan;
918 boost::shared_ptr<ChannelList> c = channels.reader();
920 for (chan = c->begin(); chan != c->end(); ++chan) {
921 if ((*chan)->playback_buf->read_space() < (size_t) distance) {
929 AudioDiskstream::internal_playback_seek (framecnt_t distance)
931 ChannelList::iterator chan;
932 boost::shared_ptr<ChannelList> c = channels.reader();
934 for (chan = c->begin(); chan != c->end(); ++chan) {
935 (*chan)->playback_buf->increment_read_ptr (llabs(distance));
938 if (first_recordable_frame < max_framepos) {
939 first_recordable_frame += distance;
941 playback_sample += distance;
946 /** Read some data for 1 channel from our playlist into a buffer.
947 * @param buf Buffer to write to.
948 * @param start Session frame to start reading from; updated to where we end up
950 * @param cnt Count of samples to read.
951 * @param reversed true if we are running backwards, otherwise false.
954 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer,
955 framepos_t& start, framecnt_t cnt,
956 int channel, bool reversed)
958 framecnt_t this_read = 0;
960 framepos_t loop_end = 0;
961 framepos_t loop_start = 0;
962 framecnt_t offset = 0;
965 /* XXX we don't currently play loops in reverse. not sure why */
969 framecnt_t loop_length = 0;
971 /* Make the use of a Location atomic for this read operation.
973 Note: Locations don't get deleted, so all we care about
974 when I say "atomic" is that we are always pointing to
975 the same one and using a start/length values obtained
979 if ((loc = loop_location) != 0) {
980 loop_start = loc->start();
981 loop_end = loc->end();
982 loop_length = loop_end - loop_start;
985 /* if we are looping, ensure that the first frame we read is at the correct
986 position within the loop.
989 if (loc && start >= loop_end) {
990 start = loop_start + ((start - loop_start) % loop_length);
998 /* We need this while loop in case we hit a loop boundary, in which case our read from
999 the playlist must be split into more than one section.
1004 /* take any loop into account. we can't read past the end of the loop. */
1006 if (loc && (loop_end - start < cnt)) {
1007 this_read = loop_end - start;
1014 if (this_read == 0) {
1018 this_read = min(cnt,this_read);
1020 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
1021 error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), id(), this_read,
1028 swap_by_ptr (buf, buf + this_read - 1);
1032 /* if we read to the end of the loop, go back to the beginning */
1042 offset += this_read;
1049 AudioDiskstream::do_refill_with_alloc ()
1051 Sample* mix_buf = new Sample[disk_io_chunk_frames];
1052 float* gain_buf = new float[disk_io_chunk_frames];
1054 int ret = _do_refill(mix_buf, gain_buf);
1062 /** Get some more data from disk and put it in our channels' playback_bufs,
1063 * if there is suitable space in them.
1066 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer)
1070 RingBufferNPT<Sample>::rw_vector vector;
1071 bool const reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1072 framecnt_t total_space;
1073 framecnt_t zero_fill;
1075 ChannelList::iterator i;
1076 boost::shared_ptr<ChannelList> c = channels.reader();
1083 assert(mixdown_buffer);
1084 assert(gain_buffer);
1091 c->front()->playback_buf->get_write_vector (&vector);
1093 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1094 /* nowhere to write to */
1098 /* if there are 2+ chunks of disk i/o possible for
1099 this track, let the caller know so that it can arrange
1100 for us to be called again, ASAP.
1103 if (total_space >= (_slaved ? 3 : 2) * disk_io_chunk_frames) {
1107 /* if we're running close to normal speed and there isn't enough
1108 space to do disk_io_chunk_frames of I/O, then don't bother.
1110 at higher speeds, just do it because the sync between butler
1111 and audio thread may not be good enough.
1113 Note: it is a design assumption that disk_io_chunk_frames is smaller
1114 than the playback buffer size, so this check should never trip when
1115 the playback buffer is empty.
1118 if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1122 /* when slaved, don't try to get too close to the read pointer. this
1123 leaves space for the buffer reversal to have something useful to
1127 if (_slaved && total_space < (framecnt_t) (c->front()->playback_buf->bufsize() / 2)) {
1131 /* never do more than disk_io_chunk_frames worth of disk input per call (limit doesn't apply for memset) */
1133 total_space = min (disk_io_chunk_frames, total_space);
1137 if (file_frame == 0) {
1139 /* at start: nothing to do but fill with silence */
1141 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1143 ChannelInfo* chan (*i);
1144 chan->playback_buf->get_write_vector (&vector);
1145 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1146 if (vector.len[1]) {
1147 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1149 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1154 if (file_frame < total_space) {
1156 /* too close to the start: read what we can,
1157 and then zero fill the rest
1160 zero_fill = total_space - file_frame;
1161 total_space = file_frame;
1170 if (file_frame == max_framepos) {
1172 /* at end: nothing to do but fill with silence */
1174 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1176 ChannelInfo* chan (*i);
1177 chan->playback_buf->get_write_vector (&vector);
1178 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1179 if (vector.len[1]) {
1180 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1182 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1187 if (file_frame > max_framepos - total_space) {
1189 /* to close to the end: read what we can, and zero fill the rest */
1191 zero_fill = total_space - (max_framepos - file_frame);
1192 total_space = max_framepos - file_frame;
1199 framepos_t file_frame_tmp = 0;
1201 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1203 ChannelInfo* chan (*i);
1206 framecnt_t len1, len2;
1208 chan->playback_buf->get_write_vector (&vector);
1210 if ((framecnt_t) vector.len[0] > disk_io_chunk_frames) {
1212 /* we're not going to fill the first chunk, so certainly do not bother with the
1213 other part. it won't be connected with the part we do fill, as in:
1215 .... => writable space
1216 ++++ => readable space
1217 ^^^^ => 1 x disk_io_chunk_frames that would be filled
1219 |......|+++++++++++++|...............................|
1224 So, just pretend that the buf1 part isn't there.
1234 file_frame_tmp = file_frame;
1236 buf1 = vector.buf[0];
1237 len1 = vector.len[0];
1238 buf2 = vector.buf[1];
1239 len2 = vector.len[1];
1241 to_read = min (ts, len1);
1242 to_read = min (to_read, disk_io_chunk_frames);
1244 assert (to_read >= 0);
1248 if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1253 chan->playback_buf->increment_write_ptr (to_read);
1257 to_read = min (ts, len2);
1261 /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1262 so read some or all of vector.len[1] as well.
1265 if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1270 chan->playback_buf->increment_write_ptr (to_read);
1274 /* XXX: do something */
1279 file_frame = file_frame_tmp;
1280 assert (file_frame >= 0);
1287 /** Flush pending data to disk.
1289 * Important note: this function will write *AT MOST* disk_io_chunk_frames
1290 * of data to disk. it will never write more than that. If it writes that
1291 * much and there is more than that waiting to be written, it will return 1,
1292 * otherwise 0 on success or -1 on failure.
1294 * If there is less than disk_io_chunk_frames to be written, no data will be
1295 * written at all unless @a force_flush is true.
1298 AudioDiskstream::do_flush (RunContext /*context*/, bool force_flush)
1302 RingBufferNPT<Sample>::rw_vector vector;
1303 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1306 transvec.buf[0] = 0;
1307 transvec.buf[1] = 0;
1311 boost::shared_ptr<ChannelList> c = channels.reader();
1312 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1314 (*chan)->capture_buf->get_read_vector (&vector);
1316 total = vector.len[0] + vector.len[1];
1318 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1322 /* if there are 2+ chunks of disk i/o possible for
1323 this track, let the caller know so that it can arrange
1324 for us to be called again, ASAP.
1326 if we are forcing a flush, then if there is* any* extra
1327 work, let the caller know.
1329 if we are no longer recording and there is any extra work,
1330 let the caller know too.
1333 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1337 to_write = min (disk_io_chunk_frames, (framecnt_t) vector.len[0]);
1339 // check the transition buffer when recording destructive
1340 // important that we get this after the capture buf
1342 if (destructive()) {
1343 (*chan)->capture_transition_buf->get_read_vector(&transvec);
1344 size_t transcount = transvec.len[0] + transvec.len[1];
1347 for (ti=0; ti < transcount; ++ti) {
1348 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1350 if (captrans.type == CaptureStart) {
1351 // by definition, the first data we got above represents the given capture pos
1353 (*chan)->write_source->mark_capture_start (captrans.capture_val);
1354 (*chan)->curr_capture_cnt = 0;
1356 } else if (captrans.type == CaptureEnd) {
1358 // capture end, the capture_val represents total frames in capture
1360 if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1362 // shorten to make the write a perfect fit
1363 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
1365 if (nto_write < to_write) {
1366 ret = 1; // should we?
1368 to_write = nto_write;
1370 (*chan)->write_source->mark_capture_end ();
1372 // increment past this transition, but go no further
1377 // actually ends just beyond this chunk, so force more work
1385 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1389 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1390 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), id()) << endmsg;
1394 (*chan)->capture_buf->increment_read_ptr (to_write);
1395 (*chan)->curr_capture_cnt += to_write;
1397 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1399 /* we wrote all of vector.len[0] but it wasn't an entire
1400 disk_io_chunk_frames of data, so arrange for some part
1401 of vector.len[1] to be flushed to disk as well.
1404 to_write = min ((framecnt_t)(disk_io_chunk_frames - to_write), (framecnt_t) vector.len[1]);
1406 if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1407 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), id()) << endmsg;
1411 (*chan)->capture_buf->increment_read_ptr (to_write);
1412 (*chan)->curr_capture_cnt += to_write;
1421 AudioDiskstream::transport_stopped_wallclock (struct tm& when, time_t twhen, bool abort_capture)
1423 uint32_t buffer_position;
1424 bool more_work = true;
1426 boost::shared_ptr<AudioRegion> region;
1427 framecnt_t total_capture;
1429 SourceList::iterator src;
1430 ChannelList::iterator chan;
1431 vector<CaptureInfo*>::iterator ci;
1432 boost::shared_ptr<ChannelList> c = channels.reader();
1434 bool mark_write_completed = false;
1438 /* butler is already stopped, but there may be work to do
1439 to flush remaining data to disk.
1442 while (more_work && !err) {
1443 switch (do_flush (TransportContext, true)) {
1450 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1455 /* XXX is there anything we can do if err != 0 ? */
1456 Glib::Threads::Mutex::Lock lm (capture_info_lock);
1458 if (capture_info.empty()) {
1462 if (abort_capture) {
1464 if (destructive()) {
1468 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1470 if ((*chan)->write_source) {
1472 (*chan)->write_source->mark_for_remove ();
1473 (*chan)->write_source->drop_references ();
1474 (*chan)->write_source.reset ();
1477 /* new source set up in "out" below */
1483 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1484 total_capture += (*ci)->frames;
1487 /* figure out the name for this take */
1489 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1491 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1495 s->update_header (capture_info.front()->start, when, twhen);
1496 s->set_captured_for (_name.val());
1497 s->mark_immutable ();
1499 if (Config->get_auto_analyse_audio()) {
1500 Analyser::queue_source_for_analysis (s, true);
1505 /* destructive tracks have a single, never changing region */
1507 if (destructive()) {
1509 /* send a signal that any UI can pick up to do the right thing. there is
1510 a small problem here in that a UI may need the peak data to be ready
1511 for the data that was recorded and this isn't interlocked with that
1512 process. this problem is deferred to the UI.
1515 _playlist->LayeringChanged(); // XXX this may not get the UI to do the right thing
1519 string whole_file_region_name;
1520 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1522 /* Register a new region with the Session that
1523 describes the entire source. Do this first
1524 so that any sub-regions will obviously be
1525 children of this one (later!)
1531 plist.add (Properties::start, c->front()->write_source->last_capture_start_frame());
1532 plist.add (Properties::length, total_capture);
1533 plist.add (Properties::name, whole_file_region_name);
1534 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1535 rx->set_automatic (true);
1536 rx->set_whole_file (true);
1538 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1539 region->special_set_position (capture_info.front()->start);
1543 catch (failed_constructor& err) {
1544 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1548 _last_capture_sources.insert (_last_capture_sources.end(), srcs.begin(), srcs.end());
1550 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1552 _playlist->clear_changes ();
1553 _playlist->set_capture_insertion_in_progress (true);
1554 _playlist->freeze ();
1556 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1560 RegionFactory::region_name (region_name, whole_file_region_name, false);
1562 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1 capture start @ %2 length %3 add new region %4\n",
1563 _name, (*ci)->start, (*ci)->frames, region_name));
1569 plist.add (Properties::start, buffer_position);
1570 plist.add (Properties::length, (*ci)->frames);
1571 plist.add (Properties::name, region_name);
1573 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1574 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1577 catch (failed_constructor& err) {
1578 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1579 continue; /* XXX is this OK? */
1582 i_am_the_modifier++;
1584 _playlist->add_region (region, (*ci)->start, 1, non_layered());
1585 _playlist->set_layer (region, DBL_MAX);
1586 i_am_the_modifier--;
1588 buffer_position += (*ci)->frames;
1592 _playlist->set_capture_insertion_in_progress (false);
1593 _session.add_command (new StatefulDiffCommand (_playlist));
1596 mark_write_completed = true;
1599 reset_write_sources (mark_write_completed);
1603 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1607 capture_info.clear ();
1608 capture_start_frame = 0;
1612 AudioDiskstream::transport_looped (framepos_t transport_frame)
1614 if (was_recording) {
1615 // all we need to do is finish this capture, with modified capture length
1616 boost::shared_ptr<ChannelList> c = channels.reader();
1618 // adjust the capture length knowing that the data will be recorded to disk
1619 // only necessary after the first loop where we're recording
1620 if (capture_info.size() == 0) {
1621 capture_captured += _capture_offset;
1623 if (_alignment_style == ExistingMaterial) {
1624 capture_captured += _session.worst_output_latency();
1626 capture_captured += _roll_delay;
1632 // the next region will start recording via the normal mechanism
1633 // we'll set the start position to the current transport pos
1634 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1635 capture_start_frame = transport_frame;
1636 first_recordable_frame = transport_frame; // mild lie
1637 last_recordable_frame = max_framepos;
1638 was_recording = true;
1640 if (recordable() && destructive()) {
1641 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1643 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1644 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1646 if (transvec.len[0] > 0) {
1647 transvec.buf[0]->type = CaptureStart;
1648 transvec.buf[0]->capture_val = capture_start_frame;
1649 (*chan)->capture_transition_buf->increment_write_ptr(1);
1653 fatal << X_("programming error: capture_transition_buf is full on rec loop! inconceivable!")
1663 AudioDiskstream::finish_capture (boost::shared_ptr<ChannelList> c)
1665 was_recording = false;
1666 first_recordable_frame = max_framepos;
1667 last_recordable_frame = max_framepos;
1669 if (capture_captured == 0) {
1673 if (recordable() && destructive()) {
1674 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1676 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1677 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1679 if (transvec.len[0] > 0) {
1680 transvec.buf[0]->type = CaptureEnd;
1681 transvec.buf[0]->capture_val = capture_captured;
1682 (*chan)->capture_transition_buf->increment_write_ptr(1);
1686 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1692 CaptureInfo* ci = new CaptureInfo;
1694 ci->start = capture_start_frame;
1695 ci->frames = capture_captured;
1697 /* XXX theoretical race condition here. Need atomic exchange ?
1698 However, the circumstances when this is called right
1699 now (either on record-disable or transport_stopped)
1700 mean that no actual race exists. I think ...
1701 We now have a capture_info_lock, but it is only to be used
1702 to synchronize in the transport_stop and the capture info
1703 accessors, so that invalidation will not occur (both non-realtime).
1706 // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1708 capture_info.push_back (ci);
1709 capture_captured = 0;
1711 /* now we've finished a capture, reset first_recordable_frame for next time */
1712 first_recordable_frame = max_framepos;
1716 AudioDiskstream::set_record_enabled (bool yn)
1718 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0) {
1722 /* can't rec-enable in destructive mode if transport is before start */
1724 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1728 /* yes, i know that this not proof against race conditions, but its
1729 good enough. i think.
1732 if (record_enabled() != yn) {
1734 engage_record_enable ();
1736 disengage_record_enable ();
1739 RecordEnableChanged (); /* EMIT SIGNAL */
1744 AudioDiskstream::prep_record_enable ()
1746 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0) {
1750 /* can't rec-enable in destructive mode if transport is before start */
1752 if (destructive() && _session.transport_frame() < _session.current_start_frame()) {
1756 bool rolling = _session.transport_speed() != 0.0f;
1757 boost::shared_ptr<ChannelList> c = channels.reader();
1759 capturing_sources.clear ();
1761 if (Config->get_monitoring_model() == HardwareMonitoring) {
1763 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1764 (*chan)->source.request_input_monitoring (!(_session.config.get_auto_input() && rolling));
1765 capturing_sources.push_back ((*chan)->write_source);
1766 (*chan)->write_source->mark_streaming_write_started ();
1770 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1771 capturing_sources.push_back ((*chan)->write_source);
1772 (*chan)->write_source->mark_streaming_write_started ();
1780 AudioDiskstream::prep_record_disable ()
1782 boost::shared_ptr<ChannelList> c = channels.reader();
1783 if (Config->get_monitoring_model() == HardwareMonitoring) {
1784 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1785 (*chan)->source.request_input_monitoring (false);
1788 capturing_sources.clear ();
1794 AudioDiskstream::get_state ()
1796 XMLNode& node (Diskstream::get_state());
1798 LocaleGuard lg (X_("POSIX"));
1800 boost::shared_ptr<ChannelList> c = channels.reader();
1801 snprintf (buf, sizeof(buf), "%u", (unsigned int) c->size());
1802 node.add_property ("channels", buf);
1804 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1806 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1807 XMLNode* cs_grandchild;
1809 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1810 cs_grandchild = new XMLNode (X_("file"));
1811 cs_grandchild->add_property (X_("path"), (*i)->path());
1812 cs_child->add_child_nocopy (*cs_grandchild);
1815 /* store the location where capture will start */
1819 if (_session.config.get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1820 snprintf (buf, sizeof (buf), "%" PRId64, pi->start());
1822 snprintf (buf, sizeof (buf), "%" PRId64, _session.transport_frame());
1825 cs_child->add_property (X_("at"), buf);
1826 node.add_child_nocopy (*cs_child);
1833 AudioDiskstream::set_state (const XMLNode& node, int version)
1835 const XMLProperty* prop;
1836 XMLNodeList nlist = node.children();
1837 XMLNodeIterator niter;
1838 uint32_t nchans = 1;
1839 XMLNode* capture_pending_node = 0;
1840 LocaleGuard lg (X_("POSIX"));
1842 /* prevent write sources from being created */
1844 in_set_state = true;
1846 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1847 if ((*niter)->name() == IO::state_node_name) {
1848 deprecated_io_node = new XMLNode (**niter);
1851 if ((*niter)->name() == X_("CapturingSources")) {
1852 capture_pending_node = *niter;
1856 if (Diskstream::set_state (node, version)) {
1860 if ((prop = node.property ("channels")) != 0) {
1861 nchans = atoi (prop->value().c_str());
1864 // create necessary extra channels
1865 // we are always constructed with one and we always need one
1867 _n_channels.set(DataType::AUDIO, channels.reader()->size());
1869 if (nchans > _n_channels.n_audio()) {
1871 add_channel (nchans - _n_channels.n_audio());
1872 IO::PortCountChanged(_n_channels);
1874 } else if (nchans < _n_channels.n_audio()) {
1876 remove_channel (_n_channels.n_audio() - nchans);
1881 if (!destructive() && capture_pending_node) {
1882 /* destructive streams have one and only one source per channel,
1883 and so they never end up in pending capture in any useful
1886 use_pending_capture_data (*capture_pending_node);
1889 in_set_state = false;
1891 /* make sure this is clear before we do anything else */
1893 capturing_sources.clear ();
1895 /* write sources are handled when we handle the input set
1896 up of the IO that owns this DS (::non_realtime_input_change())
1903 AudioDiskstream::use_new_write_source (uint32_t n)
1905 boost::shared_ptr<ChannelList> c = channels.reader();
1907 if (!recordable()) {
1911 if (n >= c->size()) {
1912 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
1916 ChannelInfo* chan = (*c)[n];
1919 if ((chan->write_source = _session.create_audio_source_for_session (
1920 n_channels().n_audio(), write_source_name(), n, destructive())) == 0) {
1921 throw failed_constructor();
1925 catch (failed_constructor &err) {
1926 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
1927 chan->write_source.reset ();
1931 /* do not remove destructive files even if they are empty */
1933 chan->write_source->set_allow_remove_if_empty (!destructive());
1939 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool /*force*/)
1941 ChannelList::iterator chan;
1942 boost::shared_ptr<ChannelList> c = channels.reader();
1945 if (!_session.writable() || !recordable()) {
1949 capturing_sources.clear ();
1951 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1953 if (!destructive()) {
1955 if ((*chan)->write_source) {
1957 if (mark_write_complete) {
1958 (*chan)->write_source->mark_streaming_write_completed ();
1959 (*chan)->write_source->done_with_peakfile_writes ();
1962 if ((*chan)->write_source->removable()) {
1963 (*chan)->write_source->mark_for_remove ();
1964 (*chan)->write_source->drop_references ();
1967 (*chan)->write_source.reset ();
1970 use_new_write_source (n);
1972 if (record_enabled()) {
1973 capturing_sources.push_back ((*chan)->write_source);
1978 if ((*chan)->write_source == 0) {
1979 use_new_write_source (n);
1984 if (destructive() && !c->empty ()) {
1986 /* we now have all our write sources set up, so create the
1987 playlist's single region.
1990 if (_playlist->empty()) {
1991 setup_destructive_playlist ();
1997 AudioDiskstream::set_block_size (pframes_t /*nframes*/)
1999 if (_session.get_block_size() > speed_buffer_size) {
2000 speed_buffer_size = _session.get_block_size();
2001 boost::shared_ptr<ChannelList> c = channels.reader();
2003 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2004 if ((*chan)->speed_buffer)
2005 delete [] (*chan)->speed_buffer;
2006 (*chan)->speed_buffer = new Sample[speed_buffer_size];
2009 allocate_temporary_buffers ();
2013 AudioDiskstream::allocate_temporary_buffers ()
2015 /* make sure the wrap buffer is at least large enough to deal
2016 with the speeds up to 1.2, to allow for micro-variation
2017 when slaving to MTC, Timecode etc.
2020 double const sp = max (fabsf (_actual_speed), 1.2f);
2021 framecnt_t required_wrap_size = (framecnt_t) ceil (_session.get_block_size() * sp) + 2;
2023 if (required_wrap_size > wrap_buffer_size) {
2025 boost::shared_ptr<ChannelList> c = channels.reader();
2027 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2028 if ((*chan)->playback_wrap_buffer) {
2029 delete [] (*chan)->playback_wrap_buffer;
2031 (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
2032 if ((*chan)->capture_wrap_buffer) {
2033 delete [] (*chan)->capture_wrap_buffer;
2035 (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
2038 wrap_buffer_size = required_wrap_size;
2043 AudioDiskstream::request_input_monitoring (bool yn)
2045 boost::shared_ptr<ChannelList> c = channels.reader();
2047 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2048 (*chan)->source.request_input_monitoring (yn);
2053 AudioDiskstream::set_align_style_from_io ()
2055 bool have_physical = false;
2057 if (_alignment_choice != Automatic) {
2065 get_input_sources ();
2067 boost::shared_ptr<ChannelList> c = channels.reader();
2069 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2070 if ((*chan)->source.is_physical ()) {
2071 have_physical = true;
2076 if (have_physical) {
2077 set_align_style (ExistingMaterial);
2079 set_align_style (CaptureTime);
2084 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2086 while (how_many--) {
2087 c->push_back (new ChannelInfo(
2088 _session.butler()->audio_diskstream_playback_buffer_size(),
2089 _session.butler()->audio_diskstream_capture_buffer_size(),
2090 speed_buffer_size, wrap_buffer_size));
2091 interpolation.add_channel_to (
2092 _session.butler()->audio_diskstream_playback_buffer_size(),
2096 _n_channels.set(DataType::AUDIO, c->size());
2102 AudioDiskstream::add_channel (uint32_t how_many)
2104 RCUWriter<ChannelList> writer (channels);
2105 boost::shared_ptr<ChannelList> c = writer.get_copy();
2107 return add_channel_to (c, how_many);
2111 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2113 while (how_many-- && !c->empty()) {
2116 interpolation.remove_channel_from ();
2119 _n_channels.set(DataType::AUDIO, c->size());
2125 AudioDiskstream::remove_channel (uint32_t how_many)
2127 RCUWriter<ChannelList> writer (channels);
2128 boost::shared_ptr<ChannelList> c = writer.get_copy();
2130 return remove_channel_from (c, how_many);
2134 AudioDiskstream::playback_buffer_load () const
2136 boost::shared_ptr<ChannelList> c = channels.reader();
2142 return (float) ((double) c->front()->playback_buf->read_space()/
2143 (double) c->front()->playback_buf->bufsize());
2147 AudioDiskstream::capture_buffer_load () const
2149 boost::shared_ptr<ChannelList> c = channels.reader();
2155 return (float) ((double) c->front()->capture_buf->write_space()/
2156 (double) c->front()->capture_buf->bufsize());
2160 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2162 const XMLProperty* prop;
2163 XMLNodeList nlist = node.children();
2164 XMLNodeIterator niter;
2165 boost::shared_ptr<AudioFileSource> fs;
2166 boost::shared_ptr<AudioFileSource> first_fs;
2167 SourceList pending_sources;
2168 framepos_t position;
2170 if ((prop = node.property (X_("at"))) == 0) {
2174 if (sscanf (prop->value().c_str(), "%" PRIu64, &position) != 1) {
2178 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2179 if ((*niter)->name() == X_("file")) {
2181 if ((prop = (*niter)->property (X_("path"))) == 0) {
2185 // This protects sessions from errant CapturingSources in stored sessions
2187 if (stat (prop->value().c_str(), &sbuf)) {
2191 /* XXX as of June 2014, we always record to mono
2192 files. Since this Source is being created as part of
2193 crash recovery, we know that we need the first
2194 channel (the final argument to the SourceFactory
2195 call below). If we ever support non-mono files for
2196 capture, this will need rethinking.
2200 fs = boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createForRecovery (DataType::AUDIO, _session, prop->value(), 0));
2203 catch (failed_constructor& err) {
2204 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2205 _name, prop->value())
2210 pending_sources.push_back (fs);
2212 if (first_fs == 0) {
2216 fs->set_captured_for (_name.val());
2220 if (pending_sources.size() == 0) {
2221 /* nothing can be done */
2225 if (pending_sources.size() != _n_channels.n_audio()) {
2226 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2233 boost::shared_ptr<AudioRegion> wf_region;
2234 boost::shared_ptr<AudioRegion> region;
2236 /* First create the whole file region */
2240 plist.add (Properties::start, 0);
2241 plist.add (Properties::length, first_fs->length (first_fs->timeline_position()));
2242 plist.add (Properties::name, region_name_from_path (first_fs->name(), true));
2244 wf_region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, plist));
2246 wf_region->set_automatic (true);
2247 wf_region->set_whole_file (true);
2248 wf_region->special_set_position (position);
2250 /* Now create a region that isn't the whole file for adding to
2253 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, plist));
2255 _playlist->add_region (region, position);
2258 catch (failed_constructor& err) {
2259 error << string_compose (
2260 _("%1: cannot create whole-file region from pending capture sources"),
2271 AudioDiskstream::set_non_layered (bool yn)
2273 if (yn != non_layered()) {
2276 _flags = Flag (_flags | NonLayered);
2278 _flags = Flag (_flags & ~NonLayered);
2286 AudioDiskstream::set_destructive (bool yn)
2288 if (yn != destructive()) {
2291 bool bounce_ignored;
2292 /* requestor should already have checked this and
2293 bounced if necessary and desired
2295 if (!can_become_destructive (bounce_ignored)) {
2298 _flags = Flag (_flags | Destructive);
2299 use_destructive_playlist ();
2301 _flags = Flag (_flags & ~Destructive);
2302 reset_write_sources (true, true);
2310 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2313 requires_bounce = false;
2317 /* is there only one region ? */
2319 if (_playlist->n_regions() != 1) {
2320 requires_bounce = true;
2324 boost::shared_ptr<Region> first = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
2326 requires_bounce = false;
2330 /* do the source(s) for the region cover the session start position ? */
2332 if (first->position() != _session.current_start_frame()) {
2333 if (first->start() > _session.current_start_frame()) {
2334 requires_bounce = true;
2339 /* is the source used by only 1 playlist ? */
2341 boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2345 if (_session.playlists->source_use_count (afirst->source()) > 1) {
2346 requires_bounce = true;
2350 requires_bounce = false;
2355 AudioDiskstream::adjust_playback_buffering ()
2357 boost::shared_ptr<ChannelList> c = channels.reader();
2359 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2360 (*chan)->resize_playback (_session.butler()->audio_diskstream_playback_buffer_size());
2365 AudioDiskstream::adjust_capture_buffering ()
2367 boost::shared_ptr<ChannelList> c = channels.reader();
2369 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2370 (*chan)->resize_capture (_session.butler()->audio_diskstream_capture_buffer_size());
2375 AudioDiskstream::ChannelSource::is_physical () const
2381 return AudioEngine::instance()->port_is_physical (name);
2385 AudioDiskstream::ChannelSource::request_input_monitoring (bool yn) const
2391 return AudioEngine::instance()->request_input_monitoring (name, yn);
2394 AudioDiskstream::ChannelInfo::ChannelInfo (framecnt_t playback_bufsize, framecnt_t capture_bufsize, framecnt_t speed_size, framecnt_t wrap_size)
2396 current_capture_buffer = 0;
2397 current_playback_buffer = 0;
2398 curr_capture_cnt = 0;
2400 speed_buffer = new Sample[speed_size];
2401 playback_wrap_buffer = new Sample[wrap_size];
2402 capture_wrap_buffer = new Sample[wrap_size];
2404 playback_buf = new RingBufferNPT<Sample> (playback_bufsize);
2405 capture_buf = new RingBufferNPT<Sample> (capture_bufsize);
2406 capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2408 /* touch the ringbuffer buffers, which will cause
2409 them to be mapped into locked physical RAM if
2410 we're running with mlockall(). this doesn't do
2414 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2415 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2416 memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2420 AudioDiskstream::ChannelInfo::resize_playback (framecnt_t playback_bufsize)
2422 delete playback_buf;
2423 playback_buf = new RingBufferNPT<Sample> (playback_bufsize);
2424 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2428 AudioDiskstream::ChannelInfo::resize_capture (framecnt_t capture_bufsize)
2432 capture_buf = new RingBufferNPT<Sample> (capture_bufsize);
2433 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2436 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2438 write_source.reset ();
2440 delete [] speed_buffer;
2443 delete [] playback_wrap_buffer;
2444 playback_wrap_buffer = 0;
2446 delete [] capture_wrap_buffer;
2447 capture_wrap_buffer = 0;
2449 delete playback_buf;
2455 delete capture_transition_buf;
2456 capture_transition_buf = 0;
2461 AudioDiskstream::set_name (string const & name)
2463 if (_name == name) {
2466 Diskstream::set_name (name);
2468 /* get a new write source so that its name reflects the new diskstream name */
2470 boost::shared_ptr<ChannelList> c = channels.reader();
2471 ChannelList::iterator i;
2474 for (n = 0, i = c->begin(); i != c->end(); ++i, ++n) {
2475 use_new_write_source (n);
2482 AudioDiskstream::set_write_source_name (const std::string& str) {
2483 if (_write_source_name == str) {
2487 Diskstream::set_write_source_name (str);
2489 if (_write_source_name == name()) {
2492 boost::shared_ptr<ChannelList> c = channels.reader();
2493 ChannelList::iterator i;
2496 for (n = 0, i = c->begin(); i != c->end(); ++i, ++n) {
2497 use_new_write_source (n);