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"
67 using namespace ARDOUR;
70 size_t AudioDiskstream::_working_buffers_size = 0;
71 Sample* AudioDiskstream::_mixdown_buffer = 0;
72 gain_t* AudioDiskstream::_gain_buffer = 0;
74 AudioDiskstream::AudioDiskstream (Session &sess, const string &name, Diskstream::Flag flag)
75 : Diskstream(sess, name, flag)
76 , deprecated_io_node(NULL)
77 , channels (new ChannelList)
79 /* prevent any write sources from being created */
89 AudioDiskstream::AudioDiskstream (Session& sess, const XMLNode& node)
90 : Diskstream(sess, node)
91 , deprecated_io_node(NULL)
92 , channels (new ChannelList)
97 if (set_state (node, Stateful::loading_state_version)) {
99 throw failed_constructor();
102 in_set_state = false;
105 use_destructive_playlist ();
110 AudioDiskstream::init (Diskstream::Flag f)
114 /* there are no channels at this point, so these
115 two calls just get speed_buffer_size and wrap_buffer
116 size setup without duplicating their code.
119 set_block_size (_session.get_block_size());
120 allocate_temporary_buffers ();
123 assert(_n_channels == ChanCount(DataType::AUDIO, 1));
126 AudioDiskstream::~AudioDiskstream ()
128 DEBUG_TRACE (DEBUG::Destruction, string_compose ("Audio Diskstream %1 destructor\n", _name));
131 RCUWriter<ChannelList> writer (channels);
132 boost::shared_ptr<ChannelList> c = writer.get_copy();
134 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
143 delete deprecated_io_node;
147 AudioDiskstream::allocate_working_buffers()
149 assert(disk_io_frames() > 0);
151 _working_buffers_size = disk_io_frames();
152 _mixdown_buffer = new Sample[_working_buffers_size];
153 _gain_buffer = new gain_t[_working_buffers_size];
157 AudioDiskstream::free_working_buffers()
159 delete [] _mixdown_buffer;
160 delete [] _gain_buffer;
161 _working_buffers_size = 0;
167 AudioDiskstream::non_realtime_input_change ()
170 Glib::Mutex::Lock lm (state_lock);
172 if (input_change_pending == NoChange) {
177 RCUWriter<ChannelList> writer (channels);
178 boost::shared_ptr<ChannelList> c = writer.get_copy();
180 _n_channels.set(DataType::AUDIO, c->size());
182 if (_io->n_ports().n_audio() > _n_channels.n_audio()) {
183 add_channel_to (c, _io->n_ports().n_audio() - _n_channels.n_audio());
184 } else if (_io->n_ports().n_audio() < _n_channels.n_audio()) {
185 remove_channel_from (c, _n_channels.n_audio() - _io->n_ports().n_audio());
189 get_input_sources ();
190 set_capture_offset ();
192 if (first_input_change) {
193 set_align_style (_persistent_alignment_style);
194 first_input_change = false;
196 set_align_style_from_io ();
199 input_change_pending = NoChange;
201 /* implicit unlock */
204 /* reset capture files */
206 reset_write_sources (false);
208 /* now refill channel buffers */
210 if (speed() != 1.0f || speed() != -1.0f) {
211 seek ((nframes_t) (_session.transport_frame() * (double) speed()));
213 seek (_session.transport_frame());
218 AudioDiskstream::non_realtime_locate (nframes_t location)
220 /* now refill channel buffers */
222 if (speed() != 1.0f || speed() != -1.0f) {
223 seek ((nframes_t) (location * (double) speed()));
230 AudioDiskstream::get_input_sources ()
232 boost::shared_ptr<ChannelList> c = channels.reader();
235 ChannelList::iterator chan;
236 uint32_t ni = _io->n_ports().n_audio();
237 vector<string> connections;
239 for (n = 0, chan = c->begin(); chan != c->end() && n < ni; ++chan, ++n) {
241 connections.clear ();
243 if (_io->nth (n)->get_connections (connections) == 0) {
245 if ((*chan)->source) {
246 // _source->disable_metering ();
252 (*chan)->source = dynamic_cast<AudioPort*>(_session.engine().get_port_by_name (connections[0]) );
258 AudioDiskstream::find_and_use_playlist (const string& name)
260 boost::shared_ptr<AudioPlaylist> playlist;
262 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (_session.playlists->by_name (name))) == 0) {
263 playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, name));
267 error << string_compose(_("AudioDiskstream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
271 return use_playlist (playlist);
275 AudioDiskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
277 assert(boost::dynamic_pointer_cast<AudioPlaylist>(playlist));
279 Diskstream::use_playlist(playlist);
285 AudioDiskstream::use_new_playlist ()
288 boost::shared_ptr<AudioPlaylist> playlist;
290 if (!in_set_state && destructive()) {
295 newname = Playlist::bump_name (_playlist->name(), _session);
297 newname = Playlist::bump_name (_name, _session);
300 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, newname, hidden()))) != 0) {
302 playlist->set_orig_diskstream_id (id());
303 return use_playlist (playlist);
311 AudioDiskstream::use_copy_playlist ()
313 assert(audio_playlist());
319 if (_playlist == 0) {
320 error << string_compose(_("AudioDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
325 boost::shared_ptr<AudioPlaylist> playlist;
327 newname = Playlist::bump_name (_playlist->name(), _session);
329 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist>(PlaylistFactory::create (audio_playlist(), newname))) != 0) {
330 playlist->set_orig_diskstream_id (id());
331 return use_playlist (playlist);
338 AudioDiskstream::setup_destructive_playlist ()
341 boost::shared_ptr<ChannelList> c = channels.reader();
343 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
344 srcs.push_back ((*chan)->write_source);
347 /* a single full-sized region */
349 assert (!srcs.empty ());
352 plist.add (Properties::name, _name.val());
353 plist.add (Properties::start, 0);
354 plist.add (Properties::length, max_frames - max_frames - srcs.front()->natural_position());
356 boost::shared_ptr<Region> region (RegionFactory::create (srcs, plist));
357 _playlist->add_region (region, srcs.front()->natural_position());
361 AudioDiskstream::use_destructive_playlist ()
363 /* this is called from the XML-based constructor or ::set_destructive. when called,
364 we already have a playlist and a region, but we need to
365 set up our sources for write. we use the sources associated
366 with the (presumed single, full-extent) region.
369 boost::shared_ptr<Region> rp = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
372 reset_write_sources (false, true);
376 boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
379 throw failed_constructor();
382 /* be sure to stretch the region out to the maximum length */
384 region->set_length (max_frames - region->position(), this);
387 ChannelList::iterator chan;
388 boost::shared_ptr<ChannelList> c = channels.reader();
390 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
391 (*chan)->write_source = boost::dynamic_pointer_cast<AudioFileSource>(region->source (n));
392 assert((*chan)->write_source);
393 (*chan)->write_source->set_allow_remove_if_empty (false);
395 /* this might be false if we switched modes, so force it */
397 (*chan)->write_source->set_destructive (true);
400 /* the source list will never be reset for a destructive track */
404 AudioDiskstream::prepare_record_status(nframes_t capture_start_frame)
406 if (recordable() && destructive()) {
407 boost::shared_ptr<ChannelList> c = channels.reader();
408 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
410 RingBufferNPT<CaptureTransition>::rw_vector transvec;
411 (*chan)->capture_transition_buf->get_write_vector(&transvec);
413 if (transvec.len[0] > 0) {
414 transvec.buf[0]->type = CaptureStart;
415 transvec.buf[0]->capture_val = capture_start_frame;
416 (*chan)->capture_transition_buf->increment_write_ptr(1);
420 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
428 AudioDiskstream::process (nframes_t transport_frame, nframes_t nframes, bool can_record, bool rec_monitors_input)
431 boost::shared_ptr<ChannelList> c = channels.reader();
432 ChannelList::iterator chan;
434 nframes_t rec_offset = 0;
435 nframes_t rec_nframes = 0;
436 bool nominally_recording;
437 bool re = record_enabled ();
438 bool collect_playback = false;
440 /* if we've already processed the frames corresponding to this call,
441 just return. this allows multiple routes that are taking input
442 from this diskstream to call our ::process() method, but have
443 this stuff only happen once. more commonly, it allows both
444 the AudioTrack that is using this AudioDiskstream *and* the Session
445 to call process() without problems.
452 commit_should_unlock = false;
454 if (!_io || !_io->active()) {
459 check_record_status (transport_frame, nframes, can_record);
461 nominally_recording = (can_record && re);
468 /* This lock is held until the end of AudioDiskstream::commit, so these two functions
469 must always be called as a pair. The only exception is if this function
470 returns a non-zero value, in which case, ::commit should not be called.
473 // If we can't take the state lock return.
474 if (!state_lock.trylock()) {
477 commit_should_unlock = true;
478 adjust_capture_position = 0;
480 for (chan = c->begin(); chan != c->end(); ++chan) {
481 (*chan)->current_capture_buffer = 0;
482 (*chan)->current_playback_buffer = 0;
485 if (nominally_recording || (_session.get_record_enabled() && _session.config.get_punch_in())) {
486 // Safeguard against situations where process() goes haywire when autopunching and last_recordable_frame < first_recordable_frame
487 if (last_recordable_frame < first_recordable_frame) {
488 last_recordable_frame = max_frames;
491 OverlapType ot = coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
493 calculate_record_range(ot, transport_frame, nframes, rec_nframes, rec_offset);
495 if (rec_nframes && !was_recording) {
496 capture_captured = 0;
497 was_recording = true;
502 if (can_record && !_last_capture_regions.empty()) {
503 _last_capture_regions.clear ();
506 if (nominally_recording || rec_nframes) {
508 uint32_t limit = _io->n_ports ().n_audio();
510 /* one or more ports could already have been removed from _io, but our
511 channel setup hasn't yet been updated. prevent us from trying to
512 use channels that correspond to missing ports. note that the
513 process callback (from which this is called) is always atomic
514 with respect to port removal/addition.
517 for (n = 0, chan = c->begin(); chan != c->end() && n < limit; ++chan, ++n) {
519 ChannelInfo* chaninfo (*chan);
521 chaninfo->capture_buf->get_write_vector (&chaninfo->capture_vector);
523 if (rec_nframes <= chaninfo->capture_vector.len[0]) {
525 chaninfo->current_capture_buffer = chaninfo->capture_vector.buf[0];
527 /* note: grab the entire port buffer, but only copy what we were supposed to
528 for recording, and use rec_offset
531 AudioPort* const ap = _io->audio (n);
533 assert(rec_nframes <= ap->get_audio_buffer(nframes).capacity());
534 memcpy (chaninfo->current_capture_buffer, ap->get_audio_buffer (rec_nframes).data(rec_offset), sizeof (Sample) * rec_nframes);
539 nframes_t total = chaninfo->capture_vector.len[0] + chaninfo->capture_vector.len[1];
541 if (rec_nframes > total) {
546 AudioPort* const ap = _io->audio (n);
549 Sample* buf = ap->get_audio_buffer(nframes).data();
550 nframes_t first = chaninfo->capture_vector.len[0];
552 memcpy (chaninfo->capture_wrap_buffer, buf, sizeof (Sample) * first);
553 memcpy (chaninfo->capture_vector.buf[0], buf, sizeof (Sample) * first);
554 memcpy (chaninfo->capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
555 memcpy (chaninfo->capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
557 chaninfo->current_capture_buffer = chaninfo->capture_wrap_buffer;
564 finish_capture (rec_monitors_input, c);
571 /* data will be written to disk */
573 if (rec_nframes == nframes && rec_offset == 0) {
575 for (chan = c->begin(); chan != c->end(); ++chan) {
576 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
579 playback_distance = nframes;
584 /* we can't use the capture buffer as the playback buffer, because
585 we recorded only a part of the current process' cycle data
589 collect_playback = true;
592 adjust_capture_position = rec_nframes;
594 } else if (nominally_recording) {
596 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
598 for (chan = c->begin(); chan != c->end(); ++chan) {
599 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
602 playback_distance = nframes;
606 collect_playback = true;
609 if (collect_playback) {
611 /* we're doing playback */
613 nframes_t necessary_samples;
615 /* no varispeed playback if we're recording, because the output .... TBD */
617 if (rec_nframes == 0 && _actual_speed != 1.0f) {
618 necessary_samples = (nframes_t) floor ((nframes * fabs (_actual_speed))) + 1;
620 necessary_samples = nframes;
623 for (chan = c->begin(); chan != c->end(); ++chan) {
624 (*chan)->playback_buf->get_read_vector (&(*chan)->playback_vector);
629 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
631 ChannelInfo* chaninfo (*chan);
633 if (necessary_samples <= chaninfo->playback_vector.len[0]) {
635 chaninfo->current_playback_buffer = chaninfo->playback_vector.buf[0];
638 nframes_t total = chaninfo->playback_vector.len[0] + chaninfo->playback_vector.len[1];
640 if (necessary_samples > total) {
641 cerr << _name << " Need " << necessary_samples << " total = " << total << endl;
642 cerr << "underrun for " << _name << endl;
648 memcpy ((char *) chaninfo->playback_wrap_buffer,
649 chaninfo->playback_vector.buf[0],
650 chaninfo->playback_vector.len[0] * sizeof (Sample));
651 memcpy (chaninfo->playback_wrap_buffer + chaninfo->playback_vector.len[0],
652 chaninfo->playback_vector.buf[1],
653 (necessary_samples - chaninfo->playback_vector.len[0])
656 chaninfo->current_playback_buffer = chaninfo->playback_wrap_buffer;
661 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
662 process_varispeed_playback(nframes, c);
664 playback_distance = nframes;
667 _speed = _target_speed;
678 /* we're exiting with failure, so ::commit will not
679 be called. unlock the state lock.
682 commit_should_unlock = false;
690 AudioDiskstream::process_varispeed_playback(nframes_t nframes, boost::shared_ptr<ChannelList> c)
692 ChannelList::iterator chan;
694 interpolation.set_speed (_target_speed);
697 for (chan = c->begin(); chan != c->end(); ++chan, ++channel) {
698 ChannelInfo* chaninfo (*chan);
700 playback_distance = interpolation.interpolate (
701 channel, nframes, chaninfo->current_playback_buffer, chaninfo->speed_buffer);
703 chaninfo->current_playback_buffer = chaninfo->speed_buffer;
708 AudioDiskstream::commit (nframes_t /*nframes*/)
710 bool need_butler = false;
712 if (!_io || !_io->active()) {
716 if (_actual_speed < 0.0) {
717 playback_sample -= playback_distance;
719 playback_sample += playback_distance;
722 boost::shared_ptr<ChannelList> c = channels.reader();
723 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
725 (*chan)->playback_buf->increment_read_ptr (playback_distance);
727 if (adjust_capture_position) {
728 (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
732 if (adjust_capture_position != 0) {
733 capture_captured += adjust_capture_position;
734 adjust_capture_position = 0;
738 if (_io && _io->active()) {
739 need_butler = c->front()->playback_buf->write_space() >= c->front()->playback_buf->bufsize() / 2;
744 if (_io && _io->active()) {
745 need_butler = c->front()->playback_buf->write_space() >= disk_io_chunk_frames
746 || c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
748 need_butler = c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
752 if (commit_should_unlock) {
762 AudioDiskstream::set_pending_overwrite (bool yn)
764 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
766 pending_overwrite = yn;
768 overwrite_frame = playback_sample;
769 overwrite_offset = channels.reader()->front()->playback_buf->get_read_ptr();
773 AudioDiskstream::overwrite_existing_buffers ()
775 boost::shared_ptr<ChannelList> c = channels.reader();
776 Sample* mixdown_buffer;
779 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
781 overwrite_queued = false;
783 /* assume all are the same size */
784 nframes_t size = c->front()->playback_buf->bufsize();
786 mixdown_buffer = new Sample[size];
787 gain_buffer = new float[size];
789 /* reduce size so that we can fill the buffer correctly. */
795 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
797 start = overwrite_frame;
798 nframes_t cnt = size;
800 /* to fill the buffer without resetting the playback sample, we need to
801 do it one or two chunks (normally two).
803 |----------------------------------------------------------------------|
807 |<- second chunk->||<----------------- first chunk ------------------>|
811 nframes_t to_read = size - overwrite_offset;
813 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, *chan, n, reversed)) {
814 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
815 _id, size, playback_sample) << endmsg;
823 if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer,
824 start, cnt, *chan, n, reversed)) {
825 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
826 _id, size, playback_sample) << endmsg;
835 pending_overwrite = false;
836 delete [] gain_buffer;
837 delete [] mixdown_buffer;
842 AudioDiskstream::seek (nframes_t frame, bool complete_refill)
846 ChannelList::iterator chan;
847 boost::shared_ptr<ChannelList> c = channels.reader();
849 Glib::Mutex::Lock lm (state_lock);
851 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
852 (*chan)->playback_buf->reset ();
853 (*chan)->capture_buf->reset ();
856 /* can't rec-enable in destructive mode if transport is before start */
858 if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
859 disengage_record_enable ();
862 playback_sample = frame;
865 if (complete_refill) {
866 while ((ret = do_refill_with_alloc ()) > 0) ;
868 ret = do_refill_with_alloc ();
875 AudioDiskstream::can_internal_playback_seek (nframes_t distance)
877 ChannelList::iterator chan;
878 boost::shared_ptr<ChannelList> c = channels.reader();
880 for (chan = c->begin(); chan != c->end(); ++chan) {
881 if ((*chan)->playback_buf->read_space() < distance) {
889 AudioDiskstream::internal_playback_seek (nframes_t distance)
891 ChannelList::iterator chan;
892 boost::shared_ptr<ChannelList> c = channels.reader();
894 for (chan = c->begin(); chan != c->end(); ++chan) {
895 (*chan)->playback_buf->increment_read_ptr (distance);
898 first_recordable_frame += distance;
899 playback_sample += distance;
905 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer, nframes_t& start, nframes_t cnt,
906 ChannelInfo* /*channel_info*/, int channel, bool reversed)
908 nframes_t this_read = 0;
910 nframes_t loop_end = 0;
911 nframes_t loop_start = 0;
912 nframes_t offset = 0;
915 /* XXX we don't currently play loops in reverse. not sure why */
919 nframes_t loop_length = 0;
921 /* Make the use of a Location atomic for this read operation.
923 Note: Locations don't get deleted, so all we care about
924 when I say "atomic" is that we are always pointing to
925 the same one and using a start/length values obtained
929 if ((loc = loop_location) != 0) {
930 loop_start = loc->start();
931 loop_end = loc->end();
932 loop_length = loop_end - loop_start;
935 /* if we are looping, ensure that the first frame we read is at the correct
936 position within the loop.
939 if (loc && start >= loop_end) {
940 //cerr << "start adjusted from " << start;
941 start = loop_start + ((start - loop_start) % loop_length);
942 //cerr << "to " << start << endl;
945 //cerr << "start is " << start << " loopstart: " << loop_start << " loopend: " << loop_end << endl;
954 /* take any loop into account. we can't read past the end of the loop. */
956 if (loc && (loop_end - start < cnt)) {
957 this_read = loop_end - start;
958 //cerr << "reloop true: thisread: " << this_read << " cnt: " << cnt << endl;
965 if (this_read == 0) {
969 this_read = min(cnt,this_read);
971 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
972 error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), _id, this_read,
977 _read_data_count = _playlist->read_data_count();
981 swap_by_ptr (buf, buf + this_read - 1);
985 /* if we read to the end of the loop, go back to the beginning */
1002 AudioDiskstream::do_refill_with_alloc ()
1004 Sample* mix_buf = new Sample[disk_io_chunk_frames];
1005 float* gain_buf = new float[disk_io_chunk_frames];
1007 int ret = _do_refill(mix_buf, gain_buf);
1016 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer)
1020 RingBufferNPT<Sample>::rw_vector vector;
1021 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1022 nframes_t total_space;
1023 nframes_t zero_fill;
1025 ChannelList::iterator i;
1026 boost::shared_ptr<ChannelList> c = channels.reader();
1033 assert(mixdown_buffer);
1034 assert(gain_buffer);
1041 c->front()->playback_buf->get_write_vector (&vector);
1043 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1047 /* if there are 2+ chunks of disk i/o possible for
1048 this track, let the caller know so that it can arrange
1049 for us to be called again, ASAP.
1052 if (total_space >= (_slaved?3:2) * disk_io_chunk_frames) {
1056 /* if we're running close to normal speed and there isn't enough
1057 space to do disk_io_chunk_frames of I/O, then don't bother.
1059 at higher speeds, just do it because the sync between butler
1060 and audio thread may not be good enough.
1063 if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1067 /* when slaved, don't try to get too close to the read pointer. this
1068 leaves space for the buffer reversal to have something useful to
1072 if (_slaved && total_space < (c->front()->playback_buf->bufsize() / 2)) {
1076 /* never do more than disk_io_chunk_frames worth of disk input per call (limit doesn't apply for memset) */
1078 total_space = min (disk_io_chunk_frames, total_space);
1082 if (file_frame == 0) {
1084 /* at start: nothing to do but fill with silence */
1086 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1088 ChannelInfo* chan (*i);
1089 chan->playback_buf->get_write_vector (&vector);
1090 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1091 if (vector.len[1]) {
1092 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1094 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1099 if (file_frame < total_space) {
1101 /* too close to the start: read what we can,
1102 and then zero fill the rest
1105 zero_fill = total_space - file_frame;
1106 total_space = file_frame;
1116 if (file_frame == max_frames) {
1118 /* at end: nothing to do but fill with silence */
1120 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1122 ChannelInfo* chan (*i);
1123 chan->playback_buf->get_write_vector (&vector);
1124 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1125 if (vector.len[1]) {
1126 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1128 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1133 if (file_frame > max_frames - total_space) {
1135 /* to close to the end: read what we can, and zero fill the rest */
1137 zero_fill = total_space - (max_frames - file_frame);
1138 total_space = max_frames - file_frame;
1145 nframes_t file_frame_tmp = 0;
1147 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1149 ChannelInfo* chan (*i);
1152 nframes_t len1, len2;
1154 chan->playback_buf->get_write_vector (&vector);
1156 if (vector.len[0] > disk_io_chunk_frames) {
1158 /* we're not going to fill the first chunk, so certainly do not bother with the
1159 other part. it won't be connected with the part we do fill, as in:
1161 .... => writable space
1162 ++++ => readable space
1163 ^^^^ => 1 x disk_io_chunk_frames that would be filled
1165 |......|+++++++++++++|...............................|
1170 So, just pretend that the buf1 part isn't there.
1180 file_frame_tmp = file_frame;
1182 buf1 = vector.buf[0];
1183 len1 = vector.len[0];
1184 buf2 = vector.buf[1];
1185 len2 = vector.len[1];
1187 to_read = min (ts, len1);
1188 to_read = min (to_read, disk_io_chunk_frames);
1192 if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1197 chan->playback_buf->increment_write_ptr (to_read);
1201 to_read = min (ts, len2);
1205 /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1206 so read some or all of vector.len[1] as well.
1209 if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1214 chan->playback_buf->increment_write_ptr (to_read);
1223 file_frame = file_frame_tmp;
1230 /** Flush pending data to disk.
1232 * Important note: this function will write *AT MOST* disk_io_chunk_frames
1233 * of data to disk. it will never write more than that. If it writes that
1234 * much and there is more than that waiting to be written, it will return 1,
1235 * otherwise 0 on success or -1 on failure.
1237 * If there is less than disk_io_chunk_frames to be written, no data will be
1238 * written at all unless @a force_flush is true.
1241 AudioDiskstream::do_flush (RunContext /*context*/, bool force_flush)
1245 RingBufferNPT<Sample>::rw_vector vector;
1246 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1249 _write_data_count = 0;
1251 transvec.buf[0] = 0;
1252 transvec.buf[1] = 0;
1256 boost::shared_ptr<ChannelList> c = channels.reader();
1257 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1259 (*chan)->capture_buf->get_read_vector (&vector);
1261 total = vector.len[0] + vector.len[1];
1263 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1267 /* if there are 2+ chunks of disk i/o possible for
1268 this track, let the caller know so that it can arrange
1269 for us to be called again, ASAP.
1271 if we are forcing a flush, then if there is* any* extra
1272 work, let the caller know.
1274 if we are no longer recording and there is any extra work,
1275 let the caller know too.
1278 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1282 to_write = min (disk_io_chunk_frames, (nframes_t) vector.len[0]);
1284 // check the transition buffer when recording destructive
1285 // important that we get this after the capture buf
1287 if (destructive()) {
1288 (*chan)->capture_transition_buf->get_read_vector(&transvec);
1289 size_t transcount = transvec.len[0] + transvec.len[1];
1290 bool have_start = false;
1293 for (ti=0; ti < transcount; ++ti) {
1294 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1296 if (captrans.type == CaptureStart) {
1297 // by definition, the first data we got above represents the given capture pos
1299 (*chan)->write_source->mark_capture_start (captrans.capture_val);
1300 (*chan)->curr_capture_cnt = 0;
1304 else if (captrans.type == CaptureEnd) {
1306 // capture end, the capture_val represents total frames in capture
1308 if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1310 // shorten to make the write a perfect fit
1311 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
1313 if (nto_write < to_write) {
1314 ret = 1; // should we?
1316 to_write = nto_write;
1318 (*chan)->write_source->mark_capture_end ();
1320 // increment past this transition, but go no further
1325 // actually ends just beyond this chunk, so force more work
1333 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1337 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1338 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1342 (*chan)->capture_buf->increment_read_ptr (to_write);
1343 (*chan)->curr_capture_cnt += to_write;
1345 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1347 /* we wrote all of vector.len[0] but it wasn't an entire
1348 disk_io_chunk_frames of data, so arrange for some part
1349 of vector.len[1] to be flushed to disk as well.
1352 to_write = min ((nframes_t)(disk_io_chunk_frames - to_write), (nframes_t) vector.len[1]);
1354 if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1355 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1359 _write_data_count += (*chan)->write_source->write_data_count();
1361 (*chan)->capture_buf->increment_read_ptr (to_write);
1362 (*chan)->curr_capture_cnt += to_write;
1371 AudioDiskstream::transport_stopped (struct tm& when, time_t twhen, bool abort_capture)
1373 uint32_t buffer_position;
1374 bool more_work = true;
1376 boost::shared_ptr<AudioRegion> region;
1377 nframes_t total_capture;
1379 SourceList::iterator src;
1380 ChannelList::iterator chan;
1381 vector<CaptureInfo*>::iterator ci;
1382 boost::shared_ptr<ChannelList> c = channels.reader();
1384 bool mark_write_completed = false;
1386 finish_capture (true, c);
1388 /* butler is already stopped, but there may be work to do
1389 to flush remaining data to disk.
1392 while (more_work && !err) {
1393 switch (do_flush (TransportContext, true)) {
1400 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1405 /* XXX is there anything we can do if err != 0 ? */
1406 Glib::Mutex::Lock lm (capture_info_lock);
1408 if (capture_info.empty()) {
1412 if (abort_capture) {
1414 if (destructive()) {
1418 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1420 if ((*chan)->write_source) {
1422 (*chan)->write_source->mark_for_remove ();
1423 (*chan)->write_source->drop_references ();
1424 (*chan)->write_source.reset ();
1427 /* new source set up in "out" below */
1433 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1434 total_capture += (*ci)->frames;
1437 /* figure out the name for this take */
1439 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1441 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1445 s->update_header (capture_info.front()->start, when, twhen);
1446 s->set_captured_for (_name.val());
1447 s->mark_immutable ();
1448 if (Config->get_auto_analyse_audio()) {
1449 Analyser::queue_source_for_analysis (s, true);
1454 /* destructive tracks have a single, never changing region */
1456 if (destructive()) {
1458 /* send a signal that any UI can pick up to do the right thing. there is
1459 a small problem here in that a UI may need the peak data to be ready
1460 for the data that was recorded and this isn't interlocked with that
1461 process. this problem is deferred to the UI.
1464 _playlist->LayeringChanged(); // XXX this may not get the UI to do the right thing
1468 string whole_file_region_name;
1469 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1471 /* Register a new region with the Session that
1472 describes the entire source. Do this first
1473 so that any sub-regions will obviously be
1474 children of this one (later!)
1480 plist.add (Properties::start, c->front()->write_source->last_capture_start_frame());
1481 plist.add (Properties::length, total_capture);
1482 plist.add (Properties::name, whole_file_region_name);
1484 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1485 rx->set_automatic (true);
1486 rx->set_whole_file (true);
1488 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1489 region->special_set_position (capture_info.front()->start);
1493 catch (failed_constructor& err) {
1494 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1498 _last_capture_regions.push_back (region);
1500 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1502 _playlist->clear_history ();
1503 _playlist->freeze ();
1505 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1509 _session.region_name (region_name, whole_file_region_name, false);
1511 // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->frames << " add region " << region_name << endl;
1517 plist.add (Properties::start, buffer_position);
1518 plist.add (Properties::length, (*ci)->frames);
1519 plist.add (Properties::name, region_name);
1521 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1522 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1525 catch (failed_constructor& err) {
1526 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1527 continue; /* XXX is this OK? */
1530 region->DropReferences.connect_same_thread (*this, boost::bind (&Diskstream::remove_region_from_last_capture, this, boost::weak_ptr<Region>(region)));
1532 _last_capture_regions.push_back (region);
1534 i_am_the_modifier++;
1535 _playlist->add_region (region, (*ci)->start, 1, non_layered());
1536 i_am_the_modifier--;
1538 buffer_position += (*ci)->frames;
1542 _session.add_command (new StatefulDiffCommand (_playlist));
1545 mark_write_completed = true;
1548 reset_write_sources (mark_write_completed);
1552 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1556 capture_info.clear ();
1557 capture_start_frame = 0;
1561 AudioDiskstream::transport_looped (nframes_t transport_frame)
1563 if (was_recording) {
1564 // all we need to do is finish this capture, with modified capture length
1565 boost::shared_ptr<ChannelList> c = channels.reader();
1567 // adjust the capture length knowing that the data will be recorded to disk
1568 // only necessary after the first loop where we're recording
1569 if (capture_info.size() == 0) {
1570 capture_captured += _capture_offset;
1572 if (_alignment_style == ExistingMaterial) {
1573 capture_captured += _session.worst_output_latency();
1575 capture_captured += _roll_delay;
1579 finish_capture (true, c);
1581 // the next region will start recording via the normal mechanism
1582 // we'll set the start position to the current transport pos
1583 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1584 capture_start_frame = transport_frame;
1585 first_recordable_frame = transport_frame; // mild lie
1586 last_recordable_frame = max_frames;
1587 was_recording = true;
1589 if (recordable() && destructive()) {
1590 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1592 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1593 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1595 if (transvec.len[0] > 0) {
1596 transvec.buf[0]->type = CaptureStart;
1597 transvec.buf[0]->capture_val = capture_start_frame;
1598 (*chan)->capture_transition_buf->increment_write_ptr(1);
1602 fatal << X_("programming error: capture_transition_buf is full on rec loop! inconceivable!")
1612 AudioDiskstream::finish_capture (bool /*rec_monitors_input*/, boost::shared_ptr<ChannelList> c)
1614 was_recording = false;
1616 if (capture_captured == 0) {
1620 if (recordable() && destructive()) {
1621 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1623 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1624 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1626 if (transvec.len[0] > 0) {
1627 transvec.buf[0]->type = CaptureEnd;
1628 transvec.buf[0]->capture_val = capture_captured;
1629 (*chan)->capture_transition_buf->increment_write_ptr(1);
1633 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1639 CaptureInfo* ci = new CaptureInfo;
1641 ci->start = capture_start_frame;
1642 ci->frames = capture_captured;
1644 /* XXX theoretical race condition here. Need atomic exchange ?
1645 However, the circumstances when this is called right
1646 now (either on record-disable or transport_stopped)
1647 mean that no actual race exists. I think ...
1648 We now have a capture_info_lock, but it is only to be used
1649 to synchronize in the transport_stop and the capture info
1650 accessors, so that invalidation will not occur (both non-realtime).
1653 // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1655 capture_info.push_back (ci);
1656 capture_captured = 0;
1658 /* now we've finished a capture, reset first_recordable_frame for next time */
1659 first_recordable_frame = max_frames;
1663 AudioDiskstream::set_record_enabled (bool yn)
1665 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0) {
1669 /* can't rec-enable in destructive mode if transport is before start */
1671 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1675 /* yes, i know that this not proof against race conditions, but its
1676 good enough. i think.
1679 if (record_enabled() != yn) {
1681 engage_record_enable ();
1683 disengage_record_enable ();
1689 AudioDiskstream::engage_record_enable ()
1691 bool rolling = _session.transport_speed() != 0.0f;
1692 boost::shared_ptr<ChannelList> c = channels.reader();
1694 g_atomic_int_set (&_record_enabled, 1);
1695 capturing_sources.clear ();
1697 if (Config->get_monitoring_model() == HardwareMonitoring) {
1699 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1700 if ((*chan)->source) {
1701 (*chan)->source->ensure_monitor_input (!(_session.config.get_auto_input() && rolling));
1703 capturing_sources.push_back ((*chan)->write_source);
1704 (*chan)->write_source->mark_streaming_write_started ();
1708 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1709 capturing_sources.push_back ((*chan)->write_source);
1710 (*chan)->write_source->mark_streaming_write_started ();
1714 RecordEnableChanged (); /* EMIT SIGNAL */
1718 AudioDiskstream::disengage_record_enable ()
1720 g_atomic_int_set (&_record_enabled, 0);
1721 boost::shared_ptr<ChannelList> c = channels.reader();
1722 if (Config->get_monitoring_model() == HardwareMonitoring) {
1723 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1724 if ((*chan)->source) {
1725 (*chan)->source->ensure_monitor_input (false);
1729 capturing_sources.clear ();
1730 RecordEnableChanged (); /* EMIT SIGNAL */
1734 AudioDiskstream::get_state ()
1736 XMLNode* node = new XMLNode ("AudioDiskstream");
1738 LocaleGuard lg (X_("POSIX"));
1739 boost::shared_ptr<ChannelList> c = channels.reader();
1741 node->add_property ("flags", enum_2_string (_flags));
1743 snprintf (buf, sizeof(buf), "%zd", c->size());
1744 node->add_property ("channels", buf);
1746 node->add_property ("playlist", _playlist->name());
1748 snprintf (buf, sizeof(buf), "%.12g", _visible_speed);
1749 node->add_property ("speed", buf);
1751 node->add_property("name", _name);
1752 id().print (buf, sizeof (buf));
1753 node->add_property("id", buf);
1755 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1757 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1758 XMLNode* cs_grandchild;
1760 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1761 cs_grandchild = new XMLNode (X_("file"));
1762 cs_grandchild->add_property (X_("path"), (*i)->path());
1763 cs_child->add_child_nocopy (*cs_grandchild);
1766 /* store the location where capture will start */
1770 if (_session.config.get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1771 snprintf (buf, sizeof (buf), "%" PRId64, pi->start());
1773 snprintf (buf, sizeof (buf), "%" PRId64, _session.transport_frame());
1776 cs_child->add_property (X_("at"), buf);
1777 node->add_child_nocopy (*cs_child);
1781 node->add_child_copy (*_extra_xml);
1788 AudioDiskstream::set_state (const XMLNode& node, int /*version*/)
1790 const XMLProperty* prop;
1791 XMLNodeList nlist = node.children();
1792 XMLNodeIterator niter;
1793 uint32_t nchans = 1;
1794 XMLNode* capture_pending_node = 0;
1795 LocaleGuard lg (X_("POSIX"));
1797 in_set_state = true;
1799 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1800 if ((*niter)->name() == IO::state_node_name) {
1801 deprecated_io_node = new XMLNode (**niter);
1804 if ((*niter)->name() == X_("CapturingSources")) {
1805 capture_pending_node = *niter;
1809 /* prevent write sources from being created */
1811 in_set_state = true;
1813 if ((prop = node.property ("name")) != 0) {
1814 _name = prop->value();
1817 if (deprecated_io_node) {
1818 if ((prop = deprecated_io_node->property ("id")) != 0) {
1819 _id = prop->value ();
1822 if ((prop = node.property ("id")) != 0) {
1823 _id = prop->value ();
1827 if ((prop = node.property ("flags")) != 0) {
1828 _flags = Flag (string_2_enum (prop->value(), _flags));
1831 if ((prop = node.property ("channels")) != 0) {
1832 nchans = atoi (prop->value().c_str());
1835 // create necessary extra channels
1836 // we are always constructed with one and we always need one
1838 _n_channels.set(DataType::AUDIO, channels.reader()->size());
1840 if (nchans > _n_channels.n_audio()) {
1842 add_channel (nchans - _n_channels.n_audio());
1843 IO::PortCountChanged(_n_channels);
1845 } else if (nchans < _n_channels.n_audio()) {
1847 remove_channel (_n_channels.n_audio() - nchans);
1850 if ((prop = node.property ("playlist")) == 0) {
1855 bool had_playlist = (_playlist != 0);
1857 if (find_and_use_playlist (prop->value())) {
1861 if (!had_playlist) {
1862 _playlist->set_orig_diskstream_id (_id);
1865 if (!destructive() && capture_pending_node) {
1866 /* destructive streams have one and only one source per channel,
1867 and so they never end up in pending capture in any useful
1870 use_pending_capture_data (*capture_pending_node);
1875 if ((prop = node.property ("speed")) != 0) {
1876 double sp = atof (prop->value().c_str());
1878 if (realtime_set_speed (sp, false)) {
1879 non_realtime_set_speed ();
1883 in_set_state = false;
1885 /* make sure this is clear before we do anything else */
1887 capturing_sources.clear ();
1889 /* write sources are handled when we handle the input set
1890 up of the IO that owns this DS (::non_realtime_input_change())
1897 AudioDiskstream::use_new_write_source (uint32_t n)
1899 boost::shared_ptr<ChannelList> c = channels.reader();
1901 if (!recordable()) {
1905 if (n >= c->size()) {
1906 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
1910 ChannelInfo* chan = (*c)[n];
1912 if (chan->write_source) {
1913 chan->write_source->done_with_peakfile_writes ();
1914 chan->write_source->set_allow_remove_if_empty (true);
1915 chan->write_source.reset ();
1919 if ((chan->write_source = _session.create_audio_source_for_session (*this, n, destructive())) == 0) {
1920 throw failed_constructor();
1924 catch (failed_constructor &err) {
1925 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
1926 chan->write_source.reset ();
1930 /* do not remove destructive files even if they are empty */
1932 chan->write_source->set_allow_remove_if_empty (!destructive());
1934 /* until we write, this file is considered removable */
1936 chan->write_source->mark_for_remove ();
1942 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool /*force*/)
1944 ChannelList::iterator chan;
1945 boost::shared_ptr<ChannelList> c = channels.reader();
1948 if (!_session.writable() || !recordable()) {
1952 capturing_sources.clear ();
1954 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1955 if (!destructive()) {
1957 if ((*chan)->write_source && mark_write_complete) {
1958 (*chan)->write_source->mark_streaming_write_completed ();
1960 use_new_write_source (n);
1962 if (record_enabled()) {
1963 capturing_sources.push_back ((*chan)->write_source);
1967 if ((*chan)->write_source == 0) {
1968 use_new_write_source (n);
1973 if (destructive() && !c->empty ()) {
1975 /* we now have all our write sources set up, so create the
1976 playlist's single region.
1979 if (_playlist->empty()) {
1980 setup_destructive_playlist ();
1986 AudioDiskstream::rename_write_sources ()
1988 ChannelList::iterator chan;
1989 boost::shared_ptr<ChannelList> c = channels.reader();
1992 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1993 if ((*chan)->write_source != 0) {
1994 (*chan)->write_source->set_source_name (_name.val(), destructive());
1995 /* XXX what to do if one of them fails ? */
2003 AudioDiskstream::set_block_size (nframes_t /*nframes*/)
2005 if (_session.get_block_size() > speed_buffer_size) {
2006 speed_buffer_size = _session.get_block_size();
2007 boost::shared_ptr<ChannelList> c = channels.reader();
2009 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2010 if ((*chan)->speed_buffer)
2011 delete [] (*chan)->speed_buffer;
2012 (*chan)->speed_buffer = new Sample[speed_buffer_size];
2015 allocate_temporary_buffers ();
2019 AudioDiskstream::allocate_temporary_buffers ()
2021 /* make sure the wrap buffer is at least large enough to deal
2022 with the speeds up to 1.2, to allow for micro-variation
2023 when slaving to MTC, Timecode etc.
2026 double sp = max (fabsf (_actual_speed), 1.2f);
2027 nframes_t required_wrap_size = (nframes_t) floor (_session.get_block_size() * sp) + 1;
2029 if (required_wrap_size > wrap_buffer_size) {
2031 boost::shared_ptr<ChannelList> c = channels.reader();
2033 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2034 if ((*chan)->playback_wrap_buffer)
2035 delete [] (*chan)->playback_wrap_buffer;
2036 (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
2037 if ((*chan)->capture_wrap_buffer)
2038 delete [] (*chan)->capture_wrap_buffer;
2039 (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
2042 wrap_buffer_size = required_wrap_size;
2047 AudioDiskstream::monitor_input (bool yn)
2049 boost::shared_ptr<ChannelList> c = channels.reader();
2051 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2053 if ((*chan)->source) {
2054 (*chan)->source->ensure_monitor_input (yn);
2060 AudioDiskstream::set_align_style_from_io ()
2062 bool have_physical = false;
2068 get_input_sources ();
2070 boost::shared_ptr<ChannelList> c = channels.reader();
2072 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2073 if ((*chan)->source && (*chan)->source->flags() & JackPortIsPhysical) {
2074 have_physical = true;
2079 if (have_physical) {
2080 set_align_style (ExistingMaterial);
2082 set_align_style (CaptureTime);
2087 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2089 while (how_many--) {
2090 c->push_back (new ChannelInfo(_session.butler()->audio_diskstream_buffer_size(), speed_buffer_size, wrap_buffer_size));
2091 interpolation.add_channel_to (_session.butler()->audio_diskstream_buffer_size(), speed_buffer_size);
2094 _n_channels.set(DataType::AUDIO, c->size());
2100 AudioDiskstream::add_channel (uint32_t how_many)
2102 RCUWriter<ChannelList> writer (channels);
2103 boost::shared_ptr<ChannelList> c = writer.get_copy();
2105 return add_channel_to (c, how_many);
2109 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2111 while (how_many-- && !c->empty()) {
2112 // FIXME: crash (thread safe with RCU?)
2113 // memory leak, when disabled.... :(
2116 interpolation.remove_channel_from ();
2119 _n_channels.set(DataType::AUDIO, c->size());
2125 AudioDiskstream::remove_channel (uint32_t how_many)
2127 RCUWriter<ChannelList> writer (channels);
2128 boost::shared_ptr<ChannelList> c = writer.get_copy();
2130 return remove_channel_from (c, how_many);
2134 AudioDiskstream::playback_buffer_load () const
2136 boost::shared_ptr<ChannelList> c = channels.reader();
2138 return (float) ((double) c->front()->playback_buf->read_space()/
2139 (double) c->front()->playback_buf->bufsize());
2143 AudioDiskstream::capture_buffer_load () const
2145 boost::shared_ptr<ChannelList> c = channels.reader();
2147 return (float) ((double) c->front()->capture_buf->write_space()/
2148 (double) c->front()->capture_buf->bufsize());
2152 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2154 const XMLProperty* prop;
2155 XMLNodeList nlist = node.children();
2156 XMLNodeIterator niter;
2157 boost::shared_ptr<AudioFileSource> fs;
2158 boost::shared_ptr<AudioFileSource> first_fs;
2159 SourceList pending_sources;
2162 if ((prop = node.property (X_("at"))) == 0) {
2166 if (sscanf (prop->value().c_str(), "%" PRIu32, &position) != 1) {
2170 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2171 if ((*niter)->name() == X_("file")) {
2173 if ((prop = (*niter)->property (X_("path"))) == 0) {
2177 // This protects sessions from errant CapturingSources in stored sessions
2179 if (stat (prop->value().c_str(), &sbuf)) {
2184 fs = boost::dynamic_pointer_cast<AudioFileSource> (
2185 SourceFactory::createWritable (DataType::AUDIO, _session,
2186 prop->value(), false, _session.frame_rate()));
2189 catch (failed_constructor& err) {
2190 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2191 _name, prop->value())
2196 pending_sources.push_back (fs);
2198 if (first_fs == 0) {
2202 fs->set_captured_for (_name.val());
2206 if (pending_sources.size() == 0) {
2207 /* nothing can be done */
2211 if (pending_sources.size() != _n_channels.n_audio()) {
2212 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2217 boost::shared_ptr<AudioRegion> region;
2223 plist.add (Properties::start, 0);
2224 plist.add (Properties::length, first_fs->length (first_fs->timeline_position()));
2225 plist.add (Properties::name, region_name_from_path (first_fs->name(), true));
2227 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, plist));
2229 region->set_automatic (true);
2230 region->set_whole_file (true);
2231 region->special_set_position (0);
2234 catch (failed_constructor& err) {
2235 error << string_compose (
2236 _("%1: cannot create whole-file region from pending capture sources"),
2242 _playlist->add_region (region, position);
2248 AudioDiskstream::set_non_layered (bool yn)
2250 if (yn != non_layered()) {
2253 _flags = Flag (_flags | NonLayered);
2255 _flags = Flag (_flags & ~NonLayered);
2263 AudioDiskstream::set_destructive (bool yn)
2265 if (yn != destructive()) {
2268 bool bounce_ignored;
2269 /* requestor should already have checked this and
2270 bounced if necessary and desired
2272 if (!can_become_destructive (bounce_ignored)) {
2275 _flags = Flag (_flags | Destructive);
2276 use_destructive_playlist ();
2278 _flags = Flag (_flags & ~Destructive);
2279 reset_write_sources (true, true);
2287 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2290 requires_bounce = false;
2294 /* is there only one region ? */
2296 if (_playlist->n_regions() != 1) {
2297 requires_bounce = true;
2301 boost::shared_ptr<Region> first = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
2303 requires_bounce = false;
2307 /* do the source(s) for the region cover the session start position ? */
2309 if (first->position() != _session.current_start_frame()) {
2310 if (first->start() > _session.current_start_frame()) {
2311 requires_bounce = true;
2316 /* is the source used by only 1 playlist ? */
2318 boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2322 if (_session.playlists->source_use_count (afirst->source()) > 1) {
2323 requires_bounce = true;
2327 requires_bounce = false;
2331 AudioDiskstream::ChannelInfo::ChannelInfo (nframes_t bufsize, nframes_t speed_size, nframes_t wrap_size)
2335 current_capture_buffer = 0;
2336 current_playback_buffer = 0;
2337 curr_capture_cnt = 0;
2339 speed_buffer = new Sample[speed_size];
2340 playback_wrap_buffer = new Sample[wrap_size];
2341 capture_wrap_buffer = new Sample[wrap_size];
2343 playback_buf = new RingBufferNPT<Sample> (bufsize);
2344 capture_buf = new RingBufferNPT<Sample> (bufsize);
2345 capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2347 /* touch the ringbuffer buffers, which will cause
2348 them to be mapped into locked physical RAM if
2349 we're running with mlockall(). this doesn't do
2353 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2354 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2355 memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2358 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2361 write_source.reset ();
2364 delete [] speed_buffer;
2367 delete [] playback_wrap_buffer;
2368 playback_wrap_buffer = 0;
2370 delete [] capture_wrap_buffer;
2371 capture_wrap_buffer = 0;
2373 delete playback_buf;
2379 delete capture_transition_buf;
2380 capture_transition_buf = 0;