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/io.h"
53 #include "ardour/playlist_factory.h"
54 #include "ardour/region_factory.h"
55 #include "ardour/send.h"
56 #include "ardour/session.h"
57 #include "ardour/source_factory.h"
58 #include "ardour/utils.h"
64 using namespace ARDOUR;
67 size_t AudioDiskstream::_working_buffers_size = 0;
68 Sample* AudioDiskstream::_mixdown_buffer = 0;
69 gain_t* AudioDiskstream::_gain_buffer = 0;
71 AudioDiskstream::AudioDiskstream (Session &sess, const string &name, Diskstream::Flag flag)
72 : Diskstream(sess, name, flag)
73 , deprecated_io_node(NULL)
74 , channels (new ChannelList)
76 /* prevent any write sources from being created */
86 AudioDiskstream::AudioDiskstream (Session& sess, const XMLNode& node)
87 : Diskstream(sess, node)
88 , deprecated_io_node(NULL)
89 , channels (new ChannelList)
94 if (set_state (node, Stateful::loading_state_version)) {
96 throw failed_constructor();
102 use_destructive_playlist ();
107 AudioDiskstream::init (Diskstream::Flag f)
111 /* there are no channels at this point, so these
112 two calls just get speed_buffer_size and wrap_buffer
113 size setup without duplicating their code.
116 set_block_size (_session.get_block_size());
117 allocate_temporary_buffers ();
120 assert(_n_channels == ChanCount(DataType::AUDIO, 1));
123 AudioDiskstream::~AudioDiskstream ()
125 cerr << "AD going away\n";
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.playlist_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 region->GoingAway.connect (bind (mem_fun (*this, &Diskstream::remove_region_from_last_capture), 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 if (yn && channels.reader()->front()->source == 0) {
1655 /* pick up connections not initiated *from* the IO object
1656 we're associated with.
1659 get_input_sources ();
1662 /* yes, i know that this not proof against race conditions, but its
1663 good enough. i think.
1666 if (record_enabled() != yn) {
1668 engage_record_enable ();
1670 disengage_record_enable ();
1676 AudioDiskstream::engage_record_enable ()
1678 bool rolling = _session.transport_speed() != 0.0f;
1679 boost::shared_ptr<ChannelList> c = channels.reader();
1681 g_atomic_int_set (&_record_enabled, 1);
1682 capturing_sources.clear ();
1684 if (Config->get_monitoring_model() == HardwareMonitoring) {
1686 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1687 if ((*chan)->source) {
1688 (*chan)->source->ensure_monitor_input (!(_session.config.get_auto_input() && rolling));
1690 capturing_sources.push_back ((*chan)->write_source);
1691 (*chan)->write_source->mark_streaming_write_started ();
1695 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1696 capturing_sources.push_back ((*chan)->write_source);
1697 (*chan)->write_source->mark_streaming_write_started ();
1701 RecordEnableChanged (); /* EMIT SIGNAL */
1705 AudioDiskstream::disengage_record_enable ()
1707 g_atomic_int_set (&_record_enabled, 0);
1708 boost::shared_ptr<ChannelList> c = channels.reader();
1709 if (Config->get_monitoring_model() == HardwareMonitoring) {
1710 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1711 if ((*chan)->source) {
1712 (*chan)->source->ensure_monitor_input (false);
1716 capturing_sources.clear ();
1717 RecordEnableChanged (); /* EMIT SIGNAL */
1721 AudioDiskstream::get_state ()
1723 XMLNode* node = new XMLNode ("AudioDiskstream");
1725 LocaleGuard lg (X_("POSIX"));
1726 boost::shared_ptr<ChannelList> c = channels.reader();
1728 node->add_property ("flags", enum_2_string (_flags));
1730 snprintf (buf, sizeof(buf), "%zd", c->size());
1731 node->add_property ("channels", buf);
1733 node->add_property ("playlist", _playlist->name());
1735 snprintf (buf, sizeof(buf), "%.12g", _visible_speed);
1736 node->add_property ("speed", buf);
1738 node->add_property("name", _name);
1739 id().print (buf, sizeof (buf));
1740 node->add_property("id", buf);
1742 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1744 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1745 XMLNode* cs_grandchild;
1747 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1748 cs_grandchild = new XMLNode (X_("file"));
1749 cs_grandchild->add_property (X_("path"), (*i)->path());
1750 cs_child->add_child_nocopy (*cs_grandchild);
1753 /* store the location where capture will start */
1757 if (_session.config.get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1758 snprintf (buf, sizeof (buf), "%" PRId64, pi->start());
1760 snprintf (buf, sizeof (buf), "%" PRId64, _session.transport_frame());
1763 cs_child->add_property (X_("at"), buf);
1764 node->add_child_nocopy (*cs_child);
1768 node->add_child_copy (*_extra_xml);
1775 AudioDiskstream::set_state (const XMLNode& node, int /*version*/)
1777 const XMLProperty* prop;
1778 XMLNodeList nlist = node.children();
1779 XMLNodeIterator niter;
1780 uint32_t nchans = 1;
1781 XMLNode* capture_pending_node = 0;
1782 LocaleGuard lg (X_("POSIX"));
1784 in_set_state = true;
1786 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1787 if ((*niter)->name() == IO::state_node_name) {
1788 deprecated_io_node = new XMLNode (**niter);
1791 if ((*niter)->name() == X_("CapturingSources")) {
1792 capture_pending_node = *niter;
1796 /* prevent write sources from being created */
1798 in_set_state = true;
1800 if ((prop = node.property ("name")) != 0) {
1801 _name = prop->value();
1804 if (deprecated_io_node) {
1805 if ((prop = deprecated_io_node->property ("id")) != 0) {
1806 _id = prop->value ();
1809 if ((prop = node.property ("id")) != 0) {
1810 _id = prop->value ();
1814 if ((prop = node.property ("flags")) != 0) {
1815 _flags = Flag (string_2_enum (prop->value(), _flags));
1818 if ((prop = node.property ("channels")) != 0) {
1819 nchans = atoi (prop->value().c_str());
1822 // create necessary extra channels
1823 // we are always constructed with one and we always need one
1825 _n_channels.set(DataType::AUDIO, channels.reader()->size());
1827 if (nchans > _n_channels.n_audio()) {
1829 add_channel (nchans - _n_channels.n_audio());
1830 IO::PortCountChanged(_n_channels);
1832 } else if (nchans < _n_channels.n_audio()) {
1834 remove_channel (_n_channels.n_audio() - nchans);
1837 if ((prop = node.property ("playlist")) == 0) {
1842 bool had_playlist = (_playlist != 0);
1844 if (find_and_use_playlist (prop->value())) {
1848 if (!had_playlist) {
1849 _playlist->set_orig_diskstream_id (_id);
1852 if (!destructive() && capture_pending_node) {
1853 /* destructive streams have one and only one source per channel,
1854 and so they never end up in pending capture in any useful
1857 use_pending_capture_data (*capture_pending_node);
1862 if ((prop = node.property ("speed")) != 0) {
1863 double sp = atof (prop->value().c_str());
1865 if (realtime_set_speed (sp, false)) {
1866 non_realtime_set_speed ();
1870 in_set_state = false;
1872 /* make sure this is clear before we do anything else */
1874 capturing_sources.clear ();
1876 /* write sources are handled when we handle the input set
1877 up of the IO that owns this DS (::non_realtime_input_change())
1884 AudioDiskstream::use_new_write_source (uint32_t n)
1886 boost::shared_ptr<ChannelList> c = channels.reader();
1888 if (!recordable()) {
1892 if (n >= c->size()) {
1893 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
1897 ChannelInfo* chan = (*c)[n];
1899 if (chan->write_source) {
1900 chan->write_source->done_with_peakfile_writes ();
1901 chan->write_source->set_allow_remove_if_empty (true);
1902 chan->write_source.reset ();
1906 if ((chan->write_source = _session.create_audio_source_for_session (*this, n, destructive())) == 0) {
1907 throw failed_constructor();
1911 catch (failed_constructor &err) {
1912 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
1913 chan->write_source.reset ();
1917 /* do not remove destructive files even if they are empty */
1919 chan->write_source->set_allow_remove_if_empty (!destructive());
1921 /* until we write, this file is considered removable */
1923 chan->write_source->mark_for_remove ();
1924 cerr << "New write source " << chan->write_source->path() << " flags " << enum_2_string (chan->write_source->flags()) << endl;
1930 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool /*force*/)
1932 ChannelList::iterator chan;
1933 boost::shared_ptr<ChannelList> c = channels.reader();
1936 if (!_session.writable() || !recordable()) {
1940 capturing_sources.clear ();
1942 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1943 if (!destructive()) {
1945 if ((*chan)->write_source && mark_write_complete) {
1946 (*chan)->write_source->mark_streaming_write_completed ();
1948 use_new_write_source (n);
1950 if (record_enabled()) {
1951 capturing_sources.push_back ((*chan)->write_source);
1955 if ((*chan)->write_source == 0) {
1956 use_new_write_source (n);
1961 if (destructive()) {
1963 /* we now have all our write sources set up, so create the
1964 playlist's single region.
1967 if (_playlist->empty()) {
1968 setup_destructive_playlist ();
1974 AudioDiskstream::rename_write_sources ()
1976 ChannelList::iterator chan;
1977 boost::shared_ptr<ChannelList> c = channels.reader();
1980 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1981 if ((*chan)->write_source != 0) {
1982 (*chan)->write_source->set_source_name (_name, destructive());
1983 /* XXX what to do if one of them fails ? */
1991 AudioDiskstream::set_block_size (nframes_t /*nframes*/)
1993 if (_session.get_block_size() > speed_buffer_size) {
1994 speed_buffer_size = _session.get_block_size();
1995 boost::shared_ptr<ChannelList> c = channels.reader();
1997 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1998 if ((*chan)->speed_buffer)
1999 delete [] (*chan)->speed_buffer;
2000 (*chan)->speed_buffer = new Sample[speed_buffer_size];
2003 allocate_temporary_buffers ();
2007 AudioDiskstream::allocate_temporary_buffers ()
2009 /* make sure the wrap buffer is at least large enough to deal
2010 with the speeds up to 1.2, to allow for micro-variation
2011 when slaving to MTC, Timecode etc.
2014 double sp = max (fabsf (_actual_speed), 1.2f);
2015 nframes_t required_wrap_size = (nframes_t) floor (_session.get_block_size() * sp) + 1;
2017 if (required_wrap_size > wrap_buffer_size) {
2019 boost::shared_ptr<ChannelList> c = channels.reader();
2021 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2022 if ((*chan)->playback_wrap_buffer)
2023 delete [] (*chan)->playback_wrap_buffer;
2024 (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
2025 if ((*chan)->capture_wrap_buffer)
2026 delete [] (*chan)->capture_wrap_buffer;
2027 (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
2030 wrap_buffer_size = required_wrap_size;
2035 AudioDiskstream::monitor_input (bool yn)
2037 boost::shared_ptr<ChannelList> c = channels.reader();
2039 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2041 if ((*chan)->source) {
2042 (*chan)->source->ensure_monitor_input (yn);
2048 AudioDiskstream::set_align_style_from_io ()
2050 bool have_physical = false;
2056 get_input_sources ();
2058 boost::shared_ptr<ChannelList> c = channels.reader();
2060 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2061 if ((*chan)->source && (*chan)->source->flags() & JackPortIsPhysical) {
2062 have_physical = true;
2067 if (have_physical) {
2068 set_align_style (ExistingMaterial);
2070 set_align_style (CaptureTime);
2075 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2077 while (how_many--) {
2078 c->push_back (new ChannelInfo(_session.butler()->audio_diskstream_buffer_size(), speed_buffer_size, wrap_buffer_size));
2079 interpolation.add_channel_to (_session.butler()->audio_diskstream_buffer_size(), speed_buffer_size);
2082 _n_channels.set(DataType::AUDIO, c->size());
2088 AudioDiskstream::add_channel (uint32_t how_many)
2090 RCUWriter<ChannelList> writer (channels);
2091 boost::shared_ptr<ChannelList> c = writer.get_copy();
2093 return add_channel_to (c, how_many);
2097 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2099 while (how_many-- && !c->empty()) {
2100 // FIXME: crash (thread safe with RCU?)
2101 // memory leak, when disabled.... :(
2104 interpolation.remove_channel_from ();
2107 _n_channels.set(DataType::AUDIO, c->size());
2113 AudioDiskstream::remove_channel (uint32_t how_many)
2115 RCUWriter<ChannelList> writer (channels);
2116 boost::shared_ptr<ChannelList> c = writer.get_copy();
2118 return remove_channel_from (c, how_many);
2122 AudioDiskstream::playback_buffer_load () const
2124 boost::shared_ptr<ChannelList> c = channels.reader();
2126 return (float) ((double) c->front()->playback_buf->read_space()/
2127 (double) c->front()->playback_buf->bufsize());
2131 AudioDiskstream::capture_buffer_load () const
2133 boost::shared_ptr<ChannelList> c = channels.reader();
2135 return (float) ((double) c->front()->capture_buf->write_space()/
2136 (double) c->front()->capture_buf->bufsize());
2140 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2142 const XMLProperty* prop;
2143 XMLNodeList nlist = node.children();
2144 XMLNodeIterator niter;
2145 boost::shared_ptr<AudioFileSource> fs;
2146 boost::shared_ptr<AudioFileSource> first_fs;
2147 SourceList pending_sources;
2150 if ((prop = node.property (X_("at"))) == 0) {
2154 if (sscanf (prop->value().c_str(), "%" PRIu32, &position) != 1) {
2158 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2159 if ((*niter)->name() == X_("file")) {
2161 if ((prop = (*niter)->property (X_("path"))) == 0) {
2165 // This protects sessions from errant CapturingSources in stored sessions
2167 if (stat (prop->value().c_str(), &sbuf)) {
2172 fs = boost::dynamic_pointer_cast<AudioFileSource> (
2173 SourceFactory::createWritable (DataType::AUDIO, _session,
2174 prop->value(), true,
2175 false, _session.frame_rate()));
2178 catch (failed_constructor& err) {
2179 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2180 _name, prop->value())
2185 pending_sources.push_back (fs);
2187 if (first_fs == 0) {
2191 fs->set_captured_for (_name);
2195 if (pending_sources.size() == 0) {
2196 /* nothing can be done */
2200 if (pending_sources.size() != _n_channels.n_audio()) {
2201 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2206 boost::shared_ptr<AudioRegion> region;
2209 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (
2210 pending_sources, 0, first_fs->length(first_fs->timeline_position()),
2211 region_name_from_path (first_fs->name(), true), 0,
2212 Region::Flag (Region::DefaultFlags|Region::Automatic|Region::WholeFile)));
2213 region->special_set_position (0);
2216 catch (failed_constructor& err) {
2217 error << string_compose (
2218 _("%1: cannot create whole-file region from pending capture sources"),
2225 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (
2226 pending_sources, 0, first_fs->length(first_fs->timeline_position()),
2227 region_name_from_path (first_fs->name(), true)));
2230 catch (failed_constructor& err) {
2231 error << string_compose (_("%1: cannot create region from pending capture sources"),
2238 _playlist->add_region (region, position);
2244 AudioDiskstream::set_non_layered (bool yn)
2246 if (yn != non_layered()) {
2249 _flags = Flag (_flags | NonLayered);
2251 _flags = Flag (_flags & ~NonLayered);
2259 AudioDiskstream::set_destructive (bool yn)
2261 bool bounce_ignored;
2263 if (yn != destructive()) {
2266 /* requestor should already have checked this and
2267 bounced if necessary and desired
2269 if (!can_become_destructive (bounce_ignored)) {
2272 _flags = Flag (_flags | Destructive);
2273 use_destructive_playlist ();
2275 _flags = Flag (_flags & ~Destructive);
2276 reset_write_sources (true, true);
2284 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2287 requires_bounce = false;
2291 /* is there only one region ? */
2293 if (_playlist->n_regions() != 1) {
2294 requires_bounce = true;
2298 boost::shared_ptr<Region> first = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
2301 /* do the source(s) for the region cover the session start position ? */
2303 if (first->position() != _session.current_start_frame()) {
2304 if (first->start() > _session.current_start_frame()) {
2305 requires_bounce = true;
2310 /* is the source used by only 1 playlist ? */
2312 boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2316 if (_session.source_use_count (afirst->source()) > 1) {
2317 requires_bounce = true;
2321 requires_bounce = false;
2325 AudioDiskstream::ChannelInfo::ChannelInfo (nframes_t bufsize, nframes_t speed_size, nframes_t wrap_size)
2329 current_capture_buffer = 0;
2330 current_playback_buffer = 0;
2331 curr_capture_cnt = 0;
2333 speed_buffer = new Sample[speed_size];
2334 playback_wrap_buffer = new Sample[wrap_size];
2335 capture_wrap_buffer = new Sample[wrap_size];
2337 playback_buf = new RingBufferNPT<Sample> (bufsize);
2338 capture_buf = new RingBufferNPT<Sample> (bufsize);
2339 capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2341 /* touch the ringbuffer buffers, which will cause
2342 them to be mapped into locked physical RAM if
2343 we're running with mlockall(). this doesn't do
2347 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2348 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2349 memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2352 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2355 write_source.reset ();
2358 delete [] speed_buffer;
2361 delete [] playback_wrap_buffer;
2362 playback_wrap_buffer = 0;
2364 delete [] capture_wrap_buffer;
2365 capture_wrap_buffer = 0;
2367 delete playback_buf;
2373 delete capture_transition_buf;
2374 capture_transition_buf = 0;