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 ()
152 Glib::Threads::Mutex::Lock lm (state_lock);
154 if (input_change_pending.type == IOChange::NoChange) {
158 if (input_change_pending.type == IOChange::ConfigurationChanged) {
159 RCUWriter<ChannelList> writer (channels);
160 boost::shared_ptr<ChannelList> c = writer.get_copy();
162 _n_channels.set(DataType::AUDIO, c->size());
164 if (_io->n_ports().n_audio() > _n_channels.n_audio()) {
165 add_channel_to (c, _io->n_ports().n_audio() - _n_channels.n_audio());
166 } else if (_io->n_ports().n_audio() < _n_channels.n_audio()) {
167 remove_channel_from (c, _n_channels.n_audio() - _io->n_ports().n_audio());
171 if (input_change_pending.type & IOChange::ConnectionsChanged) {
172 get_input_sources ();
173 set_capture_offset ();
174 set_align_style_from_io ();
177 input_change_pending = IOChange::NoChange;
179 /* implicit unlock */
182 /* reset capture files */
184 reset_write_sources (false);
186 /* now refill channel buffers */
188 if (speed() != 1.0f || speed() != -1.0f) {
189 seek ((framepos_t) (_session.transport_frame() * (double) speed()));
191 seek (_session.transport_frame());
196 AudioDiskstream::non_realtime_locate (framepos_t location)
198 /* now refill channel buffers */
200 if (speed() != 1.0f || speed() != -1.0f) {
201 seek ((framepos_t) (location * (double) speed()));
208 AudioDiskstream::get_input_sources ()
210 boost::shared_ptr<ChannelList> c = channels.reader();
213 ChannelList::iterator chan;
214 uint32_t ni = _io->n_ports().n_audio();
215 vector<string> connections;
217 for (n = 0, chan = c->begin(); chan != c->end() && n < ni; ++chan, ++n) {
219 connections.clear ();
221 if (_io->nth (n)->get_connections (connections) == 0) {
222 if (!(*chan)->source.name.empty()) {
223 // _source->disable_metering ();
225 (*chan)->source.name = string();
227 (*chan)->source.name = connections[0];
233 AudioDiskstream::find_and_use_playlist (const string& name)
235 boost::shared_ptr<AudioPlaylist> playlist;
237 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (_session.playlists->by_name (name))) == 0) {
238 playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, name));
242 error << string_compose(_("AudioDiskstream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
246 return use_playlist (playlist);
250 AudioDiskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
252 assert(boost::dynamic_pointer_cast<AudioPlaylist>(playlist));
254 Diskstream::use_playlist(playlist);
260 AudioDiskstream::use_new_playlist ()
263 boost::shared_ptr<AudioPlaylist> playlist;
265 if (!in_set_state && destructive()) {
270 newname = Playlist::bump_name (_playlist->name(), _session);
272 newname = Playlist::bump_name (_name, _session);
275 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, newname, hidden()))) != 0) {
277 return use_playlist (playlist);
285 AudioDiskstream::use_copy_playlist ()
287 assert(audio_playlist());
293 if (_playlist == 0) {
294 error << string_compose(_("AudioDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
299 boost::shared_ptr<AudioPlaylist> playlist;
301 newname = Playlist::bump_name (_playlist->name(), _session);
303 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist>(PlaylistFactory::create (audio_playlist(), newname))) != 0) {
304 return use_playlist (playlist);
311 AudioDiskstream::setup_destructive_playlist ()
314 boost::shared_ptr<ChannelList> c = channels.reader();
316 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
317 srcs.push_back ((*chan)->write_source);
320 /* a single full-sized region */
322 assert (!srcs.empty ());
325 plist.add (Properties::name, _name.val());
326 plist.add (Properties::start, 0);
327 plist.add (Properties::length, max_framepos - (max_framepos - srcs.front()->natural_position()));
329 boost::shared_ptr<Region> region (RegionFactory::create (srcs, plist));
330 _playlist->add_region (region, srcs.front()->natural_position());
334 AudioDiskstream::use_destructive_playlist ()
336 /* this is called from the XML-based constructor or ::set_destructive. when called,
337 we already have a playlist and a region, but we need to
338 set up our sources for write. we use the sources associated
339 with the (presumed single, full-extent) region.
342 boost::shared_ptr<Region> rp = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
345 reset_write_sources (false, true);
349 boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
352 throw failed_constructor();
355 /* be sure to stretch the region out to the maximum length */
357 region->set_length (max_framepos - region->position());
360 ChannelList::iterator chan;
361 boost::shared_ptr<ChannelList> c = channels.reader();
363 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
364 (*chan)->write_source = boost::dynamic_pointer_cast<AudioFileSource>(region->source (n));
365 assert((*chan)->write_source);
366 (*chan)->write_source->set_allow_remove_if_empty (false);
368 /* this might be false if we switched modes, so force it */
370 (*chan)->write_source->set_destructive (true);
373 /* the source list will never be reset for a destructive track */
377 AudioDiskstream::prepare_record_status(framepos_t capture_start_frame)
379 if (recordable() && destructive()) {
380 boost::shared_ptr<ChannelList> c = channels.reader();
381 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
383 RingBufferNPT<CaptureTransition>::rw_vector transitions;
384 (*chan)->capture_transition_buf->get_write_vector (&transitions);
386 if (transitions.len[0] > 0) {
387 transitions.buf[0]->type = CaptureStart;
388 transitions.buf[0]->capture_val = capture_start_frame;
389 (*chan)->capture_transition_buf->increment_write_ptr(1);
392 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
400 /** Do some record stuff [not described in this comment!]
403 * - Setup playback_distance with the nframes, or nframes adjusted
404 * for current varispeed, if appropriate.
405 * - Setup current_playback_buffer in each ChannelInfo to point to data
406 * that someone can read playback_distance worth of data from.
409 AudioDiskstream::process (BufferSet& bufs, framepos_t transport_frame, pframes_t nframes, framecnt_t& playback_distance, bool need_disk_signal)
412 boost::shared_ptr<ChannelList> c = channels.reader();
413 ChannelList::iterator chan;
414 framecnt_t rec_offset = 0;
415 framecnt_t rec_nframes = 0;
416 bool collect_playback = false;
417 bool can_record = _session.actively_recording ();
419 playback_distance = 0;
421 if (!_io || !_io->active()) {
425 check_record_status (transport_frame, can_record);
431 Glib::Threads::Mutex::Lock sm (state_lock, Glib::Threads::TRY_LOCK);
437 adjust_capture_position = 0;
439 for (chan = c->begin(); chan != c->end(); ++chan) {
440 (*chan)->current_capture_buffer = 0;
441 (*chan)->current_playback_buffer = 0;
444 // Safeguard against situations where process() goes haywire when autopunching
445 // and last_recordable_frame < first_recordable_frame
447 if (last_recordable_frame < first_recordable_frame) {
448 last_recordable_frame = max_framepos;
451 if (record_enabled()) {
453 Evoral::OverlapType ot = Evoral::coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
454 calculate_record_range (ot, transport_frame, nframes, rec_nframes, rec_offset);
456 if (rec_nframes && !was_recording) {
457 capture_captured = 0;
458 was_recording = true;
462 if (can_record && !_last_capture_sources.empty()) {
463 _last_capture_sources.clear ();
468 uint32_t limit = _io->n_ports ().n_audio();
470 /* one or more ports could already have been removed from _io, but our
471 channel setup hasn't yet been updated. prevent us from trying to
472 use channels that correspond to missing ports. note that the
473 process callback (from which this is called) is always atomic
474 with respect to port removal/addition.
477 for (n = 0, chan = c->begin(); chan != c->end() && n < limit; ++chan, ++n) {
479 ChannelInfo* chaninfo (*chan);
481 chaninfo->capture_buf->get_write_vector (&chaninfo->capture_vector);
483 if (rec_nframes <= (framecnt_t) chaninfo->capture_vector.len[0]) {
485 chaninfo->current_capture_buffer = chaninfo->capture_vector.buf[0];
487 /* note: grab the entire port buffer, but only copy what we were supposed to
488 for recording, and use rec_offset
491 boost::shared_ptr<AudioPort> const ap = _io->audio (n);
493 assert(rec_nframes <= (framecnt_t) ap->get_audio_buffer(nframes).capacity());
495 Sample *buf = bufs.get_audio (n).data(rec_offset);
496 memcpy (chaninfo->current_capture_buffer, buf, sizeof (Sample) * rec_nframes);
500 framecnt_t total = chaninfo->capture_vector.len[0] + chaninfo->capture_vector.len[1];
502 if (rec_nframes > total) {
507 boost::shared_ptr<AudioPort> const ap = _io->audio (n);
510 Sample *buf = bufs.get_audio (n).data(rec_offset);
511 framecnt_t first = chaninfo->capture_vector.len[0];
513 memcpy (chaninfo->capture_wrap_buffer, buf, sizeof (Sample) * first);
514 memcpy (chaninfo->capture_vector.buf[0], buf, sizeof (Sample) * first);
515 memcpy (chaninfo->capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
516 memcpy (chaninfo->capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
518 chaninfo->current_capture_buffer = chaninfo->capture_wrap_buffer;
532 /* data will be written to disk */
534 if (rec_nframes == nframes && rec_offset == 0) {
536 for (chan = c->begin(); chan != c->end(); ++chan) {
537 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
540 playback_distance = nframes;
545 /* we can't use the capture buffer as the playback buffer, because
546 we recorded only a part of the current process' cycle data
550 collect_playback = true;
553 adjust_capture_position = rec_nframes;
555 } else if (can_record && record_enabled()) {
557 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
559 for (chan = c->begin(); chan != c->end(); ++chan) {
560 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
563 playback_distance = nframes;
567 collect_playback = true;
570 if ((_track->monitoring_state () & MonitoringDisk) || collect_playback) {
572 /* we're doing playback */
574 framecnt_t necessary_samples;
576 /* no varispeed playback if we're recording, because the output .... TBD */
578 if (rec_nframes == 0 && _actual_speed != 1.0f) {
579 necessary_samples = (framecnt_t) ceil ((nframes * fabs (_actual_speed))) + 2;
581 necessary_samples = nframes;
584 for (chan = c->begin(); chan != c->end(); ++chan) {
585 (*chan)->playback_buf->get_read_vector (&(*chan)->playback_vector);
590 /* Setup current_playback_buffer in each ChannelInfo to point to data that someone
591 can read necessary_samples (== nframes at a transport speed of 1) worth of data
595 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
597 ChannelInfo* chaninfo (*chan);
599 if (necessary_samples <= (framecnt_t) chaninfo->playback_vector.len[0]) {
600 /* There are enough samples in the first part of the ringbuffer */
601 chaninfo->current_playback_buffer = chaninfo->playback_vector.buf[0];
604 framecnt_t total = chaninfo->playback_vector.len[0] + chaninfo->playback_vector.len[1];
606 if (necessary_samples > total) {
607 cerr << _name << " Need " << necessary_samples << " total = " << total << endl;
608 cerr << "underrun for " << _name << endl;
614 /* We have enough samples, but not in one lump. Coalesce the two parts
615 into one in playback_wrap_buffer in our ChannelInfo, and specify that
616 as our current_playback_buffer.
619 assert(wrap_buffer_size >= necessary_samples);
621 /* Copy buf[0] from playback_buf */
622 memcpy ((char *) chaninfo->playback_wrap_buffer,
623 chaninfo->playback_vector.buf[0],
624 chaninfo->playback_vector.len[0] * sizeof (Sample));
626 /* Copy buf[1] from playback_buf */
627 memcpy (chaninfo->playback_wrap_buffer + chaninfo->playback_vector.len[0],
628 chaninfo->playback_vector.buf[1],
629 (necessary_samples - chaninfo->playback_vector.len[0])
632 chaninfo->current_playback_buffer = chaninfo->playback_wrap_buffer;
637 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
639 interpolation.set_speed (_target_speed);
642 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++channel) {
643 ChannelInfo* chaninfo (*chan);
645 playback_distance = interpolation.interpolate (
646 channel, nframes, chaninfo->current_playback_buffer, chaninfo->speed_buffer);
648 chaninfo->current_playback_buffer = chaninfo->speed_buffer;
652 playback_distance = nframes;
655 _speed = _target_speed;
658 if (need_disk_signal) {
660 /* copy data over to buffer set */
662 size_t n_buffers = bufs.count().n_audio();
663 size_t n_chans = c->size();
664 gain_t scaling = 1.0f;
666 if (n_chans > n_buffers) {
667 scaling = ((float) n_buffers)/n_chans;
670 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
672 AudioBuffer& buf (bufs.get_audio (n%n_buffers));
673 ChannelInfo* chaninfo (*chan);
676 if (scaling != 1.0f) {
677 buf.read_from_with_gain (chaninfo->current_playback_buffer, nframes, scaling);
679 buf.read_from (chaninfo->current_playback_buffer, nframes);
682 if (scaling != 1.0f) {
683 buf.accumulate_with_gain_from (chaninfo->current_playback_buffer, nframes, scaling);
685 buf.accumulate_from (chaninfo->current_playback_buffer, nframes);
690 /* leave the MIDI count alone */
691 ChanCount cnt (DataType::AUDIO, n_chans);
692 cnt.set (DataType::MIDI, bufs.count().n_midi());
693 bufs.set_count (cnt);
695 /* extra buffers will already be silent, so leave them alone */
701 /** Update various things including playback_sample, read pointer on each channel's playback_buf
702 * and write pointer on each channel's capture_buf. Also wout whether the butler is needed.
703 * @return true if the butler is required.
706 AudioDiskstream::commit (framecnt_t playback_distance)
708 bool need_butler = false;
710 if (!_io || !_io->active()) {
714 if (_actual_speed < 0.0) {
715 playback_sample -= playback_distance;
717 playback_sample += playback_distance;
720 boost::shared_ptr<ChannelList> c = channels.reader();
721 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
723 (*chan)->playback_buf->increment_read_ptr (playback_distance);
725 if (adjust_capture_position) {
726 (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
730 if (adjust_capture_position != 0) {
731 capture_captured += adjust_capture_position;
732 adjust_capture_position = 0;
740 if (_io && _io->active()) {
741 need_butler = c->front()->playback_buf->write_space() >= c->front()->playback_buf->bufsize() / 2;
746 if (_io && _io->active()) {
747 need_butler = ((framecnt_t) c->front()->playback_buf->write_space() >= disk_io_chunk_frames)
748 || ((framecnt_t) c->front()->capture_buf->read_space() >= disk_io_chunk_frames);
750 need_butler = ((framecnt_t) c->front()->capture_buf->read_space() >= disk_io_chunk_frames);
758 AudioDiskstream::set_pending_overwrite (bool yn)
760 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
762 _pending_overwrite = yn;
764 overwrite_frame = playback_sample;
766 boost::shared_ptr<ChannelList> c = channels.reader ();
768 overwrite_offset = c->front()->playback_buf->get_read_ptr();
773 AudioDiskstream::overwrite_existing_buffers ()
775 boost::shared_ptr<ChannelList> c = channels.reader();
777 _pending_overwrite = false;
781 Sample* mixdown_buffer;
784 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
786 overwrite_queued = false;
788 /* assume all are the same size */
789 framecnt_t size = c->front()->playback_buf->bufsize();
791 mixdown_buffer = new Sample[size];
792 gain_buffer = new float[size];
794 /* reduce size so that we can fill the buffer correctly (ringbuffers
795 can only handle size-1, otherwise they appear to be empty)
802 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
804 start = overwrite_frame;
805 framecnt_t cnt = size;
807 /* to fill the buffer without resetting the playback sample, we need to
808 do it one or two chunks (normally two).
810 |----------------------------------------------------------------------|
814 |<- second chunk->||<----------------- first chunk ------------------>|
818 framecnt_t to_read = size - overwrite_offset;
820 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, n, reversed)) {
821 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
822 id(), size, playback_sample) << endmsg;
830 if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer, start, cnt, n, reversed)) {
831 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
832 id(), size, playback_sample) << endmsg;
841 _pending_overwrite = false;
842 delete [] gain_buffer;
843 delete [] mixdown_buffer;
848 AudioDiskstream::seek (framepos_t frame, bool complete_refill)
852 ChannelList::iterator chan;
853 boost::shared_ptr<ChannelList> c = channels.reader();
855 Glib::Threads::Mutex::Lock lm (state_lock);
857 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
858 (*chan)->playback_buf->reset ();
859 (*chan)->capture_buf->reset ();
862 /* can't rec-enable in destructive mode if transport is before start */
864 if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
865 disengage_record_enable ();
868 playback_sample = frame;
871 if (complete_refill) {
872 while ((ret = do_refill_with_alloc ()) > 0) ;
874 ret = do_refill_with_alloc ();
881 AudioDiskstream::can_internal_playback_seek (framecnt_t distance)
883 ChannelList::iterator chan;
884 boost::shared_ptr<ChannelList> c = channels.reader();
886 for (chan = c->begin(); chan != c->end(); ++chan) {
887 if ((*chan)->playback_buf->read_space() < (size_t) distance) {
895 AudioDiskstream::internal_playback_seek (framecnt_t distance)
897 ChannelList::iterator chan;
898 boost::shared_ptr<ChannelList> c = channels.reader();
900 for (chan = c->begin(); chan != c->end(); ++chan) {
901 (*chan)->playback_buf->increment_read_ptr (distance);
904 if (first_recordable_frame < max_framepos) {
905 first_recordable_frame += distance;
907 playback_sample += distance;
912 /** Read some data for 1 channel from our playlist into a buffer.
913 * @param buf Buffer to write to.
914 * @param start Session frame to start reading from; updated to where we end up
916 * @param cnt Count of samples to read.
917 * @param reversed true if we are running backwards, otherwise false.
920 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer,
921 framepos_t& start, framecnt_t cnt,
922 int channel, bool reversed)
924 framecnt_t this_read = 0;
926 framepos_t loop_end = 0;
927 framepos_t loop_start = 0;
928 framecnt_t offset = 0;
931 /* XXX we don't currently play loops in reverse. not sure why */
935 framecnt_t loop_length = 0;
937 /* Make the use of a Location atomic for this read operation.
939 Note: Locations don't get deleted, so all we care about
940 when I say "atomic" is that we are always pointing to
941 the same one and using a start/length values obtained
945 if ((loc = loop_location) != 0) {
946 loop_start = loc->start();
947 loop_end = loc->end();
948 loop_length = loop_end - loop_start;
951 /* if we are looping, ensure that the first frame we read is at the correct
952 position within the loop.
955 if (loc && start >= loop_end) {
956 start = loop_start + ((start - loop_start) % loop_length);
964 /* We need this while loop in case we hit a loop boundary, in which case our read from
965 the playlist must be split into more than one section.
970 /* take any loop into account. we can't read past the end of the loop. */
972 if (loc && (loop_end - start < cnt)) {
973 this_read = loop_end - start;
980 if (this_read == 0) {
984 this_read = min(cnt,this_read);
986 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
987 error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), id(), this_read,
994 swap_by_ptr (buf, buf + this_read - 1);
998 /* if we read to the end of the loop, go back to the beginning */
1008 offset += this_read;
1015 AudioDiskstream::do_refill_with_alloc ()
1017 Sample* mix_buf = new Sample[disk_io_chunk_frames];
1018 float* gain_buf = new float[disk_io_chunk_frames];
1020 int ret = _do_refill(mix_buf, gain_buf);
1028 /** Get some more data from disk and put it in our channels' playback_bufs,
1029 * if there is suitable space in them.
1032 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer)
1036 RingBufferNPT<Sample>::rw_vector vector;
1037 bool const reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1038 framecnt_t total_space;
1039 framecnt_t zero_fill;
1041 ChannelList::iterator i;
1042 boost::shared_ptr<ChannelList> c = channels.reader();
1049 assert(mixdown_buffer);
1050 assert(gain_buffer);
1057 c->front()->playback_buf->get_write_vector (&vector);
1059 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1060 /* nowhere to write to */
1064 /* if there are 2+ chunks of disk i/o possible for
1065 this track, let the caller know so that it can arrange
1066 for us to be called again, ASAP.
1069 if (total_space >= (_slaved ? 3 : 2) * disk_io_chunk_frames) {
1073 /* if we're running close to normal speed and there isn't enough
1074 space to do disk_io_chunk_frames of I/O, then don't bother.
1076 at higher speeds, just do it because the sync between butler
1077 and audio thread may not be good enough.
1079 Note: it is a design assumption that disk_io_chunk_frames is smaller
1080 than the playback buffer size, so this check should never trip when
1081 the playback buffer is empty.
1084 if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1088 /* when slaved, don't try to get too close to the read pointer. this
1089 leaves space for the buffer reversal to have something useful to
1093 if (_slaved && total_space < (framecnt_t) (c->front()->playback_buf->bufsize() / 2)) {
1097 /* never do more than disk_io_chunk_frames worth of disk input per call (limit doesn't apply for memset) */
1099 total_space = min (disk_io_chunk_frames, total_space);
1103 if (file_frame == 0) {
1105 /* at start: nothing to do but fill with silence */
1107 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1109 ChannelInfo* chan (*i);
1110 chan->playback_buf->get_write_vector (&vector);
1111 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1112 if (vector.len[1]) {
1113 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1115 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1120 if (file_frame < total_space) {
1122 /* too close to the start: read what we can,
1123 and then zero fill the rest
1126 zero_fill = total_space - file_frame;
1127 total_space = file_frame;
1136 if (file_frame == max_framepos) {
1138 /* at end: nothing to do but fill with silence */
1140 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1142 ChannelInfo* chan (*i);
1143 chan->playback_buf->get_write_vector (&vector);
1144 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1145 if (vector.len[1]) {
1146 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1148 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1153 if (file_frame > max_framepos - total_space) {
1155 /* to close to the end: read what we can, and zero fill the rest */
1157 zero_fill = total_space - (max_framepos - file_frame);
1158 total_space = max_framepos - file_frame;
1165 framepos_t file_frame_tmp = 0;
1167 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1169 ChannelInfo* chan (*i);
1172 framecnt_t len1, len2;
1174 chan->playback_buf->get_write_vector (&vector);
1176 if ((framecnt_t) vector.len[0] > disk_io_chunk_frames) {
1178 /* we're not going to fill the first chunk, so certainly do not bother with the
1179 other part. it won't be connected with the part we do fill, as in:
1181 .... => writable space
1182 ++++ => readable space
1183 ^^^^ => 1 x disk_io_chunk_frames that would be filled
1185 |......|+++++++++++++|...............................|
1190 So, just pretend that the buf1 part isn't there.
1200 file_frame_tmp = file_frame;
1202 buf1 = vector.buf[0];
1203 len1 = vector.len[0];
1204 buf2 = vector.buf[1];
1205 len2 = vector.len[1];
1207 to_read = min (ts, len1);
1208 to_read = min (to_read, disk_io_chunk_frames);
1210 assert (to_read >= 0);
1214 if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1219 chan->playback_buf->increment_write_ptr (to_read);
1223 to_read = min (ts, len2);
1227 /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1228 so read some or all of vector.len[1] as well.
1231 if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1236 chan->playback_buf->increment_write_ptr (to_read);
1240 /* XXX: do something */
1245 file_frame = file_frame_tmp;
1246 assert (file_frame >= 0);
1253 /** Flush pending data to disk.
1255 * Important note: this function will write *AT MOST* disk_io_chunk_frames
1256 * of data to disk. it will never write more than that. If it writes that
1257 * much and there is more than that waiting to be written, it will return 1,
1258 * otherwise 0 on success or -1 on failure.
1260 * If there is less than disk_io_chunk_frames to be written, no data will be
1261 * written at all unless @a force_flush is true.
1264 AudioDiskstream::do_flush (RunContext /*context*/, bool force_flush)
1268 RingBufferNPT<Sample>::rw_vector vector;
1269 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1272 transvec.buf[0] = 0;
1273 transvec.buf[1] = 0;
1277 boost::shared_ptr<ChannelList> c = channels.reader();
1278 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1280 (*chan)->capture_buf->get_read_vector (&vector);
1282 total = vector.len[0] + vector.len[1];
1284 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1288 /* if there are 2+ chunks of disk i/o possible for
1289 this track, let the caller know so that it can arrange
1290 for us to be called again, ASAP.
1292 if we are forcing a flush, then if there is* any* extra
1293 work, let the caller know.
1295 if we are no longer recording and there is any extra work,
1296 let the caller know too.
1299 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1303 to_write = min (disk_io_chunk_frames, (framecnt_t) vector.len[0]);
1305 // check the transition buffer when recording destructive
1306 // important that we get this after the capture buf
1308 if (destructive()) {
1309 (*chan)->capture_transition_buf->get_read_vector(&transvec);
1310 size_t transcount = transvec.len[0] + transvec.len[1];
1313 for (ti=0; ti < transcount; ++ti) {
1314 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1316 if (captrans.type == CaptureStart) {
1317 // by definition, the first data we got above represents the given capture pos
1319 (*chan)->write_source->mark_capture_start (captrans.capture_val);
1320 (*chan)->curr_capture_cnt = 0;
1322 } else if (captrans.type == CaptureEnd) {
1324 // capture end, the capture_val represents total frames in capture
1326 if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1328 // shorten to make the write a perfect fit
1329 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
1331 if (nto_write < to_write) {
1332 ret = 1; // should we?
1334 to_write = nto_write;
1336 (*chan)->write_source->mark_capture_end ();
1338 // increment past this transition, but go no further
1343 // actually ends just beyond this chunk, so force more work
1351 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1355 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1356 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), id()) << endmsg;
1360 (*chan)->capture_buf->increment_read_ptr (to_write);
1361 (*chan)->curr_capture_cnt += to_write;
1363 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1365 /* we wrote all of vector.len[0] but it wasn't an entire
1366 disk_io_chunk_frames of data, so arrange for some part
1367 of vector.len[1] to be flushed to disk as well.
1370 to_write = min ((framecnt_t)(disk_io_chunk_frames - to_write), (framecnt_t) vector.len[1]);
1372 if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1373 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), id()) << endmsg;
1377 (*chan)->capture_buf->increment_read_ptr (to_write);
1378 (*chan)->curr_capture_cnt += to_write;
1387 AudioDiskstream::transport_stopped_wallclock (struct tm& when, time_t twhen, bool abort_capture)
1389 uint32_t buffer_position;
1390 bool more_work = true;
1392 boost::shared_ptr<AudioRegion> region;
1393 framecnt_t total_capture;
1395 SourceList::iterator src;
1396 ChannelList::iterator chan;
1397 vector<CaptureInfo*>::iterator ci;
1398 boost::shared_ptr<ChannelList> c = channels.reader();
1400 bool mark_write_completed = false;
1404 /* butler is already stopped, but there may be work to do
1405 to flush remaining data to disk.
1408 while (more_work && !err) {
1409 switch (do_flush (TransportContext, true)) {
1416 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1421 /* XXX is there anything we can do if err != 0 ? */
1422 Glib::Threads::Mutex::Lock lm (capture_info_lock);
1424 if (capture_info.empty()) {
1428 if (abort_capture) {
1430 if (destructive()) {
1434 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1436 if ((*chan)->write_source) {
1438 (*chan)->write_source->mark_for_remove ();
1439 (*chan)->write_source->drop_references ();
1440 (*chan)->write_source.reset ();
1443 /* new source set up in "out" below */
1449 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1450 total_capture += (*ci)->frames;
1453 /* figure out the name for this take */
1455 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1457 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1461 s->update_header (capture_info.front()->start, when, twhen);
1462 s->set_captured_for (_name.val());
1463 s->mark_immutable ();
1465 if (Config->get_auto_analyse_audio()) {
1466 Analyser::queue_source_for_analysis (s, true);
1471 /* destructive tracks have a single, never changing region */
1473 if (destructive()) {
1475 /* send a signal that any UI can pick up to do the right thing. there is
1476 a small problem here in that a UI may need the peak data to be ready
1477 for the data that was recorded and this isn't interlocked with that
1478 process. this problem is deferred to the UI.
1481 _playlist->LayeringChanged(); // XXX this may not get the UI to do the right thing
1485 string whole_file_region_name;
1486 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1488 /* Register a new region with the Session that
1489 describes the entire source. Do this first
1490 so that any sub-regions will obviously be
1491 children of this one (later!)
1497 plist.add (Properties::start, c->front()->write_source->last_capture_start_frame());
1498 plist.add (Properties::length, total_capture);
1499 plist.add (Properties::name, whole_file_region_name);
1500 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1501 rx->set_automatic (true);
1502 rx->set_whole_file (true);
1504 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1505 region->special_set_position (capture_info.front()->start);
1509 catch (failed_constructor& err) {
1510 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1514 _last_capture_sources.insert (_last_capture_sources.end(), srcs.begin(), srcs.end());
1516 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1518 _playlist->clear_changes ();
1519 _playlist->set_capture_insertion_in_progress (true);
1520 _playlist->freeze ();
1522 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1526 RegionFactory::region_name (region_name, whole_file_region_name, false);
1528 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1 capture start @ %2 length %3 add new region %4\n",
1529 _name, (*ci)->start, (*ci)->frames, region_name));
1535 plist.add (Properties::start, buffer_position);
1536 plist.add (Properties::length, (*ci)->frames);
1537 plist.add (Properties::name, region_name);
1539 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1540 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1543 catch (failed_constructor& err) {
1544 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1545 continue; /* XXX is this OK? */
1548 i_am_the_modifier++;
1550 _playlist->add_region (region, (*ci)->start, 1, non_layered());
1551 _playlist->set_layer (region, DBL_MAX);
1552 i_am_the_modifier--;
1554 buffer_position += (*ci)->frames;
1558 _playlist->set_capture_insertion_in_progress (false);
1559 _session.add_command (new StatefulDiffCommand (_playlist));
1562 mark_write_completed = true;
1565 reset_write_sources (mark_write_completed);
1569 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1573 capture_info.clear ();
1574 capture_start_frame = 0;
1578 AudioDiskstream::transport_looped (framepos_t transport_frame)
1580 if (was_recording) {
1581 // all we need to do is finish this capture, with modified capture length
1582 boost::shared_ptr<ChannelList> c = channels.reader();
1584 // adjust the capture length knowing that the data will be recorded to disk
1585 // only necessary after the first loop where we're recording
1586 if (capture_info.size() == 0) {
1587 capture_captured += _capture_offset;
1589 if (_alignment_style == ExistingMaterial) {
1590 capture_captured += _session.worst_output_latency();
1592 capture_captured += _roll_delay;
1598 // the next region will start recording via the normal mechanism
1599 // we'll set the start position to the current transport pos
1600 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1601 capture_start_frame = transport_frame;
1602 first_recordable_frame = transport_frame; // mild lie
1603 last_recordable_frame = max_framepos;
1604 was_recording = true;
1606 if (recordable() && destructive()) {
1607 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1609 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1610 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1612 if (transvec.len[0] > 0) {
1613 transvec.buf[0]->type = CaptureStart;
1614 transvec.buf[0]->capture_val = capture_start_frame;
1615 (*chan)->capture_transition_buf->increment_write_ptr(1);
1619 fatal << X_("programming error: capture_transition_buf is full on rec loop! inconceivable!")
1629 AudioDiskstream::finish_capture (boost::shared_ptr<ChannelList> c)
1631 was_recording = false;
1632 first_recordable_frame = max_framepos;
1633 last_recordable_frame = max_framepos;
1635 if (capture_captured == 0) {
1639 if (recordable() && destructive()) {
1640 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1642 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1643 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1645 if (transvec.len[0] > 0) {
1646 transvec.buf[0]->type = CaptureEnd;
1647 transvec.buf[0]->capture_val = capture_captured;
1648 (*chan)->capture_transition_buf->increment_write_ptr(1);
1652 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1658 CaptureInfo* ci = new CaptureInfo;
1660 ci->start = capture_start_frame;
1661 ci->frames = capture_captured;
1663 /* XXX theoretical race condition here. Need atomic exchange ?
1664 However, the circumstances when this is called right
1665 now (either on record-disable or transport_stopped)
1666 mean that no actual race exists. I think ...
1667 We now have a capture_info_lock, but it is only to be used
1668 to synchronize in the transport_stop and the capture info
1669 accessors, so that invalidation will not occur (both non-realtime).
1672 // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1674 capture_info.push_back (ci);
1675 capture_captured = 0;
1677 /* now we've finished a capture, reset first_recordable_frame for next time */
1678 first_recordable_frame = max_framepos;
1682 AudioDiskstream::set_record_enabled (bool yn)
1684 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0) {
1688 /* can't rec-enable in destructive mode if transport is before start */
1690 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1694 /* yes, i know that this not proof against race conditions, but its
1695 good enough. i think.
1698 if (record_enabled() != yn) {
1700 engage_record_enable ();
1702 disengage_record_enable ();
1705 RecordEnableChanged (); /* EMIT SIGNAL */
1710 AudioDiskstream::prep_record_enable ()
1712 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0) {
1716 /* can't rec-enable in destructive mode if transport is before start */
1718 if (destructive() && _session.transport_frame() < _session.current_start_frame()) {
1722 bool rolling = _session.transport_speed() != 0.0f;
1723 boost::shared_ptr<ChannelList> c = channels.reader();
1725 capturing_sources.clear ();
1727 if (Config->get_monitoring_model() == HardwareMonitoring) {
1729 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1730 (*chan)->source.request_jack_monitors_input (!(_session.config.get_auto_input() && rolling));
1731 capturing_sources.push_back ((*chan)->write_source);
1732 (*chan)->write_source->mark_streaming_write_started ();
1736 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1737 capturing_sources.push_back ((*chan)->write_source);
1738 (*chan)->write_source->mark_streaming_write_started ();
1746 AudioDiskstream::prep_record_disable ()
1748 boost::shared_ptr<ChannelList> c = channels.reader();
1749 if (Config->get_monitoring_model() == HardwareMonitoring) {
1750 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1751 (*chan)->source.request_jack_monitors_input (false);
1754 capturing_sources.clear ();
1760 AudioDiskstream::get_state ()
1762 XMLNode& node (Diskstream::get_state());
1764 LocaleGuard lg (X_("POSIX"));
1766 boost::shared_ptr<ChannelList> c = channels.reader();
1767 snprintf (buf, sizeof(buf), "%zd", c->size());
1768 node.add_property ("channels", buf);
1770 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1772 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1773 XMLNode* cs_grandchild;
1775 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1776 cs_grandchild = new XMLNode (X_("file"));
1777 cs_grandchild->add_property (X_("path"), (*i)->path());
1778 cs_child->add_child_nocopy (*cs_grandchild);
1781 /* store the location where capture will start */
1785 if (_session.config.get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1786 snprintf (buf, sizeof (buf), "%" PRId64, pi->start());
1788 snprintf (buf, sizeof (buf), "%" PRId64, _session.transport_frame());
1791 cs_child->add_property (X_("at"), buf);
1792 node.add_child_nocopy (*cs_child);
1799 AudioDiskstream::set_state (const XMLNode& node, int version)
1801 const XMLProperty* prop;
1802 XMLNodeList nlist = node.children();
1803 XMLNodeIterator niter;
1804 uint32_t nchans = 1;
1805 XMLNode* capture_pending_node = 0;
1806 LocaleGuard lg (X_("POSIX"));
1808 /* prevent write sources from being created */
1810 in_set_state = true;
1812 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1813 if ((*niter)->name() == IO::state_node_name) {
1814 deprecated_io_node = new XMLNode (**niter);
1817 if ((*niter)->name() == X_("CapturingSources")) {
1818 capture_pending_node = *niter;
1822 if (Diskstream::set_state (node, version)) {
1826 if ((prop = node.property ("channels")) != 0) {
1827 nchans = atoi (prop->value().c_str());
1830 // create necessary extra channels
1831 // we are always constructed with one and we always need one
1833 _n_channels.set(DataType::AUDIO, channels.reader()->size());
1835 if (nchans > _n_channels.n_audio()) {
1837 add_channel (nchans - _n_channels.n_audio());
1838 IO::PortCountChanged(_n_channels);
1840 } else if (nchans < _n_channels.n_audio()) {
1842 remove_channel (_n_channels.n_audio() - nchans);
1847 if (!destructive() && capture_pending_node) {
1848 /* destructive streams have one and only one source per channel,
1849 and so they never end up in pending capture in any useful
1852 use_pending_capture_data (*capture_pending_node);
1855 in_set_state = false;
1857 /* make sure this is clear before we do anything else */
1859 capturing_sources.clear ();
1861 /* write sources are handled when we handle the input set
1862 up of the IO that owns this DS (::non_realtime_input_change())
1869 AudioDiskstream::use_new_write_source (uint32_t n)
1871 boost::shared_ptr<ChannelList> c = channels.reader();
1873 if (!recordable()) {
1877 if (n >= c->size()) {
1878 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
1882 ChannelInfo* chan = (*c)[n];
1885 if ((chan->write_source = _session.create_audio_source_for_session (
1886 n_channels().n_audio(), name(), n, destructive())) == 0) {
1887 throw failed_constructor();
1891 catch (failed_constructor &err) {
1892 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
1893 chan->write_source.reset ();
1897 /* do not remove destructive files even if they are empty */
1899 chan->write_source->set_allow_remove_if_empty (!destructive());
1904 list<boost::shared_ptr<Source> >
1905 AudioDiskstream::steal_write_sources()
1907 /* not possible to steal audio write sources */
1908 list<boost::shared_ptr<Source> > ret;
1913 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool /*force*/)
1915 ChannelList::iterator chan;
1916 boost::shared_ptr<ChannelList> c = channels.reader();
1919 if (!_session.writable() || !recordable()) {
1923 capturing_sources.clear ();
1925 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1927 if (!destructive()) {
1929 if ((*chan)->write_source) {
1931 if (mark_write_complete) {
1932 (*chan)->write_source->mark_streaming_write_completed ();
1933 (*chan)->write_source->done_with_peakfile_writes ();
1936 if ((*chan)->write_source->removable()) {
1937 (*chan)->write_source->mark_for_remove ();
1938 (*chan)->write_source->drop_references ();
1941 (*chan)->write_source.reset ();
1944 use_new_write_source (n);
1946 if (record_enabled()) {
1947 capturing_sources.push_back ((*chan)->write_source);
1952 if ((*chan)->write_source == 0) {
1953 use_new_write_source (n);
1958 if (destructive() && !c->empty ()) {
1960 /* we now have all our write sources set up, so create the
1961 playlist's single region.
1964 if (_playlist->empty()) {
1965 setup_destructive_playlist ();
1971 AudioDiskstream::set_block_size (pframes_t /*nframes*/)
1973 if (_session.get_block_size() > speed_buffer_size) {
1974 speed_buffer_size = _session.get_block_size();
1975 boost::shared_ptr<ChannelList> c = channels.reader();
1977 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1978 if ((*chan)->speed_buffer)
1979 delete [] (*chan)->speed_buffer;
1980 (*chan)->speed_buffer = new Sample[speed_buffer_size];
1983 allocate_temporary_buffers ();
1987 AudioDiskstream::allocate_temporary_buffers ()
1989 /* make sure the wrap buffer is at least large enough to deal
1990 with the speeds up to 1.2, to allow for micro-variation
1991 when slaving to MTC, Timecode etc.
1994 double const sp = max (fabsf (_actual_speed), 1.2f);
1995 framecnt_t required_wrap_size = (framecnt_t) ceil (_session.get_block_size() * sp) + 2;
1997 if (required_wrap_size > wrap_buffer_size) {
1999 boost::shared_ptr<ChannelList> c = channels.reader();
2001 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2002 if ((*chan)->playback_wrap_buffer) {
2003 delete [] (*chan)->playback_wrap_buffer;
2005 (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
2006 if ((*chan)->capture_wrap_buffer) {
2007 delete [] (*chan)->capture_wrap_buffer;
2009 (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
2012 wrap_buffer_size = required_wrap_size;
2017 AudioDiskstream::request_jack_monitors_input (bool yn)
2019 boost::shared_ptr<ChannelList> c = channels.reader();
2021 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2022 (*chan)->source.request_jack_monitors_input (yn);
2027 AudioDiskstream::set_align_style_from_io ()
2029 bool have_physical = false;
2031 if (_alignment_choice != Automatic) {
2039 get_input_sources ();
2041 boost::shared_ptr<ChannelList> c = channels.reader();
2043 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2044 if ((*chan)->source.is_physical ()) {
2045 have_physical = true;
2050 if (have_physical) {
2051 set_align_style (ExistingMaterial);
2053 set_align_style (CaptureTime);
2058 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2060 while (how_many--) {
2061 c->push_back (new ChannelInfo(
2062 _session.butler()->audio_diskstream_playback_buffer_size(),
2063 _session.butler()->audio_diskstream_capture_buffer_size(),
2064 speed_buffer_size, wrap_buffer_size));
2065 interpolation.add_channel_to (
2066 _session.butler()->audio_diskstream_playback_buffer_size(),
2070 _n_channels.set(DataType::AUDIO, c->size());
2076 AudioDiskstream::add_channel (uint32_t how_many)
2078 RCUWriter<ChannelList> writer (channels);
2079 boost::shared_ptr<ChannelList> c = writer.get_copy();
2081 return add_channel_to (c, how_many);
2085 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2087 while (how_many-- && !c->empty()) {
2090 interpolation.remove_channel_from ();
2093 _n_channels.set(DataType::AUDIO, c->size());
2099 AudioDiskstream::remove_channel (uint32_t how_many)
2101 RCUWriter<ChannelList> writer (channels);
2102 boost::shared_ptr<ChannelList> c = writer.get_copy();
2104 return remove_channel_from (c, how_many);
2108 AudioDiskstream::playback_buffer_load () const
2110 boost::shared_ptr<ChannelList> c = channels.reader();
2116 return (float) ((double) c->front()->playback_buf->read_space()/
2117 (double) c->front()->playback_buf->bufsize());
2121 AudioDiskstream::capture_buffer_load () const
2123 boost::shared_ptr<ChannelList> c = channels.reader();
2129 return (float) ((double) c->front()->capture_buf->write_space()/
2130 (double) c->front()->capture_buf->bufsize());
2134 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2136 const XMLProperty* prop;
2137 XMLNodeList nlist = node.children();
2138 XMLNodeIterator niter;
2139 boost::shared_ptr<AudioFileSource> fs;
2140 boost::shared_ptr<AudioFileSource> first_fs;
2141 SourceList pending_sources;
2142 framepos_t position;
2144 if ((prop = node.property (X_("at"))) == 0) {
2148 if (sscanf (prop->value().c_str(), "%" PRIu64, &position) != 1) {
2152 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2153 if ((*niter)->name() == X_("file")) {
2155 if ((prop = (*niter)->property (X_("path"))) == 0) {
2159 // This protects sessions from errant CapturingSources in stored sessions
2161 if (stat (prop->value().c_str(), &sbuf)) {
2166 fs = boost::dynamic_pointer_cast<AudioFileSource> (
2167 SourceFactory::createWritable (
2168 DataType::AUDIO, _session,
2169 prop->value(), false, _session.frame_rate()));
2172 catch (failed_constructor& err) {
2173 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2174 _name, prop->value())
2179 pending_sources.push_back (fs);
2181 if (first_fs == 0) {
2185 fs->set_captured_for (_name.val());
2189 if (pending_sources.size() == 0) {
2190 /* nothing can be done */
2194 if (pending_sources.size() != _n_channels.n_audio()) {
2195 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2200 boost::shared_ptr<AudioRegion> region;
2206 plist.add (Properties::start, 0);
2207 plist.add (Properties::length, first_fs->length (first_fs->timeline_position()));
2208 plist.add (Properties::name, region_name_from_path (first_fs->name(), true));
2210 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, plist));
2212 region->set_automatic (true);
2213 region->set_whole_file (true);
2214 region->special_set_position (0);
2217 catch (failed_constructor& err) {
2218 error << string_compose (
2219 _("%1: cannot create whole-file region from pending capture sources"),
2225 _playlist->add_region (region, position);
2231 AudioDiskstream::set_non_layered (bool yn)
2233 if (yn != non_layered()) {
2236 _flags = Flag (_flags | NonLayered);
2238 _flags = Flag (_flags & ~NonLayered);
2246 AudioDiskstream::set_destructive (bool yn)
2248 if (yn != destructive()) {
2251 bool bounce_ignored;
2252 /* requestor should already have checked this and
2253 bounced if necessary and desired
2255 if (!can_become_destructive (bounce_ignored)) {
2258 _flags = Flag (_flags | Destructive);
2259 use_destructive_playlist ();
2261 _flags = Flag (_flags & ~Destructive);
2262 reset_write_sources (true, true);
2270 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2273 requires_bounce = false;
2277 /* is there only one region ? */
2279 if (_playlist->n_regions() != 1) {
2280 requires_bounce = true;
2284 boost::shared_ptr<Region> first = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
2286 requires_bounce = false;
2290 /* do the source(s) for the region cover the session start position ? */
2292 if (first->position() != _session.current_start_frame()) {
2293 if (first->start() > _session.current_start_frame()) {
2294 requires_bounce = true;
2299 /* is the source used by only 1 playlist ? */
2301 boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2305 if (_session.playlists->source_use_count (afirst->source()) > 1) {
2306 requires_bounce = true;
2310 requires_bounce = false;
2315 AudioDiskstream::adjust_playback_buffering ()
2317 boost::shared_ptr<ChannelList> c = channels.reader();
2319 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2320 (*chan)->resize_playback (_session.butler()->audio_diskstream_playback_buffer_size());
2325 AudioDiskstream::adjust_capture_buffering ()
2327 boost::shared_ptr<ChannelList> c = channels.reader();
2329 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2330 (*chan)->resize_capture (_session.butler()->audio_diskstream_capture_buffer_size());
2335 AudioDiskstream::ChannelSource::is_physical () const
2341 return AudioEngine::instance()->port_is_physical (name);
2345 AudioDiskstream::ChannelSource::request_jack_monitors_input (bool yn) const
2351 return AudioEngine::instance()->request_jack_monitors_input (name, yn);
2354 AudioDiskstream::ChannelInfo::ChannelInfo (framecnt_t playback_bufsize, framecnt_t capture_bufsize, framecnt_t speed_size, framecnt_t wrap_size)
2356 current_capture_buffer = 0;
2357 current_playback_buffer = 0;
2358 curr_capture_cnt = 0;
2360 speed_buffer = new Sample[speed_size];
2361 playback_wrap_buffer = new Sample[wrap_size];
2362 capture_wrap_buffer = new Sample[wrap_size];
2364 playback_buf = new RingBufferNPT<Sample> (playback_bufsize);
2365 capture_buf = new RingBufferNPT<Sample> (capture_bufsize);
2366 capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2368 /* touch the ringbuffer buffers, which will cause
2369 them to be mapped into locked physical RAM if
2370 we're running with mlockall(). this doesn't do
2374 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2375 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2376 memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2380 AudioDiskstream::ChannelInfo::resize_playback (framecnt_t playback_bufsize)
2382 delete playback_buf;
2383 playback_buf = new RingBufferNPT<Sample> (playback_bufsize);
2384 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2388 AudioDiskstream::ChannelInfo::resize_capture (framecnt_t capture_bufsize)
2392 capture_buf = new RingBufferNPT<Sample> (capture_bufsize);
2393 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2396 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2398 write_source.reset ();
2400 delete [] speed_buffer;
2403 delete [] playback_wrap_buffer;
2404 playback_wrap_buffer = 0;
2406 delete [] capture_wrap_buffer;
2407 capture_wrap_buffer = 0;
2409 delete playback_buf;
2415 delete capture_transition_buf;
2416 capture_transition_buf = 0;
2421 AudioDiskstream::set_name (string const & name)
2423 Diskstream::set_name (name);
2425 /* get a new write source so that its name reflects the new diskstream name */
2427 boost::shared_ptr<ChannelList> c = channels.reader();
2428 ChannelList::iterator i;
2431 for (n = 0, i = c->begin(); i != c->end(); ++i, ++n) {
2432 use_new_write_source (n);