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 AudioDiskstream::~AudioDiskstream ()
121 DEBUG_TRACE (DEBUG::Destruction, string_compose ("Audio Diskstream %1 destructor\n", _name));
124 RCUWriter<ChannelList> writer (channels);
125 boost::shared_ptr<ChannelList> c = writer.get_copy();
127 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
136 delete deprecated_io_node;
140 AudioDiskstream::allocate_working_buffers()
142 assert(disk_io_frames() > 0);
144 _working_buffers_size = disk_io_frames();
145 _mixdown_buffer = new Sample[_working_buffers_size];
146 _gain_buffer = new gain_t[_working_buffers_size];
150 AudioDiskstream::free_working_buffers()
152 delete [] _mixdown_buffer;
153 delete [] _gain_buffer;
154 _working_buffers_size = 0;
160 AudioDiskstream::non_realtime_input_change ()
163 Glib::Mutex::Lock lm (state_lock);
165 if (input_change_pending.type == IOChange::NoChange) {
170 RCUWriter<ChannelList> writer (channels);
171 boost::shared_ptr<ChannelList> c = writer.get_copy();
173 _n_channels.set(DataType::AUDIO, c->size());
175 if (_io->n_ports().n_audio() > _n_channels.n_audio()) {
176 add_channel_to (c, _io->n_ports().n_audio() - _n_channels.n_audio());
177 } else if (_io->n_ports().n_audio() < _n_channels.n_audio()) {
178 remove_channel_from (c, _n_channels.n_audio() - _io->n_ports().n_audio());
182 get_input_sources ();
183 set_capture_offset ();
185 if (first_input_change) {
186 set_align_style (_persistent_alignment_style);
187 first_input_change = false;
189 set_align_style_from_io ();
192 input_change_pending = IOChange::NoChange;
194 /* implicit unlock */
197 /* reset capture files */
199 reset_write_sources (false);
201 /* now refill channel buffers */
203 if (speed() != 1.0f || speed() != -1.0f) {
204 seek ((framepos_t) (_session.transport_frame() * (double) speed()));
206 seek (_session.transport_frame());
211 AudioDiskstream::non_realtime_locate (framepos_t location)
213 /* now refill channel buffers */
215 if (speed() != 1.0f || speed() != -1.0f) {
216 seek ((framepos_t) (location * (double) speed()));
223 AudioDiskstream::get_input_sources ()
225 boost::shared_ptr<ChannelList> c = channels.reader();
228 ChannelList::iterator chan;
229 uint32_t ni = _io->n_ports().n_audio();
230 vector<string> connections;
232 for (n = 0, chan = c->begin(); chan != c->end() && n < ni; ++chan, ++n) {
234 connections.clear ();
236 if (_io->nth (n)->get_connections (connections) == 0) {
238 if ((*chan)->source) {
239 // _source->disable_metering ();
245 (*chan)->source = dynamic_cast<AudioPort*>(_session.engine().get_port_by_name (connections[0]) );
251 AudioDiskstream::find_and_use_playlist (const string& name)
253 boost::shared_ptr<AudioPlaylist> playlist;
255 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (_session.playlists->by_name (name))) == 0) {
256 playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, name));
260 error << string_compose(_("AudioDiskstream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
264 return use_playlist (playlist);
268 AudioDiskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
270 assert(boost::dynamic_pointer_cast<AudioPlaylist>(playlist));
272 Diskstream::use_playlist(playlist);
278 AudioDiskstream::use_new_playlist ()
281 boost::shared_ptr<AudioPlaylist> playlist;
283 if (!in_set_state && destructive()) {
288 newname = Playlist::bump_name (_playlist->name(), _session);
290 newname = Playlist::bump_name (_name, _session);
293 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, newname, hidden()))) != 0) {
295 playlist->set_orig_diskstream_id (id());
296 return use_playlist (playlist);
304 AudioDiskstream::use_copy_playlist ()
306 assert(audio_playlist());
312 if (_playlist == 0) {
313 error << string_compose(_("AudioDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
318 boost::shared_ptr<AudioPlaylist> playlist;
320 newname = Playlist::bump_name (_playlist->name(), _session);
322 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist>(PlaylistFactory::create (audio_playlist(), newname))) != 0) {
323 playlist->set_orig_diskstream_id (id());
324 return use_playlist (playlist);
331 AudioDiskstream::setup_destructive_playlist ()
334 boost::shared_ptr<ChannelList> c = channels.reader();
336 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
337 srcs.push_back ((*chan)->write_source);
340 /* a single full-sized region */
342 assert (!srcs.empty ());
345 plist.add (Properties::name, _name.val());
346 plist.add (Properties::start, 0);
347 plist.add (Properties::length, max_framepos - (max_framepos - srcs.front()->natural_position()));
349 boost::shared_ptr<Region> region (RegionFactory::create (srcs, plist));
350 _playlist->add_region (region, srcs.front()->natural_position());
354 AudioDiskstream::use_destructive_playlist ()
356 /* this is called from the XML-based constructor or ::set_destructive. when called,
357 we already have a playlist and a region, but we need to
358 set up our sources for write. we use the sources associated
359 with the (presumed single, full-extent) region.
362 boost::shared_ptr<Region> rp = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
365 reset_write_sources (false, true);
369 boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
372 throw failed_constructor();
375 /* be sure to stretch the region out to the maximum length */
377 region->set_length (max_framepos - region->position(), this);
380 ChannelList::iterator chan;
381 boost::shared_ptr<ChannelList> c = channels.reader();
383 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
384 (*chan)->write_source = boost::dynamic_pointer_cast<AudioFileSource>(region->source (n));
385 assert((*chan)->write_source);
386 (*chan)->write_source->set_allow_remove_if_empty (false);
388 /* this might be false if we switched modes, so force it */
390 (*chan)->write_source->set_destructive (true);
393 /* the source list will never be reset for a destructive track */
397 AudioDiskstream::prepare_record_status(framepos_t capture_start_frame)
399 if (recordable() && destructive()) {
400 boost::shared_ptr<ChannelList> c = channels.reader();
401 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
403 RingBufferNPT<CaptureTransition>::rw_vector transvec;
404 (*chan)->capture_transition_buf->get_write_vector(&transvec);
406 if (transvec.len[0] > 0) {
407 transvec.buf[0]->type = CaptureStart;
408 transvec.buf[0]->capture_val = capture_start_frame;
409 (*chan)->capture_transition_buf->increment_write_ptr(1);
412 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
420 AudioDiskstream::process (framepos_t transport_frame, pframes_t nframes, bool can_record, bool rec_monitors_input, bool& need_butler)
423 boost::shared_ptr<ChannelList> c = channels.reader();
424 ChannelList::iterator chan;
426 framecnt_t rec_offset = 0;
427 framecnt_t rec_nframes = 0;
428 bool collect_playback = false;
430 playback_distance = 0;
432 if (!_io || !_io->active()) {
436 check_record_status (transport_frame, can_record);
442 Glib::Mutex::Lock sm (state_lock, Glib::TRY_LOCK);
448 adjust_capture_position = 0;
450 for (chan = c->begin(); chan != c->end(); ++chan) {
451 (*chan)->current_capture_buffer = 0;
452 (*chan)->current_playback_buffer = 0;
455 /* two conditions to test for here:
457 A: this track is rec-enabled, and the session has confirmed that we can record
458 B: this track is rec-enabled, has been recording, and we are set up for auto-punch-in
460 The second test is necessary to capture the extra material that arrives AFTER the transport
461 frame has left the punch range (which will cause the "can_record" argument to be false).
465 // Safeguard against situations where process() goes haywire when autopunching
466 // and last_recordable_frame < first_recordable_frame
468 if (last_recordable_frame < first_recordable_frame) {
469 last_recordable_frame = max_framepos;
472 OverlapType ot = coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
474 calculate_record_range (ot, transport_frame, nframes, rec_nframes, rec_offset);
476 if (rec_nframes && !was_recording) {
477 capture_captured = 0;
478 was_recording = true;
481 if (can_record && !_last_capture_sources.empty()) {
482 _last_capture_sources.clear ();
487 uint32_t limit = _io->n_ports ().n_audio();
489 /* one or more ports could already have been removed from _io, but our
490 channel setup hasn't yet been updated. prevent us from trying to
491 use channels that correspond to missing ports. note that the
492 process callback (from which this is called) is always atomic
493 with respect to port removal/addition.
496 for (n = 0, chan = c->begin(); chan != c->end() && n < limit; ++chan, ++n) {
498 ChannelInfo* chaninfo (*chan);
500 chaninfo->capture_buf->get_write_vector (&chaninfo->capture_vector);
502 if (rec_nframes <= (framecnt_t) chaninfo->capture_vector.len[0]) {
504 chaninfo->current_capture_buffer = chaninfo->capture_vector.buf[0];
506 /* note: grab the entire port buffer, but only copy what we were supposed to
507 for recording, and use rec_offset
510 AudioPort* const ap = _io->audio (n);
512 assert(rec_nframes <= (framecnt_t) ap->get_audio_buffer(nframes).capacity());
513 memcpy (chaninfo->current_capture_buffer, ap->get_audio_buffer (nframes).data(rec_offset), sizeof (Sample) * rec_nframes);
518 framecnt_t total = chaninfo->capture_vector.len[0] + chaninfo->capture_vector.len[1];
520 if (rec_nframes > total) {
525 AudioPort* const ap = _io->audio (n);
528 Sample* buf = ap->get_audio_buffer(nframes).data();
529 framecnt_t first = chaninfo->capture_vector.len[0];
531 memcpy (chaninfo->capture_wrap_buffer, buf, sizeof (Sample) * first);
532 memcpy (chaninfo->capture_vector.buf[0], buf, sizeof (Sample) * first);
533 memcpy (chaninfo->capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
534 memcpy (chaninfo->capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
536 chaninfo->current_capture_buffer = chaninfo->capture_wrap_buffer;
543 finish_capture (rec_monitors_input, c);
550 /* data will be written to disk */
552 if (rec_nframes == nframes && rec_offset == 0) {
554 for (chan = c->begin(); chan != c->end(); ++chan) {
555 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
558 playback_distance = nframes;
563 /* we can't use the capture buffer as the playback buffer, because
564 we recorded only a part of the current process' cycle data
568 collect_playback = true;
571 adjust_capture_position = rec_nframes;
573 } else if (can_record && record_enabled()) {
575 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
577 for (chan = c->begin(); chan != c->end(); ++chan) {
578 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
581 playback_distance = nframes;
585 collect_playback = true;
588 if (collect_playback) {
590 /* we're doing playback */
592 framecnt_t necessary_samples;
594 /* no varispeed playback if we're recording, because the output .... TBD */
596 if (rec_nframes == 0 && _actual_speed != 1.0f) {
597 necessary_samples = (framecnt_t) floor ((nframes * fabs (_actual_speed))) + 1;
599 necessary_samples = nframes;
602 for (chan = c->begin(); chan != c->end(); ++chan) {
603 (*chan)->playback_buf->get_read_vector (&(*chan)->playback_vector);
608 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
610 ChannelInfo* chaninfo (*chan);
612 if (necessary_samples <= (framecnt_t) chaninfo->playback_vector.len[0]) {
614 chaninfo->current_playback_buffer = chaninfo->playback_vector.buf[0];
617 framecnt_t total = chaninfo->playback_vector.len[0] + chaninfo->playback_vector.len[1];
619 if (necessary_samples > total) {
620 cerr << _name << " Need " << necessary_samples << " total = " << total << endl;
621 cerr << "underrun for " << _name << endl;
627 memcpy ((char *) chaninfo->playback_wrap_buffer,
628 chaninfo->playback_vector.buf[0],
629 chaninfo->playback_vector.len[0] * sizeof (Sample));
630 memcpy (chaninfo->playback_wrap_buffer + chaninfo->playback_vector.len[0],
631 chaninfo->playback_vector.buf[1],
632 (necessary_samples - chaninfo->playback_vector.len[0])
635 chaninfo->current_playback_buffer = chaninfo->playback_wrap_buffer;
640 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
641 process_varispeed_playback(nframes, c);
643 playback_distance = nframes;
646 _speed = _target_speed;
652 if (commit (nframes)) {
661 AudioDiskstream::process_varispeed_playback (pframes_t nframes, boost::shared_ptr<ChannelList> c)
663 ChannelList::iterator chan;
665 interpolation.set_speed (_target_speed);
668 for (chan = c->begin(); chan != c->end(); ++chan, ++channel) {
669 ChannelInfo* chaninfo (*chan);
671 playback_distance = interpolation.interpolate (
672 channel, nframes, chaninfo->current_playback_buffer, chaninfo->speed_buffer);
674 chaninfo->current_playback_buffer = chaninfo->speed_buffer;
679 AudioDiskstream::commit (framecnt_t /* nframes */)
681 bool need_butler = false;
683 if (!_io || !_io->active()) {
687 if (_actual_speed < 0.0) {
688 playback_sample -= playback_distance;
690 playback_sample += playback_distance;
693 boost::shared_ptr<ChannelList> c = channels.reader();
694 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
696 (*chan)->playback_buf->increment_read_ptr (playback_distance);
698 if (adjust_capture_position) {
699 (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
703 if (adjust_capture_position != 0) {
704 capture_captured += adjust_capture_position;
705 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 = ((framecnt_t) c->front()->playback_buf->write_space() >= disk_io_chunk_frames)
721 || ((framecnt_t) c->front()->capture_buf->read_space() >= disk_io_chunk_frames);
723 need_butler = ((framecnt_t) 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;
739 boost::shared_ptr<ChannelList> c = channels.reader ();
741 overwrite_offset = c->front()->playback_buf->get_read_ptr();
746 AudioDiskstream::overwrite_existing_buffers ()
748 boost::shared_ptr<ChannelList> c = channels.reader();
750 _pending_overwrite = false;
754 Sample* mixdown_buffer;
757 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
759 overwrite_queued = false;
761 /* assume all are the same size */
762 framecnt_t size = c->front()->playback_buf->bufsize();
764 mixdown_buffer = new Sample[size];
765 gain_buffer = new float[size];
767 /* reduce size so that we can fill the buffer correctly. */
773 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
775 start = overwrite_frame;
776 framecnt_t cnt = size;
778 /* to fill the buffer without resetting the playback sample, we need to
779 do it one or two chunks (normally two).
781 |----------------------------------------------------------------------|
785 |<- second chunk->||<----------------- first chunk ------------------>|
789 framecnt_t to_read = size - overwrite_offset;
791 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, *chan, n, reversed)) {
792 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
793 _id, size, playback_sample) << endmsg;
801 if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer,
802 start, cnt, *chan, n, reversed)) {
803 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
804 _id, size, playback_sample) << endmsg;
813 _pending_overwrite = false;
814 delete [] gain_buffer;
815 delete [] mixdown_buffer;
820 AudioDiskstream::seek (framepos_t frame, bool complete_refill)
824 ChannelList::iterator chan;
825 boost::shared_ptr<ChannelList> c = channels.reader();
827 Glib::Mutex::Lock lm (state_lock);
829 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
830 (*chan)->playback_buf->reset ();
831 (*chan)->capture_buf->reset ();
834 /* can't rec-enable in destructive mode if transport is before start */
836 if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
837 disengage_record_enable ();
840 playback_sample = frame;
843 if (complete_refill) {
844 while ((ret = do_refill_with_alloc ()) > 0) ;
846 ret = do_refill_with_alloc ();
853 AudioDiskstream::can_internal_playback_seek (framecnt_t distance)
855 ChannelList::iterator chan;
856 boost::shared_ptr<ChannelList> c = channels.reader();
858 for (chan = c->begin(); chan != c->end(); ++chan) {
859 if ((*chan)->playback_buf->read_space() < (size_t) distance) {
867 AudioDiskstream::internal_playback_seek (framecnt_t distance)
869 ChannelList::iterator chan;
870 boost::shared_ptr<ChannelList> c = channels.reader();
872 for (chan = c->begin(); chan != c->end(); ++chan) {
873 (*chan)->playback_buf->increment_read_ptr (distance);
876 if (first_recordable_frame < max_framepos) {
877 first_recordable_frame += distance;
879 playback_sample += distance;
885 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer,
886 framepos_t& start, framecnt_t cnt,
887 ChannelInfo* /*channel_info*/, int channel, bool reversed)
889 framecnt_t this_read = 0;
891 framepos_t loop_end = 0;
892 framepos_t loop_start = 0;
893 framecnt_t offset = 0;
896 /* XXX we don't currently play loops in reverse. not sure why */
900 framecnt_t loop_length = 0;
902 /* Make the use of a Location atomic for this read operation.
904 Note: Locations don't get deleted, so all we care about
905 when I say "atomic" is that we are always pointing to
906 the same one and using a start/length values obtained
910 if ((loc = loop_location) != 0) {
911 loop_start = loc->start();
912 loop_end = loc->end();
913 loop_length = loop_end - loop_start;
916 /* if we are looping, ensure that the first frame we read is at the correct
917 position within the loop.
920 if (loc && start >= loop_end) {
921 //cerr << "start adjusted from " << start;
922 start = loop_start + ((start - loop_start) % loop_length);
923 //cerr << "to " << start << endl;
926 //cerr << "start is " << start << " loopstart: " << loop_start << " loopend: " << loop_end << endl;
935 /* take any loop into account. we can't read past the end of the loop. */
937 if (loc && (loop_end - start < cnt)) {
938 this_read = loop_end - start;
939 //cerr << "reloop true: thisread: " << this_read << " cnt: " << cnt << endl;
946 if (this_read == 0) {
950 this_read = min(cnt,this_read);
952 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
953 error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), _id, this_read,
958 _read_data_count = _playlist->read_data_count();
962 swap_by_ptr (buf, buf + this_read - 1);
966 /* if we read to the end of the loop, go back to the beginning */
983 AudioDiskstream::do_refill_with_alloc ()
985 Sample* mix_buf = new Sample[disk_io_chunk_frames];
986 float* gain_buf = new float[disk_io_chunk_frames];
988 int ret = _do_refill(mix_buf, gain_buf);
997 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer)
1001 RingBufferNPT<Sample>::rw_vector vector;
1002 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1003 framecnt_t total_space;
1004 framecnt_t zero_fill;
1006 ChannelList::iterator i;
1007 boost::shared_ptr<ChannelList> c = channels.reader();
1014 assert(mixdown_buffer);
1015 assert(gain_buffer);
1022 c->front()->playback_buf->get_write_vector (&vector);
1024 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1028 /* if there are 2+ chunks of disk i/o possible for
1029 this track, let the caller know so that it can arrange
1030 for us to be called again, ASAP.
1033 if (total_space >= (_slaved?3:2) * disk_io_chunk_frames) {
1037 /* if we're running close to normal speed and there isn't enough
1038 space to do disk_io_chunk_frames of I/O, then don't bother.
1040 at higher speeds, just do it because the sync between butler
1041 and audio thread may not be good enough.
1044 if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1048 /* when slaved, don't try to get too close to the read pointer. this
1049 leaves space for the buffer reversal to have something useful to
1053 if (_slaved && total_space < (framecnt_t) (c->front()->playback_buf->bufsize() / 2)) {
1057 /* never do more than disk_io_chunk_frames worth of disk input per call (limit doesn't apply for memset) */
1059 total_space = min (disk_io_chunk_frames, total_space);
1063 if (file_frame == 0) {
1065 /* at start: nothing to do but fill with silence */
1067 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1069 ChannelInfo* chan (*i);
1070 chan->playback_buf->get_write_vector (&vector);
1071 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1072 if (vector.len[1]) {
1073 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1075 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1080 if (file_frame < total_space) {
1082 /* too close to the start: read what we can,
1083 and then zero fill the rest
1086 zero_fill = total_space - file_frame;
1087 total_space = file_frame;
1097 if (file_frame == max_framepos) {
1099 /* at end: nothing to do but fill with silence */
1101 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1103 ChannelInfo* chan (*i);
1104 chan->playback_buf->get_write_vector (&vector);
1105 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1106 if (vector.len[1]) {
1107 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1109 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1114 if (file_frame > max_framepos - total_space) {
1116 /* to close to the end: read what we can, and zero fill the rest */
1118 zero_fill = total_space - (max_framepos - file_frame);
1119 total_space = max_framepos - file_frame;
1126 framepos_t file_frame_tmp = 0;
1128 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1130 ChannelInfo* chan (*i);
1133 framecnt_t len1, len2;
1135 chan->playback_buf->get_write_vector (&vector);
1137 if ((framecnt_t) vector.len[0] > disk_io_chunk_frames) {
1139 /* we're not going to fill the first chunk, so certainly do not bother with the
1140 other part. it won't be connected with the part we do fill, as in:
1142 .... => writable space
1143 ++++ => readable space
1144 ^^^^ => 1 x disk_io_chunk_frames that would be filled
1146 |......|+++++++++++++|...............................|
1151 So, just pretend that the buf1 part isn't there.
1161 file_frame_tmp = file_frame;
1163 buf1 = vector.buf[0];
1164 len1 = vector.len[0];
1165 buf2 = vector.buf[1];
1166 len2 = vector.len[1];
1168 to_read = min (ts, len1);
1169 to_read = min (to_read, disk_io_chunk_frames);
1173 if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1178 chan->playback_buf->increment_write_ptr (to_read);
1182 to_read = min (ts, len2);
1186 /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1187 so read some or all of vector.len[1] as well.
1190 if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1195 chan->playback_buf->increment_write_ptr (to_read);
1204 file_frame = file_frame_tmp;
1211 /** Flush pending data to disk.
1213 * Important note: this function will write *AT MOST* disk_io_chunk_frames
1214 * of data to disk. it will never write more than that. If it writes that
1215 * much and there is more than that waiting to be written, it will return 1,
1216 * otherwise 0 on success or -1 on failure.
1218 * If there is less than disk_io_chunk_frames to be written, no data will be
1219 * written at all unless @a force_flush is true.
1222 AudioDiskstream::do_flush (RunContext /*context*/, bool force_flush)
1226 RingBufferNPT<Sample>::rw_vector vector;
1227 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1230 _write_data_count = 0;
1232 transvec.buf[0] = 0;
1233 transvec.buf[1] = 0;
1237 boost::shared_ptr<ChannelList> c = channels.reader();
1238 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1240 (*chan)->capture_buf->get_read_vector (&vector);
1242 total = vector.len[0] + vector.len[1];
1244 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1248 /* if there are 2+ chunks of disk i/o possible for
1249 this track, let the caller know so that it can arrange
1250 for us to be called again, ASAP.
1252 if we are forcing a flush, then if there is* any* extra
1253 work, let the caller know.
1255 if we are no longer recording and there is any extra work,
1256 let the caller know too.
1259 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1263 to_write = min (disk_io_chunk_frames, (framecnt_t) vector.len[0]);
1265 // check the transition buffer when recording destructive
1266 // important that we get this after the capture buf
1268 if (destructive()) {
1269 (*chan)->capture_transition_buf->get_read_vector(&transvec);
1270 size_t transcount = transvec.len[0] + transvec.len[1];
1271 bool have_start = false;
1274 for (ti=0; ti < transcount; ++ti) {
1275 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1277 if (captrans.type == CaptureStart) {
1278 // by definition, the first data we got above represents the given capture pos
1280 (*chan)->write_source->mark_capture_start (captrans.capture_val);
1281 (*chan)->curr_capture_cnt = 0;
1285 else if (captrans.type == CaptureEnd) {
1287 // capture end, the capture_val represents total frames in capture
1289 if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1291 // shorten to make the write a perfect fit
1292 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
1294 if (nto_write < to_write) {
1295 ret = 1; // should we?
1297 to_write = nto_write;
1299 (*chan)->write_source->mark_capture_end ();
1301 // increment past this transition, but go no further
1306 // actually ends just beyond this chunk, so force more work
1314 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1318 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1319 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1323 (*chan)->capture_buf->increment_read_ptr (to_write);
1324 (*chan)->curr_capture_cnt += to_write;
1326 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1328 /* we wrote all of vector.len[0] but it wasn't an entire
1329 disk_io_chunk_frames of data, so arrange for some part
1330 of vector.len[1] to be flushed to disk as well.
1333 to_write = min ((framecnt_t)(disk_io_chunk_frames - to_write), (framecnt_t) vector.len[1]);
1335 if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1336 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1340 _write_data_count += (*chan)->write_source->write_data_count();
1342 (*chan)->capture_buf->increment_read_ptr (to_write);
1343 (*chan)->curr_capture_cnt += to_write;
1352 AudioDiskstream::transport_stopped_wallclock (struct tm& when, time_t twhen, bool abort_capture)
1354 uint32_t buffer_position;
1355 bool more_work = true;
1357 boost::shared_ptr<AudioRegion> region;
1358 framecnt_t total_capture;
1360 SourceList::iterator src;
1361 ChannelList::iterator chan;
1362 vector<CaptureInfo*>::iterator ci;
1363 boost::shared_ptr<ChannelList> c = channels.reader();
1365 bool mark_write_completed = false;
1367 finish_capture (true, c);
1369 /* butler is already stopped, but there may be work to do
1370 to flush remaining data to disk.
1373 while (more_work && !err) {
1374 switch (do_flush (TransportContext, true)) {
1381 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1386 /* XXX is there anything we can do if err != 0 ? */
1387 Glib::Mutex::Lock lm (capture_info_lock);
1389 if (capture_info.empty()) {
1393 if (abort_capture) {
1395 if (destructive()) {
1399 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1401 if ((*chan)->write_source) {
1403 (*chan)->write_source->mark_for_remove ();
1404 (*chan)->write_source->drop_references ();
1405 _session.remove_source ((*chan)->write_source);
1406 (*chan)->write_source.reset ();
1409 /* new source set up in "out" below */
1415 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1416 total_capture += (*ci)->frames;
1419 /* figure out the name for this take */
1421 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1423 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1427 if (s->unstubify ()) {
1428 error << string_compose (_("Could not move capture file from %1"), s->path()) << endmsg;
1430 s->update_header (capture_info.front()->start, when, twhen);
1431 s->set_captured_for (_name.val());
1432 s->mark_immutable ();
1434 if (Config->get_auto_analyse_audio()) {
1435 Analyser::queue_source_for_analysis (s, true);
1440 /* destructive tracks have a single, never changing region */
1442 if (destructive()) {
1444 /* send a signal that any UI can pick up to do the right thing. there is
1445 a small problem here in that a UI may need the peak data to be ready
1446 for the data that was recorded and this isn't interlocked with that
1447 process. this problem is deferred to the UI.
1450 _playlist->LayeringChanged(); // XXX this may not get the UI to do the right thing
1454 string whole_file_region_name;
1455 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1457 /* Register a new region with the Session that
1458 describes the entire source. Do this first
1459 so that any sub-regions will obviously be
1460 children of this one (later!)
1466 plist.add (Properties::start, c->front()->write_source->last_capture_start_frame());
1467 plist.add (Properties::length, total_capture);
1468 plist.add (Properties::name, whole_file_region_name);
1469 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1470 rx->set_automatic (true);
1471 rx->set_whole_file (true);
1473 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1474 region->special_set_position (capture_info.front()->start);
1478 catch (failed_constructor& err) {
1479 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1483 _last_capture_sources.insert (_last_capture_sources.end(), srcs.begin(), srcs.end());
1485 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1487 _playlist->clear_changes ();
1488 _playlist->freeze ();
1490 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1494 RegionFactory::region_name (region_name, whole_file_region_name, false);
1496 // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->frames << " add region " << region_name << endl;
1502 plist.add (Properties::start, buffer_position);
1503 plist.add (Properties::length, (*ci)->frames);
1504 plist.add (Properties::name, region_name);
1506 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1507 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1510 catch (failed_constructor& err) {
1511 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1512 continue; /* XXX is this OK? */
1515 i_am_the_modifier++;
1517 if (_playlist->explicit_relayering()) {
1518 /* We are in `explicit relayering' mode, so we must specify which layer this new region
1519 should end up on. Put it at the top.
1521 region->set_layer (_playlist->top_layer() + 1);
1522 region->set_pending_explicit_relayer (true);
1525 _playlist->add_region (region, (*ci)->start, 1, non_layered());
1526 i_am_the_modifier--;
1528 buffer_position += (*ci)->frames;
1532 _session.add_command (new StatefulDiffCommand (_playlist));
1535 mark_write_completed = true;
1538 reset_write_sources (mark_write_completed);
1542 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1546 capture_info.clear ();
1547 capture_start_frame = 0;
1551 AudioDiskstream::transport_looped (framepos_t transport_frame)
1553 if (was_recording) {
1554 // all we need to do is finish this capture, with modified capture length
1555 boost::shared_ptr<ChannelList> c = channels.reader();
1557 // adjust the capture length knowing that the data will be recorded to disk
1558 // only necessary after the first loop where we're recording
1559 if (capture_info.size() == 0) {
1560 capture_captured += _capture_offset;
1562 if (_alignment_style == ExistingMaterial) {
1563 capture_captured += _session.worst_output_latency();
1565 capture_captured += _roll_delay;
1569 finish_capture (true, c);
1571 // the next region will start recording via the normal mechanism
1572 // we'll set the start position to the current transport pos
1573 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1574 capture_start_frame = transport_frame;
1575 first_recordable_frame = transport_frame; // mild lie
1576 last_recordable_frame = max_framepos;
1577 was_recording = true;
1579 if (recordable() && destructive()) {
1580 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1582 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1583 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1585 if (transvec.len[0] > 0) {
1586 transvec.buf[0]->type = CaptureStart;
1587 transvec.buf[0]->capture_val = capture_start_frame;
1588 (*chan)->capture_transition_buf->increment_write_ptr(1);
1592 fatal << X_("programming error: capture_transition_buf is full on rec loop! inconceivable!")
1602 AudioDiskstream::finish_capture (bool /*rec_monitors_input*/, boost::shared_ptr<ChannelList> c)
1604 was_recording = false;
1605 first_recordable_frame = max_framepos;
1606 last_recordable_frame = max_framepos;
1608 if (capture_captured == 0) {
1612 if (recordable() && destructive()) {
1613 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1615 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1616 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1618 if (transvec.len[0] > 0) {
1619 transvec.buf[0]->type = CaptureEnd;
1620 transvec.buf[0]->capture_val = capture_captured;
1621 (*chan)->capture_transition_buf->increment_write_ptr(1);
1625 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1631 CaptureInfo* ci = new CaptureInfo;
1633 ci->start = capture_start_frame;
1634 ci->frames = capture_captured;
1636 /* XXX theoretical race condition here. Need atomic exchange ?
1637 However, the circumstances when this is called right
1638 now (either on record-disable or transport_stopped)
1639 mean that no actual race exists. I think ...
1640 We now have a capture_info_lock, but it is only to be used
1641 to synchronize in the transport_stop and the capture info
1642 accessors, so that invalidation will not occur (both non-realtime).
1645 // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1647 capture_info.push_back (ci);
1648 capture_captured = 0;
1650 /* now we've finished a capture, reset first_recordable_frame for next time */
1651 first_recordable_frame = max_framepos;
1655 AudioDiskstream::set_record_enabled (bool yn)
1657 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0) {
1661 /* can't rec-enable in destructive mode if transport is before start */
1663 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1667 /* yes, i know that this not proof against race conditions, but its
1668 good enough. i think.
1671 if (record_enabled() != yn) {
1673 engage_record_enable ();
1675 disengage_record_enable ();
1681 AudioDiskstream::engage_record_enable ()
1683 bool rolling = _session.transport_speed() != 0.0f;
1684 boost::shared_ptr<ChannelList> c = channels.reader();
1686 g_atomic_int_set (&_record_enabled, 1);
1687 capturing_sources.clear ();
1689 if (Config->get_monitoring_model() == HardwareMonitoring) {
1691 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1692 if ((*chan)->source) {
1693 (*chan)->source->ensure_monitor_input (!(_session.config.get_auto_input() && rolling));
1695 capturing_sources.push_back ((*chan)->write_source);
1696 (*chan)->write_source->mark_streaming_write_started ();
1700 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1701 capturing_sources.push_back ((*chan)->write_source);
1702 (*chan)->write_source->mark_streaming_write_started ();
1706 RecordEnableChanged (); /* EMIT SIGNAL */
1710 AudioDiskstream::disengage_record_enable ()
1712 g_atomic_int_set (&_record_enabled, 0);
1713 boost::shared_ptr<ChannelList> c = channels.reader();
1714 if (Config->get_monitoring_model() == HardwareMonitoring) {
1715 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1716 if ((*chan)->source) {
1717 (*chan)->source->ensure_monitor_input (false);
1721 capturing_sources.clear ();
1722 RecordEnableChanged (); /* EMIT SIGNAL */
1726 AudioDiskstream::get_state ()
1728 XMLNode* node = new XMLNode ("Diskstream");
1730 LocaleGuard lg (X_("POSIX"));
1731 boost::shared_ptr<ChannelList> c = channels.reader();
1733 node->add_property ("flags", enum_2_string (_flags));
1735 snprintf (buf, sizeof(buf), "%zd", c->size());
1736 node->add_property ("channels", buf);
1738 node->add_property ("playlist", _playlist->name());
1740 snprintf (buf, sizeof(buf), "%.12g", _visible_speed);
1741 node->add_property ("speed", buf);
1743 node->add_property("name", _name);
1744 id().print (buf, sizeof (buf));
1745 node->add_property("id", buf);
1747 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1749 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1750 XMLNode* cs_grandchild;
1752 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1753 cs_grandchild = new XMLNode (X_("file"));
1754 cs_grandchild->add_property (X_("path"), (*i)->path());
1755 cs_child->add_child_nocopy (*cs_grandchild);
1758 /* store the location where capture will start */
1762 if (_session.config.get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1763 snprintf (buf, sizeof (buf), "%" PRId64, pi->start());
1765 snprintf (buf, sizeof (buf), "%" PRId64, _session.transport_frame());
1768 cs_child->add_property (X_("at"), buf);
1769 node->add_child_nocopy (*cs_child);
1773 node->add_child_copy (*_extra_xml);
1780 AudioDiskstream::set_state (const XMLNode& node, int /*version*/)
1782 const XMLProperty* prop;
1783 XMLNodeList nlist = node.children();
1784 XMLNodeIterator niter;
1785 uint32_t nchans = 1;
1786 XMLNode* capture_pending_node = 0;
1787 LocaleGuard lg (X_("POSIX"));
1789 in_set_state = true;
1791 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1792 if ((*niter)->name() == IO::state_node_name) {
1793 deprecated_io_node = new XMLNode (**niter);
1796 if ((*niter)->name() == X_("CapturingSources")) {
1797 capture_pending_node = *niter;
1801 /* prevent write sources from being created */
1803 in_set_state = true;
1805 if ((prop = node.property ("name")) != 0) {
1806 _name = prop->value();
1809 if (deprecated_io_node) {
1810 if ((prop = deprecated_io_node->property ("id")) != 0) {
1811 _id = prop->value ();
1814 if ((prop = node.property ("id")) != 0) {
1815 _id = prop->value ();
1819 if ((prop = node.property ("flags")) != 0) {
1820 _flags = Flag (string_2_enum (prop->value(), _flags));
1823 if ((prop = node.property ("channels")) != 0) {
1824 nchans = atoi (prop->value().c_str());
1827 // create necessary extra channels
1828 // we are always constructed with one and we always need one
1830 _n_channels.set(DataType::AUDIO, channels.reader()->size());
1832 if (nchans > _n_channels.n_audio()) {
1834 add_channel (nchans - _n_channels.n_audio());
1835 IO::PortCountChanged(_n_channels);
1837 } else if (nchans < _n_channels.n_audio()) {
1839 remove_channel (_n_channels.n_audio() - nchans);
1842 if ((prop = node.property ("playlist")) == 0) {
1847 bool had_playlist = (_playlist != 0);
1849 if (find_and_use_playlist (prop->value())) {
1853 if (!had_playlist) {
1854 _playlist->set_orig_diskstream_id (id());
1857 if (!destructive() && capture_pending_node) {
1858 /* destructive streams have one and only one source per channel,
1859 and so they never end up in pending capture in any useful
1862 use_pending_capture_data (*capture_pending_node);
1867 if ((prop = node.property ("speed")) != 0) {
1868 double sp = atof (prop->value().c_str());
1870 if (realtime_set_speed (sp, false)) {
1871 non_realtime_set_speed ();
1875 in_set_state = false;
1877 /* make sure this is clear before we do anything else */
1879 capturing_sources.clear ();
1881 /* write sources are handled when we handle the input set
1882 up of the IO that owns this DS (::non_realtime_input_change())
1889 AudioDiskstream::use_new_write_source (uint32_t n)
1891 boost::shared_ptr<ChannelList> c = channels.reader();
1893 if (!recordable()) {
1897 if (n >= c->size()) {
1898 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
1902 ChannelInfo* chan = (*c)[n];
1905 /* file starts off as a stub file, it will be converted
1906 when we're done with a capture pass.
1909 if ((chan->write_source = _session.create_audio_source_for_session (n_channels().n_audio(),
1910 name(), n, destructive(),
1912 throw failed_constructor();
1916 catch (failed_constructor &err) {
1917 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
1918 chan->write_source.reset ();
1922 /* do not remove destructive files even if they are empty */
1924 chan->write_source->set_allow_remove_if_empty (!destructive());
1929 list<boost::shared_ptr<Source> >
1930 AudioDiskstream::steal_write_sources()
1932 /* not possible to steal audio write sources */
1933 list<boost::shared_ptr<Source> > ret;
1938 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool /*force*/)
1940 ChannelList::iterator chan;
1941 boost::shared_ptr<ChannelList> c = channels.reader();
1944 if (!_session.writable() || !recordable()) {
1948 capturing_sources.clear ();
1950 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1952 if (!destructive()) {
1954 if ((*chan)->write_source) {
1956 if (mark_write_complete) {
1957 (*chan)->write_source->mark_streaming_write_completed ();
1958 (*chan)->write_source->done_with_peakfile_writes ();
1961 if ((*chan)->write_source->removable()) {
1962 (*chan)->write_source->mark_for_remove ();
1963 (*chan)->write_source->drop_references ();
1964 _session.remove_source ((*chan)->write_source);
1967 (*chan)->write_source.reset ();
1970 use_new_write_source (n);
1972 if (record_enabled()) {
1973 capturing_sources.push_back ((*chan)->write_source);
1978 if ((*chan)->write_source == 0) {
1979 use_new_write_source (n);
1984 if (destructive() && !c->empty ()) {
1986 /* we now have all our write sources set up, so create the
1987 playlist's single region.
1990 if (_playlist->empty()) {
1991 setup_destructive_playlist ();
1997 AudioDiskstream::rename_write_sources ()
1999 ChannelList::iterator chan;
2000 boost::shared_ptr<ChannelList> c = channels.reader();
2003 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
2004 if ((*chan)->write_source != 0) {
2005 (*chan)->write_source->set_source_name (_name.val(), destructive());
2006 /* XXX what to do if one of them fails ? */
2014 AudioDiskstream::set_block_size (pframes_t /*nframes*/)
2016 if (_session.get_block_size() > speed_buffer_size) {
2017 speed_buffer_size = _session.get_block_size();
2018 boost::shared_ptr<ChannelList> c = channels.reader();
2020 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2021 if ((*chan)->speed_buffer)
2022 delete [] (*chan)->speed_buffer;
2023 (*chan)->speed_buffer = new Sample[speed_buffer_size];
2026 allocate_temporary_buffers ();
2030 AudioDiskstream::allocate_temporary_buffers ()
2032 /* make sure the wrap buffer is at least large enough to deal
2033 with the speeds up to 1.2, to allow for micro-variation
2034 when slaving to MTC, Timecode etc.
2037 double const sp = max (fabsf (_actual_speed), 1.2f);
2038 framecnt_t required_wrap_size = (framecnt_t) floor (_session.get_block_size() * sp) + 1;
2040 if (required_wrap_size > wrap_buffer_size) {
2042 boost::shared_ptr<ChannelList> c = channels.reader();
2044 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2045 if ((*chan)->playback_wrap_buffer)
2046 delete [] (*chan)->playback_wrap_buffer;
2047 (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
2048 if ((*chan)->capture_wrap_buffer)
2049 delete [] (*chan)->capture_wrap_buffer;
2050 (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
2053 wrap_buffer_size = required_wrap_size;
2058 AudioDiskstream::monitor_input (bool yn)
2060 boost::shared_ptr<ChannelList> c = channels.reader();
2062 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2064 if ((*chan)->source) {
2065 (*chan)->source->ensure_monitor_input (yn);
2071 AudioDiskstream::set_align_style_from_io ()
2073 bool have_physical = false;
2079 get_input_sources ();
2081 boost::shared_ptr<ChannelList> c = channels.reader();
2083 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2084 if ((*chan)->source && (*chan)->source->flags() & JackPortIsPhysical) {
2085 have_physical = true;
2090 if (have_physical) {
2091 set_align_style (ExistingMaterial);
2093 set_align_style (CaptureTime);
2098 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2100 while (how_many--) {
2101 c->push_back (new ChannelInfo(_session.butler()->audio_diskstream_playback_buffer_size(),
2102 _session.butler()->audio_diskstream_capture_buffer_size(),
2103 speed_buffer_size, wrap_buffer_size));
2104 interpolation.add_channel_to (_session.butler()->audio_diskstream_playback_buffer_size(), speed_buffer_size);
2107 _n_channels.set(DataType::AUDIO, c->size());
2113 AudioDiskstream::add_channel (uint32_t how_many)
2115 RCUWriter<ChannelList> writer (channels);
2116 boost::shared_ptr<ChannelList> c = writer.get_copy();
2118 return add_channel_to (c, how_many);
2122 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2124 while (how_many-- && !c->empty()) {
2127 interpolation.remove_channel_from ();
2130 _n_channels.set(DataType::AUDIO, c->size());
2136 AudioDiskstream::remove_channel (uint32_t how_many)
2138 RCUWriter<ChannelList> writer (channels);
2139 boost::shared_ptr<ChannelList> c = writer.get_copy();
2141 return remove_channel_from (c, how_many);
2145 AudioDiskstream::playback_buffer_load () const
2147 boost::shared_ptr<ChannelList> c = channels.reader();
2153 return (float) ((double) c->front()->playback_buf->read_space()/
2154 (double) c->front()->playback_buf->bufsize());
2158 AudioDiskstream::capture_buffer_load () const
2160 boost::shared_ptr<ChannelList> c = channels.reader();
2166 return (float) ((double) c->front()->capture_buf->write_space()/
2167 (double) c->front()->capture_buf->bufsize());
2171 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2173 const XMLProperty* prop;
2174 XMLNodeList nlist = node.children();
2175 XMLNodeIterator niter;
2176 boost::shared_ptr<AudioFileSource> fs;
2177 boost::shared_ptr<AudioFileSource> first_fs;
2178 SourceList pending_sources;
2179 framepos_t position;
2181 if ((prop = node.property (X_("at"))) == 0) {
2185 if (sscanf (prop->value().c_str(), "%" PRIu64, &position) != 1) {
2189 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2190 if ((*niter)->name() == X_("file")) {
2192 if ((prop = (*niter)->property (X_("path"))) == 0) {
2196 // This protects sessions from errant CapturingSources in stored sessions
2198 if (stat (prop->value().c_str(), &sbuf)) {
2203 fs = boost::dynamic_pointer_cast<AudioFileSource> (
2204 SourceFactory::createWritable (DataType::AUDIO, _session,
2205 prop->value(), string(), false, _session.frame_rate()));
2208 catch (failed_constructor& err) {
2209 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2210 _name, prop->value())
2215 pending_sources.push_back (fs);
2217 if (first_fs == 0) {
2221 fs->set_captured_for (_name.val());
2225 if (pending_sources.size() == 0) {
2226 /* nothing can be done */
2230 if (pending_sources.size() != _n_channels.n_audio()) {
2231 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2236 boost::shared_ptr<AudioRegion> region;
2242 plist.add (Properties::start, 0);
2243 plist.add (Properties::length, first_fs->length (first_fs->timeline_position()));
2244 plist.add (Properties::name, region_name_from_path (first_fs->name(), true));
2246 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, plist));
2248 region->set_automatic (true);
2249 region->set_whole_file (true);
2250 region->special_set_position (0);
2253 catch (failed_constructor& err) {
2254 error << string_compose (
2255 _("%1: cannot create whole-file region from pending capture sources"),
2261 _playlist->add_region (region, position);
2267 AudioDiskstream::set_non_layered (bool yn)
2269 if (yn != non_layered()) {
2272 _flags = Flag (_flags | NonLayered);
2274 _flags = Flag (_flags & ~NonLayered);
2282 AudioDiskstream::set_destructive (bool yn)
2284 if (yn != destructive()) {
2287 bool bounce_ignored;
2288 /* requestor should already have checked this and
2289 bounced if necessary and desired
2291 if (!can_become_destructive (bounce_ignored)) {
2294 _flags = Flag (_flags | Destructive);
2295 use_destructive_playlist ();
2297 _flags = Flag (_flags & ~Destructive);
2298 reset_write_sources (true, true);
2306 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2309 requires_bounce = false;
2313 /* is there only one region ? */
2315 if (_playlist->n_regions() != 1) {
2316 requires_bounce = true;
2320 boost::shared_ptr<Region> first = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
2322 requires_bounce = false;
2326 /* do the source(s) for the region cover the session start position ? */
2328 if (first->position() != _session.current_start_frame()) {
2329 if (first->start() > _session.current_start_frame()) {
2330 requires_bounce = true;
2335 /* is the source used by only 1 playlist ? */
2337 boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2341 if (_session.playlists->source_use_count (afirst->source()) > 1) {
2342 requires_bounce = true;
2346 requires_bounce = false;
2351 AudioDiskstream::adjust_playback_buffering ()
2353 boost::shared_ptr<ChannelList> c = channels.reader();
2355 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2356 (*chan)->resize_playback (_session.butler()->audio_diskstream_playback_buffer_size());
2361 AudioDiskstream::adjust_capture_buffering ()
2363 boost::shared_ptr<ChannelList> c = channels.reader();
2365 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2366 (*chan)->resize_capture (_session.butler()->audio_diskstream_capture_buffer_size());
2370 AudioDiskstream::ChannelInfo::ChannelInfo (framecnt_t playback_bufsize, framecnt_t capture_bufsize, framecnt_t speed_size, framecnt_t wrap_size)
2374 current_capture_buffer = 0;
2375 current_playback_buffer = 0;
2376 curr_capture_cnt = 0;
2378 speed_buffer = new Sample[speed_size];
2379 playback_wrap_buffer = new Sample[wrap_size];
2380 capture_wrap_buffer = new Sample[wrap_size];
2382 playback_buf = new RingBufferNPT<Sample> (playback_bufsize);
2383 capture_buf = new RingBufferNPT<Sample> (capture_bufsize);
2384 capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2386 /* touch the ringbuffer buffers, which will cause
2387 them to be mapped into locked physical RAM if
2388 we're running with mlockall(). this doesn't do
2392 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2393 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2394 memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2398 AudioDiskstream::ChannelInfo::resize_playback (framecnt_t playback_bufsize)
2400 delete playback_buf;
2401 playback_buf = new RingBufferNPT<Sample> (playback_bufsize);
2402 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2406 AudioDiskstream::ChannelInfo::resize_capture (framecnt_t capture_bufsize)
2410 capture_buf = new RingBufferNPT<Sample> (capture_bufsize);
2411 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2414 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2416 write_source.reset ();
2418 delete [] speed_buffer;
2421 delete [] playback_wrap_buffer;
2422 playback_wrap_buffer = 0;
2424 delete [] capture_wrap_buffer;
2425 capture_wrap_buffer = 0;
2427 delete playback_buf;
2433 delete capture_transition_buf;
2434 capture_transition_buf = 0;