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/stateful_diff_command.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"
48 #include "ardour/audioplaylist.h"
49 #include "ardour/audioregion.h"
50 #include "ardour/butler.h"
51 #include "ardour/configuration.h"
52 #include "ardour/cycle_timer.h"
53 #include "ardour/debug.h"
54 #include "ardour/io.h"
55 #include "ardour/playlist_factory.h"
56 #include "ardour/region_factory.h"
57 #include "ardour/send.h"
58 #include "ardour/session.h"
59 #include "ardour/source_factory.h"
60 #include "ardour/utils.h"
61 #include "ardour/session_playlists.h"
62 #include "ardour/route.h"
68 using namespace ARDOUR;
71 size_t AudioDiskstream::_working_buffers_size = 0;
72 Sample* AudioDiskstream::_mixdown_buffer = 0;
73 gain_t* AudioDiskstream::_gain_buffer = 0;
75 AudioDiskstream::AudioDiskstream (Session &sess, const string &name, Diskstream::Flag flag)
76 : Diskstream(sess, name, flag)
77 , channels (new ChannelList)
79 /* prevent any write sources from being created */
86 AudioDiskstream::AudioDiskstream (Session& sess, const XMLNode& node)
87 : Diskstream(sess, node)
88 , channels (new ChannelList)
93 if (set_state (node, Stateful::loading_state_version)) {
95 throw failed_constructor();
101 use_destructive_playlist ();
106 AudioDiskstream::init ()
108 /* there are no channels at this point, so these
109 two calls just get speed_buffer_size and wrap_buffer
110 size setup without duplicating their code.
113 set_block_size (_session.get_block_size());
114 allocate_temporary_buffers ();
117 AudioDiskstream::~AudioDiskstream ()
119 DEBUG_TRACE (DEBUG::Destruction, string_compose ("Audio Diskstream %1 destructor\n", _name));
122 RCUWriter<ChannelList> writer (channels);
123 boost::shared_ptr<ChannelList> c = writer.get_copy();
125 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
136 AudioDiskstream::allocate_working_buffers()
138 assert(disk_io_frames() > 0);
140 _working_buffers_size = disk_io_frames();
141 _mixdown_buffer = new Sample[_working_buffers_size];
142 _gain_buffer = new gain_t[_working_buffers_size];
146 AudioDiskstream::free_working_buffers()
148 delete [] _mixdown_buffer;
149 delete [] _gain_buffer;
150 _working_buffers_size = 0;
156 AudioDiskstream::non_realtime_input_change ()
159 Glib::Mutex::Lock lm (state_lock);
161 if (input_change_pending.type == IOChange::NoChange) {
166 RCUWriter<ChannelList> writer (channels);
167 boost::shared_ptr<ChannelList> c = writer.get_copy();
169 _n_channels.set(DataType::AUDIO, c->size());
171 if (_io->n_ports().n_audio() > _n_channels.n_audio()) {
172 add_channel_to (c, _io->n_ports().n_audio() - _n_channels.n_audio());
173 } else if (_io->n_ports().n_audio() < _n_channels.n_audio()) {
174 remove_channel_from (c, _n_channels.n_audio() - _io->n_ports().n_audio());
178 get_input_sources ();
179 set_capture_offset ();
180 set_align_style_from_io ();
182 input_change_pending = IOChange::NoChange;
184 /* implicit unlock */
187 /* reset capture files */
189 reset_write_sources (false);
191 /* now refill channel buffers */
193 if (speed() != 1.0f || speed() != -1.0f) {
194 seek ((framepos_t) (_session.transport_frame() * (double) speed()));
196 seek (_session.transport_frame());
201 AudioDiskstream::non_realtime_locate (framepos_t location)
203 /* now refill channel buffers */
205 if (speed() != 1.0f || speed() != -1.0f) {
206 seek ((framepos_t) (location * (double) speed()));
213 AudioDiskstream::get_input_sources ()
215 boost::shared_ptr<ChannelList> c = channels.reader();
218 ChannelList::iterator chan;
219 uint32_t ni = _io->n_ports().n_audio();
220 vector<string> connections;
222 for (n = 0, chan = c->begin(); chan != c->end() && n < ni; ++chan, ++n) {
224 connections.clear ();
226 if (_io->nth (n)->get_connections (connections) == 0) {
228 if ((*chan)->source) {
229 // _source->disable_metering ();
235 (*chan)->source = dynamic_cast<AudioPort*>(_session.engine().get_port_by_name (connections[0]) );
241 AudioDiskstream::find_and_use_playlist (const string& name)
243 boost::shared_ptr<AudioPlaylist> playlist;
245 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (_session.playlists->by_name (name))) == 0) {
246 playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, name));
250 error << string_compose(_("AudioDiskstream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
254 return use_playlist (playlist);
258 AudioDiskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
260 assert(boost::dynamic_pointer_cast<AudioPlaylist>(playlist));
262 Diskstream::use_playlist(playlist);
268 AudioDiskstream::use_new_playlist ()
271 boost::shared_ptr<AudioPlaylist> playlist;
273 if (!in_set_state && destructive()) {
278 newname = Playlist::bump_name (_playlist->name(), _session);
280 newname = Playlist::bump_name (_name, _session);
283 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, newname, hidden()))) != 0) {
285 playlist->set_orig_diskstream_id (id());
286 return use_playlist (playlist);
294 AudioDiskstream::use_copy_playlist ()
296 assert(audio_playlist());
302 if (_playlist == 0) {
303 error << string_compose(_("AudioDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
308 boost::shared_ptr<AudioPlaylist> playlist;
310 newname = Playlist::bump_name (_playlist->name(), _session);
312 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist>(PlaylistFactory::create (audio_playlist(), newname))) != 0) {
313 playlist->set_orig_diskstream_id (id());
314 return use_playlist (playlist);
321 AudioDiskstream::setup_destructive_playlist ()
324 boost::shared_ptr<ChannelList> c = channels.reader();
326 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
327 srcs.push_back ((*chan)->write_source);
330 /* a single full-sized region */
332 assert (!srcs.empty ());
335 plist.add (Properties::name, _name.val());
336 plist.add (Properties::start, 0);
337 plist.add (Properties::length, max_framepos - (max_framepos - srcs.front()->natural_position()));
339 boost::shared_ptr<Region> region (RegionFactory::create (srcs, plist));
340 _playlist->add_region (region, srcs.front()->natural_position());
344 AudioDiskstream::use_destructive_playlist ()
346 /* this is called from the XML-based constructor or ::set_destructive. when called,
347 we already have a playlist and a region, but we need to
348 set up our sources for write. we use the sources associated
349 with the (presumed single, full-extent) region.
352 boost::shared_ptr<Region> rp = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
355 reset_write_sources (false, true);
359 boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
362 throw failed_constructor();
365 /* be sure to stretch the region out to the maximum length */
367 region->set_length (max_framepos - region->position(), this);
370 ChannelList::iterator chan;
371 boost::shared_ptr<ChannelList> c = channels.reader();
373 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
374 (*chan)->write_source = boost::dynamic_pointer_cast<AudioFileSource>(region->source (n));
375 assert((*chan)->write_source);
376 (*chan)->write_source->set_allow_remove_if_empty (false);
378 /* this might be false if we switched modes, so force it */
380 (*chan)->write_source->set_destructive (true);
383 /* the source list will never be reset for a destructive track */
387 AudioDiskstream::prepare_record_status(framepos_t capture_start_frame)
389 if (recordable() && destructive()) {
390 boost::shared_ptr<ChannelList> c = channels.reader();
391 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
393 RingBufferNPT<CaptureTransition>::rw_vector transitions;
394 (*chan)->capture_transition_buf->get_write_vector (&transitions);
396 if (transitions.len[0] > 0) {
397 transitions.buf[0]->type = CaptureStart;
398 transitions.buf[0]->capture_val = capture_start_frame;
399 (*chan)->capture_transition_buf->increment_write_ptr(1);
402 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
410 AudioDiskstream::process (framepos_t transport_frame, pframes_t nframes, bool can_record, bool rec_monitors_input, bool& need_butler)
413 boost::shared_ptr<ChannelList> c = channels.reader();
414 ChannelList::iterator chan;
416 framecnt_t rec_offset = 0;
417 framecnt_t rec_nframes = 0;
418 bool collect_playback = false;
420 playback_distance = 0;
422 if (!_io || !_io->active()) {
426 check_record_status (transport_frame, can_record);
432 Glib::Mutex::Lock sm (state_lock, Glib::TRY_LOCK);
438 adjust_capture_position = 0;
440 for (chan = c->begin(); chan != c->end(); ++chan) {
441 (*chan)->current_capture_buffer = 0;
442 (*chan)->current_playback_buffer = 0;
445 /* two conditions to test for here:
447 A: this track is rec-enabled, and the session has confirmed that we can record
448 B: this track is rec-enabled, has been recording, and we are set up for auto-punch-in
450 The second test is necessary to capture the extra material that arrives AFTER the transport
451 frame has left the punch range (which will cause the "can_record" argument to be false).
455 // Safeguard against situations where process() goes haywire when autopunching
456 // and last_recordable_frame < first_recordable_frame
458 if (last_recordable_frame < first_recordable_frame) {
459 last_recordable_frame = max_framepos;
462 OverlapType ot = coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
464 calculate_record_range (ot, transport_frame, nframes, rec_nframes, rec_offset);
466 if (rec_nframes && !was_recording) {
467 capture_captured = 0;
468 was_recording = true;
471 if (can_record && !_last_capture_sources.empty()) {
472 _last_capture_sources.clear ();
477 uint32_t limit = _io->n_ports ().n_audio();
479 /* one or more ports could already have been removed from _io, but our
480 channel setup hasn't yet been updated. prevent us from trying to
481 use channels that correspond to missing ports. note that the
482 process callback (from which this is called) is always atomic
483 with respect to port removal/addition.
486 for (n = 0, chan = c->begin(); chan != c->end() && n < limit; ++chan, ++n) {
488 ChannelInfo* chaninfo (*chan);
490 chaninfo->capture_buf->get_write_vector (&chaninfo->capture_vector);
492 if (rec_nframes <= (framecnt_t) chaninfo->capture_vector.len[0]) {
494 chaninfo->current_capture_buffer = chaninfo->capture_vector.buf[0];
496 /* note: grab the entire port buffer, but only copy what we were supposed to
497 for recording, and use rec_offset
500 AudioPort* const ap = _io->audio (n);
502 assert(rec_nframes <= (framecnt_t) ap->get_audio_buffer(nframes).capacity());
503 memcpy (chaninfo->current_capture_buffer, ap->get_audio_buffer (nframes).data(rec_offset), sizeof (Sample) * rec_nframes);
508 framecnt_t total = chaninfo->capture_vector.len[0] + chaninfo->capture_vector.len[1];
510 if (rec_nframes > total) {
515 AudioPort* const ap = _io->audio (n);
518 Sample* buf = ap->get_audio_buffer(nframes).data();
519 framecnt_t first = chaninfo->capture_vector.len[0];
521 memcpy (chaninfo->capture_wrap_buffer, buf, sizeof (Sample) * first);
522 memcpy (chaninfo->capture_vector.buf[0], buf, sizeof (Sample) * first);
523 memcpy (chaninfo->capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
524 memcpy (chaninfo->capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
526 chaninfo->current_capture_buffer = chaninfo->capture_wrap_buffer;
533 finish_capture (rec_monitors_input, c);
540 /* data will be written to disk */
542 if (rec_nframes == nframes && rec_offset == 0) {
544 for (chan = c->begin(); chan != c->end(); ++chan) {
545 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
548 playback_distance = nframes;
553 /* we can't use the capture buffer as the playback buffer, because
554 we recorded only a part of the current process' cycle data
558 collect_playback = true;
561 adjust_capture_position = rec_nframes;
563 } else if (can_record && record_enabled()) {
565 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
567 for (chan = c->begin(); chan != c->end(); ++chan) {
568 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
571 playback_distance = nframes;
575 collect_playback = true;
578 if (collect_playback) {
580 /* we're doing playback */
582 framecnt_t necessary_samples;
584 /* no varispeed playback if we're recording, because the output .... TBD */
586 if (rec_nframes == 0 && _actual_speed != 1.0f) {
587 necessary_samples = (framecnt_t) floor ((nframes * fabs (_actual_speed))) + 1;
589 necessary_samples = nframes;
592 for (chan = c->begin(); chan != c->end(); ++chan) {
593 (*chan)->playback_buf->get_read_vector (&(*chan)->playback_vector);
598 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
600 ChannelInfo* chaninfo (*chan);
602 if (necessary_samples <= (framecnt_t) chaninfo->playback_vector.len[0]) {
604 chaninfo->current_playback_buffer = chaninfo->playback_vector.buf[0];
607 framecnt_t total = chaninfo->playback_vector.len[0] + chaninfo->playback_vector.len[1];
609 if (necessary_samples > total) {
610 cerr << _name << " Need " << necessary_samples << " total = " << total << endl;
611 cerr << "underrun for " << _name << endl;
617 memcpy ((char *) chaninfo->playback_wrap_buffer,
618 chaninfo->playback_vector.buf[0],
619 chaninfo->playback_vector.len[0] * sizeof (Sample));
620 memcpy (chaninfo->playback_wrap_buffer + chaninfo->playback_vector.len[0],
621 chaninfo->playback_vector.buf[1],
622 (necessary_samples - chaninfo->playback_vector.len[0])
625 chaninfo->current_playback_buffer = chaninfo->playback_wrap_buffer;
630 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
631 process_varispeed_playback(nframes, c);
633 playback_distance = nframes;
636 _speed = _target_speed;
642 if (commit (nframes)) {
651 AudioDiskstream::process_varispeed_playback (pframes_t nframes, boost::shared_ptr<ChannelList> c)
653 ChannelList::iterator chan;
655 interpolation.set_speed (_target_speed);
658 for (chan = c->begin(); chan != c->end(); ++chan, ++channel) {
659 ChannelInfo* chaninfo (*chan);
661 playback_distance = interpolation.interpolate (
662 channel, nframes, chaninfo->current_playback_buffer, chaninfo->speed_buffer);
664 chaninfo->current_playback_buffer = chaninfo->speed_buffer;
669 AudioDiskstream::commit (framecnt_t /* nframes */)
671 bool need_butler = false;
673 if (!_io || !_io->active()) {
677 if (_actual_speed < 0.0) {
678 playback_sample -= playback_distance;
680 playback_sample += playback_distance;
683 boost::shared_ptr<ChannelList> c = channels.reader();
684 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
686 (*chan)->playback_buf->increment_read_ptr (playback_distance);
688 if (adjust_capture_position) {
689 (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
693 if (adjust_capture_position != 0) {
694 capture_captured += adjust_capture_position;
695 adjust_capture_position = 0;
703 if (_io && _io->active()) {
704 need_butler = c->front()->playback_buf->write_space() >= c->front()->playback_buf->bufsize() / 2;
709 if (_io && _io->active()) {
710 need_butler = ((framecnt_t) c->front()->playback_buf->write_space() >= disk_io_chunk_frames)
711 || ((framecnt_t) c->front()->capture_buf->read_space() >= disk_io_chunk_frames);
713 need_butler = ((framecnt_t) c->front()->capture_buf->read_space() >= disk_io_chunk_frames);
721 AudioDiskstream::set_pending_overwrite (bool yn)
723 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
725 _pending_overwrite = yn;
727 overwrite_frame = playback_sample;
729 boost::shared_ptr<ChannelList> c = channels.reader ();
731 overwrite_offset = c->front()->playback_buf->get_read_ptr();
736 AudioDiskstream::overwrite_existing_buffers ()
738 boost::shared_ptr<ChannelList> c = channels.reader();
740 _pending_overwrite = false;
744 Sample* mixdown_buffer;
747 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
749 overwrite_queued = false;
751 /* assume all are the same size */
752 framecnt_t size = c->front()->playback_buf->bufsize();
754 mixdown_buffer = new Sample[size];
755 gain_buffer = new float[size];
757 /* reduce size so that we can fill the buffer correctly. */
763 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
765 start = overwrite_frame;
766 framecnt_t cnt = size;
768 /* to fill the buffer without resetting the playback sample, we need to
769 do it one or two chunks (normally two).
771 |----------------------------------------------------------------------|
775 |<- second chunk->||<----------------- first chunk ------------------>|
779 framecnt_t to_read = size - overwrite_offset;
781 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, *chan, n, reversed)) {
782 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
783 _id, size, playback_sample) << endmsg;
791 if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer,
792 start, cnt, *chan, n, reversed)) {
793 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
794 _id, size, playback_sample) << endmsg;
803 _pending_overwrite = false;
804 delete [] gain_buffer;
805 delete [] mixdown_buffer;
810 AudioDiskstream::seek (framepos_t frame, bool complete_refill)
814 ChannelList::iterator chan;
815 boost::shared_ptr<ChannelList> c = channels.reader();
817 Glib::Mutex::Lock lm (state_lock);
819 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
820 (*chan)->playback_buf->reset ();
821 (*chan)->capture_buf->reset ();
824 /* can't rec-enable in destructive mode if transport is before start */
826 if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
827 disengage_record_enable ();
830 playback_sample = frame;
833 if (complete_refill) {
834 while ((ret = do_refill_with_alloc ()) > 0) ;
836 ret = do_refill_with_alloc ();
843 AudioDiskstream::can_internal_playback_seek (framecnt_t distance)
845 ChannelList::iterator chan;
846 boost::shared_ptr<ChannelList> c = channels.reader();
848 for (chan = c->begin(); chan != c->end(); ++chan) {
849 if ((*chan)->playback_buf->read_space() < (size_t) distance) {
857 AudioDiskstream::internal_playback_seek (framecnt_t distance)
859 ChannelList::iterator chan;
860 boost::shared_ptr<ChannelList> c = channels.reader();
862 for (chan = c->begin(); chan != c->end(); ++chan) {
863 (*chan)->playback_buf->increment_read_ptr (distance);
866 if (first_recordable_frame < max_framepos) {
867 first_recordable_frame += distance;
869 playback_sample += distance;
875 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer,
876 framepos_t& start, framecnt_t cnt,
877 ChannelInfo* /*channel_info*/, int channel, bool reversed)
879 framecnt_t this_read = 0;
881 framepos_t loop_end = 0;
882 framepos_t loop_start = 0;
883 framecnt_t offset = 0;
886 /* XXX we don't currently play loops in reverse. not sure why */
890 framecnt_t loop_length = 0;
892 /* Make the use of a Location atomic for this read operation.
894 Note: Locations don't get deleted, so all we care about
895 when I say "atomic" is that we are always pointing to
896 the same one and using a start/length values obtained
900 if ((loc = loop_location) != 0) {
901 loop_start = loc->start();
902 loop_end = loc->end();
903 loop_length = loop_end - loop_start;
906 /* if we are looping, ensure that the first frame we read is at the correct
907 position within the loop.
910 if (loc && start >= loop_end) {
911 //cerr << "start adjusted from " << start;
912 start = loop_start + ((start - loop_start) % loop_length);
913 //cerr << "to " << start << endl;
916 //cerr << "start is " << start << " loopstart: " << loop_start << " loopend: " << loop_end << endl;
925 /* take any loop into account. we can't read past the end of the loop. */
927 if (loc && (loop_end - start < cnt)) {
928 this_read = loop_end - start;
929 //cerr << "reloop true: thisread: " << this_read << " cnt: " << cnt << endl;
936 if (this_read == 0) {
940 this_read = min(cnt,this_read);
942 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
943 error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), _id, this_read,
948 _read_data_count = _playlist->read_data_count();
952 swap_by_ptr (buf, buf + this_read - 1);
956 /* if we read to the end of the loop, go back to the beginning */
973 AudioDiskstream::do_refill_with_alloc ()
975 Sample* mix_buf = new Sample[disk_io_chunk_frames];
976 float* gain_buf = new float[disk_io_chunk_frames];
978 int ret = _do_refill(mix_buf, gain_buf);
987 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer)
991 RingBufferNPT<Sample>::rw_vector vector;
992 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
993 framecnt_t total_space;
994 framecnt_t zero_fill;
996 ChannelList::iterator i;
997 boost::shared_ptr<ChannelList> c = channels.reader();
1004 assert(mixdown_buffer);
1005 assert(gain_buffer);
1012 c->front()->playback_buf->get_write_vector (&vector);
1014 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1018 /* if there are 2+ chunks of disk i/o possible for
1019 this track, let the caller know so that it can arrange
1020 for us to be called again, ASAP.
1023 if (total_space >= (_slaved?3:2) * disk_io_chunk_frames) {
1027 /* if we're running close to normal speed and there isn't enough
1028 space to do disk_io_chunk_frames of I/O, then don't bother.
1030 at higher speeds, just do it because the sync between butler
1031 and audio thread may not be good enough.
1034 if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1038 /* when slaved, don't try to get too close to the read pointer. this
1039 leaves space for the buffer reversal to have something useful to
1043 if (_slaved && total_space < (framecnt_t) (c->front()->playback_buf->bufsize() / 2)) {
1047 /* never do more than disk_io_chunk_frames worth of disk input per call (limit doesn't apply for memset) */
1049 total_space = min (disk_io_chunk_frames, total_space);
1053 if (file_frame == 0) {
1055 /* at start: nothing to do but fill with silence */
1057 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1059 ChannelInfo* chan (*i);
1060 chan->playback_buf->get_write_vector (&vector);
1061 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1062 if (vector.len[1]) {
1063 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1065 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1070 if (file_frame < total_space) {
1072 /* too close to the start: read what we can,
1073 and then zero fill the rest
1076 zero_fill = total_space - file_frame;
1077 total_space = file_frame;
1086 if (file_frame == max_framepos) {
1088 /* at end: nothing to do but fill with silence */
1090 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1092 ChannelInfo* chan (*i);
1093 chan->playback_buf->get_write_vector (&vector);
1094 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1095 if (vector.len[1]) {
1096 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1098 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1103 if (file_frame > max_framepos - total_space) {
1105 /* to close to the end: read what we can, and zero fill the rest */
1107 zero_fill = total_space - (max_framepos - file_frame);
1108 total_space = max_framepos - file_frame;
1115 framepos_t file_frame_tmp = 0;
1117 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1119 ChannelInfo* chan (*i);
1122 framecnt_t len1, len2;
1124 chan->playback_buf->get_write_vector (&vector);
1126 if ((framecnt_t) vector.len[0] > disk_io_chunk_frames) {
1128 /* we're not going to fill the first chunk, so certainly do not bother with the
1129 other part. it won't be connected with the part we do fill, as in:
1131 .... => writable space
1132 ++++ => readable space
1133 ^^^^ => 1 x disk_io_chunk_frames that would be filled
1135 |......|+++++++++++++|...............................|
1140 So, just pretend that the buf1 part isn't there.
1150 file_frame_tmp = file_frame;
1152 buf1 = vector.buf[0];
1153 len1 = vector.len[0];
1154 buf2 = vector.buf[1];
1155 len2 = vector.len[1];
1157 to_read = min (ts, len1);
1158 to_read = min (to_read, disk_io_chunk_frames);
1160 assert (to_read >= 0);
1164 if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1169 chan->playback_buf->increment_write_ptr (to_read);
1173 to_read = min (ts, len2);
1177 /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1178 so read some or all of vector.len[1] as well.
1181 if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1186 chan->playback_buf->increment_write_ptr (to_read);
1195 file_frame = file_frame_tmp;
1196 assert (file_frame >= 0);
1203 /** Flush pending data to disk.
1205 * Important note: this function will write *AT MOST* disk_io_chunk_frames
1206 * of data to disk. it will never write more than that. If it writes that
1207 * much and there is more than that waiting to be written, it will return 1,
1208 * otherwise 0 on success or -1 on failure.
1210 * If there is less than disk_io_chunk_frames to be written, no data will be
1211 * written at all unless @a force_flush is true.
1214 AudioDiskstream::do_flush (RunContext /*context*/, bool force_flush)
1218 RingBufferNPT<Sample>::rw_vector vector;
1219 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1222 _write_data_count = 0;
1224 transvec.buf[0] = 0;
1225 transvec.buf[1] = 0;
1229 boost::shared_ptr<ChannelList> c = channels.reader();
1230 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1232 (*chan)->capture_buf->get_read_vector (&vector);
1234 total = vector.len[0] + vector.len[1];
1236 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1240 /* if there are 2+ chunks of disk i/o possible for
1241 this track, let the caller know so that it can arrange
1242 for us to be called again, ASAP.
1244 if we are forcing a flush, then if there is* any* extra
1245 work, let the caller know.
1247 if we are no longer recording and there is any extra work,
1248 let the caller know too.
1251 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1255 to_write = min (disk_io_chunk_frames, (framecnt_t) vector.len[0]);
1257 // check the transition buffer when recording destructive
1258 // important that we get this after the capture buf
1260 if (destructive()) {
1261 (*chan)->capture_transition_buf->get_read_vector(&transvec);
1262 size_t transcount = transvec.len[0] + transvec.len[1];
1263 bool have_start = false;
1266 for (ti=0; ti < transcount; ++ti) {
1267 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1269 if (captrans.type == CaptureStart) {
1270 // by definition, the first data we got above represents the given capture pos
1272 (*chan)->write_source->mark_capture_start (captrans.capture_val);
1273 (*chan)->curr_capture_cnt = 0;
1277 else if (captrans.type == CaptureEnd) {
1279 // capture end, the capture_val represents total frames in capture
1281 if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1283 // shorten to make the write a perfect fit
1284 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
1286 if (nto_write < to_write) {
1287 ret = 1; // should we?
1289 to_write = nto_write;
1291 (*chan)->write_source->mark_capture_end ();
1293 // increment past this transition, but go no further
1298 // actually ends just beyond this chunk, so force more work
1306 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1310 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1311 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1315 (*chan)->capture_buf->increment_read_ptr (to_write);
1316 (*chan)->curr_capture_cnt += to_write;
1318 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1320 /* we wrote all of vector.len[0] but it wasn't an entire
1321 disk_io_chunk_frames of data, so arrange for some part
1322 of vector.len[1] to be flushed to disk as well.
1325 to_write = min ((framecnt_t)(disk_io_chunk_frames - to_write), (framecnt_t) vector.len[1]);
1327 if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1328 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1332 _write_data_count += (*chan)->write_source->write_data_count();
1334 (*chan)->capture_buf->increment_read_ptr (to_write);
1335 (*chan)->curr_capture_cnt += to_write;
1344 AudioDiskstream::transport_stopped_wallclock (struct tm& when, time_t twhen, bool abort_capture)
1346 uint32_t buffer_position;
1347 bool more_work = true;
1349 boost::shared_ptr<AudioRegion> region;
1350 framecnt_t total_capture;
1352 SourceList::iterator src;
1353 ChannelList::iterator chan;
1354 vector<CaptureInfo*>::iterator ci;
1355 boost::shared_ptr<ChannelList> c = channels.reader();
1357 bool mark_write_completed = false;
1359 finish_capture (true, c);
1361 /* butler is already stopped, but there may be work to do
1362 to flush remaining data to disk.
1365 while (more_work && !err) {
1366 switch (do_flush (TransportContext, true)) {
1373 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1378 /* XXX is there anything we can do if err != 0 ? */
1379 Glib::Mutex::Lock lm (capture_info_lock);
1381 if (capture_info.empty()) {
1385 if (abort_capture) {
1387 if (destructive()) {
1391 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1393 if ((*chan)->write_source) {
1395 (*chan)->write_source->mark_for_remove ();
1396 (*chan)->write_source->drop_references ();
1397 (*chan)->write_source.reset ();
1400 /* new source set up in "out" below */
1406 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1407 total_capture += (*ci)->frames;
1410 /* figure out the name for this take */
1412 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1414 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1418 s->update_header (capture_info.front()->start, when, twhen);
1419 s->set_captured_for (_name.val());
1420 s->mark_immutable ();
1422 if (Config->get_auto_analyse_audio()) {
1423 Analyser::queue_source_for_analysis (s, true);
1428 /* destructive tracks have a single, never changing region */
1430 if (destructive()) {
1432 /* send a signal that any UI can pick up to do the right thing. there is
1433 a small problem here in that a UI may need the peak data to be ready
1434 for the data that was recorded and this isn't interlocked with that
1435 process. this problem is deferred to the UI.
1438 _playlist->LayeringChanged(); // XXX this may not get the UI to do the right thing
1442 string whole_file_region_name;
1443 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1445 /* Register a new region with the Session that
1446 describes the entire source. Do this first
1447 so that any sub-regions will obviously be
1448 children of this one (later!)
1454 plist.add (Properties::start, c->front()->write_source->last_capture_start_frame());
1455 plist.add (Properties::length, total_capture);
1456 plist.add (Properties::name, whole_file_region_name);
1457 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1458 rx->set_automatic (true);
1459 rx->set_whole_file (true);
1461 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1462 region->special_set_position (capture_info.front()->start);
1466 catch (failed_constructor& err) {
1467 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1471 _last_capture_sources.insert (_last_capture_sources.end(), srcs.begin(), srcs.end());
1473 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1475 _playlist->clear_changes ();
1476 _playlist->freeze ();
1478 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1482 RegionFactory::region_name (region_name, whole_file_region_name, false);
1484 // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->frames << " add region " << region_name << endl;
1490 plist.add (Properties::start, buffer_position);
1491 plist.add (Properties::length, (*ci)->frames);
1492 plist.add (Properties::name, region_name);
1494 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1495 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1498 catch (failed_constructor& err) {
1499 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1500 continue; /* XXX is this OK? */
1503 i_am_the_modifier++;
1505 if (_playlist->explicit_relayering()) {
1506 /* We are in `explicit relayering' mode, so we must specify which layer this new region
1507 should end up on. Put it at the top.
1509 region->set_layer (_playlist->top_layer() + 1);
1510 region->set_pending_explicit_relayer (true);
1513 _playlist->add_region (region, (*ci)->start, 1, non_layered());
1514 i_am_the_modifier--;
1516 buffer_position += (*ci)->frames;
1520 _session.add_command (new StatefulDiffCommand (_playlist));
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 (framepos_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_framepos;
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;
1593 first_recordable_frame = max_framepos;
1594 last_recordable_frame = max_framepos;
1596 if (capture_captured == 0) {
1600 if (recordable() && destructive()) {
1601 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1603 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1604 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1606 if (transvec.len[0] > 0) {
1607 transvec.buf[0]->type = CaptureEnd;
1608 transvec.buf[0]->capture_val = capture_captured;
1609 (*chan)->capture_transition_buf->increment_write_ptr(1);
1613 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1619 CaptureInfo* ci = new CaptureInfo;
1621 ci->start = capture_start_frame;
1622 ci->frames = capture_captured;
1624 /* XXX theoretical race condition here. Need atomic exchange ?
1625 However, the circumstances when this is called right
1626 now (either on record-disable or transport_stopped)
1627 mean that no actual race exists. I think ...
1628 We now have a capture_info_lock, but it is only to be used
1629 to synchronize in the transport_stop and the capture info
1630 accessors, so that invalidation will not occur (both non-realtime).
1633 // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1635 capture_info.push_back (ci);
1636 capture_captured = 0;
1638 /* now we've finished a capture, reset first_recordable_frame for next time */
1639 first_recordable_frame = max_framepos;
1643 AudioDiskstream::set_record_enabled (bool yn)
1645 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0) {
1649 /* can't rec-enable in destructive mode if transport is before start */
1651 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1655 /* yes, i know that this not proof against race conditions, but its
1656 good enough. i think.
1659 if (record_enabled() != yn) {
1661 engage_record_enable ();
1663 disengage_record_enable ();
1669 AudioDiskstream::engage_record_enable ()
1671 bool rolling = _session.transport_speed() != 0.0f;
1672 boost::shared_ptr<ChannelList> c = channels.reader();
1674 g_atomic_int_set (&_record_enabled, 1);
1675 capturing_sources.clear ();
1677 if (Config->get_monitoring_model() == HardwareMonitoring) {
1679 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1680 if ((*chan)->source) {
1681 (*chan)->source->ensure_monitor_input (!(_session.config.get_auto_input() && rolling));
1683 capturing_sources.push_back ((*chan)->write_source);
1684 (*chan)->write_source->mark_streaming_write_started ();
1688 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1689 capturing_sources.push_back ((*chan)->write_source);
1690 (*chan)->write_source->mark_streaming_write_started ();
1694 RecordEnableChanged (); /* EMIT SIGNAL */
1698 AudioDiskstream::disengage_record_enable ()
1700 g_atomic_int_set (&_record_enabled, 0);
1701 boost::shared_ptr<ChannelList> c = channels.reader();
1702 if (Config->get_monitoring_model() == HardwareMonitoring) {
1703 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1704 if ((*chan)->source) {
1705 (*chan)->source->ensure_monitor_input (false);
1709 capturing_sources.clear ();
1710 RecordEnableChanged (); /* EMIT SIGNAL */
1714 AudioDiskstream::get_state ()
1716 XMLNode& node (Diskstream::get_state());
1718 LocaleGuard lg (X_("POSIX"));
1720 boost::shared_ptr<ChannelList> c = channels.reader();
1721 snprintf (buf, sizeof(buf), "%zd", c->size());
1722 node.add_property ("channels", buf);
1724 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1726 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1727 XMLNode* cs_grandchild;
1729 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1730 cs_grandchild = new XMLNode (X_("file"));
1731 cs_grandchild->add_property (X_("path"), (*i)->path());
1732 cs_child->add_child_nocopy (*cs_grandchild);
1735 /* store the location where capture will start */
1739 if (_session.config.get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1740 snprintf (buf, sizeof (buf), "%" PRId64, pi->start());
1742 snprintf (buf, sizeof (buf), "%" PRId64, _session.transport_frame());
1745 cs_child->add_property (X_("at"), buf);
1746 node.add_child_nocopy (*cs_child);
1753 AudioDiskstream::set_state (const XMLNode& node, int version)
1755 const XMLProperty* prop;
1756 XMLNodeList nlist = node.children();
1757 XMLNodeIterator niter;
1758 uint32_t nchans = 1;
1759 XMLNode* capture_pending_node = 0;
1760 LocaleGuard lg (X_("POSIX"));
1762 /* prevent write sources from being created */
1764 in_set_state = true;
1766 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1767 if ((*niter)->name() == IO::state_node_name) {
1768 deprecated_io_node = new XMLNode (**niter);
1771 if ((*niter)->name() == X_("CapturingSources")) {
1772 capture_pending_node = *niter;
1776 if (Diskstream::set_state (node, version)) {
1780 if ((prop = node.property ("channels")) != 0) {
1781 nchans = atoi (prop->value().c_str());
1784 // create necessary extra channels
1785 // we are always constructed with one and we always need one
1787 _n_channels.set(DataType::AUDIO, channels.reader()->size());
1789 if (nchans > _n_channels.n_audio()) {
1791 add_channel (nchans - _n_channels.n_audio());
1792 IO::PortCountChanged(_n_channels);
1794 } else if (nchans < _n_channels.n_audio()) {
1796 remove_channel (_n_channels.n_audio() - nchans);
1801 if (!destructive() && capture_pending_node) {
1802 /* destructive streams have one and only one source per channel,
1803 and so they never end up in pending capture in any useful
1806 use_pending_capture_data (*capture_pending_node);
1809 in_set_state = false;
1811 /* make sure this is clear before we do anything else */
1813 capturing_sources.clear ();
1815 /* write sources are handled when we handle the input set
1816 up of the IO that owns this DS (::non_realtime_input_change())
1823 AudioDiskstream::use_new_write_source (uint32_t n)
1825 boost::shared_ptr<ChannelList> c = channels.reader();
1827 if (!recordable()) {
1831 if (n >= c->size()) {
1832 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
1836 ChannelInfo* chan = (*c)[n];
1839 if ((chan->write_source = _session.create_audio_source_for_session (n_channels().n_audio(),
1840 name(), n, destructive())) == 0) {
1841 throw failed_constructor();
1845 catch (failed_constructor &err) {
1846 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
1847 chan->write_source.reset ();
1851 /* do not remove destructive files even if they are empty */
1853 chan->write_source->set_allow_remove_if_empty (!destructive());
1858 list<boost::shared_ptr<Source> >
1859 AudioDiskstream::steal_write_sources()
1861 /* not possible to steal audio write sources */
1862 list<boost::shared_ptr<Source> > ret;
1867 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool /*force*/)
1869 ChannelList::iterator chan;
1870 boost::shared_ptr<ChannelList> c = channels.reader();
1873 if (!_session.writable() || !recordable()) {
1877 capturing_sources.clear ();
1879 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1881 if (!destructive()) {
1883 if ((*chan)->write_source) {
1885 if (mark_write_complete) {
1886 (*chan)->write_source->mark_streaming_write_completed ();
1887 (*chan)->write_source->done_with_peakfile_writes ();
1890 if ((*chan)->write_source->removable()) {
1891 (*chan)->write_source->mark_for_remove ();
1892 (*chan)->write_source->drop_references ();
1895 (*chan)->write_source.reset ();
1898 use_new_write_source (n);
1900 if (record_enabled()) {
1901 capturing_sources.push_back ((*chan)->write_source);
1906 if ((*chan)->write_source == 0) {
1907 use_new_write_source (n);
1912 if (destructive() && !c->empty ()) {
1914 /* we now have all our write sources set up, so create the
1915 playlist's single region.
1918 if (_playlist->empty()) {
1919 setup_destructive_playlist ();
1925 AudioDiskstream::rename_write_sources ()
1927 ChannelList::iterator chan;
1928 boost::shared_ptr<ChannelList> c = channels.reader();
1931 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1932 if ((*chan)->write_source != 0) {
1933 (*chan)->write_source->set_source_name (_name.val(), destructive());
1934 /* XXX what to do if one of them fails ? */
1942 AudioDiskstream::set_block_size (pframes_t /*nframes*/)
1944 if (_session.get_block_size() > speed_buffer_size) {
1945 speed_buffer_size = _session.get_block_size();
1946 boost::shared_ptr<ChannelList> c = channels.reader();
1948 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1949 if ((*chan)->speed_buffer)
1950 delete [] (*chan)->speed_buffer;
1951 (*chan)->speed_buffer = new Sample[speed_buffer_size];
1954 allocate_temporary_buffers ();
1958 AudioDiskstream::allocate_temporary_buffers ()
1960 /* make sure the wrap buffer is at least large enough to deal
1961 with the speeds up to 1.2, to allow for micro-variation
1962 when slaving to MTC, Timecode etc.
1965 double const sp = max (fabsf (_actual_speed), 1.2f);
1966 framecnt_t required_wrap_size = (framecnt_t) floor (_session.get_block_size() * sp) + 1;
1968 if (required_wrap_size > wrap_buffer_size) {
1970 boost::shared_ptr<ChannelList> c = channels.reader();
1972 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1973 if ((*chan)->playback_wrap_buffer)
1974 delete [] (*chan)->playback_wrap_buffer;
1975 (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
1976 if ((*chan)->capture_wrap_buffer)
1977 delete [] (*chan)->capture_wrap_buffer;
1978 (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
1981 wrap_buffer_size = required_wrap_size;
1986 AudioDiskstream::monitor_input (bool yn)
1988 boost::shared_ptr<ChannelList> c = channels.reader();
1990 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1992 if ((*chan)->source) {
1993 (*chan)->source->ensure_monitor_input (yn);
1999 AudioDiskstream::set_align_style_from_io ()
2001 bool have_physical = false;
2003 if (_alignment_choice != Automatic) {
2011 get_input_sources ();
2013 boost::shared_ptr<ChannelList> c = channels.reader();
2015 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2016 if ((*chan)->source && (*chan)->source->flags() & JackPortIsPhysical) {
2017 have_physical = true;
2022 if (have_physical) {
2023 set_align_style (ExistingMaterial);
2025 set_align_style (CaptureTime);
2030 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2032 while (how_many--) {
2033 c->push_back (new ChannelInfo(_session.butler()->audio_diskstream_playback_buffer_size(),
2034 _session.butler()->audio_diskstream_capture_buffer_size(),
2035 speed_buffer_size, wrap_buffer_size));
2036 interpolation.add_channel_to (_session.butler()->audio_diskstream_playback_buffer_size(), speed_buffer_size);
2039 _n_channels.set(DataType::AUDIO, c->size());
2045 AudioDiskstream::add_channel (uint32_t how_many)
2047 RCUWriter<ChannelList> writer (channels);
2048 boost::shared_ptr<ChannelList> c = writer.get_copy();
2050 return add_channel_to (c, how_many);
2054 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2056 while (how_many-- && !c->empty()) {
2059 interpolation.remove_channel_from ();
2062 _n_channels.set(DataType::AUDIO, c->size());
2068 AudioDiskstream::remove_channel (uint32_t how_many)
2070 RCUWriter<ChannelList> writer (channels);
2071 boost::shared_ptr<ChannelList> c = writer.get_copy();
2073 return remove_channel_from (c, how_many);
2077 AudioDiskstream::playback_buffer_load () const
2079 boost::shared_ptr<ChannelList> c = channels.reader();
2085 return (float) ((double) c->front()->playback_buf->read_space()/
2086 (double) c->front()->playback_buf->bufsize());
2090 AudioDiskstream::capture_buffer_load () const
2092 boost::shared_ptr<ChannelList> c = channels.reader();
2098 return (float) ((double) c->front()->capture_buf->write_space()/
2099 (double) c->front()->capture_buf->bufsize());
2103 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2105 const XMLProperty* prop;
2106 XMLNodeList nlist = node.children();
2107 XMLNodeIterator niter;
2108 boost::shared_ptr<AudioFileSource> fs;
2109 boost::shared_ptr<AudioFileSource> first_fs;
2110 SourceList pending_sources;
2111 framepos_t position;
2113 if ((prop = node.property (X_("at"))) == 0) {
2117 if (sscanf (prop->value().c_str(), "%" PRIu64, &position) != 1) {
2121 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2122 if ((*niter)->name() == X_("file")) {
2124 if ((prop = (*niter)->property (X_("path"))) == 0) {
2128 // This protects sessions from errant CapturingSources in stored sessions
2130 if (stat (prop->value().c_str(), &sbuf)) {
2135 fs = boost::dynamic_pointer_cast<AudioFileSource> (
2136 SourceFactory::createWritable (DataType::AUDIO, _session,
2137 prop->value(), string(), false, _session.frame_rate()));
2140 catch (failed_constructor& err) {
2141 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2142 _name, prop->value())
2147 pending_sources.push_back (fs);
2149 if (first_fs == 0) {
2153 fs->set_captured_for (_name.val());
2157 if (pending_sources.size() == 0) {
2158 /* nothing can be done */
2162 if (pending_sources.size() != _n_channels.n_audio()) {
2163 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2168 boost::shared_ptr<AudioRegion> region;
2174 plist.add (Properties::start, 0);
2175 plist.add (Properties::length, first_fs->length (first_fs->timeline_position()));
2176 plist.add (Properties::name, region_name_from_path (first_fs->name(), true));
2178 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, plist));
2180 region->set_automatic (true);
2181 region->set_whole_file (true);
2182 region->special_set_position (0);
2185 catch (failed_constructor& err) {
2186 error << string_compose (
2187 _("%1: cannot create whole-file region from pending capture sources"),
2193 _playlist->add_region (region, position);
2199 AudioDiskstream::set_non_layered (bool yn)
2201 if (yn != non_layered()) {
2204 _flags = Flag (_flags | NonLayered);
2206 _flags = Flag (_flags & ~NonLayered);
2214 AudioDiskstream::set_destructive (bool yn)
2216 if (yn != destructive()) {
2219 bool bounce_ignored;
2220 /* requestor should already have checked this and
2221 bounced if necessary and desired
2223 if (!can_become_destructive (bounce_ignored)) {
2226 _flags = Flag (_flags | Destructive);
2227 use_destructive_playlist ();
2229 _flags = Flag (_flags & ~Destructive);
2230 reset_write_sources (true, true);
2238 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2241 requires_bounce = false;
2245 /* is there only one region ? */
2247 if (_playlist->n_regions() != 1) {
2248 requires_bounce = true;
2252 boost::shared_ptr<Region> first = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
2254 requires_bounce = false;
2258 /* do the source(s) for the region cover the session start position ? */
2260 if (first->position() != _session.current_start_frame()) {
2261 if (first->start() > _session.current_start_frame()) {
2262 requires_bounce = true;
2267 /* is the source used by only 1 playlist ? */
2269 boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2273 if (_session.playlists->source_use_count (afirst->source()) > 1) {
2274 requires_bounce = true;
2278 requires_bounce = false;
2283 AudioDiskstream::adjust_playback_buffering ()
2285 boost::shared_ptr<ChannelList> c = channels.reader();
2287 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2288 (*chan)->resize_playback (_session.butler()->audio_diskstream_playback_buffer_size());
2293 AudioDiskstream::adjust_capture_buffering ()
2295 boost::shared_ptr<ChannelList> c = channels.reader();
2297 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2298 (*chan)->resize_capture (_session.butler()->audio_diskstream_capture_buffer_size());
2302 AudioDiskstream::ChannelInfo::ChannelInfo (framecnt_t playback_bufsize, framecnt_t capture_bufsize, framecnt_t speed_size, framecnt_t wrap_size)
2306 current_capture_buffer = 0;
2307 current_playback_buffer = 0;
2308 curr_capture_cnt = 0;
2310 speed_buffer = new Sample[speed_size];
2311 playback_wrap_buffer = new Sample[wrap_size];
2312 capture_wrap_buffer = new Sample[wrap_size];
2314 playback_buf = new RingBufferNPT<Sample> (playback_bufsize);
2315 capture_buf = new RingBufferNPT<Sample> (capture_bufsize);
2316 capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2318 /* touch the ringbuffer buffers, which will cause
2319 them to be mapped into locked physical RAM if
2320 we're running with mlockall(). this doesn't do
2324 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2325 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2326 memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2330 AudioDiskstream::ChannelInfo::resize_playback (framecnt_t playback_bufsize)
2332 delete playback_buf;
2333 playback_buf = new RingBufferNPT<Sample> (playback_bufsize);
2334 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2338 AudioDiskstream::ChannelInfo::resize_capture (framecnt_t capture_bufsize)
2342 capture_buf = new RingBufferNPT<Sample> (capture_bufsize);
2343 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2346 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2348 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;