2 Copyright (C) 2000-2006 Paul Davis
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
33 #include "pbd/error.h"
34 #include <glibmm/thread.h>
35 #include "pbd/xml++.h"
36 #include "pbd/memento_command.h"
37 #include "pbd/enumwriter.h"
38 #include "pbd/stacktrace.h"
40 #include "ardour/analyser.h"
41 #include "ardour/ardour.h"
42 #include "ardour/audio_buffer.h"
43 #include "ardour/audio_diskstream.h"
44 #include "ardour/audio_port.h"
45 #include "ardour/audioengine.h"
46 #include "ardour/audiofilesource.h"
47 #include "ardour/audioplaylist.h"
48 #include "ardour/audioregion.h"
49 #include "ardour/butler.h"
50 #include "ardour/configuration.h"
51 #include "ardour/cycle_timer.h"
52 #include "ardour/debug.h"
53 #include "ardour/io.h"
54 #include "ardour/playlist_factory.h"
55 #include "ardour/region_factory.h"
56 #include "ardour/send.h"
57 #include "ardour/session.h"
58 #include "ardour/source_factory.h"
59 #include "ardour/utils.h"
60 #include "ardour/session_playlists.h"
66 using namespace ARDOUR;
69 size_t AudioDiskstream::_working_buffers_size = 0;
70 Sample* AudioDiskstream::_mixdown_buffer = 0;
71 gain_t* AudioDiskstream::_gain_buffer = 0;
73 AudioDiskstream::AudioDiskstream (Session &sess, const string &name, Diskstream::Flag flag)
74 : Diskstream(sess, name, flag)
75 , deprecated_io_node(NULL)
76 , channels (new ChannelList)
78 /* prevent any write sources from being created */
88 AudioDiskstream::AudioDiskstream (Session& sess, const XMLNode& node)
89 : Diskstream(sess, node)
90 , deprecated_io_node(NULL)
91 , channels (new ChannelList)
96 if (set_state (node, Stateful::loading_state_version)) {
98 throw failed_constructor();
101 in_set_state = false;
104 use_destructive_playlist ();
109 AudioDiskstream::init (Diskstream::Flag f)
113 /* there are no channels at this point, so these
114 two calls just get speed_buffer_size and wrap_buffer
115 size setup without duplicating their code.
118 set_block_size (_session.get_block_size());
119 allocate_temporary_buffers ();
122 assert(_n_channels == ChanCount(DataType::AUDIO, 1));
125 AudioDiskstream::~AudioDiskstream ()
127 DEBUG_TRACE (DEBUG::Destruction, string_compose ("Audio Diskstream %1 destructor\n", _name));
130 RCUWriter<ChannelList> writer (channels);
131 boost::shared_ptr<ChannelList> c = writer.get_copy();
133 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
144 AudioDiskstream::allocate_working_buffers()
146 assert(disk_io_frames() > 0);
148 _working_buffers_size = disk_io_frames();
149 _mixdown_buffer = new Sample[_working_buffers_size];
150 _gain_buffer = new gain_t[_working_buffers_size];
154 AudioDiskstream::free_working_buffers()
156 delete [] _mixdown_buffer;
157 delete [] _gain_buffer;
158 _working_buffers_size = 0;
164 AudioDiskstream::non_realtime_input_change ()
167 Glib::Mutex::Lock lm (state_lock);
169 if (input_change_pending == NoChange) {
174 RCUWriter<ChannelList> writer (channels);
175 boost::shared_ptr<ChannelList> c = writer.get_copy();
177 _n_channels.set(DataType::AUDIO, c->size());
179 if (_io->n_ports().n_audio() > _n_channels.n_audio()) {
180 add_channel_to (c, _io->n_ports().n_audio() - _n_channels.n_audio());
181 } else if (_io->n_ports().n_audio() < _n_channels.n_audio()) {
182 remove_channel_from (c, _n_channels.n_audio() - _io->n_ports().n_audio());
186 get_input_sources ();
187 set_capture_offset ();
189 if (first_input_change) {
190 set_align_style (_persistent_alignment_style);
191 first_input_change = false;
193 set_align_style_from_io ();
196 input_change_pending = NoChange;
198 /* implicit unlock */
201 /* reset capture files */
203 reset_write_sources (false);
205 /* now refill channel buffers */
207 if (speed() != 1.0f || speed() != -1.0f) {
208 seek ((nframes_t) (_session.transport_frame() * (double) speed()));
210 seek (_session.transport_frame());
215 AudioDiskstream::non_realtime_locate (nframes_t location)
217 /* now refill channel buffers */
219 if (speed() != 1.0f || speed() != -1.0f) {
220 seek ((nframes_t) (location * (double) speed()));
227 AudioDiskstream::get_input_sources ()
229 boost::shared_ptr<ChannelList> c = channels.reader();
232 ChannelList::iterator chan;
233 uint32_t ni = _io->n_ports().n_audio();
234 vector<string> connections;
236 for (n = 0, chan = c->begin(); chan != c->end() && n < ni; ++chan, ++n) {
238 connections.clear ();
240 if (_io->nth (n)->get_connections (connections) == 0) {
242 if ((*chan)->source) {
243 // _source->disable_metering ();
249 (*chan)->source = dynamic_cast<AudioPort*>(_session.engine().get_port_by_name (connections[0]) );
255 AudioDiskstream::find_and_use_playlist (const string& name)
257 boost::shared_ptr<AudioPlaylist> playlist;
259 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (_session.playlists->by_name (name))) == 0) {
260 playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, name));
264 error << string_compose(_("AudioDiskstream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
268 return use_playlist (playlist);
272 AudioDiskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
274 assert(boost::dynamic_pointer_cast<AudioPlaylist>(playlist));
276 Diskstream::use_playlist(playlist);
282 AudioDiskstream::use_new_playlist ()
285 boost::shared_ptr<AudioPlaylist> playlist;
287 if (!in_set_state && destructive()) {
292 newname = Playlist::bump_name (_playlist->name(), _session);
294 newname = Playlist::bump_name (_name, _session);
297 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, newname, hidden()))) != 0) {
299 playlist->set_orig_diskstream_id (id());
300 return use_playlist (playlist);
308 AudioDiskstream::use_copy_playlist ()
310 assert(audio_playlist());
316 if (_playlist == 0) {
317 error << string_compose(_("AudioDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
322 boost::shared_ptr<AudioPlaylist> playlist;
324 newname = Playlist::bump_name (_playlist->name(), _session);
326 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist>(PlaylistFactory::create (audio_playlist(), newname))) != 0) {
327 playlist->set_orig_diskstream_id (id());
328 return use_playlist (playlist);
335 AudioDiskstream::setup_destructive_playlist ()
338 boost::shared_ptr<ChannelList> c = channels.reader();
340 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
341 srcs.push_back ((*chan)->write_source);
344 /* a single full-sized region */
346 boost::shared_ptr<Region> region (RegionFactory::create (srcs, 0, max_frames - srcs.front()->natural_position(), _name));
347 _playlist->add_region (region, srcs.front()->natural_position());
351 AudioDiskstream::use_destructive_playlist ()
353 /* this is called from the XML-based constructor or ::set_destructive. when called,
354 we already have a playlist and a region, but we need to
355 set up our sources for write. we use the sources associated
356 with the (presumed single, full-extent) region.
359 boost::shared_ptr<Region> rp = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
362 reset_write_sources (false, true);
366 boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
369 throw failed_constructor();
372 /* be sure to stretch the region out to the maximum length */
374 region->set_length (max_frames - region->position(), this);
377 ChannelList::iterator chan;
378 boost::shared_ptr<ChannelList> c = channels.reader();
380 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
381 (*chan)->write_source = boost::dynamic_pointer_cast<AudioFileSource>(region->source (n));
382 assert((*chan)->write_source);
383 (*chan)->write_source->set_allow_remove_if_empty (false);
385 /* this might be false if we switched modes, so force it */
387 (*chan)->write_source->set_destructive (true);
390 /* the source list will never be reset for a destructive track */
394 AudioDiskstream::prepare_record_status(nframes_t capture_start_frame)
396 if (recordable() && destructive()) {
397 boost::shared_ptr<ChannelList> c = channels.reader();
398 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
400 RingBufferNPT<CaptureTransition>::rw_vector transvec;
401 (*chan)->capture_transition_buf->get_write_vector(&transvec);
403 if (transvec.len[0] > 0) {
404 transvec.buf[0]->type = CaptureStart;
405 transvec.buf[0]->capture_val = capture_start_frame;
406 (*chan)->capture_transition_buf->increment_write_ptr(1);
410 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
418 AudioDiskstream::process (nframes_t transport_frame, nframes_t nframes, bool can_record, bool rec_monitors_input)
421 boost::shared_ptr<ChannelList> c = channels.reader();
422 ChannelList::iterator chan;
424 nframes_t rec_offset = 0;
425 nframes_t rec_nframes = 0;
426 bool nominally_recording;
427 bool re = record_enabled ();
428 bool collect_playback = false;
430 /* if we've already processed the frames corresponding to this call,
431 just return. this allows multiple routes that are taking input
432 from this diskstream to call our ::process() method, but have
433 this stuff only happen once. more commonly, it allows both
434 the AudioTrack that is using this AudioDiskstream *and* the Session
435 to call process() without problems.
442 commit_should_unlock = false;
444 if (!_io || !_io->active()) {
449 check_record_status (transport_frame, nframes, can_record);
451 nominally_recording = (can_record && re);
458 /* This lock is held until the end of AudioDiskstream::commit, so these two functions
459 must always be called as a pair. The only exception is if this function
460 returns a non-zero value, in which case, ::commit should not be called.
463 // If we can't take the state lock return.
464 if (!state_lock.trylock()) {
467 commit_should_unlock = true;
468 adjust_capture_position = 0;
470 for (chan = c->begin(); chan != c->end(); ++chan) {
471 (*chan)->current_capture_buffer = 0;
472 (*chan)->current_playback_buffer = 0;
475 if (nominally_recording || (_session.get_record_enabled() && _session.config.get_punch_in())) {
476 // Safeguard against situations where process() goes haywire when autopunching and last_recordable_frame < first_recordable_frame
477 if (last_recordable_frame < first_recordable_frame) {
478 last_recordable_frame = max_frames;
481 OverlapType ot = coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
483 calculate_record_range(ot, transport_frame, nframes, rec_nframes, rec_offset);
485 if (rec_nframes && !was_recording) {
486 capture_captured = 0;
487 was_recording = true;
492 if (can_record && !_last_capture_regions.empty()) {
493 _last_capture_regions.clear ();
496 if (nominally_recording || rec_nframes) {
498 uint32_t limit = _io->n_ports ().n_audio();
500 /* one or more ports could already have been removed from _io, but our
501 channel setup hasn't yet been updated. prevent us from trying to
502 use channels that correspond to missing ports. note that the
503 process callback (from which this is called) is always atomic
504 with respect to port removal/addition.
507 for (n = 0, chan = c->begin(); chan != c->end() && n < limit; ++chan, ++n) {
509 ChannelInfo* chaninfo (*chan);
511 chaninfo->capture_buf->get_write_vector (&chaninfo->capture_vector);
513 if (rec_nframes <= chaninfo->capture_vector.len[0]) {
515 chaninfo->current_capture_buffer = chaninfo->capture_vector.buf[0];
517 /* note: grab the entire port buffer, but only copy what we were supposed to
518 for recording, and use rec_offset
521 AudioPort* const ap = _io->audio (n);
523 assert(rec_nframes <= ap->get_audio_buffer(nframes).capacity());
524 memcpy (chaninfo->current_capture_buffer, ap->get_audio_buffer (rec_nframes).data(rec_offset), sizeof (Sample) * rec_nframes);
529 nframes_t total = chaninfo->capture_vector.len[0] + chaninfo->capture_vector.len[1];
531 if (rec_nframes > total) {
536 AudioPort* const ap = _io->audio (n);
539 Sample* buf = ap->get_audio_buffer(nframes).data();
540 nframes_t first = chaninfo->capture_vector.len[0];
542 memcpy (chaninfo->capture_wrap_buffer, buf, sizeof (Sample) * first);
543 memcpy (chaninfo->capture_vector.buf[0], buf, sizeof (Sample) * first);
544 memcpy (chaninfo->capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
545 memcpy (chaninfo->capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
547 chaninfo->current_capture_buffer = chaninfo->capture_wrap_buffer;
554 finish_capture (rec_monitors_input, c);
561 /* data will be written to disk */
563 if (rec_nframes == nframes && rec_offset == 0) {
565 for (chan = c->begin(); chan != c->end(); ++chan) {
566 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
569 playback_distance = nframes;
574 /* we can't use the capture buffer as the playback buffer, because
575 we recorded only a part of the current process' cycle data
579 collect_playback = true;
582 adjust_capture_position = rec_nframes;
584 } else if (nominally_recording) {
586 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
588 for (chan = c->begin(); chan != c->end(); ++chan) {
589 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
592 playback_distance = nframes;
596 collect_playback = true;
599 if (collect_playback) {
601 /* we're doing playback */
603 nframes_t necessary_samples;
605 /* no varispeed playback if we're recording, because the output .... TBD */
607 if (rec_nframes == 0 && _actual_speed != 1.0f) {
608 necessary_samples = (nframes_t) floor ((nframes * fabs (_actual_speed))) + 1;
610 necessary_samples = nframes;
613 for (chan = c->begin(); chan != c->end(); ++chan) {
614 (*chan)->playback_buf->get_read_vector (&(*chan)->playback_vector);
619 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
621 ChannelInfo* chaninfo (*chan);
623 if (necessary_samples <= chaninfo->playback_vector.len[0]) {
625 chaninfo->current_playback_buffer = chaninfo->playback_vector.buf[0];
628 nframes_t total = chaninfo->playback_vector.len[0] + chaninfo->playback_vector.len[1];
630 if (necessary_samples > total) {
631 cerr << _name << " Need " << necessary_samples << " total = " << total << endl;
632 cerr << "underrun for " << _name << endl;
638 memcpy ((char *) chaninfo->playback_wrap_buffer,
639 chaninfo->playback_vector.buf[0],
640 chaninfo->playback_vector.len[0] * sizeof (Sample));
641 memcpy (chaninfo->playback_wrap_buffer + chaninfo->playback_vector.len[0],
642 chaninfo->playback_vector.buf[1],
643 (necessary_samples - chaninfo->playback_vector.len[0])
646 chaninfo->current_playback_buffer = chaninfo->playback_wrap_buffer;
651 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
652 process_varispeed_playback(nframes, c);
654 playback_distance = nframes;
657 _speed = _target_speed;
668 /* we're exiting with failure, so ::commit will not
669 be called. unlock the state lock.
672 commit_should_unlock = false;
680 AudioDiskstream::process_varispeed_playback(nframes_t nframes, boost::shared_ptr<ChannelList> c)
682 ChannelList::iterator chan;
684 interpolation.set_speed (_target_speed);
687 for (chan = c->begin(); chan != c->end(); ++chan, ++channel) {
688 ChannelInfo* chaninfo (*chan);
690 playback_distance = interpolation.interpolate (
691 channel, nframes, chaninfo->current_playback_buffer, chaninfo->speed_buffer);
693 chaninfo->current_playback_buffer = chaninfo->speed_buffer;
698 AudioDiskstream::commit (nframes_t /*nframes*/)
700 bool need_butler = false;
702 if (!_io || !_io->active()) {
706 if (_actual_speed < 0.0) {
707 playback_sample -= playback_distance;
709 playback_sample += playback_distance;
712 boost::shared_ptr<ChannelList> c = channels.reader();
713 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
715 (*chan)->playback_buf->increment_read_ptr (playback_distance);
717 if (adjust_capture_position) {
718 (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
722 if (adjust_capture_position != 0) {
723 capture_captured += adjust_capture_position;
724 adjust_capture_position = 0;
728 if (_io && _io->active()) {
729 need_butler = c->front()->playback_buf->write_space() >= c->front()->playback_buf->bufsize() / 2;
734 if (_io && _io->active()) {
735 need_butler = c->front()->playback_buf->write_space() >= disk_io_chunk_frames
736 || c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
738 need_butler = c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
742 if (commit_should_unlock) {
752 AudioDiskstream::set_pending_overwrite (bool yn)
754 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
756 pending_overwrite = yn;
758 overwrite_frame = playback_sample;
759 overwrite_offset = channels.reader()->front()->playback_buf->get_read_ptr();
763 AudioDiskstream::overwrite_existing_buffers ()
765 boost::shared_ptr<ChannelList> c = channels.reader();
766 Sample* mixdown_buffer;
769 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
771 overwrite_queued = false;
773 /* assume all are the same size */
774 nframes_t size = c->front()->playback_buf->bufsize();
776 mixdown_buffer = new Sample[size];
777 gain_buffer = new float[size];
779 /* reduce size so that we can fill the buffer correctly. */
785 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
787 start = overwrite_frame;
788 nframes_t cnt = size;
790 /* to fill the buffer without resetting the playback sample, we need to
791 do it one or two chunks (normally two).
793 |----------------------------------------------------------------------|
797 |<- second chunk->||<----------------- first chunk ------------------>|
801 nframes_t to_read = size - overwrite_offset;
803 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, *chan, n, reversed)) {
804 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
805 _id, size, playback_sample) << endmsg;
813 if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer,
814 start, cnt, *chan, n, reversed)) {
815 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
816 _id, size, playback_sample) << endmsg;
825 pending_overwrite = false;
826 delete [] gain_buffer;
827 delete [] mixdown_buffer;
832 AudioDiskstream::seek (nframes_t frame, bool complete_refill)
836 ChannelList::iterator chan;
837 boost::shared_ptr<ChannelList> c = channels.reader();
839 Glib::Mutex::Lock lm (state_lock);
841 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
842 (*chan)->playback_buf->reset ();
843 (*chan)->capture_buf->reset ();
846 /* can't rec-enable in destructive mode if transport is before start */
848 if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
849 disengage_record_enable ();
852 playback_sample = frame;
855 if (complete_refill) {
856 while ((ret = do_refill_with_alloc ()) > 0) ;
858 ret = do_refill_with_alloc ();
865 AudioDiskstream::can_internal_playback_seek (nframes_t distance)
867 ChannelList::iterator chan;
868 boost::shared_ptr<ChannelList> c = channels.reader();
870 for (chan = c->begin(); chan != c->end(); ++chan) {
871 if ((*chan)->playback_buf->read_space() < distance) {
879 AudioDiskstream::internal_playback_seek (nframes_t distance)
881 ChannelList::iterator chan;
882 boost::shared_ptr<ChannelList> c = channels.reader();
884 for (chan = c->begin(); chan != c->end(); ++chan) {
885 (*chan)->playback_buf->increment_read_ptr (distance);
888 first_recordable_frame += distance;
889 playback_sample += distance;
895 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer, nframes_t& start, nframes_t cnt,
896 ChannelInfo* /*channel_info*/, int channel, bool reversed)
898 nframes_t this_read = 0;
900 nframes_t loop_end = 0;
901 nframes_t loop_start = 0;
902 nframes_t loop_length = 0;
903 nframes_t offset = 0;
906 /* XXX we don't currently play loops in reverse. not sure why */
910 /* Make the use of a Location atomic for this read operation.
912 Note: Locations don't get deleted, so all we care about
913 when I say "atomic" is that we are always pointing to
914 the same one and using a start/length values obtained
918 if ((loc = loop_location) != 0) {
919 loop_start = loc->start();
920 loop_end = loc->end();
921 loop_length = loop_end - loop_start;
924 /* if we are looping, ensure that the first frame we read is at the correct
925 position within the loop.
928 if (loc && start >= loop_end) {
929 //cerr << "start adjusted from " << start;
930 start = loop_start + ((start - loop_start) % loop_length);
931 //cerr << "to " << start << endl;
934 //cerr << "start is " << start << " loopstart: " << loop_start << " loopend: " << loop_end << endl;
943 /* take any loop into account. we can't read past the end of the loop. */
945 if (loc && (loop_end - start < cnt)) {
946 this_read = loop_end - start;
947 //cerr << "reloop true: thisread: " << this_read << " cnt: " << cnt << endl;
954 if (this_read == 0) {
958 this_read = min(cnt,this_read);
960 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
961 error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), _id, this_read,
966 _read_data_count = _playlist->read_data_count();
970 swap_by_ptr (buf, buf + this_read - 1);
974 /* if we read to the end of the loop, go back to the beginning */
991 AudioDiskstream::do_refill_with_alloc ()
993 Sample* mix_buf = new Sample[disk_io_chunk_frames];
994 float* gain_buf = new float[disk_io_chunk_frames];
996 int ret = _do_refill(mix_buf, gain_buf);
1005 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer)
1009 RingBufferNPT<Sample>::rw_vector vector;
1010 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1011 nframes_t total_space;
1012 nframes_t zero_fill;
1014 ChannelList::iterator i;
1015 boost::shared_ptr<ChannelList> c = channels.reader();
1022 assert(mixdown_buffer);
1023 assert(gain_buffer);
1030 c->front()->playback_buf->get_write_vector (&vector);
1032 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1036 /* if there are 2+ chunks of disk i/o possible for
1037 this track, let the caller know so that it can arrange
1038 for us to be called again, ASAP.
1041 if (total_space >= (_slaved?3:2) * disk_io_chunk_frames) {
1045 /* if we're running close to normal speed and there isn't enough
1046 space to do disk_io_chunk_frames of I/O, then don't bother.
1048 at higher speeds, just do it because the sync between butler
1049 and audio thread may not be good enough.
1052 if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1056 /* when slaved, don't try to get too close to the read pointer. this
1057 leaves space for the buffer reversal to have something useful to
1061 if (_slaved && total_space < (c->front()->playback_buf->bufsize() / 2)) {
1065 /* never do more than disk_io_chunk_frames worth of disk input per call (limit doesn't apply for memset) */
1067 total_space = min (disk_io_chunk_frames, total_space);
1071 if (file_frame == 0) {
1073 /* at start: nothing to do but fill with silence */
1075 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1077 ChannelInfo* chan (*i);
1078 chan->playback_buf->get_write_vector (&vector);
1079 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1080 if (vector.len[1]) {
1081 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1083 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1088 if (file_frame < total_space) {
1090 /* too close to the start: read what we can,
1091 and then zero fill the rest
1094 zero_fill = total_space - file_frame;
1095 total_space = file_frame;
1105 if (file_frame == max_frames) {
1107 /* at end: nothing to do but fill with silence */
1109 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1111 ChannelInfo* chan (*i);
1112 chan->playback_buf->get_write_vector (&vector);
1113 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1114 if (vector.len[1]) {
1115 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1117 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1122 if (file_frame > max_frames - total_space) {
1124 /* to close to the end: read what we can, and zero fill the rest */
1126 zero_fill = total_space - (max_frames - file_frame);
1127 total_space = max_frames - file_frame;
1134 nframes_t file_frame_tmp = 0;
1136 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1138 ChannelInfo* chan (*i);
1141 nframes_t len1, len2;
1143 chan->playback_buf->get_write_vector (&vector);
1145 if (vector.len[0] > disk_io_chunk_frames) {
1147 /* we're not going to fill the first chunk, so certainly do not bother with the
1148 other part. it won't be connected with the part we do fill, as in:
1150 .... => writable space
1151 ++++ => readable space
1152 ^^^^ => 1 x disk_io_chunk_frames that would be filled
1154 |......|+++++++++++++|...............................|
1159 So, just pretend that the buf1 part isn't there.
1169 file_frame_tmp = file_frame;
1171 buf1 = vector.buf[0];
1172 len1 = vector.len[0];
1173 buf2 = vector.buf[1];
1174 len2 = vector.len[1];
1176 to_read = min (ts, len1);
1177 to_read = min (to_read, disk_io_chunk_frames);
1181 if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1186 chan->playback_buf->increment_write_ptr (to_read);
1190 to_read = min (ts, len2);
1194 /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1195 so read some or all of vector.len[1] as well.
1198 if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1203 chan->playback_buf->increment_write_ptr (to_read);
1212 file_frame = file_frame_tmp;
1219 /** Flush pending data to disk.
1221 * Important note: this function will write *AT MOST* disk_io_chunk_frames
1222 * of data to disk. it will never write more than that. If it writes that
1223 * much and there is more than that waiting to be written, it will return 1,
1224 * otherwise 0 on success or -1 on failure.
1226 * If there is less than disk_io_chunk_frames to be written, no data will be
1227 * written at all unless @a force_flush is true.
1230 AudioDiskstream::do_flush (RunContext /*context*/, bool force_flush)
1234 RingBufferNPT<Sample>::rw_vector vector;
1235 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1238 _write_data_count = 0;
1240 transvec.buf[0] = 0;
1241 transvec.buf[1] = 0;
1245 boost::shared_ptr<ChannelList> c = channels.reader();
1246 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1248 (*chan)->capture_buf->get_read_vector (&vector);
1250 total = vector.len[0] + vector.len[1];
1252 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1256 /* if there are 2+ chunks of disk i/o possible for
1257 this track, let the caller know so that it can arrange
1258 for us to be called again, ASAP.
1260 if we are forcing a flush, then if there is* any* extra
1261 work, let the caller know.
1263 if we are no longer recording and there is any extra work,
1264 let the caller know too.
1267 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1271 to_write = min (disk_io_chunk_frames, (nframes_t) vector.len[0]);
1273 // check the transition buffer when recording destructive
1274 // important that we get this after the capture buf
1276 if (destructive()) {
1277 (*chan)->capture_transition_buf->get_read_vector(&transvec);
1278 size_t transcount = transvec.len[0] + transvec.len[1];
1279 bool have_start = false;
1282 for (ti=0; ti < transcount; ++ti) {
1283 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1285 if (captrans.type == CaptureStart) {
1286 // by definition, the first data we got above represents the given capture pos
1288 (*chan)->write_source->mark_capture_start (captrans.capture_val);
1289 (*chan)->curr_capture_cnt = 0;
1293 else if (captrans.type == CaptureEnd) {
1295 // capture end, the capture_val represents total frames in capture
1297 if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1299 // shorten to make the write a perfect fit
1300 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
1302 if (nto_write < to_write) {
1303 ret = 1; // should we?
1305 to_write = nto_write;
1307 (*chan)->write_source->mark_capture_end ();
1309 // increment past this transition, but go no further
1314 // actually ends just beyond this chunk, so force more work
1322 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1326 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1327 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1331 (*chan)->capture_buf->increment_read_ptr (to_write);
1332 (*chan)->curr_capture_cnt += to_write;
1334 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1336 /* we wrote all of vector.len[0] but it wasn't an entire
1337 disk_io_chunk_frames of data, so arrange for some part
1338 of vector.len[1] to be flushed to disk as well.
1341 to_write = min ((nframes_t)(disk_io_chunk_frames - to_write), (nframes_t) vector.len[1]);
1343 if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1344 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1348 _write_data_count += (*chan)->write_source->write_data_count();
1350 (*chan)->capture_buf->increment_read_ptr (to_write);
1351 (*chan)->curr_capture_cnt += to_write;
1360 AudioDiskstream::transport_stopped (struct tm& when, time_t twhen, bool abort_capture)
1362 uint32_t buffer_position;
1363 bool more_work = true;
1365 boost::shared_ptr<AudioRegion> region;
1366 nframes_t total_capture;
1368 SourceList::iterator src;
1369 ChannelList::iterator chan;
1370 vector<CaptureInfo*>::iterator ci;
1371 boost::shared_ptr<ChannelList> c = channels.reader();
1373 bool mark_write_completed = false;
1375 finish_capture (true, c);
1377 /* butler is already stopped, but there may be work to do
1378 to flush remaining data to disk.
1381 while (more_work && !err) {
1382 switch (do_flush (TransportContext, true)) {
1389 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1394 /* XXX is there anything we can do if err != 0 ? */
1395 Glib::Mutex::Lock lm (capture_info_lock);
1397 if (capture_info.empty()) {
1401 if (abort_capture) {
1403 if (destructive()) {
1407 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1409 if ((*chan)->write_source) {
1411 (*chan)->write_source->mark_for_remove ();
1412 (*chan)->write_source->drop_references ();
1413 (*chan)->write_source.reset ();
1416 /* new source set up in "out" below */
1422 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1423 total_capture += (*ci)->frames;
1426 /* figure out the name for this take */
1428 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1430 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1434 s->update_header (capture_info.front()->start, when, twhen);
1435 s->set_captured_for (_name);
1436 s->mark_immutable ();
1437 if (Config->get_auto_analyse_audio()) {
1438 Analyser::queue_source_for_analysis (s, true);
1443 /* destructive tracks have a single, never changing region */
1445 if (destructive()) {
1447 /* send a signal that any UI can pick up to do the right thing. there is
1448 a small problem here in that a UI may need the peak data to be ready
1449 for the data that was recorded and this isn't interlocked with that
1450 process. this problem is deferred to the UI.
1453 _playlist->Modified();
1457 string whole_file_region_name;
1458 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1460 /* Register a new region with the Session that
1461 describes the entire source. Do this first
1462 so that any sub-regions will obviously be
1463 children of this one (later!)
1467 boost::shared_ptr<Region> rx (RegionFactory::create (srcs,
1468 c->front()->write_source->last_capture_start_frame(), total_capture,
1469 whole_file_region_name, 0,
1470 Region::Flag (Region::DefaultFlags|Region::Automatic|Region::WholeFile)));
1472 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1473 region->special_set_position (capture_info.front()->start);
1477 catch (failed_constructor& err) {
1478 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1482 _last_capture_regions.push_back (region);
1484 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1486 XMLNode &before = _playlist->get_state();
1487 _playlist->freeze ();
1489 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1493 _session.region_name (region_name, whole_file_region_name, false);
1495 // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->frames << " add region " << region_name << endl;
1498 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, buffer_position, (*ci)->frames, region_name));
1499 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1502 catch (failed_constructor& err) {
1503 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1504 continue; /* XXX is this OK? */
1507 scoped_connect (region->GoingAway, boost::bind (&Diskstream::remove_region_from_last_capture, this, boost::weak_ptr<Region>(region)));
1509 _last_capture_regions.push_back (region);
1511 i_am_the_modifier++;
1512 _playlist->add_region (region, (*ci)->start, 1, non_layered());
1513 i_am_the_modifier--;
1515 buffer_position += (*ci)->frames;
1519 XMLNode &after = _playlist->get_state();
1520 _session.add_command (new MementoCommand<Playlist>(*_playlist, &before, &after));
1523 mark_write_completed = true;
1526 reset_write_sources (mark_write_completed);
1530 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1534 capture_info.clear ();
1535 capture_start_frame = 0;
1539 AudioDiskstream::transport_looped (nframes_t transport_frame)
1541 if (was_recording) {
1542 // all we need to do is finish this capture, with modified capture length
1543 boost::shared_ptr<ChannelList> c = channels.reader();
1545 // adjust the capture length knowing that the data will be recorded to disk
1546 // only necessary after the first loop where we're recording
1547 if (capture_info.size() == 0) {
1548 capture_captured += _capture_offset;
1550 if (_alignment_style == ExistingMaterial) {
1551 capture_captured += _session.worst_output_latency();
1553 capture_captured += _roll_delay;
1557 finish_capture (true, c);
1559 // the next region will start recording via the normal mechanism
1560 // we'll set the start position to the current transport pos
1561 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1562 capture_start_frame = transport_frame;
1563 first_recordable_frame = transport_frame; // mild lie
1564 last_recordable_frame = max_frames;
1565 was_recording = true;
1567 if (recordable() && destructive()) {
1568 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1570 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1571 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1573 if (transvec.len[0] > 0) {
1574 transvec.buf[0]->type = CaptureStart;
1575 transvec.buf[0]->capture_val = capture_start_frame;
1576 (*chan)->capture_transition_buf->increment_write_ptr(1);
1580 fatal << X_("programming error: capture_transition_buf is full on rec loop! inconceivable!")
1590 AudioDiskstream::finish_capture (bool /*rec_monitors_input*/, boost::shared_ptr<ChannelList> c)
1592 was_recording = false;
1594 if (capture_captured == 0) {
1598 if (recordable() && destructive()) {
1599 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1601 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1602 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1604 if (transvec.len[0] > 0) {
1605 transvec.buf[0]->type = CaptureEnd;
1606 transvec.buf[0]->capture_val = capture_captured;
1607 (*chan)->capture_transition_buf->increment_write_ptr(1);
1611 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1617 CaptureInfo* ci = new CaptureInfo;
1619 ci->start = capture_start_frame;
1620 ci->frames = capture_captured;
1622 /* XXX theoretical race condition here. Need atomic exchange ?
1623 However, the circumstances when this is called right
1624 now (either on record-disable or transport_stopped)
1625 mean that no actual race exists. I think ...
1626 We now have a capture_info_lock, but it is only to be used
1627 to synchronize in the transport_stop and the capture info
1628 accessors, so that invalidation will not occur (both non-realtime).
1631 // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1633 capture_info.push_back (ci);
1634 capture_captured = 0;
1636 /* now we've finished a capture, reset first_recordable_frame for next time */
1637 first_recordable_frame = max_frames;
1641 AudioDiskstream::set_record_enabled (bool yn)
1643 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0) {
1647 /* can't rec-enable in destructive mode if transport is before start */
1649 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1653 /* yes, i know that this not proof against race conditions, but its
1654 good enough. i think.
1657 if (record_enabled() != yn) {
1659 engage_record_enable ();
1661 disengage_record_enable ();
1667 AudioDiskstream::engage_record_enable ()
1669 bool rolling = _session.transport_speed() != 0.0f;
1670 boost::shared_ptr<ChannelList> c = channels.reader();
1672 g_atomic_int_set (&_record_enabled, 1);
1673 capturing_sources.clear ();
1675 if (Config->get_monitoring_model() == HardwareMonitoring) {
1677 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1678 if ((*chan)->source) {
1679 (*chan)->source->ensure_monitor_input (!(_session.config.get_auto_input() && rolling));
1681 capturing_sources.push_back ((*chan)->write_source);
1682 (*chan)->write_source->mark_streaming_write_started ();
1686 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1687 capturing_sources.push_back ((*chan)->write_source);
1688 (*chan)->write_source->mark_streaming_write_started ();
1692 RecordEnableChanged (); /* EMIT SIGNAL */
1696 AudioDiskstream::disengage_record_enable ()
1698 g_atomic_int_set (&_record_enabled, 0);
1699 boost::shared_ptr<ChannelList> c = channels.reader();
1700 if (Config->get_monitoring_model() == HardwareMonitoring) {
1701 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1702 if ((*chan)->source) {
1703 (*chan)->source->ensure_monitor_input (false);
1707 capturing_sources.clear ();
1708 RecordEnableChanged (); /* EMIT SIGNAL */
1712 AudioDiskstream::get_state ()
1714 XMLNode* node = new XMLNode ("AudioDiskstream");
1716 LocaleGuard lg (X_("POSIX"));
1717 boost::shared_ptr<ChannelList> c = channels.reader();
1719 node->add_property ("flags", enum_2_string (_flags));
1721 snprintf (buf, sizeof(buf), "%zd", c->size());
1722 node->add_property ("channels", buf);
1724 node->add_property ("playlist", _playlist->name());
1726 snprintf (buf, sizeof(buf), "%.12g", _visible_speed);
1727 node->add_property ("speed", buf);
1729 node->add_property("name", _name);
1730 id().print (buf, sizeof (buf));
1731 node->add_property("id", buf);
1733 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1735 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1736 XMLNode* cs_grandchild;
1738 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1739 cs_grandchild = new XMLNode (X_("file"));
1740 cs_grandchild->add_property (X_("path"), (*i)->path());
1741 cs_child->add_child_nocopy (*cs_grandchild);
1744 /* store the location where capture will start */
1748 if (_session.config.get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1749 snprintf (buf, sizeof (buf), "%" PRId64, pi->start());
1751 snprintf (buf, sizeof (buf), "%" PRId64, _session.transport_frame());
1754 cs_child->add_property (X_("at"), buf);
1755 node->add_child_nocopy (*cs_child);
1759 node->add_child_copy (*_extra_xml);
1766 AudioDiskstream::set_state (const XMLNode& node, int /*version*/)
1768 const XMLProperty* prop;
1769 XMLNodeList nlist = node.children();
1770 XMLNodeIterator niter;
1771 uint32_t nchans = 1;
1772 XMLNode* capture_pending_node = 0;
1773 LocaleGuard lg (X_("POSIX"));
1775 in_set_state = true;
1777 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1778 if ((*niter)->name() == IO::state_node_name) {
1779 deprecated_io_node = new XMLNode (**niter);
1782 if ((*niter)->name() == X_("CapturingSources")) {
1783 capture_pending_node = *niter;
1787 /* prevent write sources from being created */
1789 in_set_state = true;
1791 if ((prop = node.property ("name")) != 0) {
1792 _name = prop->value();
1795 if (deprecated_io_node) {
1796 if ((prop = deprecated_io_node->property ("id")) != 0) {
1797 _id = prop->value ();
1800 if ((prop = node.property ("id")) != 0) {
1801 _id = prop->value ();
1805 if ((prop = node.property ("flags")) != 0) {
1806 _flags = Flag (string_2_enum (prop->value(), _flags));
1809 if ((prop = node.property ("channels")) != 0) {
1810 nchans = atoi (prop->value().c_str());
1813 // create necessary extra channels
1814 // we are always constructed with one and we always need one
1816 _n_channels.set(DataType::AUDIO, channels.reader()->size());
1818 if (nchans > _n_channels.n_audio()) {
1820 add_channel (nchans - _n_channels.n_audio());
1821 IO::PortCountChanged(_n_channels);
1823 } else if (nchans < _n_channels.n_audio()) {
1825 remove_channel (_n_channels.n_audio() - nchans);
1828 if ((prop = node.property ("playlist")) == 0) {
1833 bool had_playlist = (_playlist != 0);
1835 if (find_and_use_playlist (prop->value())) {
1839 if (!had_playlist) {
1840 _playlist->set_orig_diskstream_id (_id);
1843 if (!destructive() && capture_pending_node) {
1844 /* destructive streams have one and only one source per channel,
1845 and so they never end up in pending capture in any useful
1848 use_pending_capture_data (*capture_pending_node);
1853 if ((prop = node.property ("speed")) != 0) {
1854 double sp = atof (prop->value().c_str());
1856 if (realtime_set_speed (sp, false)) {
1857 non_realtime_set_speed ();
1861 in_set_state = false;
1863 /* make sure this is clear before we do anything else */
1865 capturing_sources.clear ();
1867 /* write sources are handled when we handle the input set
1868 up of the IO that owns this DS (::non_realtime_input_change())
1875 AudioDiskstream::use_new_write_source (uint32_t n)
1877 boost::shared_ptr<ChannelList> c = channels.reader();
1879 if (!recordable()) {
1883 if (n >= c->size()) {
1884 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
1888 ChannelInfo* chan = (*c)[n];
1890 if (chan->write_source) {
1891 chan->write_source->done_with_peakfile_writes ();
1892 chan->write_source->set_allow_remove_if_empty (true);
1893 chan->write_source.reset ();
1897 if ((chan->write_source = _session.create_audio_source_for_session (*this, n, destructive())) == 0) {
1898 throw failed_constructor();
1902 catch (failed_constructor &err) {
1903 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
1904 chan->write_source.reset ();
1908 /* do not remove destructive files even if they are empty */
1910 chan->write_source->set_allow_remove_if_empty (!destructive());
1912 /* until we write, this file is considered removable */
1914 chan->write_source->mark_for_remove ();
1920 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool /*force*/)
1922 ChannelList::iterator chan;
1923 boost::shared_ptr<ChannelList> c = channels.reader();
1926 if (!_session.writable() || !recordable()) {
1930 capturing_sources.clear ();
1932 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1933 if (!destructive()) {
1935 if ((*chan)->write_source && mark_write_complete) {
1936 (*chan)->write_source->mark_streaming_write_completed ();
1938 use_new_write_source (n);
1940 if (record_enabled()) {
1941 capturing_sources.push_back ((*chan)->write_source);
1945 if ((*chan)->write_source == 0) {
1946 use_new_write_source (n);
1951 if (destructive()) {
1953 /* we now have all our write sources set up, so create the
1954 playlist's single region.
1957 if (_playlist->empty()) {
1958 setup_destructive_playlist ();
1964 AudioDiskstream::rename_write_sources ()
1966 ChannelList::iterator chan;
1967 boost::shared_ptr<ChannelList> c = channels.reader();
1970 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1971 if ((*chan)->write_source != 0) {
1972 (*chan)->write_source->set_source_name (_name, destructive());
1973 /* XXX what to do if one of them fails ? */
1981 AudioDiskstream::set_block_size (nframes_t /*nframes*/)
1983 if (_session.get_block_size() > speed_buffer_size) {
1984 speed_buffer_size = _session.get_block_size();
1985 boost::shared_ptr<ChannelList> c = channels.reader();
1987 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1988 if ((*chan)->speed_buffer)
1989 delete [] (*chan)->speed_buffer;
1990 (*chan)->speed_buffer = new Sample[speed_buffer_size];
1993 allocate_temporary_buffers ();
1997 AudioDiskstream::allocate_temporary_buffers ()
1999 /* make sure the wrap buffer is at least large enough to deal
2000 with the speeds up to 1.2, to allow for micro-variation
2001 when slaving to MTC, Timecode etc.
2004 double sp = max (fabsf (_actual_speed), 1.2f);
2005 nframes_t required_wrap_size = (nframes_t) floor (_session.get_block_size() * sp) + 1;
2007 if (required_wrap_size > wrap_buffer_size) {
2009 boost::shared_ptr<ChannelList> c = channels.reader();
2011 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2012 if ((*chan)->playback_wrap_buffer)
2013 delete [] (*chan)->playback_wrap_buffer;
2014 (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
2015 if ((*chan)->capture_wrap_buffer)
2016 delete [] (*chan)->capture_wrap_buffer;
2017 (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
2020 wrap_buffer_size = required_wrap_size;
2025 AudioDiskstream::monitor_input (bool yn)
2027 boost::shared_ptr<ChannelList> c = channels.reader();
2029 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2031 if ((*chan)->source) {
2032 (*chan)->source->ensure_monitor_input (yn);
2038 AudioDiskstream::set_align_style_from_io ()
2040 bool have_physical = false;
2046 get_input_sources ();
2048 boost::shared_ptr<ChannelList> c = channels.reader();
2050 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2051 if ((*chan)->source && (*chan)->source->flags() & JackPortIsPhysical) {
2052 have_physical = true;
2057 if (have_physical) {
2058 set_align_style (ExistingMaterial);
2060 set_align_style (CaptureTime);
2065 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2067 while (how_many--) {
2068 c->push_back (new ChannelInfo(_session.butler()->audio_diskstream_buffer_size(), speed_buffer_size, wrap_buffer_size));
2069 interpolation.add_channel_to (_session.butler()->audio_diskstream_buffer_size(), speed_buffer_size);
2072 _n_channels.set(DataType::AUDIO, c->size());
2078 AudioDiskstream::add_channel (uint32_t how_many)
2080 RCUWriter<ChannelList> writer (channels);
2081 boost::shared_ptr<ChannelList> c = writer.get_copy();
2083 return add_channel_to (c, how_many);
2087 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2089 while (how_many-- && !c->empty()) {
2090 // FIXME: crash (thread safe with RCU?)
2091 // memory leak, when disabled.... :(
2094 interpolation.remove_channel_from ();
2097 _n_channels.set(DataType::AUDIO, c->size());
2103 AudioDiskstream::remove_channel (uint32_t how_many)
2105 RCUWriter<ChannelList> writer (channels);
2106 boost::shared_ptr<ChannelList> c = writer.get_copy();
2108 return remove_channel_from (c, how_many);
2112 AudioDiskstream::playback_buffer_load () const
2114 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();
2125 return (float) ((double) c->front()->capture_buf->write_space()/
2126 (double) c->front()->capture_buf->bufsize());
2130 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2132 const XMLProperty* prop;
2133 XMLNodeList nlist = node.children();
2134 XMLNodeIterator niter;
2135 boost::shared_ptr<AudioFileSource> fs;
2136 boost::shared_ptr<AudioFileSource> first_fs;
2137 SourceList pending_sources;
2140 if ((prop = node.property (X_("at"))) == 0) {
2144 if (sscanf (prop->value().c_str(), "%" PRIu32, &position) != 1) {
2148 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2149 if ((*niter)->name() == X_("file")) {
2151 if ((prop = (*niter)->property (X_("path"))) == 0) {
2155 // This protects sessions from errant CapturingSources in stored sessions
2157 if (stat (prop->value().c_str(), &sbuf)) {
2162 fs = boost::dynamic_pointer_cast<AudioFileSource> (
2163 SourceFactory::createWritable (DataType::AUDIO, _session,
2164 prop->value(), false, _session.frame_rate()));
2167 catch (failed_constructor& err) {
2168 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2169 _name, prop->value())
2174 pending_sources.push_back (fs);
2176 if (first_fs == 0) {
2180 fs->set_captured_for (_name);
2184 if (pending_sources.size() == 0) {
2185 /* nothing can be done */
2189 if (pending_sources.size() != _n_channels.n_audio()) {
2190 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2195 boost::shared_ptr<AudioRegion> region;
2198 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (
2199 pending_sources, 0, first_fs->length(first_fs->timeline_position()),
2200 region_name_from_path (first_fs->name(), true), 0,
2201 Region::Flag (Region::DefaultFlags|Region::Automatic|Region::WholeFile)));
2202 region->special_set_position (0);
2205 catch (failed_constructor& err) {
2206 error << string_compose (
2207 _("%1: cannot create whole-file region from pending capture sources"),
2214 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (
2215 pending_sources, 0, first_fs->length(first_fs->timeline_position()),
2216 region_name_from_path (first_fs->name(), true)));
2219 catch (failed_constructor& err) {
2220 error << string_compose (_("%1: cannot create region from pending capture sources"),
2227 _playlist->add_region (region, position);
2233 AudioDiskstream::set_non_layered (bool yn)
2235 if (yn != non_layered()) {
2238 _flags = Flag (_flags | NonLayered);
2240 _flags = Flag (_flags & ~NonLayered);
2248 AudioDiskstream::set_destructive (bool yn)
2250 bool bounce_ignored;
2252 if (yn != destructive()) {
2255 /* requestor should already have checked this and
2256 bounced if necessary and desired
2258 if (!can_become_destructive (bounce_ignored)) {
2261 _flags = Flag (_flags | Destructive);
2262 use_destructive_playlist ();
2264 _flags = Flag (_flags & ~Destructive);
2265 reset_write_sources (true, true);
2273 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2276 requires_bounce = false;
2280 /* is there only one region ? */
2282 if (_playlist->n_regions() != 1) {
2283 requires_bounce = true;
2287 boost::shared_ptr<Region> first = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
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;
2314 AudioDiskstream::ChannelInfo::ChannelInfo (nframes_t bufsize, nframes_t speed_size, nframes_t wrap_size)
2318 current_capture_buffer = 0;
2319 current_playback_buffer = 0;
2320 curr_capture_cnt = 0;
2322 speed_buffer = new Sample[speed_size];
2323 playback_wrap_buffer = new Sample[wrap_size];
2324 capture_wrap_buffer = new Sample[wrap_size];
2326 playback_buf = new RingBufferNPT<Sample> (bufsize);
2327 capture_buf = new RingBufferNPT<Sample> (bufsize);
2328 capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2330 /* touch the ringbuffer buffers, which will cause
2331 them to be mapped into locked physical RAM if
2332 we're running with mlockall(). this doesn't do
2336 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2337 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2338 memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2341 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2344 write_source.reset ();
2347 delete [] speed_buffer;
2350 delete [] playback_wrap_buffer;
2351 playback_wrap_buffer = 0;
2353 delete [] capture_wrap_buffer;
2354 capture_wrap_buffer = 0;
2356 delete playback_buf;
2362 delete capture_transition_buf;
2363 capture_transition_buf = 0;