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 , deprecated_io_node(NULL)
78 , channels (new ChannelList)
80 /* prevent any write sources from being created */
87 AudioDiskstream::AudioDiskstream (Session& sess, const XMLNode& node)
88 : Diskstream(sess, node)
89 , deprecated_io_node(NULL)
90 , channels (new ChannelList)
95 if (set_state (node, Stateful::loading_state_version)) {
97 throw failed_constructor();
100 in_set_state = false;
103 use_destructive_playlist ();
108 AudioDiskstream::init ()
110 /* there are no channels at this point, so these
111 two calls just get speed_buffer_size and wrap_buffer
112 size setup without duplicating their code.
115 set_block_size (_session.get_block_size());
116 allocate_temporary_buffers ();
119 assert(_n_channels == ChanCount(DataType::AUDIO, 1));
122 AudioDiskstream::~AudioDiskstream ()
124 DEBUG_TRACE (DEBUG::Destruction, string_compose ("Audio Diskstream %1 destructor\n", _name));
127 RCUWriter<ChannelList> writer (channels);
128 boost::shared_ptr<ChannelList> c = writer.get_copy();
130 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
139 delete deprecated_io_node;
143 AudioDiskstream::allocate_working_buffers()
145 assert(disk_io_frames() > 0);
147 _working_buffers_size = disk_io_frames();
148 _mixdown_buffer = new Sample[_working_buffers_size];
149 _gain_buffer = new gain_t[_working_buffers_size];
153 AudioDiskstream::free_working_buffers()
155 delete [] _mixdown_buffer;
156 delete [] _gain_buffer;
157 _working_buffers_size = 0;
163 AudioDiskstream::non_realtime_input_change ()
166 Glib::Mutex::Lock lm (state_lock);
168 if (input_change_pending.type == IOChange::NoChange) {
173 RCUWriter<ChannelList> writer (channels);
174 boost::shared_ptr<ChannelList> c = writer.get_copy();
176 _n_channels.set(DataType::AUDIO, c->size());
178 if (_io->n_ports().n_audio() > _n_channels.n_audio()) {
179 add_channel_to (c, _io->n_ports().n_audio() - _n_channels.n_audio());
180 } else if (_io->n_ports().n_audio() < _n_channels.n_audio()) {
181 remove_channel_from (c, _n_channels.n_audio() - _io->n_ports().n_audio());
185 get_input_sources ();
186 set_capture_offset ();
188 if (first_input_change) {
189 set_align_style (_persistent_alignment_style);
190 first_input_change = false;
192 set_align_style_from_io ();
195 input_change_pending = IOChange::NoChange;
197 /* implicit unlock */
200 /* reset capture files */
202 reset_write_sources (false);
204 /* now refill channel buffers */
206 if (speed() != 1.0f || speed() != -1.0f) {
207 seek ((framepos_t) (_session.transport_frame() * (double) speed()));
209 seek (_session.transport_frame());
214 AudioDiskstream::non_realtime_locate (framepos_t location)
216 /* now refill channel buffers */
218 if (speed() != 1.0f || speed() != -1.0f) {
219 seek ((framepos_t) (location * (double) speed()));
226 AudioDiskstream::get_input_sources ()
228 boost::shared_ptr<ChannelList> c = channels.reader();
231 ChannelList::iterator chan;
232 uint32_t ni = _io->n_ports().n_audio();
233 vector<string> connections;
235 for (n = 0, chan = c->begin(); chan != c->end() && n < ni; ++chan, ++n) {
237 connections.clear ();
239 if (_io->nth (n)->get_connections (connections) == 0) {
241 if ((*chan)->source) {
242 // _source->disable_metering ();
248 (*chan)->source = dynamic_cast<AudioPort*>(_session.engine().get_port_by_name (connections[0]) );
254 AudioDiskstream::find_and_use_playlist (const string& name)
256 boost::shared_ptr<AudioPlaylist> playlist;
258 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (_session.playlists->by_name (name))) == 0) {
259 playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, name));
263 error << string_compose(_("AudioDiskstream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
267 return use_playlist (playlist);
271 AudioDiskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
273 assert(boost::dynamic_pointer_cast<AudioPlaylist>(playlist));
275 Diskstream::use_playlist(playlist);
281 AudioDiskstream::use_new_playlist ()
284 boost::shared_ptr<AudioPlaylist> playlist;
286 if (!in_set_state && destructive()) {
291 newname = Playlist::bump_name (_playlist->name(), _session);
293 newname = Playlist::bump_name (_name, _session);
296 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, newname, hidden()))) != 0) {
298 playlist->set_orig_diskstream_id (id());
299 return use_playlist (playlist);
307 AudioDiskstream::use_copy_playlist ()
309 assert(audio_playlist());
315 if (_playlist == 0) {
316 error << string_compose(_("AudioDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
321 boost::shared_ptr<AudioPlaylist> playlist;
323 newname = Playlist::bump_name (_playlist->name(), _session);
325 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist>(PlaylistFactory::create (audio_playlist(), newname))) != 0) {
326 playlist->set_orig_diskstream_id (id());
327 return use_playlist (playlist);
334 AudioDiskstream::setup_destructive_playlist ()
337 boost::shared_ptr<ChannelList> c = channels.reader();
339 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
340 srcs.push_back ((*chan)->write_source);
343 /* a single full-sized region */
345 assert (!srcs.empty ());
348 plist.add (Properties::name, _name.val());
349 plist.add (Properties::start, 0);
350 plist.add (Properties::length, max_framepos - (max_framepos - srcs.front()->natural_position()));
352 boost::shared_ptr<Region> region (RegionFactory::create (srcs, plist));
353 _playlist->add_region (region, srcs.front()->natural_position());
357 AudioDiskstream::use_destructive_playlist ()
359 /* this is called from the XML-based constructor or ::set_destructive. when called,
360 we already have a playlist and a region, but we need to
361 set up our sources for write. we use the sources associated
362 with the (presumed single, full-extent) region.
365 boost::shared_ptr<Region> rp = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
368 reset_write_sources (false, true);
372 boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
375 throw failed_constructor();
378 /* be sure to stretch the region out to the maximum length */
380 region->set_length (max_framepos - region->position(), this);
383 ChannelList::iterator chan;
384 boost::shared_ptr<ChannelList> c = channels.reader();
386 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
387 (*chan)->write_source = boost::dynamic_pointer_cast<AudioFileSource>(region->source (n));
388 assert((*chan)->write_source);
389 (*chan)->write_source->set_allow_remove_if_empty (false);
391 /* this might be false if we switched modes, so force it */
393 (*chan)->write_source->set_destructive (true);
396 /* the source list will never be reset for a destructive track */
400 AudioDiskstream::prepare_record_status(framepos_t capture_start_frame)
402 if (recordable() && destructive()) {
403 boost::shared_ptr<ChannelList> c = channels.reader();
404 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
406 RingBufferNPT<CaptureTransition>::rw_vector transvec;
407 (*chan)->capture_transition_buf->get_write_vector(&transvec);
409 if (transvec.len[0] > 0) {
410 transvec.buf[0]->type = CaptureStart;
411 transvec.buf[0]->capture_val = capture_start_frame;
412 (*chan)->capture_transition_buf->increment_write_ptr(1);
416 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
424 AudioDiskstream::process (framepos_t transport_frame, nframes_t nframes, bool can_record, bool rec_monitors_input, bool& need_butler)
427 boost::shared_ptr<ChannelList> c = channels.reader();
428 ChannelList::iterator chan;
430 nframes_t rec_offset = 0;
431 nframes_t rec_nframes = 0;
432 bool collect_playback = false;
434 playback_distance = 0;
436 if (!_io || !_io->active()) {
440 check_record_status (transport_frame, can_record);
446 Glib::Mutex::Lock sm (state_lock, Glib::TRY_LOCK);
452 adjust_capture_position = 0;
454 for (chan = c->begin(); chan != c->end(); ++chan) {
455 (*chan)->current_capture_buffer = 0;
456 (*chan)->current_playback_buffer = 0;
459 /* two conditions to test for here:
461 A: this track is rec-enabled, and the session has confirmed that we can record
462 B: this track is rec-enabled, has been recording, and we are set up for auto-punch-in
464 The second test is necessary to capture the extra material that arrives AFTER the transport
465 frame has left the punch range (which will cause the "can_record" argument to be false).
469 // Safeguard against situations where process() goes haywire when autopunching
470 // and last_recordable_frame < first_recordable_frame
472 if (last_recordable_frame < first_recordable_frame) {
473 last_recordable_frame = max_framepos;
476 OverlapType ot = coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
478 calculate_record_range (ot, transport_frame, nframes, rec_nframes, rec_offset);
480 if (rec_nframes && !was_recording) {
481 capture_captured = 0;
482 was_recording = true;
485 if (can_record && !_last_capture_sources.empty()) {
486 _last_capture_sources.clear ();
491 uint32_t limit = _io->n_ports ().n_audio();
493 /* one or more ports could already have been removed from _io, but our
494 channel setup hasn't yet been updated. prevent us from trying to
495 use channels that correspond to missing ports. note that the
496 process callback (from which this is called) is always atomic
497 with respect to port removal/addition.
500 for (n = 0, chan = c->begin(); chan != c->end() && n < limit; ++chan, ++n) {
502 ChannelInfo* chaninfo (*chan);
504 chaninfo->capture_buf->get_write_vector (&chaninfo->capture_vector);
506 if (rec_nframes <= chaninfo->capture_vector.len[0]) {
508 chaninfo->current_capture_buffer = chaninfo->capture_vector.buf[0];
510 /* note: grab the entire port buffer, but only copy what we were supposed to
511 for recording, and use rec_offset
514 AudioPort* const ap = _io->audio (n);
516 assert(rec_nframes <= ap->get_audio_buffer(nframes).capacity());
517 memcpy (chaninfo->current_capture_buffer, ap->get_audio_buffer (nframes).data(rec_offset), sizeof (Sample) * rec_nframes);
522 nframes_t total = chaninfo->capture_vector.len[0] + chaninfo->capture_vector.len[1];
524 if (rec_nframes > total) {
529 AudioPort* const ap = _io->audio (n);
532 Sample* buf = ap->get_audio_buffer(nframes).data();
533 nframes_t first = chaninfo->capture_vector.len[0];
535 memcpy (chaninfo->capture_wrap_buffer, buf, sizeof (Sample) * first);
536 memcpy (chaninfo->capture_vector.buf[0], buf, sizeof (Sample) * first);
537 memcpy (chaninfo->capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
538 memcpy (chaninfo->capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
540 chaninfo->current_capture_buffer = chaninfo->capture_wrap_buffer;
547 finish_capture (rec_monitors_input, c);
554 /* data will be written to disk */
556 if (rec_nframes == nframes && rec_offset == 0) {
558 for (chan = c->begin(); chan != c->end(); ++chan) {
559 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
562 playback_distance = nframes;
567 /* we can't use the capture buffer as the playback buffer, because
568 we recorded only a part of the current process' cycle data
572 collect_playback = true;
575 adjust_capture_position = rec_nframes;
577 } else if (can_record && record_enabled()) {
579 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
581 for (chan = c->begin(); chan != c->end(); ++chan) {
582 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
585 playback_distance = nframes;
589 collect_playback = true;
592 if (collect_playback) {
594 /* we're doing playback */
596 nframes_t necessary_samples;
598 /* no varispeed playback if we're recording, because the output .... TBD */
600 if (rec_nframes == 0 && _actual_speed != 1.0f) {
601 necessary_samples = (nframes_t) floor ((nframes * fabs (_actual_speed))) + 1;
603 necessary_samples = nframes;
606 for (chan = c->begin(); chan != c->end(); ++chan) {
607 (*chan)->playback_buf->get_read_vector (&(*chan)->playback_vector);
612 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
614 ChannelInfo* chaninfo (*chan);
616 if (necessary_samples <= chaninfo->playback_vector.len[0]) {
618 chaninfo->current_playback_buffer = chaninfo->playback_vector.buf[0];
621 nframes_t total = chaninfo->playback_vector.len[0] + chaninfo->playback_vector.len[1];
623 if (necessary_samples > total) {
624 cerr << _name << " Need " << necessary_samples << " total = " << total << endl;
625 cerr << "underrun for " << _name << endl;
631 memcpy ((char *) chaninfo->playback_wrap_buffer,
632 chaninfo->playback_vector.buf[0],
633 chaninfo->playback_vector.len[0] * sizeof (Sample));
634 memcpy (chaninfo->playback_wrap_buffer + chaninfo->playback_vector.len[0],
635 chaninfo->playback_vector.buf[1],
636 (necessary_samples - chaninfo->playback_vector.len[0])
639 chaninfo->current_playback_buffer = chaninfo->playback_wrap_buffer;
644 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
645 process_varispeed_playback(nframes, c);
647 playback_distance = nframes;
650 _speed = _target_speed;
656 if (commit (nframes)) {
665 AudioDiskstream::process_varispeed_playback(nframes_t nframes, boost::shared_ptr<ChannelList> c)
667 ChannelList::iterator chan;
669 interpolation.set_speed (_target_speed);
672 for (chan = c->begin(); chan != c->end(); ++chan, ++channel) {
673 ChannelInfo* chaninfo (*chan);
675 playback_distance = interpolation.interpolate (
676 channel, nframes, chaninfo->current_playback_buffer, chaninfo->speed_buffer);
678 chaninfo->current_playback_buffer = chaninfo->speed_buffer;
683 AudioDiskstream::commit (nframes_t /* nframes */)
685 bool need_butler = false;
687 if (!_io || !_io->active()) {
691 if (_actual_speed < 0.0) {
692 playback_sample -= playback_distance;
694 playback_sample += playback_distance;
697 boost::shared_ptr<ChannelList> c = channels.reader();
698 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
700 (*chan)->playback_buf->increment_read_ptr (playback_distance);
702 if (adjust_capture_position) {
703 (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
707 if (adjust_capture_position != 0) {
708 capture_captured += adjust_capture_position;
709 adjust_capture_position = 0;
713 if (_io && _io->active()) {
714 need_butler = c->front()->playback_buf->write_space() >= c->front()->playback_buf->bufsize() / 2;
719 if (_io && _io->active()) {
720 need_butler = c->front()->playback_buf->write_space() >= disk_io_chunk_frames
721 || c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
723 need_butler = c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
731 AudioDiskstream::set_pending_overwrite (bool yn)
733 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
735 _pending_overwrite = yn;
737 overwrite_frame = playback_sample;
738 overwrite_offset = channels.reader()->front()->playback_buf->get_read_ptr();
742 AudioDiskstream::overwrite_existing_buffers ()
744 boost::shared_ptr<ChannelList> c = channels.reader();
745 Sample* mixdown_buffer;
748 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
750 overwrite_queued = false;
752 /* assume all are the same size */
753 nframes_t size = c->front()->playback_buf->bufsize();
755 mixdown_buffer = new Sample[size];
756 gain_buffer = new float[size];
758 /* reduce size so that we can fill the buffer correctly. */
764 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
766 start = overwrite_frame;
767 nframes_t cnt = size;
769 /* to fill the buffer without resetting the playback sample, we need to
770 do it one or two chunks (normally two).
772 |----------------------------------------------------------------------|
776 |<- second chunk->||<----------------- first chunk ------------------>|
780 nframes_t to_read = size - overwrite_offset;
782 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, *chan, n, reversed)) {
783 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
784 _id, size, playback_sample) << endmsg;
792 if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer,
793 start, cnt, *chan, n, reversed)) {
794 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
795 _id, size, playback_sample) << endmsg;
804 _pending_overwrite = false;
805 delete [] gain_buffer;
806 delete [] mixdown_buffer;
811 AudioDiskstream::seek (framepos_t frame, bool complete_refill)
815 ChannelList::iterator chan;
816 boost::shared_ptr<ChannelList> c = channels.reader();
818 Glib::Mutex::Lock lm (state_lock);
820 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
821 (*chan)->playback_buf->reset ();
822 (*chan)->capture_buf->reset ();
825 /* can't rec-enable in destructive mode if transport is before start */
827 if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
828 disengage_record_enable ();
831 playback_sample = frame;
834 if (complete_refill) {
835 while ((ret = do_refill_with_alloc ()) > 0) ;
837 ret = do_refill_with_alloc ();
844 AudioDiskstream::can_internal_playback_seek (framecnt_t distance)
846 ChannelList::iterator chan;
847 boost::shared_ptr<ChannelList> c = channels.reader();
849 for (chan = c->begin(); chan != c->end(); ++chan) {
850 if ((*chan)->playback_buf->read_space() < (size_t) distance) {
858 AudioDiskstream::internal_playback_seek (framecnt_t distance)
860 ChannelList::iterator chan;
861 boost::shared_ptr<ChannelList> c = channels.reader();
863 for (chan = c->begin(); chan != c->end(); ++chan) {
864 (*chan)->playback_buf->increment_read_ptr (distance);
867 if (first_recordable_frame < max_framepos) {
868 first_recordable_frame += distance;
870 playback_sample += distance;
876 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer,
877 framepos_t& start, nframes_t cnt,
878 ChannelInfo* /*channel_info*/, int channel, bool reversed)
880 nframes_t this_read = 0;
882 framepos_t loop_end = 0;
883 framepos_t loop_start = 0;
884 nframes_t offset = 0;
887 /* XXX we don't currently play loops in reverse. not sure why */
891 framecnt_t loop_length = 0;
893 /* Make the use of a Location atomic for this read operation.
895 Note: Locations don't get deleted, so all we care about
896 when I say "atomic" is that we are always pointing to
897 the same one and using a start/length values obtained
901 if ((loc = loop_location) != 0) {
902 loop_start = loc->start();
903 loop_end = loc->end();
904 loop_length = loop_end - loop_start;
907 /* if we are looping, ensure that the first frame we read is at the correct
908 position within the loop.
911 if (loc && start >= loop_end) {
912 //cerr << "start adjusted from " << start;
913 start = loop_start + ((start - loop_start) % loop_length);
914 //cerr << "to " << start << endl;
917 //cerr << "start is " << start << " loopstart: " << loop_start << " loopend: " << loop_end << endl;
926 /* take any loop into account. we can't read past the end of the loop. */
928 if (loc && (loop_end - start < cnt)) {
929 this_read = loop_end - start;
930 //cerr << "reloop true: thisread: " << this_read << " cnt: " << cnt << endl;
937 if (this_read == 0) {
941 this_read = min(cnt,this_read);
943 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
944 error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), _id, this_read,
949 _read_data_count = _playlist->read_data_count();
953 swap_by_ptr (buf, buf + this_read - 1);
957 /* if we read to the end of the loop, go back to the beginning */
974 AudioDiskstream::do_refill_with_alloc ()
976 Sample* mix_buf = new Sample[disk_io_chunk_frames];
977 float* gain_buf = new float[disk_io_chunk_frames];
979 int ret = _do_refill(mix_buf, gain_buf);
988 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer)
992 RingBufferNPT<Sample>::rw_vector vector;
993 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
994 nframes_t total_space;
997 ChannelList::iterator i;
998 boost::shared_ptr<ChannelList> c = channels.reader();
1005 assert(mixdown_buffer);
1006 assert(gain_buffer);
1013 c->front()->playback_buf->get_write_vector (&vector);
1015 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1019 /* if there are 2+ chunks of disk i/o possible for
1020 this track, let the caller know so that it can arrange
1021 for us to be called again, ASAP.
1024 if (total_space >= (_slaved?3:2) * disk_io_chunk_frames) {
1028 /* if we're running close to normal speed and there isn't enough
1029 space to do disk_io_chunk_frames of I/O, then don't bother.
1031 at higher speeds, just do it because the sync between butler
1032 and audio thread may not be good enough.
1035 if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1039 /* when slaved, don't try to get too close to the read pointer. this
1040 leaves space for the buffer reversal to have something useful to
1044 if (_slaved && total_space < (c->front()->playback_buf->bufsize() / 2)) {
1048 /* never do more than disk_io_chunk_frames worth of disk input per call (limit doesn't apply for memset) */
1050 total_space = min (disk_io_chunk_frames, total_space);
1054 if (file_frame == 0) {
1056 /* at start: nothing to do but fill with silence */
1058 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1060 ChannelInfo* chan (*i);
1061 chan->playback_buf->get_write_vector (&vector);
1062 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1063 if (vector.len[1]) {
1064 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1066 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1071 if (file_frame < total_space) {
1073 /* too close to the start: read what we can,
1074 and then zero fill the rest
1077 zero_fill = total_space - file_frame;
1078 total_space = file_frame;
1088 if (file_frame == max_framepos) {
1090 /* at end: nothing to do but fill with silence */
1092 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1094 ChannelInfo* chan (*i);
1095 chan->playback_buf->get_write_vector (&vector);
1096 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1097 if (vector.len[1]) {
1098 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1100 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1105 if (file_frame > max_framepos - total_space) {
1107 /* to close to the end: read what we can, and zero fill the rest */
1109 zero_fill = total_space - (max_framepos - file_frame);
1110 total_space = max_framepos - file_frame;
1117 framepos_t file_frame_tmp = 0;
1119 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1121 ChannelInfo* chan (*i);
1124 nframes_t len1, len2;
1126 chan->playback_buf->get_write_vector (&vector);
1128 if (vector.len[0] > disk_io_chunk_frames) {
1130 /* we're not going to fill the first chunk, so certainly do not bother with the
1131 other part. it won't be connected with the part we do fill, as in:
1133 .... => writable space
1134 ++++ => readable space
1135 ^^^^ => 1 x disk_io_chunk_frames that would be filled
1137 |......|+++++++++++++|...............................|
1142 So, just pretend that the buf1 part isn't there.
1152 file_frame_tmp = file_frame;
1154 buf1 = vector.buf[0];
1155 len1 = vector.len[0];
1156 buf2 = vector.buf[1];
1157 len2 = vector.len[1];
1159 to_read = min (ts, len1);
1160 to_read = min (to_read, disk_io_chunk_frames);
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;
1202 /** Flush pending data to disk.
1204 * Important note: this function will write *AT MOST* disk_io_chunk_frames
1205 * of data to disk. it will never write more than that. If it writes that
1206 * much and there is more than that waiting to be written, it will return 1,
1207 * otherwise 0 on success or -1 on failure.
1209 * If there is less than disk_io_chunk_frames to be written, no data will be
1210 * written at all unless @a force_flush is true.
1213 AudioDiskstream::do_flush (RunContext /*context*/, bool force_flush)
1217 RingBufferNPT<Sample>::rw_vector vector;
1218 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1221 _write_data_count = 0;
1223 transvec.buf[0] = 0;
1224 transvec.buf[1] = 0;
1228 boost::shared_ptr<ChannelList> c = channels.reader();
1229 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1231 (*chan)->capture_buf->get_read_vector (&vector);
1233 total = vector.len[0] + vector.len[1];
1235 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1239 /* if there are 2+ chunks of disk i/o possible for
1240 this track, let the caller know so that it can arrange
1241 for us to be called again, ASAP.
1243 if we are forcing a flush, then if there is* any* extra
1244 work, let the caller know.
1246 if we are no longer recording and there is any extra work,
1247 let the caller know too.
1250 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1254 to_write = min (disk_io_chunk_frames, (nframes_t) vector.len[0]);
1256 // check the transition buffer when recording destructive
1257 // important that we get this after the capture buf
1259 if (destructive()) {
1260 (*chan)->capture_transition_buf->get_read_vector(&transvec);
1261 size_t transcount = transvec.len[0] + transvec.len[1];
1262 bool have_start = false;
1265 for (ti=0; ti < transcount; ++ti) {
1266 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1268 if (captrans.type == CaptureStart) {
1269 // by definition, the first data we got above represents the given capture pos
1271 (*chan)->write_source->mark_capture_start (captrans.capture_val);
1272 (*chan)->curr_capture_cnt = 0;
1276 else if (captrans.type == CaptureEnd) {
1278 // capture end, the capture_val represents total frames in capture
1280 if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1282 // shorten to make the write a perfect fit
1283 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
1285 if (nto_write < to_write) {
1286 ret = 1; // should we?
1288 to_write = nto_write;
1290 (*chan)->write_source->mark_capture_end ();
1292 // increment past this transition, but go no further
1297 // actually ends just beyond this chunk, so force more work
1305 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1309 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1310 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1314 (*chan)->capture_buf->increment_read_ptr (to_write);
1315 (*chan)->curr_capture_cnt += to_write;
1317 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1319 /* we wrote all of vector.len[0] but it wasn't an entire
1320 disk_io_chunk_frames of data, so arrange for some part
1321 of vector.len[1] to be flushed to disk as well.
1324 to_write = min ((nframes_t)(disk_io_chunk_frames - to_write), (nframes_t) vector.len[1]);
1326 if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1327 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1331 _write_data_count += (*chan)->write_source->write_data_count();
1333 (*chan)->capture_buf->increment_read_ptr (to_write);
1334 (*chan)->curr_capture_cnt += to_write;
1343 AudioDiskstream::transport_stopped_wallclock (struct tm& when, time_t twhen, bool abort_capture)
1345 uint32_t buffer_position;
1346 bool more_work = true;
1348 boost::shared_ptr<AudioRegion> region;
1349 nframes_t total_capture;
1351 SourceList::iterator src;
1352 ChannelList::iterator chan;
1353 vector<CaptureInfo*>::iterator ci;
1354 boost::shared_ptr<ChannelList> c = channels.reader();
1356 bool mark_write_completed = false;
1358 finish_capture (true, c);
1360 /* butler is already stopped, but there may be work to do
1361 to flush remaining data to disk.
1364 while (more_work && !err) {
1365 switch (do_flush (TransportContext, true)) {
1372 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1377 /* XXX is there anything we can do if err != 0 ? */
1378 Glib::Mutex::Lock lm (capture_info_lock);
1380 if (capture_info.empty()) {
1384 if (abort_capture) {
1386 if (destructive()) {
1390 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1392 if ((*chan)->write_source) {
1394 (*chan)->write_source->mark_for_remove ();
1395 (*chan)->write_source->drop_references ();
1396 _session.remove_source ((*chan)->write_source);
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 if (s->unstubify ()) {
1419 error << string_compose (_("Could not move capture file from %1"), s->path()) << endmsg;
1421 s->update_header (capture_info.front()->start, when, twhen);
1422 s->set_captured_for (_name.val());
1423 s->mark_immutable ();
1425 if (Config->get_auto_analyse_audio()) {
1426 Analyser::queue_source_for_analysis (s, true);
1431 /* destructive tracks have a single, never changing region */
1433 if (destructive()) {
1435 /* send a signal that any UI can pick up to do the right thing. there is
1436 a small problem here in that a UI may need the peak data to be ready
1437 for the data that was recorded and this isn't interlocked with that
1438 process. this problem is deferred to the UI.
1441 _playlist->LayeringChanged(); // XXX this may not get the UI to do the right thing
1445 string whole_file_region_name;
1446 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1448 /* Register a new region with the Session that
1449 describes the entire source. Do this first
1450 so that any sub-regions will obviously be
1451 children of this one (later!)
1457 plist.add (Properties::start, c->front()->write_source->last_capture_start_frame());
1458 plist.add (Properties::length, total_capture);
1459 plist.add (Properties::name, whole_file_region_name);
1460 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1461 rx->set_automatic (true);
1462 rx->set_whole_file (true);
1464 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1465 region->special_set_position (capture_info.front()->start);
1469 catch (failed_constructor& err) {
1470 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1474 _last_capture_sources.insert (_last_capture_sources.end(), srcs.begin(), srcs.end());
1476 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1478 _playlist->clear_changes ();
1479 _playlist->freeze ();
1481 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1485 RegionFactory::region_name (region_name, whole_file_region_name, false);
1487 // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->frames << " add region " << region_name << endl;
1493 plist.add (Properties::start, buffer_position);
1494 plist.add (Properties::length, (*ci)->frames);
1495 plist.add (Properties::name, region_name);
1497 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1498 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1501 catch (failed_constructor& err) {
1502 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1503 continue; /* XXX is this OK? */
1506 i_am_the_modifier++;
1507 _playlist->add_region (region, (*ci)->start, 1, non_layered());
1508 i_am_the_modifier--;
1510 buffer_position += (*ci)->frames;
1514 _session.add_command (new StatefulDiffCommand (_playlist));
1517 mark_write_completed = true;
1520 reset_write_sources (mark_write_completed);
1524 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1528 capture_info.clear ();
1529 capture_start_frame = 0;
1533 AudioDiskstream::transport_looped (framepos_t transport_frame)
1535 if (was_recording) {
1536 // all we need to do is finish this capture, with modified capture length
1537 boost::shared_ptr<ChannelList> c = channels.reader();
1539 // adjust the capture length knowing that the data will be recorded to disk
1540 // only necessary after the first loop where we're recording
1541 if (capture_info.size() == 0) {
1542 capture_captured += _capture_offset;
1544 if (_alignment_style == ExistingMaterial) {
1545 capture_captured += _session.worst_output_latency();
1547 capture_captured += _roll_delay;
1551 finish_capture (true, c);
1553 // the next region will start recording via the normal mechanism
1554 // we'll set the start position to the current transport pos
1555 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1556 capture_start_frame = transport_frame;
1557 first_recordable_frame = transport_frame; // mild lie
1558 last_recordable_frame = max_framepos;
1559 was_recording = true;
1561 if (recordable() && destructive()) {
1562 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1564 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1565 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1567 if (transvec.len[0] > 0) {
1568 transvec.buf[0]->type = CaptureStart;
1569 transvec.buf[0]->capture_val = capture_start_frame;
1570 (*chan)->capture_transition_buf->increment_write_ptr(1);
1574 fatal << X_("programming error: capture_transition_buf is full on rec loop! inconceivable!")
1584 AudioDiskstream::finish_capture (bool /*rec_monitors_input*/, boost::shared_ptr<ChannelList> c)
1586 was_recording = false;
1587 first_recordable_frame = max_framepos;
1588 last_recordable_frame = max_framepos;
1590 if (capture_captured == 0) {
1594 if (recordable() && destructive()) {
1595 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1597 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1598 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1600 if (transvec.len[0] > 0) {
1601 transvec.buf[0]->type = CaptureEnd;
1602 transvec.buf[0]->capture_val = capture_captured;
1603 (*chan)->capture_transition_buf->increment_write_ptr(1);
1607 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1613 CaptureInfo* ci = new CaptureInfo;
1615 ci->start = capture_start_frame;
1616 ci->frames = capture_captured;
1618 /* XXX theoretical race condition here. Need atomic exchange ?
1619 However, the circumstances when this is called right
1620 now (either on record-disable or transport_stopped)
1621 mean that no actual race exists. I think ...
1622 We now have a capture_info_lock, but it is only to be used
1623 to synchronize in the transport_stop and the capture info
1624 accessors, so that invalidation will not occur (both non-realtime).
1627 // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1629 capture_info.push_back (ci);
1630 capture_captured = 0;
1632 /* now we've finished a capture, reset first_recordable_frame for next time */
1633 first_recordable_frame = max_framepos;
1637 AudioDiskstream::set_record_enabled (bool yn)
1639 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0) {
1643 /* can't rec-enable in destructive mode if transport is before start */
1645 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1649 /* yes, i know that this not proof against race conditions, but its
1650 good enough. i think.
1653 if (record_enabled() != yn) {
1655 engage_record_enable ();
1657 disengage_record_enable ();
1663 AudioDiskstream::engage_record_enable ()
1665 bool rolling = _session.transport_speed() != 0.0f;
1666 boost::shared_ptr<ChannelList> c = channels.reader();
1668 g_atomic_int_set (&_record_enabled, 1);
1669 capturing_sources.clear ();
1671 if (Config->get_monitoring_model() == HardwareMonitoring) {
1673 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1674 if ((*chan)->source) {
1675 (*chan)->source->ensure_monitor_input (!(_session.config.get_auto_input() && rolling));
1677 capturing_sources.push_back ((*chan)->write_source);
1678 (*chan)->write_source->mark_streaming_write_started ();
1682 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1683 capturing_sources.push_back ((*chan)->write_source);
1684 (*chan)->write_source->mark_streaming_write_started ();
1688 RecordEnableChanged (); /* EMIT SIGNAL */
1692 AudioDiskstream::disengage_record_enable ()
1694 g_atomic_int_set (&_record_enabled, 0);
1695 boost::shared_ptr<ChannelList> c = channels.reader();
1696 if (Config->get_monitoring_model() == HardwareMonitoring) {
1697 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1698 if ((*chan)->source) {
1699 (*chan)->source->ensure_monitor_input (false);
1703 capturing_sources.clear ();
1704 RecordEnableChanged (); /* EMIT SIGNAL */
1708 AudioDiskstream::get_state ()
1710 XMLNode* node = new XMLNode ("Diskstream");
1712 LocaleGuard lg (X_("POSIX"));
1713 boost::shared_ptr<ChannelList> c = channels.reader();
1715 node->add_property ("flags", enum_2_string (_flags));
1717 snprintf (buf, sizeof(buf), "%zd", c->size());
1718 node->add_property ("channels", buf);
1720 node->add_property ("playlist", _playlist->name());
1722 snprintf (buf, sizeof(buf), "%.12g", _visible_speed);
1723 node->add_property ("speed", buf);
1725 node->add_property("name", _name);
1726 id().print (buf, sizeof (buf));
1727 node->add_property("id", buf);
1729 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1731 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1732 XMLNode* cs_grandchild;
1734 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1735 cs_grandchild = new XMLNode (X_("file"));
1736 cs_grandchild->add_property (X_("path"), (*i)->path());
1737 cs_child->add_child_nocopy (*cs_grandchild);
1740 /* store the location where capture will start */
1744 if (_session.config.get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1745 snprintf (buf, sizeof (buf), "%" PRId64, pi->start());
1747 snprintf (buf, sizeof (buf), "%" PRId64, _session.transport_frame());
1750 cs_child->add_property (X_("at"), buf);
1751 node->add_child_nocopy (*cs_child);
1755 node->add_child_copy (*_extra_xml);
1762 AudioDiskstream::set_state (const XMLNode& node, int /*version*/)
1764 const XMLProperty* prop;
1765 XMLNodeList nlist = node.children();
1766 XMLNodeIterator niter;
1767 uint32_t nchans = 1;
1768 XMLNode* capture_pending_node = 0;
1769 LocaleGuard lg (X_("POSIX"));
1771 in_set_state = true;
1773 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1774 if ((*niter)->name() == IO::state_node_name) {
1775 deprecated_io_node = new XMLNode (**niter);
1778 if ((*niter)->name() == X_("CapturingSources")) {
1779 capture_pending_node = *niter;
1783 /* prevent write sources from being created */
1785 in_set_state = true;
1787 if ((prop = node.property ("name")) != 0) {
1788 _name = prop->value();
1791 if (deprecated_io_node) {
1792 if ((prop = deprecated_io_node->property ("id")) != 0) {
1793 _id = prop->value ();
1796 if ((prop = node.property ("id")) != 0) {
1797 _id = prop->value ();
1801 if ((prop = node.property ("flags")) != 0) {
1802 _flags = Flag (string_2_enum (prop->value(), _flags));
1805 if ((prop = node.property ("channels")) != 0) {
1806 nchans = atoi (prop->value().c_str());
1809 // create necessary extra channels
1810 // we are always constructed with one and we always need one
1812 _n_channels.set(DataType::AUDIO, channels.reader()->size());
1814 if (nchans > _n_channels.n_audio()) {
1816 add_channel (nchans - _n_channels.n_audio());
1817 IO::PortCountChanged(_n_channels);
1819 } else if (nchans < _n_channels.n_audio()) {
1821 remove_channel (_n_channels.n_audio() - nchans);
1824 if ((prop = node.property ("playlist")) == 0) {
1829 bool had_playlist = (_playlist != 0);
1831 if (find_and_use_playlist (prop->value())) {
1835 if (!had_playlist) {
1836 _playlist->set_orig_diskstream_id (id());
1839 if (!destructive() && capture_pending_node) {
1840 /* destructive streams have one and only one source per channel,
1841 and so they never end up in pending capture in any useful
1844 use_pending_capture_data (*capture_pending_node);
1849 if ((prop = node.property ("speed")) != 0) {
1850 double sp = atof (prop->value().c_str());
1852 if (realtime_set_speed (sp, false)) {
1853 non_realtime_set_speed ();
1857 in_set_state = false;
1859 /* make sure this is clear before we do anything else */
1861 capturing_sources.clear ();
1863 /* write sources are handled when we handle the input set
1864 up of the IO that owns this DS (::non_realtime_input_change())
1871 AudioDiskstream::use_new_write_source (uint32_t n)
1873 boost::shared_ptr<ChannelList> c = channels.reader();
1875 if (!recordable()) {
1879 if (n >= c->size()) {
1880 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
1884 ChannelInfo* chan = (*c)[n];
1887 /* file starts off as a stub file, it will be converted
1888 when we're done with a capture pass.
1891 if ((chan->write_source = _session.create_audio_source_for_session (n_channels().n_audio(),
1892 name(), n, destructive(),
1894 throw failed_constructor();
1898 catch (failed_constructor &err) {
1899 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
1900 chan->write_source.reset ();
1904 /* do not remove destructive files even if they are empty */
1906 chan->write_source->set_allow_remove_if_empty (!destructive());
1911 list<boost::shared_ptr<Source> >
1912 AudioDiskstream::steal_write_sources()
1914 /* not possible to steal audio write sources */
1915 list<boost::shared_ptr<Source> > ret;
1920 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool /*force*/)
1922 ChannelList::iterator chan;
1923 boost::shared_ptr<ChannelList> c = channels.reader();
1926 if (!_session.writable() || !recordable()) {
1930 capturing_sources.clear ();
1932 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1934 if (!destructive()) {
1936 if ((*chan)->write_source) {
1938 if (mark_write_complete) {
1939 (*chan)->write_source->mark_streaming_write_completed ();
1940 (*chan)->write_source->done_with_peakfile_writes ();
1943 if ((*chan)->write_source->removable()) {
1944 (*chan)->write_source->mark_for_remove ();
1945 (*chan)->write_source->drop_references ();
1946 _session.remove_source ((*chan)->write_source);
1949 (*chan)->write_source.reset ();
1952 use_new_write_source (n);
1954 if (record_enabled()) {
1955 capturing_sources.push_back ((*chan)->write_source);
1960 if ((*chan)->write_source == 0) {
1961 use_new_write_source (n);
1966 if (destructive() && !c->empty ()) {
1968 /* we now have all our write sources set up, so create the
1969 playlist's single region.
1972 if (_playlist->empty()) {
1973 setup_destructive_playlist ();
1979 AudioDiskstream::rename_write_sources ()
1981 ChannelList::iterator chan;
1982 boost::shared_ptr<ChannelList> c = channels.reader();
1985 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1986 if ((*chan)->write_source != 0) {
1987 (*chan)->write_source->set_source_name (_name.val(), destructive());
1988 /* XXX what to do if one of them fails ? */
1996 AudioDiskstream::set_block_size (nframes_t /*nframes*/)
1998 if (_session.get_block_size() > speed_buffer_size) {
1999 speed_buffer_size = _session.get_block_size();
2000 boost::shared_ptr<ChannelList> c = channels.reader();
2002 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2003 if ((*chan)->speed_buffer)
2004 delete [] (*chan)->speed_buffer;
2005 (*chan)->speed_buffer = new Sample[speed_buffer_size];
2008 allocate_temporary_buffers ();
2012 AudioDiskstream::allocate_temporary_buffers ()
2014 /* make sure the wrap buffer is at least large enough to deal
2015 with the speeds up to 1.2, to allow for micro-variation
2016 when slaving to MTC, Timecode etc.
2019 double const sp = max (fabsf (_actual_speed), 1.2f);
2020 nframes_t required_wrap_size = (nframes_t) floor (_session.get_block_size() * sp) + 1;
2022 if (required_wrap_size > wrap_buffer_size) {
2024 boost::shared_ptr<ChannelList> c = channels.reader();
2026 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2027 if ((*chan)->playback_wrap_buffer)
2028 delete [] (*chan)->playback_wrap_buffer;
2029 (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
2030 if ((*chan)->capture_wrap_buffer)
2031 delete [] (*chan)->capture_wrap_buffer;
2032 (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
2035 wrap_buffer_size = required_wrap_size;
2040 AudioDiskstream::monitor_input (bool yn)
2042 boost::shared_ptr<ChannelList> c = channels.reader();
2044 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2046 if ((*chan)->source) {
2047 (*chan)->source->ensure_monitor_input (yn);
2053 AudioDiskstream::set_align_style_from_io ()
2055 bool have_physical = false;
2061 get_input_sources ();
2063 boost::shared_ptr<ChannelList> c = channels.reader();
2065 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2066 if ((*chan)->source && (*chan)->source->flags() & JackPortIsPhysical) {
2067 have_physical = true;
2072 if (have_physical) {
2073 set_align_style (ExistingMaterial);
2075 set_align_style (CaptureTime);
2080 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2082 while (how_many--) {
2083 c->push_back (new ChannelInfo(_session.butler()->audio_diskstream_playback_buffer_size(),
2084 _session.butler()->audio_diskstream_capture_buffer_size(),
2085 speed_buffer_size, wrap_buffer_size));
2086 interpolation.add_channel_to (_session.butler()->audio_diskstream_playback_buffer_size(), speed_buffer_size);
2089 _n_channels.set(DataType::AUDIO, c->size());
2095 AudioDiskstream::add_channel (uint32_t how_many)
2097 RCUWriter<ChannelList> writer (channels);
2098 boost::shared_ptr<ChannelList> c = writer.get_copy();
2100 return add_channel_to (c, how_many);
2104 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2106 while (how_many-- && !c->empty()) {
2109 interpolation.remove_channel_from ();
2112 _n_channels.set(DataType::AUDIO, c->size());
2118 AudioDiskstream::remove_channel (uint32_t how_many)
2120 RCUWriter<ChannelList> writer (channels);
2121 boost::shared_ptr<ChannelList> c = writer.get_copy();
2123 return remove_channel_from (c, how_many);
2127 AudioDiskstream::playback_buffer_load () const
2129 boost::shared_ptr<ChannelList> c = channels.reader();
2131 return (float) ((double) c->front()->playback_buf->read_space()/
2132 (double) c->front()->playback_buf->bufsize());
2136 AudioDiskstream::capture_buffer_load () const
2138 boost::shared_ptr<ChannelList> c = channels.reader();
2140 return (float) ((double) c->front()->capture_buf->write_space()/
2141 (double) c->front()->capture_buf->bufsize());
2145 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2147 const XMLProperty* prop;
2148 XMLNodeList nlist = node.children();
2149 XMLNodeIterator niter;
2150 boost::shared_ptr<AudioFileSource> fs;
2151 boost::shared_ptr<AudioFileSource> first_fs;
2152 SourceList pending_sources;
2153 framepos_t position;
2155 if ((prop = node.property (X_("at"))) == 0) {
2159 if (sscanf (prop->value().c_str(), "%" PRIu64, &position) != 1) {
2163 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2164 if ((*niter)->name() == X_("file")) {
2166 if ((prop = (*niter)->property (X_("path"))) == 0) {
2170 // This protects sessions from errant CapturingSources in stored sessions
2172 if (stat (prop->value().c_str(), &sbuf)) {
2177 fs = boost::dynamic_pointer_cast<AudioFileSource> (
2178 SourceFactory::createWritable (DataType::AUDIO, _session,
2179 prop->value(), string(), false, _session.frame_rate()));
2182 catch (failed_constructor& err) {
2183 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2184 _name, prop->value())
2189 pending_sources.push_back (fs);
2191 if (first_fs == 0) {
2195 fs->set_captured_for (_name.val());
2199 if (pending_sources.size() == 0) {
2200 /* nothing can be done */
2204 if (pending_sources.size() != _n_channels.n_audio()) {
2205 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2210 boost::shared_ptr<AudioRegion> region;
2216 plist.add (Properties::start, 0);
2217 plist.add (Properties::length, first_fs->length (first_fs->timeline_position()));
2218 plist.add (Properties::name, region_name_from_path (first_fs->name(), true));
2220 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, plist));
2222 region->set_automatic (true);
2223 region->set_whole_file (true);
2224 region->special_set_position (0);
2227 catch (failed_constructor& err) {
2228 error << string_compose (
2229 _("%1: cannot create whole-file region from pending capture sources"),
2235 _playlist->add_region (region, position);
2241 AudioDiskstream::set_non_layered (bool yn)
2243 if (yn != non_layered()) {
2246 _flags = Flag (_flags | NonLayered);
2248 _flags = Flag (_flags & ~NonLayered);
2256 AudioDiskstream::set_destructive (bool yn)
2258 if (yn != destructive()) {
2261 bool bounce_ignored;
2262 /* requestor should already have checked this and
2263 bounced if necessary and desired
2265 if (!can_become_destructive (bounce_ignored)) {
2268 _flags = Flag (_flags | Destructive);
2269 use_destructive_playlist ();
2271 _flags = Flag (_flags & ~Destructive);
2272 reset_write_sources (true, true);
2280 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2283 requires_bounce = false;
2287 /* is there only one region ? */
2289 if (_playlist->n_regions() != 1) {
2290 requires_bounce = true;
2294 boost::shared_ptr<Region> first = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
2296 requires_bounce = false;
2300 /* do the source(s) for the region cover the session start position ? */
2302 if (first->position() != _session.current_start_frame()) {
2303 if (first->start() > _session.current_start_frame()) {
2304 requires_bounce = true;
2309 /* is the source used by only 1 playlist ? */
2311 boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2315 if (_session.playlists->source_use_count (afirst->source()) > 1) {
2316 requires_bounce = true;
2320 requires_bounce = false;
2325 AudioDiskstream::adjust_playback_buffering ()
2327 boost::shared_ptr<ChannelList> c = channels.reader();
2329 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2330 (*chan)->resize_playback (_session.butler()->audio_diskstream_playback_buffer_size());
2335 AudioDiskstream::adjust_capture_buffering ()
2337 boost::shared_ptr<ChannelList> c = channels.reader();
2339 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2340 (*chan)->resize_capture (_session.butler()->audio_diskstream_capture_buffer_size());
2344 AudioDiskstream::ChannelInfo::ChannelInfo (nframes_t playback_bufsize, nframes_t capture_bufsize, nframes_t speed_size, nframes_t wrap_size)
2348 current_capture_buffer = 0;
2349 current_playback_buffer = 0;
2350 curr_capture_cnt = 0;
2352 speed_buffer = new Sample[speed_size];
2353 playback_wrap_buffer = new Sample[wrap_size];
2354 capture_wrap_buffer = new Sample[wrap_size];
2356 playback_buf = new RingBufferNPT<Sample> (playback_bufsize);
2357 capture_buf = new RingBufferNPT<Sample> (capture_bufsize);
2358 capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2360 /* touch the ringbuffer buffers, which will cause
2361 them to be mapped into locked physical RAM if
2362 we're running with mlockall(). this doesn't do
2366 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2367 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2368 memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2372 AudioDiskstream::ChannelInfo::resize_playback (nframes_t playback_bufsize)
2374 delete playback_buf;
2375 playback_buf = new RingBufferNPT<Sample> (playback_bufsize);
2376 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2380 AudioDiskstream::ChannelInfo::resize_capture (nframes_t capture_bufsize)
2384 capture_buf = new RingBufferNPT<Sample> (capture_bufsize);
2385 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2388 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2390 write_source.reset ();
2392 delete [] speed_buffer;
2395 delete [] playback_wrap_buffer;
2396 playback_wrap_buffer = 0;
2398 delete [] capture_wrap_buffer;
2399 capture_wrap_buffer = 0;
2401 delete playback_buf;
2407 delete capture_transition_buf;
2408 capture_transition_buf = 0;