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 ()
128 RCUWriter<ChannelList> writer (channels);
129 boost::shared_ptr<ChannelList> c = writer.get_copy();
131 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
142 AudioDiskstream::allocate_working_buffers()
144 assert(disk_io_frames() > 0);
146 _working_buffers_size = disk_io_frames();
147 _mixdown_buffer = new Sample[_working_buffers_size];
148 _gain_buffer = new gain_t[_working_buffers_size];
152 AudioDiskstream::free_working_buffers()
154 delete [] _mixdown_buffer;
155 delete [] _gain_buffer;
156 _working_buffers_size = 0;
162 AudioDiskstream::non_realtime_input_change ()
165 Glib::Mutex::Lock lm (state_lock);
167 if (input_change_pending == NoChange) {
172 RCUWriter<ChannelList> writer (channels);
173 boost::shared_ptr<ChannelList> c = writer.get_copy();
175 _n_channels.set(DataType::AUDIO, c->size());
177 if (_io->n_ports().n_audio() > _n_channels.n_audio()) {
178 add_channel_to (c, _io->n_ports().n_audio() - _n_channels.n_audio());
179 } else if (_io->n_ports().n_audio() < _n_channels.n_audio()) {
180 remove_channel_from (c, _n_channels.n_audio() - _io->n_ports().n_audio());
184 get_input_sources ();
185 set_capture_offset ();
187 if (first_input_change) {
188 set_align_style (_persistent_alignment_style);
189 first_input_change = false;
191 set_align_style_from_io ();
194 input_change_pending = NoChange;
196 /* implicit unlock */
199 /* reset capture files */
201 reset_write_sources (false);
203 /* now refill channel buffers */
205 if (speed() != 1.0f || speed() != -1.0f) {
206 seek ((nframes_t) (_session.transport_frame() * (double) speed()));
208 seek (_session.transport_frame());
213 AudioDiskstream::non_realtime_locate (nframes_t location)
215 /* now refill channel buffers */
217 if (speed() != 1.0f || speed() != -1.0f) {
218 seek ((nframes_t) (location * (double) speed()));
225 AudioDiskstream::get_input_sources ()
227 boost::shared_ptr<ChannelList> c = channels.reader();
230 ChannelList::iterator chan;
231 uint32_t ni = _io->n_ports().n_audio();
232 vector<string> connections;
234 for (n = 0, chan = c->begin(); chan != c->end() && n < ni; ++chan, ++n) {
236 connections.clear ();
238 if (_io->nth (n)->get_connections (connections) == 0) {
240 if ((*chan)->source) {
241 // _source->disable_metering ();
247 (*chan)->source = dynamic_cast<AudioPort*>(_session.engine().get_port_by_name (connections[0]) );
253 AudioDiskstream::find_and_use_playlist (const string& name)
255 boost::shared_ptr<AudioPlaylist> playlist;
257 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (_session.playlist_by_name (name))) == 0) {
258 playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, name));
262 error << string_compose(_("AudioDiskstream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
266 return use_playlist (playlist);
270 AudioDiskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
272 assert(boost::dynamic_pointer_cast<AudioPlaylist>(playlist));
274 Diskstream::use_playlist(playlist);
280 AudioDiskstream::use_new_playlist ()
283 boost::shared_ptr<AudioPlaylist> playlist;
285 if (!in_set_state && destructive()) {
290 newname = Playlist::bump_name (_playlist->name(), _session);
292 newname = Playlist::bump_name (_name, _session);
295 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, newname, hidden()))) != 0) {
297 playlist->set_orig_diskstream_id (id());
298 return use_playlist (playlist);
306 AudioDiskstream::use_copy_playlist ()
308 assert(audio_playlist());
314 if (_playlist == 0) {
315 error << string_compose(_("AudioDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
320 boost::shared_ptr<AudioPlaylist> playlist;
322 newname = Playlist::bump_name (_playlist->name(), _session);
324 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist>(PlaylistFactory::create (audio_playlist(), newname))) != 0) {
325 playlist->set_orig_diskstream_id (id());
326 return use_playlist (playlist);
333 AudioDiskstream::setup_destructive_playlist ()
336 boost::shared_ptr<ChannelList> c = channels.reader();
338 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
339 srcs.push_back ((*chan)->write_source);
342 /* a single full-sized region */
344 boost::shared_ptr<Region> region (RegionFactory::create (srcs, 0, max_frames - srcs.front()->natural_position(), _name));
345 _playlist->add_region (region, srcs.front()->natural_position());
349 AudioDiskstream::use_destructive_playlist ()
351 /* this is called from the XML-based constructor or ::set_destructive. when called,
352 we already have a playlist and a region, but we need to
353 set up our sources for write. we use the sources associated
354 with the (presumed single, full-extent) region.
357 boost::shared_ptr<Region> rp = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
360 reset_write_sources (false, true);
364 boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
367 throw failed_constructor();
370 /* be sure to stretch the region out to the maximum length */
372 region->set_length (max_frames - region->position(), this);
375 ChannelList::iterator chan;
376 boost::shared_ptr<ChannelList> c = channels.reader();
378 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
379 (*chan)->write_source = boost::dynamic_pointer_cast<AudioFileSource>(region->source (n));
380 assert((*chan)->write_source);
381 (*chan)->write_source->set_allow_remove_if_empty (false);
383 /* this might be false if we switched modes, so force it */
385 (*chan)->write_source->set_destructive (true);
388 /* the source list will never be reset for a destructive track */
392 AudioDiskstream::prepare_record_status(nframes_t capture_start_frame)
394 if (recordable() && destructive()) {
395 boost::shared_ptr<ChannelList> c = channels.reader();
396 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
398 RingBufferNPT<CaptureTransition>::rw_vector transvec;
399 (*chan)->capture_transition_buf->get_write_vector(&transvec);
401 if (transvec.len[0] > 0) {
402 transvec.buf[0]->type = CaptureStart;
403 transvec.buf[0]->capture_val = capture_start_frame;
404 (*chan)->capture_transition_buf->increment_write_ptr(1);
408 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
416 AudioDiskstream::process (nframes_t transport_frame, nframes_t nframes, bool can_record, bool rec_monitors_input)
419 boost::shared_ptr<ChannelList> c = channels.reader();
420 ChannelList::iterator chan;
422 nframes_t rec_offset = 0;
423 nframes_t rec_nframes = 0;
424 bool nominally_recording;
425 bool re = record_enabled ();
426 bool collect_playback = false;
428 /* if we've already processed the frames corresponding to this call,
429 just return. this allows multiple routes that are taking input
430 from this diskstream to call our ::process() method, but have
431 this stuff only happen once. more commonly, it allows both
432 the AudioTrack that is using this AudioDiskstream *and* the Session
433 to call process() without problems.
440 commit_should_unlock = false;
442 if (!_io || !_io->active()) {
447 check_record_status (transport_frame, nframes, can_record);
449 nominally_recording = (can_record && re);
456 /* This lock is held until the end of AudioDiskstream::commit, so these two functions
457 must always be called as a pair. The only exception is if this function
458 returns a non-zero value, in which case, ::commit should not be called.
461 // If we can't take the state lock return.
462 if (!state_lock.trylock()) {
465 commit_should_unlock = true;
466 adjust_capture_position = 0;
468 for (chan = c->begin(); chan != c->end(); ++chan) {
469 (*chan)->current_capture_buffer = 0;
470 (*chan)->current_playback_buffer = 0;
473 if (nominally_recording || (_session.get_record_enabled() && _session.config.get_punch_in())) {
474 // Safeguard against situations where process() goes haywire when autopunching and last_recordable_frame < first_recordable_frame
475 if (last_recordable_frame < first_recordable_frame) {
476 last_recordable_frame = max_frames;
479 OverlapType ot = coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
481 calculate_record_range(ot, transport_frame, nframes, rec_nframes, rec_offset);
483 if (rec_nframes && !was_recording) {
484 capture_captured = 0;
485 was_recording = true;
490 if (can_record && !_last_capture_regions.empty()) {
491 _last_capture_regions.clear ();
494 if (nominally_recording || rec_nframes) {
496 uint32_t limit = _io->n_ports ().n_audio();
498 /* one or more ports could already have been removed from _io, but our
499 channel setup hasn't yet been updated. prevent us from trying to
500 use channels that correspond to missing ports. note that the
501 process callback (from which this is called) is always atomic
502 with respect to port removal/addition.
505 for (n = 0, chan = c->begin(); chan != c->end() && n < limit; ++chan, ++n) {
507 ChannelInfo* chaninfo (*chan);
509 chaninfo->capture_buf->get_write_vector (&chaninfo->capture_vector);
511 if (rec_nframes <= chaninfo->capture_vector.len[0]) {
513 chaninfo->current_capture_buffer = chaninfo->capture_vector.buf[0];
515 /* note: grab the entire port buffer, but only copy what we were supposed to
516 for recording, and use rec_offset
519 AudioPort* const ap = _io->audio (n);
521 assert(rec_nframes <= ap->get_audio_buffer(nframes).capacity());
522 memcpy (chaninfo->current_capture_buffer, ap->get_audio_buffer (rec_nframes).data(rec_offset), sizeof (Sample) * rec_nframes);
527 nframes_t total = chaninfo->capture_vector.len[0] + chaninfo->capture_vector.len[1];
529 if (rec_nframes > total) {
534 AudioPort* const ap = _io->audio (n);
537 Sample* buf = ap->get_audio_buffer(nframes).data();
538 nframes_t first = chaninfo->capture_vector.len[0];
540 memcpy (chaninfo->capture_wrap_buffer, buf, sizeof (Sample) * first);
541 memcpy (chaninfo->capture_vector.buf[0], buf, sizeof (Sample) * first);
542 memcpy (chaninfo->capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
543 memcpy (chaninfo->capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
545 chaninfo->current_capture_buffer = chaninfo->capture_wrap_buffer;
552 finish_capture (rec_monitors_input, c);
559 /* data will be written to disk */
561 if (rec_nframes == nframes && rec_offset == 0) {
563 for (chan = c->begin(); chan != c->end(); ++chan) {
564 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
567 playback_distance = nframes;
572 /* we can't use the capture buffer as the playback buffer, because
573 we recorded only a part of the current process' cycle data
577 collect_playback = true;
580 adjust_capture_position = rec_nframes;
582 } else if (nominally_recording) {
584 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
586 for (chan = c->begin(); chan != c->end(); ++chan) {
587 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
590 playback_distance = nframes;
594 collect_playback = true;
597 if (collect_playback) {
599 /* we're doing playback */
601 nframes_t necessary_samples;
603 /* no varispeed playback if we're recording, because the output .... TBD */
605 if (rec_nframes == 0 && _actual_speed != 1.0f) {
606 necessary_samples = (nframes_t) floor ((nframes * fabs (_actual_speed))) + 1;
608 necessary_samples = nframes;
611 for (chan = c->begin(); chan != c->end(); ++chan) {
612 (*chan)->playback_buf->get_read_vector (&(*chan)->playback_vector);
617 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
619 ChannelInfo* chaninfo (*chan);
621 if (necessary_samples <= chaninfo->playback_vector.len[0]) {
623 chaninfo->current_playback_buffer = chaninfo->playback_vector.buf[0];
626 nframes_t total = chaninfo->playback_vector.len[0] + chaninfo->playback_vector.len[1];
628 if (necessary_samples > total) {
629 cerr << "underrun for " << _name << endl;
635 memcpy ((char *) chaninfo->playback_wrap_buffer,
636 chaninfo->playback_vector.buf[0],
637 chaninfo->playback_vector.len[0] * sizeof (Sample));
638 memcpy (chaninfo->playback_wrap_buffer + chaninfo->playback_vector.len[0],
639 chaninfo->playback_vector.buf[1],
640 (necessary_samples - chaninfo->playback_vector.len[0])
643 chaninfo->current_playback_buffer = chaninfo->playback_wrap_buffer;
648 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
649 process_varispeed_playback(nframes, c);
651 playback_distance = nframes;
654 _speed = _target_speed;
665 /* we're exiting with failure, so ::commit will not
666 be called. unlock the state lock.
669 commit_should_unlock = false;
677 AudioDiskstream::process_varispeed_playback(nframes_t nframes, boost::shared_ptr<ChannelList> c)
679 ChannelList::iterator chan;
681 interpolation.set_speed (_target_speed);
684 for (chan = c->begin(); chan != c->end(); ++chan, ++channel) {
685 ChannelInfo* chaninfo (*chan);
687 playback_distance = interpolation.interpolate (
688 channel, nframes, chaninfo->current_playback_buffer, chaninfo->speed_buffer);
690 chaninfo->current_playback_buffer = chaninfo->speed_buffer;
695 AudioDiskstream::commit (nframes_t /*nframes*/)
697 bool need_butler = false;
699 if (!_io || !_io->active()) {
703 if (_actual_speed < 0.0) {
704 playback_sample -= playback_distance;
706 playback_sample += playback_distance;
709 boost::shared_ptr<ChannelList> c = channels.reader();
710 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
712 (*chan)->playback_buf->increment_read_ptr (playback_distance);
714 if (adjust_capture_position) {
715 (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
719 if (adjust_capture_position != 0) {
720 capture_captured += adjust_capture_position;
721 adjust_capture_position = 0;
725 if (_io && _io->active()) {
726 need_butler = c->front()->playback_buf->write_space() >= c->front()->playback_buf->bufsize() / 2;
731 if (_io && _io->active()) {
732 need_butler = c->front()->playback_buf->write_space() >= disk_io_chunk_frames
733 || c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
735 need_butler = c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
739 if (commit_should_unlock) {
749 AudioDiskstream::set_pending_overwrite (bool yn)
751 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
753 pending_overwrite = yn;
755 overwrite_frame = playback_sample;
756 overwrite_offset = channels.reader()->front()->playback_buf->get_read_ptr();
760 AudioDiskstream::overwrite_existing_buffers ()
762 boost::shared_ptr<ChannelList> c = channels.reader();
763 Sample* mixdown_buffer;
766 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
768 overwrite_queued = false;
770 /* assume all are the same size */
771 nframes_t size = c->front()->playback_buf->bufsize();
773 mixdown_buffer = new Sample[size];
774 gain_buffer = new float[size];
776 /* reduce size so that we can fill the buffer correctly. */
782 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
784 start = overwrite_frame;
785 nframes_t cnt = size;
787 /* to fill the buffer without resetting the playback sample, we need to
788 do it one or two chunks (normally two).
790 |----------------------------------------------------------------------|
794 |<- second chunk->||<----------------- first chunk ------------------>|
798 nframes_t to_read = size - overwrite_offset;
800 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, *chan, n, reversed)) {
801 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
802 _id, size, playback_sample) << endmsg;
810 if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer,
811 start, cnt, *chan, n, reversed)) {
812 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
813 _id, size, playback_sample) << endmsg;
822 pending_overwrite = false;
823 delete [] gain_buffer;
824 delete [] mixdown_buffer;
829 AudioDiskstream::seek (nframes_t frame, bool complete_refill)
833 ChannelList::iterator chan;
834 boost::shared_ptr<ChannelList> c = channels.reader();
836 Glib::Mutex::Lock lm (state_lock);
838 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
839 (*chan)->playback_buf->reset ();
840 (*chan)->capture_buf->reset ();
843 /* can't rec-enable in destructive mode if transport is before start */
845 if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
846 disengage_record_enable ();
849 playback_sample = frame;
852 if (complete_refill) {
853 while ((ret = do_refill_with_alloc ()) > 0) ;
855 ret = do_refill_with_alloc ();
862 AudioDiskstream::can_internal_playback_seek (nframes_t distance)
864 ChannelList::iterator chan;
865 boost::shared_ptr<ChannelList> c = channels.reader();
867 for (chan = c->begin(); chan != c->end(); ++chan) {
868 if ((*chan)->playback_buf->read_space() < distance) {
876 AudioDiskstream::internal_playback_seek (nframes_t distance)
878 ChannelList::iterator chan;
879 boost::shared_ptr<ChannelList> c = channels.reader();
881 for (chan = c->begin(); chan != c->end(); ++chan) {
882 (*chan)->playback_buf->increment_read_ptr (distance);
885 first_recordable_frame += distance;
886 playback_sample += distance;
892 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer, nframes_t& start, nframes_t cnt,
893 ChannelInfo* /*channel_info*/, int channel, bool reversed)
895 nframes_t this_read = 0;
897 nframes_t loop_end = 0;
898 nframes_t loop_start = 0;
899 nframes_t loop_length = 0;
900 nframes_t offset = 0;
903 /* XXX we don't currently play loops in reverse. not sure why */
907 /* Make the use of a Location atomic for this read operation.
909 Note: Locations don't get deleted, so all we care about
910 when I say "atomic" is that we are always pointing to
911 the same one and using a start/length values obtained
915 if ((loc = loop_location) != 0) {
916 loop_start = loc->start();
917 loop_end = loc->end();
918 loop_length = loop_end - loop_start;
921 /* if we are looping, ensure that the first frame we read is at the correct
922 position within the loop.
925 if (loc && start >= loop_end) {
926 //cerr << "start adjusted from " << start;
927 start = loop_start + ((start - loop_start) % loop_length);
928 //cerr << "to " << start << endl;
931 //cerr << "start is " << start << " loopstart: " << loop_start << " loopend: " << loop_end << endl;
940 /* take any loop into account. we can't read past the end of the loop. */
942 if (loc && (loop_end - start < cnt)) {
943 this_read = loop_end - start;
944 //cerr << "reloop true: thisread: " << this_read << " cnt: " << cnt << endl;
951 if (this_read == 0) {
955 this_read = min(cnt,this_read);
957 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
958 error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), _id, this_read,
963 _read_data_count = _playlist->read_data_count();
967 swap_by_ptr (buf, buf + this_read - 1);
971 /* if we read to the end of the loop, go back to the beginning */
988 AudioDiskstream::do_refill_with_alloc ()
990 Sample* mix_buf = new Sample[disk_io_chunk_frames];
991 float* gain_buf = new float[disk_io_chunk_frames];
993 int ret = _do_refill(mix_buf, gain_buf);
1002 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer)
1006 RingBufferNPT<Sample>::rw_vector vector;
1007 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1008 nframes_t total_space;
1009 nframes_t zero_fill;
1011 ChannelList::iterator i;
1012 boost::shared_ptr<ChannelList> c = channels.reader();
1019 assert(mixdown_buffer);
1020 assert(gain_buffer);
1027 c->front()->playback_buf->get_write_vector (&vector);
1029 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1033 /* if there are 2+ chunks of disk i/o possible for
1034 this track, let the caller know so that it can arrange
1035 for us to be called again, ASAP.
1038 if (total_space >= (_slaved?3:2) * disk_io_chunk_frames) {
1042 /* if we're running close to normal speed and there isn't enough
1043 space to do disk_io_chunk_frames of I/O, then don't bother.
1045 at higher speeds, just do it because the sync between butler
1046 and audio thread may not be good enough.
1049 if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1053 /* when slaved, don't try to get too close to the read pointer. this
1054 leaves space for the buffer reversal to have something useful to
1058 if (_slaved && total_space < (c->front()->playback_buf->bufsize() / 2)) {
1062 /* never do more than disk_io_chunk_frames worth of disk input per call (limit doesn't apply for memset) */
1064 total_space = min (disk_io_chunk_frames, total_space);
1068 if (file_frame == 0) {
1070 /* at start: nothing to do but fill with silence */
1072 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1074 ChannelInfo* chan (*i);
1075 chan->playback_buf->get_write_vector (&vector);
1076 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1077 if (vector.len[1]) {
1078 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1080 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1085 if (file_frame < total_space) {
1087 /* too close to the start: read what we can,
1088 and then zero fill the rest
1091 zero_fill = total_space - file_frame;
1092 total_space = file_frame;
1102 if (file_frame == max_frames) {
1104 /* at end: nothing to do but fill with silence */
1106 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1108 ChannelInfo* chan (*i);
1109 chan->playback_buf->get_write_vector (&vector);
1110 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1111 if (vector.len[1]) {
1112 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1114 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1119 if (file_frame > max_frames - total_space) {
1121 /* to close to the end: read what we can, and zero fill the rest */
1123 zero_fill = total_space - (max_frames - file_frame);
1124 total_space = max_frames - file_frame;
1131 nframes_t file_frame_tmp = 0;
1133 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1135 ChannelInfo* chan (*i);
1138 nframes_t len1, len2;
1140 chan->playback_buf->get_write_vector (&vector);
1142 if (vector.len[0] > disk_io_chunk_frames) {
1144 /* we're not going to fill the first chunk, so certainly do not bother with the
1145 other part. it won't be connected with the part we do fill, as in:
1147 .... => writable space
1148 ++++ => readable space
1149 ^^^^ => 1 x disk_io_chunk_frames that would be filled
1151 |......|+++++++++++++|...............................|
1156 So, just pretend that the buf1 part isn't there.
1166 file_frame_tmp = file_frame;
1168 buf1 = vector.buf[0];
1169 len1 = vector.len[0];
1170 buf2 = vector.buf[1];
1171 len2 = vector.len[1];
1173 to_read = min (ts, len1);
1174 to_read = min (to_read, disk_io_chunk_frames);
1178 if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1183 chan->playback_buf->increment_write_ptr (to_read);
1187 to_read = min (ts, len2);
1191 /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1192 so read some or all of vector.len[1] as well.
1195 if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1200 chan->playback_buf->increment_write_ptr (to_read);
1209 file_frame = file_frame_tmp;
1216 /** Flush pending data to disk.
1218 * Important note: this function will write *AT MOST* disk_io_chunk_frames
1219 * of data to disk. it will never write more than that. If it writes that
1220 * much and there is more than that waiting to be written, it will return 1,
1221 * otherwise 0 on success or -1 on failure.
1223 * If there is less than disk_io_chunk_frames to be written, no data will be
1224 * written at all unless @a force_flush is true.
1227 AudioDiskstream::do_flush (RunContext /*context*/, bool force_flush)
1231 RingBufferNPT<Sample>::rw_vector vector;
1232 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1235 _write_data_count = 0;
1237 transvec.buf[0] = 0;
1238 transvec.buf[1] = 0;
1242 boost::shared_ptr<ChannelList> c = channels.reader();
1243 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1245 (*chan)->capture_buf->get_read_vector (&vector);
1247 total = vector.len[0] + vector.len[1];
1249 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1253 /* if there are 2+ chunks of disk i/o possible for
1254 this track, let the caller know so that it can arrange
1255 for us to be called again, ASAP.
1257 if we are forcing a flush, then if there is* any* extra
1258 work, let the caller know.
1260 if we are no longer recording and there is any extra work,
1261 let the caller know too.
1264 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1268 to_write = min (disk_io_chunk_frames, (nframes_t) vector.len[0]);
1270 // check the transition buffer when recording destructive
1271 // important that we get this after the capture buf
1273 if (destructive()) {
1274 (*chan)->capture_transition_buf->get_read_vector(&transvec);
1275 size_t transcount = transvec.len[0] + transvec.len[1];
1276 bool have_start = false;
1279 for (ti=0; ti < transcount; ++ti) {
1280 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1282 if (captrans.type == CaptureStart) {
1283 // by definition, the first data we got above represents the given capture pos
1285 (*chan)->write_source->mark_capture_start (captrans.capture_val);
1286 (*chan)->curr_capture_cnt = 0;
1290 else if (captrans.type == CaptureEnd) {
1292 // capture end, the capture_val represents total frames in capture
1294 if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1296 // shorten to make the write a perfect fit
1297 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
1299 if (nto_write < to_write) {
1300 ret = 1; // should we?
1302 to_write = nto_write;
1304 (*chan)->write_source->mark_capture_end ();
1306 // increment past this transition, but go no further
1311 // actually ends just beyond this chunk, so force more work
1319 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1323 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1324 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1328 (*chan)->capture_buf->increment_read_ptr (to_write);
1329 (*chan)->curr_capture_cnt += to_write;
1331 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1333 /* we wrote all of vector.len[0] but it wasn't an entire
1334 disk_io_chunk_frames of data, so arrange for some part
1335 of vector.len[1] to be flushed to disk as well.
1338 to_write = min ((nframes_t)(disk_io_chunk_frames - to_write), (nframes_t) vector.len[1]);
1340 if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1341 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1345 _write_data_count += (*chan)->write_source->write_data_count();
1347 (*chan)->capture_buf->increment_read_ptr (to_write);
1348 (*chan)->curr_capture_cnt += to_write;
1357 AudioDiskstream::transport_stopped (struct tm& when, time_t twhen, bool abort_capture)
1359 uint32_t buffer_position;
1360 bool more_work = true;
1362 boost::shared_ptr<AudioRegion> region;
1363 nframes_t total_capture;
1365 SourceList::iterator src;
1366 ChannelList::iterator chan;
1367 vector<CaptureInfo*>::iterator ci;
1368 boost::shared_ptr<ChannelList> c = channels.reader();
1370 bool mark_write_completed = false;
1372 finish_capture (true, c);
1374 /* butler is already stopped, but there may be work to do
1375 to flush remaining data to disk.
1378 while (more_work && !err) {
1379 switch (do_flush (TransportContext, true)) {
1386 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1391 /* XXX is there anything we can do if err != 0 ? */
1392 Glib::Mutex::Lock lm (capture_info_lock);
1394 if (capture_info.empty()) {
1398 if (abort_capture) {
1400 if (destructive()) {
1404 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1406 if ((*chan)->write_source) {
1408 (*chan)->write_source->mark_for_remove ();
1409 (*chan)->write_source->drop_references ();
1410 (*chan)->write_source.reset ();
1413 /* new source set up in "out" below */
1419 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1420 total_capture += (*ci)->frames;
1423 /* figure out the name for this take */
1425 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1427 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1431 s->update_header (capture_info.front()->start, when, twhen);
1432 s->set_captured_for (_name);
1433 s->mark_immutable ();
1434 if (Config->get_auto_analyse_audio()) {
1435 Analyser::queue_source_for_analysis (s, true);
1440 /* destructive tracks have a single, never changing region */
1442 if (destructive()) {
1444 /* send a signal that any UI can pick up to do the right thing. there is
1445 a small problem here in that a UI may need the peak data to be ready
1446 for the data that was recorded and this isn't interlocked with that
1447 process. this problem is deferred to the UI.
1450 _playlist->Modified();
1454 string whole_file_region_name;
1455 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1457 /* Register a new region with the Session that
1458 describes the entire source. Do this first
1459 so that any sub-regions will obviously be
1460 children of this one (later!)
1464 boost::shared_ptr<Region> rx (RegionFactory::create (srcs,
1465 c->front()->write_source->last_capture_start_frame(), total_capture,
1466 whole_file_region_name, 0,
1467 Region::Flag (Region::DefaultFlags|Region::Automatic|Region::WholeFile)));
1469 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1470 region->special_set_position (capture_info.front()->start);
1474 catch (failed_constructor& err) {
1475 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1479 _last_capture_regions.push_back (region);
1481 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1483 XMLNode &before = _playlist->get_state();
1484 _playlist->freeze ();
1486 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1490 _session.region_name (region_name, whole_file_region_name, false);
1492 // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->frames << " add region " << region_name << endl;
1495 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, buffer_position, (*ci)->frames, region_name));
1496 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1499 catch (failed_constructor& err) {
1500 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1501 continue; /* XXX is this OK? */
1504 region->GoingAway.connect (bind (mem_fun (*this, &Diskstream::remove_region_from_last_capture), boost::weak_ptr<Region>(region)));
1506 _last_capture_regions.push_back (region);
1508 i_am_the_modifier++;
1509 _playlist->add_region (region, (*ci)->start, 1, non_layered());
1510 i_am_the_modifier--;
1512 buffer_position += (*ci)->frames;
1516 XMLNode &after = _playlist->get_state();
1517 _session.add_command (new MementoCommand<Playlist>(*_playlist, &before, &after));
1520 mark_write_completed = true;
1523 reset_write_sources (mark_write_completed);
1527 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1531 capture_info.clear ();
1532 capture_start_frame = 0;
1536 AudioDiskstream::transport_looped (nframes_t transport_frame)
1538 if (was_recording) {
1539 // all we need to do is finish this capture, with modified capture length
1540 boost::shared_ptr<ChannelList> c = channels.reader();
1542 // adjust the capture length knowing that the data will be recorded to disk
1543 // only necessary after the first loop where we're recording
1544 if (capture_info.size() == 0) {
1545 capture_captured += _capture_offset;
1547 if (_alignment_style == ExistingMaterial) {
1548 capture_captured += _session.worst_output_latency();
1550 capture_captured += _roll_delay;
1554 finish_capture (true, c);
1556 // the next region will start recording via the normal mechanism
1557 // we'll set the start position to the current transport pos
1558 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1559 capture_start_frame = transport_frame;
1560 first_recordable_frame = transport_frame; // mild lie
1561 last_recordable_frame = max_frames;
1562 was_recording = true;
1564 if (recordable() && destructive()) {
1565 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1567 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1568 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1570 if (transvec.len[0] > 0) {
1571 transvec.buf[0]->type = CaptureStart;
1572 transvec.buf[0]->capture_val = capture_start_frame;
1573 (*chan)->capture_transition_buf->increment_write_ptr(1);
1577 fatal << X_("programming error: capture_transition_buf is full on rec loop! inconceivable!")
1587 AudioDiskstream::finish_capture (bool /*rec_monitors_input*/, boost::shared_ptr<ChannelList> c)
1589 was_recording = false;
1591 if (capture_captured == 0) {
1595 if (recordable() && destructive()) {
1596 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1598 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1599 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1601 if (transvec.len[0] > 0) {
1602 transvec.buf[0]->type = CaptureEnd;
1603 transvec.buf[0]->capture_val = capture_captured;
1604 (*chan)->capture_transition_buf->increment_write_ptr(1);
1608 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1614 CaptureInfo* ci = new CaptureInfo;
1616 ci->start = capture_start_frame;
1617 ci->frames = capture_captured;
1619 /* XXX theoretical race condition here. Need atomic exchange ?
1620 However, the circumstances when this is called right
1621 now (either on record-disable or transport_stopped)
1622 mean that no actual race exists. I think ...
1623 We now have a capture_info_lock, but it is only to be used
1624 to synchronize in the transport_stop and the capture info
1625 accessors, so that invalidation will not occur (both non-realtime).
1628 // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1630 capture_info.push_back (ci);
1631 capture_captured = 0;
1633 /* now we've finished a capture, reset first_recordable_frame for next time */
1634 first_recordable_frame = max_frames;
1638 AudioDiskstream::set_record_enabled (bool yn)
1640 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0) {
1644 /* can't rec-enable in destructive mode if transport is before start */
1646 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1650 if (yn && channels.reader()->front()->source == 0) {
1652 /* pick up connections not initiated *from* the IO object
1653 we're associated with.
1656 get_input_sources ();
1659 /* yes, i know that this not proof against race conditions, but its
1660 good enough. i think.
1663 if (record_enabled() != yn) {
1665 engage_record_enable ();
1667 disengage_record_enable ();
1673 AudioDiskstream::engage_record_enable ()
1675 bool rolling = _session.transport_speed() != 0.0f;
1676 boost::shared_ptr<ChannelList> c = channels.reader();
1678 g_atomic_int_set (&_record_enabled, 1);
1679 capturing_sources.clear ();
1681 if (Config->get_monitoring_model() == HardwareMonitoring) {
1683 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1684 if ((*chan)->source) {
1685 (*chan)->source->ensure_monitor_input (!(_session.config.get_auto_input() && rolling));
1687 capturing_sources.push_back ((*chan)->write_source);
1688 (*chan)->write_source->mark_streaming_write_started ();
1692 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1693 capturing_sources.push_back ((*chan)->write_source);
1694 (*chan)->write_source->mark_streaming_write_started ();
1698 RecordEnableChanged (); /* EMIT SIGNAL */
1702 AudioDiskstream::disengage_record_enable ()
1704 g_atomic_int_set (&_record_enabled, 0);
1705 boost::shared_ptr<ChannelList> c = channels.reader();
1706 if (Config->get_monitoring_model() == HardwareMonitoring) {
1707 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1708 if ((*chan)->source) {
1709 (*chan)->source->ensure_monitor_input (false);
1713 capturing_sources.clear ();
1714 RecordEnableChanged (); /* EMIT SIGNAL */
1718 AudioDiskstream::get_state ()
1720 XMLNode* node = new XMLNode ("AudioDiskstream");
1722 LocaleGuard lg (X_("POSIX"));
1723 boost::shared_ptr<ChannelList> c = channels.reader();
1725 node->add_property ("flags", enum_2_string (_flags));
1727 snprintf (buf, sizeof(buf), "%zd", c->size());
1728 node->add_property ("channels", buf);
1730 node->add_property ("playlist", _playlist->name());
1732 snprintf (buf, sizeof(buf), "%.12g", _visible_speed);
1733 node->add_property ("speed", buf);
1735 node->add_property("name", _name);
1736 id().print (buf, sizeof (buf));
1737 node->add_property("id", buf);
1739 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1741 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1742 XMLNode* cs_grandchild;
1744 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1745 cs_grandchild = new XMLNode (X_("file"));
1746 cs_grandchild->add_property (X_("path"), (*i)->path());
1747 cs_child->add_child_nocopy (*cs_grandchild);
1750 /* store the location where capture will start */
1754 if (_session.config.get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1755 snprintf (buf, sizeof (buf), "%" PRId64, pi->start());
1757 snprintf (buf, sizeof (buf), "%" PRIu32, _session.transport_frame());
1760 cs_child->add_property (X_("at"), buf);
1761 node->add_child_nocopy (*cs_child);
1765 node->add_child_copy (*_extra_xml);
1772 AudioDiskstream::set_state (const XMLNode& node, int /*version*/)
1774 const XMLProperty* prop;
1775 XMLNodeList nlist = node.children();
1776 XMLNodeIterator niter;
1777 uint32_t nchans = 1;
1778 XMLNode* capture_pending_node = 0;
1779 LocaleGuard lg (X_("POSIX"));
1781 in_set_state = true;
1783 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1784 if ((*niter)->name() == IO::state_node_name) {
1785 deprecated_io_node = new XMLNode (**niter);
1788 if ((*niter)->name() == X_("CapturingSources")) {
1789 capture_pending_node = *niter;
1793 /* prevent write sources from being created */
1795 in_set_state = true;
1797 if ((prop = node.property ("name")) != 0) {
1798 _name = prop->value();
1801 if (deprecated_io_node) {
1802 if ((prop = deprecated_io_node->property ("id")) != 0) {
1803 _id = prop->value ();
1806 if ((prop = node.property ("id")) != 0) {
1807 _id = prop->value ();
1811 if ((prop = node.property ("flags")) != 0) {
1812 _flags = Flag (string_2_enum (prop->value(), _flags));
1815 if ((prop = node.property ("channels")) != 0) {
1816 nchans = atoi (prop->value().c_str());
1819 // create necessary extra channels
1820 // we are always constructed with one and we always need one
1822 _n_channels.set(DataType::AUDIO, channels.reader()->size());
1824 if (nchans > _n_channels.n_audio()) {
1826 add_channel (nchans - _n_channels.n_audio());
1827 IO::PortCountChanged(_n_channels);
1829 } else if (nchans < _n_channels.n_audio()) {
1831 remove_channel (_n_channels.n_audio() - nchans);
1834 if ((prop = node.property ("playlist")) == 0) {
1839 bool had_playlist = (_playlist != 0);
1841 if (find_and_use_playlist (prop->value())) {
1845 if (!had_playlist) {
1846 _playlist->set_orig_diskstream_id (_id);
1849 if (!destructive() && capture_pending_node) {
1850 /* destructive streams have one and only one source per channel,
1851 and so they never end up in pending capture in any useful
1854 use_pending_capture_data (*capture_pending_node);
1859 if ((prop = node.property ("speed")) != 0) {
1860 double sp = atof (prop->value().c_str());
1862 if (realtime_set_speed (sp, false)) {
1863 non_realtime_set_speed ();
1867 in_set_state = false;
1869 /* make sure this is clear before we do anything else */
1871 capturing_sources.clear ();
1873 /* write sources are handled when we handle the input set
1874 up of the IO that owns this DS (::non_realtime_input_change())
1881 AudioDiskstream::use_new_write_source (uint32_t n)
1883 boost::shared_ptr<ChannelList> c = channels.reader();
1885 if (!recordable()) {
1889 if (n >= c->size()) {
1890 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
1894 ChannelInfo* chan = (*c)[n];
1896 if (chan->write_source) {
1897 chan->write_source->done_with_peakfile_writes ();
1898 chan->write_source->set_allow_remove_if_empty (true);
1899 chan->write_source.reset ();
1903 if ((chan->write_source = _session.create_audio_source_for_session (*this, n, destructive())) == 0) {
1904 throw failed_constructor();
1908 catch (failed_constructor &err) {
1909 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
1910 chan->write_source.reset ();
1914 /* do not remove destructive files even if they are empty */
1916 chan->write_source->set_allow_remove_if_empty (!destructive());
1922 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool /*force*/)
1924 ChannelList::iterator chan;
1925 boost::shared_ptr<ChannelList> c = channels.reader();
1928 if (!_session.writable() || !recordable()) {
1932 capturing_sources.clear ();
1934 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1935 if (!destructive()) {
1937 if ((*chan)->write_source && mark_write_complete) {
1938 (*chan)->write_source->mark_streaming_write_completed ();
1940 use_new_write_source (n);
1942 if (record_enabled()) {
1943 capturing_sources.push_back ((*chan)->write_source);
1947 if ((*chan)->write_source == 0) {
1948 use_new_write_source (n);
1953 if (destructive()) {
1955 /* we now have all our write sources set up, so create the
1956 playlist's single region.
1959 if (_playlist->empty()) {
1960 setup_destructive_playlist ();
1966 AudioDiskstream::rename_write_sources ()
1968 ChannelList::iterator chan;
1969 boost::shared_ptr<ChannelList> c = channels.reader();
1972 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1973 if ((*chan)->write_source != 0) {
1974 (*chan)->write_source->set_source_name (_name, destructive());
1975 /* XXX what to do if one of them fails ? */
1983 AudioDiskstream::set_block_size (nframes_t /*nframes*/)
1985 if (_session.get_block_size() > speed_buffer_size) {
1986 speed_buffer_size = _session.get_block_size();
1987 boost::shared_ptr<ChannelList> c = channels.reader();
1989 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1990 if ((*chan)->speed_buffer)
1991 delete [] (*chan)->speed_buffer;
1992 (*chan)->speed_buffer = new Sample[speed_buffer_size];
1995 allocate_temporary_buffers ();
1999 AudioDiskstream::allocate_temporary_buffers ()
2001 /* make sure the wrap buffer is at least large enough to deal
2002 with the speeds up to 1.2, to allow for micro-variation
2003 when slaving to MTC, Timecode etc.
2006 double sp = max (fabsf (_actual_speed), 1.2f);
2007 nframes_t required_wrap_size = (nframes_t) floor (_session.get_block_size() * sp) + 1;
2009 if (required_wrap_size > wrap_buffer_size) {
2011 boost::shared_ptr<ChannelList> c = channels.reader();
2013 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2014 if ((*chan)->playback_wrap_buffer)
2015 delete [] (*chan)->playback_wrap_buffer;
2016 (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
2017 if ((*chan)->capture_wrap_buffer)
2018 delete [] (*chan)->capture_wrap_buffer;
2019 (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
2022 wrap_buffer_size = required_wrap_size;
2027 AudioDiskstream::monitor_input (bool yn)
2029 boost::shared_ptr<ChannelList> c = channels.reader();
2031 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2033 if ((*chan)->source) {
2034 (*chan)->source->ensure_monitor_input (yn);
2040 AudioDiskstream::set_align_style_from_io ()
2042 bool have_physical = false;
2048 get_input_sources ();
2050 boost::shared_ptr<ChannelList> c = channels.reader();
2052 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2053 if ((*chan)->source && (*chan)->source->flags() & JackPortIsPhysical) {
2054 have_physical = true;
2059 if (have_physical) {
2060 set_align_style (ExistingMaterial);
2062 set_align_style (CaptureTime);
2067 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2069 while (how_many--) {
2070 c->push_back (new ChannelInfo(_session.butler()->audio_diskstream_buffer_size(), speed_buffer_size, wrap_buffer_size));
2071 interpolation.add_channel_to (_session.butler()->audio_diskstream_buffer_size(), speed_buffer_size);
2074 _n_channels.set(DataType::AUDIO, c->size());
2080 AudioDiskstream::add_channel (uint32_t how_many)
2082 RCUWriter<ChannelList> writer (channels);
2083 boost::shared_ptr<ChannelList> c = writer.get_copy();
2085 return add_channel_to (c, how_many);
2089 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2091 while (how_many-- && !c->empty()) {
2092 // FIXME: crash (thread safe with RCU?)
2093 // memory leak, when disabled.... :(
2096 interpolation.remove_channel_from ();
2099 _n_channels.set(DataType::AUDIO, c->size());
2105 AudioDiskstream::remove_channel (uint32_t how_many)
2107 RCUWriter<ChannelList> writer (channels);
2108 boost::shared_ptr<ChannelList> c = writer.get_copy();
2110 return remove_channel_from (c, how_many);
2114 AudioDiskstream::playback_buffer_load () const
2116 boost::shared_ptr<ChannelList> c = channels.reader();
2118 return (float) ((double) c->front()->playback_buf->read_space()/
2119 (double) c->front()->playback_buf->bufsize());
2123 AudioDiskstream::capture_buffer_load () const
2125 boost::shared_ptr<ChannelList> c = channels.reader();
2127 return (float) ((double) c->front()->capture_buf->write_space()/
2128 (double) c->front()->capture_buf->bufsize());
2132 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2134 const XMLProperty* prop;
2135 XMLNodeList nlist = node.children();
2136 XMLNodeIterator niter;
2137 boost::shared_ptr<AudioFileSource> fs;
2138 boost::shared_ptr<AudioFileSource> first_fs;
2139 SourceList pending_sources;
2142 if ((prop = node.property (X_("at"))) == 0) {
2146 if (sscanf (prop->value().c_str(), "%" PRIu32, &position) != 1) {
2150 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2151 if ((*niter)->name() == X_("file")) {
2153 if ((prop = (*niter)->property (X_("path"))) == 0) {
2157 // This protects sessions from errant CapturingSources in stored sessions
2159 if (stat (prop->value().c_str(), &sbuf)) {
2164 fs = boost::dynamic_pointer_cast<AudioFileSource> (
2165 SourceFactory::createWritable (DataType::AUDIO, _session,
2166 prop->value(), true,
2167 false, _session.frame_rate()));
2170 catch (failed_constructor& err) {
2171 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2172 _name, prop->value())
2177 pending_sources.push_back (fs);
2179 if (first_fs == 0) {
2183 fs->set_captured_for (_name);
2187 if (pending_sources.size() == 0) {
2188 /* nothing can be done */
2192 if (pending_sources.size() != _n_channels.n_audio()) {
2193 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2198 boost::shared_ptr<AudioRegion> region;
2201 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (
2202 pending_sources, 0, first_fs->length(first_fs->timeline_position()),
2203 region_name_from_path (first_fs->name(), true), 0,
2204 Region::Flag (Region::DefaultFlags|Region::Automatic|Region::WholeFile)));
2205 region->special_set_position (0);
2208 catch (failed_constructor& err) {
2209 error << string_compose (
2210 _("%1: cannot create whole-file region from pending capture sources"),
2217 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (
2218 pending_sources, 0, first_fs->length(first_fs->timeline_position()),
2219 region_name_from_path (first_fs->name(), true)));
2222 catch (failed_constructor& err) {
2223 error << string_compose (_("%1: cannot create region from pending capture sources"),
2230 _playlist->add_region (region, position);
2236 AudioDiskstream::set_non_layered (bool yn)
2238 if (yn != non_layered()) {
2241 _flags = Flag (_flags | NonLayered);
2243 _flags = Flag (_flags & ~NonLayered);
2251 AudioDiskstream::set_destructive (bool yn)
2253 bool bounce_ignored;
2255 if (yn != destructive()) {
2258 /* requestor should already have checked this and
2259 bounced if necessary and desired
2261 if (!can_become_destructive (bounce_ignored)) {
2264 _flags = Flag (_flags | Destructive);
2265 use_destructive_playlist ();
2267 _flags = Flag (_flags & ~Destructive);
2268 reset_write_sources (true, true);
2276 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2279 requires_bounce = false;
2283 /* is there only one region ? */
2285 if (_playlist->n_regions() != 1) {
2286 requires_bounce = true;
2290 boost::shared_ptr<Region> first = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
2293 /* do the source(s) for the region cover the session start position ? */
2295 if (first->position() != _session.current_start_frame()) {
2296 if (first->start() > _session.current_start_frame()) {
2297 requires_bounce = true;
2302 /* is the source used by only 1 playlist ? */
2304 boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2308 if (_session.source_use_count (afirst->source()) > 1) {
2309 requires_bounce = true;
2313 requires_bounce = false;
2317 AudioDiskstream::ChannelInfo::ChannelInfo (nframes_t bufsize, nframes_t speed_size, nframes_t wrap_size)
2321 current_capture_buffer = 0;
2322 current_playback_buffer = 0;
2323 curr_capture_cnt = 0;
2325 speed_buffer = new Sample[speed_size];
2326 playback_wrap_buffer = new Sample[wrap_size];
2327 capture_wrap_buffer = new Sample[wrap_size];
2329 playback_buf = new RingBufferNPT<Sample> (bufsize);
2330 capture_buf = new RingBufferNPT<Sample> (bufsize);
2331 capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2333 /* touch the ringbuffer buffers, which will cause
2334 them to be mapped into locked physical RAM if
2335 we're running with mlockall(). this doesn't do
2339 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2340 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2341 memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2344 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2347 write_source.reset ();
2350 delete [] speed_buffer;
2353 delete [] playback_wrap_buffer;
2354 playback_wrap_buffer = 0;
2356 delete [] capture_wrap_buffer;
2357 capture_wrap_buffer = 0;
2359 delete playback_buf;
2365 delete capture_transition_buf;
2366 capture_transition_buf = 0;