2 Copyright (C) 2000-2006 Paul Davis
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
33 #include "pbd/error.h"
34 #include <glibmm/thread.h>
35 #include "pbd/xml++.h"
36 #include "pbd/memento_command.h"
37 #include "pbd/enumwriter.h"
38 #include "pbd/stacktrace.h"
40 #include "ardour/ardour.h"
41 #include "ardour/audioengine.h"
42 #include "ardour/analyser.h"
43 #include "ardour/audio_diskstream.h"
44 #include "ardour/utils.h"
45 #include "ardour/configuration.h"
46 #include "ardour/audiofilesource.h"
47 #include "ardour/send.h"
48 #include "ardour/region_factory.h"
49 #include "ardour/audioplaylist.h"
50 #include "ardour/playlist_factory.h"
51 #include "ardour/cycle_timer.h"
52 #include "ardour/audioregion.h"
53 #include "ardour/audio_port.h"
54 #include "ardour/source_factory.h"
55 #include "ardour/audio_buffer.h"
56 #include "ardour/session.h"
57 #include "ardour/io.h"
63 using namespace ARDOUR;
66 size_t AudioDiskstream::_working_buffers_size = 0;
67 Sample* AudioDiskstream::_mixdown_buffer = 0;
68 gain_t* AudioDiskstream::_gain_buffer = 0;
70 AudioDiskstream::AudioDiskstream (Session &sess, const string &name, Diskstream::Flag flag)
71 : Diskstream(sess, name, flag)
72 , deprecated_io_node(NULL)
73 , channels (new ChannelList)
75 /* prevent any write sources from being created */
85 AudioDiskstream::AudioDiskstream (Session& sess, const XMLNode& node)
86 : Diskstream(sess, node)
87 , deprecated_io_node(NULL)
88 , channels (new ChannelList)
93 if (set_state (node, Stateful::loading_state_version)) {
95 throw failed_constructor();
101 use_destructive_playlist ();
106 AudioDiskstream::init (Diskstream::Flag f)
110 /* there are no channels at this point, so these
111 two calls just get speed_buffer_size and wrap_buffer
112 size setup without duplicating their code.
115 set_block_size (_session.get_block_size());
116 allocate_temporary_buffers ();
119 assert(_n_channels == ChanCount(DataType::AUDIO, 1));
122 AudioDiskstream::~AudioDiskstream ()
127 RCUWriter<ChannelList> writer (channels);
128 boost::shared_ptr<ChannelList> c = writer.get_copy();
130 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
141 AudioDiskstream::allocate_working_buffers()
143 assert(disk_io_frames() > 0);
145 _working_buffers_size = disk_io_frames();
146 _mixdown_buffer = new Sample[_working_buffers_size];
147 _gain_buffer = new gain_t[_working_buffers_size];
151 AudioDiskstream::free_working_buffers()
153 delete [] _mixdown_buffer;
154 delete [] _gain_buffer;
155 _working_buffers_size = 0;
161 AudioDiskstream::non_realtime_input_change ()
164 Glib::Mutex::Lock lm (state_lock);
166 if (input_change_pending == NoChange) {
171 RCUWriter<ChannelList> writer (channels);
172 boost::shared_ptr<ChannelList> c = writer.get_copy();
174 _n_channels.set(DataType::AUDIO, c->size());
176 if (_io->n_ports().n_audio() > _n_channels.n_audio()) {
177 add_channel_to (c, _io->n_ports().n_audio() - _n_channels.n_audio());
178 } else if (_io->n_ports().n_audio() < _n_channels.n_audio()) {
179 remove_channel_from (c, _n_channels.n_audio() - _io->n_ports().n_audio());
183 get_input_sources ();
184 set_capture_offset ();
186 if (first_input_change) {
187 set_align_style (_persistent_alignment_style);
188 first_input_change = false;
190 set_align_style_from_io ();
193 input_change_pending = NoChange;
195 /* implicit unlock */
198 /* reset capture files */
200 reset_write_sources (false);
202 /* now refill channel buffers */
204 if (speed() != 1.0f || speed() != -1.0f) {
205 seek ((nframes_t) (_session.transport_frame() * (double) speed()));
207 seek (_session.transport_frame());
212 AudioDiskstream::non_realtime_locate (nframes_t location)
214 /* now refill channel buffers */
216 if (speed() != 1.0f || speed() != -1.0f) {
217 seek ((nframes_t) (location * (double) speed()));
224 AudioDiskstream::get_input_sources ()
226 boost::shared_ptr<ChannelList> c = channels.reader();
229 ChannelList::iterator chan;
230 uint32_t ni = _io->n_ports().n_audio();
231 vector<string> connections;
233 for (n = 0, chan = c->begin(); chan != c->end() && n < ni; ++chan, ++n) {
235 connections.clear ();
237 if (_io->nth (n)->get_connections (connections) == 0) {
239 if ((*chan)->source) {
240 // _source->disable_metering ();
246 (*chan)->source = dynamic_cast<AudioPort*>(_session.engine().get_port_by_name (connections[0]) );
252 AudioDiskstream::find_and_use_playlist (const string& name)
254 boost::shared_ptr<AudioPlaylist> playlist;
256 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (_session.playlist_by_name (name))) == 0) {
257 playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, name));
261 error << string_compose(_("AudioDiskstream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
265 return use_playlist (playlist);
269 AudioDiskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
271 assert(boost::dynamic_pointer_cast<AudioPlaylist>(playlist));
273 Diskstream::use_playlist(playlist);
279 AudioDiskstream::use_new_playlist ()
282 boost::shared_ptr<AudioPlaylist> playlist;
284 if (!in_set_state && destructive()) {
289 newname = Playlist::bump_name (_playlist->name(), _session);
291 newname = Playlist::bump_name (_name, _session);
294 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, newname, hidden()))) != 0) {
296 playlist->set_orig_diskstream_id (id());
297 return use_playlist (playlist);
305 AudioDiskstream::use_copy_playlist ()
307 assert(audio_playlist());
313 if (_playlist == 0) {
314 error << string_compose(_("AudioDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
319 boost::shared_ptr<AudioPlaylist> playlist;
321 newname = Playlist::bump_name (_playlist->name(), _session);
323 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist>(PlaylistFactory::create (audio_playlist(), newname))) != 0) {
324 playlist->set_orig_diskstream_id (id());
325 return use_playlist (playlist);
332 AudioDiskstream::setup_destructive_playlist ()
335 boost::shared_ptr<ChannelList> c = channels.reader();
337 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
338 srcs.push_back ((*chan)->write_source);
341 /* a single full-sized region */
343 boost::shared_ptr<Region> region (RegionFactory::create (srcs, 0, max_frames - srcs.front()->natural_position(), _name));
344 _playlist->add_region (region, srcs.front()->natural_position());
348 AudioDiskstream::use_destructive_playlist ()
350 /* this is called from the XML-based constructor or ::set_destructive. when called,
351 we already have a playlist and a region, but we need to
352 set up our sources for write. we use the sources associated
353 with the (presumed single, full-extent) region.
356 boost::shared_ptr<Region> rp = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
359 reset_write_sources (false, true);
363 boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
366 throw failed_constructor();
369 /* be sure to stretch the region out to the maximum length */
371 region->set_length (max_frames - region->position(), this);
374 ChannelList::iterator chan;
375 boost::shared_ptr<ChannelList> c = channels.reader();
377 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
378 (*chan)->write_source = boost::dynamic_pointer_cast<AudioFileSource>(region->source (n));
379 assert((*chan)->write_source);
380 (*chan)->write_source->set_allow_remove_if_empty (false);
382 /* this might be false if we switched modes, so force it */
384 (*chan)->write_source->set_destructive (true);
387 /* the source list will never be reset for a destructive track */
391 AudioDiskstream::prepare_record_status(nframes_t capture_start_frame)
393 if (recordable() && destructive()) {
394 boost::shared_ptr<ChannelList> c = channels.reader();
395 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
397 RingBufferNPT<CaptureTransition>::rw_vector transvec;
398 (*chan)->capture_transition_buf->get_write_vector(&transvec);
400 if (transvec.len[0] > 0) {
401 transvec.buf[0]->type = CaptureStart;
402 transvec.buf[0]->capture_val = capture_start_frame;
403 (*chan)->capture_transition_buf->increment_write_ptr(1);
407 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
415 AudioDiskstream::process (nframes_t transport_frame, nframes_t nframes, bool can_record, bool rec_monitors_input)
418 boost::shared_ptr<ChannelList> c = channels.reader();
419 ChannelList::iterator chan;
421 nframes_t rec_offset = 0;
422 nframes_t rec_nframes = 0;
423 bool nominally_recording;
424 bool re = record_enabled ();
425 bool collect_playback = false;
427 /* if we've already processed the frames corresponding to this call,
428 just return. this allows multiple routes that are taking input
429 from this diskstream to call our ::process() method, but have
430 this stuff only happen once. more commonly, it allows both
431 the AudioTrack that is using this AudioDiskstream *and* the Session
432 to call process() without problems.
439 commit_should_unlock = false;
441 if (!_io || !_io->active()) {
446 check_record_status (transport_frame, nframes, can_record);
448 nominally_recording = (can_record && re);
455 /* This lock is held until the end of AudioDiskstream::commit, so these two functions
456 must always be called as a pair. The only exception is if this function
457 returns a non-zero value, in which case, ::commit should not be called.
460 // If we can't take the state lock return.
461 if (!state_lock.trylock()) {
464 commit_should_unlock = true;
465 adjust_capture_position = 0;
467 for (chan = c->begin(); chan != c->end(); ++chan) {
468 (*chan)->current_capture_buffer = 0;
469 (*chan)->current_playback_buffer = 0;
472 if (nominally_recording || (_session.get_record_enabled() && _session.config.get_punch_in())) {
473 // Safeguard against situations where process() goes haywire when autopunching and last_recordable_frame < first_recordable_frame
474 if (last_recordable_frame < first_recordable_frame) {
475 last_recordable_frame = max_frames;
478 OverlapType ot = coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
480 calculate_record_range(ot, transport_frame, nframes, rec_nframes, rec_offset);
482 if (rec_nframes && !was_recording) {
483 capture_captured = 0;
484 was_recording = true;
489 if (can_record && !_last_capture_regions.empty()) {
490 _last_capture_regions.clear ();
493 if (nominally_recording || rec_nframes) {
495 uint32_t limit = _io->n_ports ().n_audio();
497 /* one or more ports could already have been removed from _io, but our
498 channel setup hasn't yet been updated. prevent us from trying to
499 use channels that correspond to missing ports. note that the
500 process callback (from which this is called) is always atomic
501 with respect to port removal/addition.
504 for (n = 0, chan = c->begin(); chan != c->end() && n < limit; ++chan, ++n) {
506 ChannelInfo* chaninfo (*chan);
508 chaninfo->capture_buf->get_write_vector (&chaninfo->capture_vector);
510 if (rec_nframes <= chaninfo->capture_vector.len[0]) {
512 chaninfo->current_capture_buffer = chaninfo->capture_vector.buf[0];
514 /* note: grab the entire port buffer, but only copy what we were supposed to
515 for recording, and use rec_offset
518 AudioPort* const ap = _io->audio (n);
520 assert(rec_nframes <= ap->get_audio_buffer(nframes).capacity());
521 memcpy (chaninfo->current_capture_buffer, ap->get_audio_buffer (rec_nframes).data(rec_offset), sizeof (Sample) * rec_nframes);
526 nframes_t total = chaninfo->capture_vector.len[0] + chaninfo->capture_vector.len[1];
528 if (rec_nframes > total) {
533 AudioPort* const ap = _io->audio (n);
536 Sample* buf = ap->get_audio_buffer(nframes).data();
537 nframes_t first = chaninfo->capture_vector.len[0];
539 memcpy (chaninfo->capture_wrap_buffer, buf, sizeof (Sample) * first);
540 memcpy (chaninfo->capture_vector.buf[0], buf, sizeof (Sample) * first);
541 memcpy (chaninfo->capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
542 memcpy (chaninfo->capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
544 chaninfo->current_capture_buffer = chaninfo->capture_wrap_buffer;
551 finish_capture (rec_monitors_input, c);
558 /* data will be written to disk */
560 if (rec_nframes == nframes && rec_offset == 0) {
562 for (chan = c->begin(); chan != c->end(); ++chan) {
563 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
566 playback_distance = nframes;
571 /* we can't use the capture buffer as the playback buffer, because
572 we recorded only a part of the current process' cycle data
576 collect_playback = true;
579 adjust_capture_position = rec_nframes;
581 } else if (nominally_recording) {
583 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
585 for (chan = c->begin(); chan != c->end(); ++chan) {
586 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
589 playback_distance = nframes;
593 collect_playback = true;
596 if (collect_playback) {
598 /* we're doing playback */
600 nframes_t necessary_samples;
602 /* no varispeed playback if we're recording, because the output .... TBD */
604 if (rec_nframes == 0 && _actual_speed != 1.0f) {
605 necessary_samples = (nframes_t) floor ((nframes * fabs (_actual_speed))) + 1;
607 necessary_samples = nframes;
610 for (chan = c->begin(); chan != c->end(); ++chan) {
611 (*chan)->playback_buf->get_read_vector (&(*chan)->playback_vector);
616 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
618 ChannelInfo* chaninfo (*chan);
620 if (necessary_samples <= chaninfo->playback_vector.len[0]) {
622 chaninfo->current_playback_buffer = chaninfo->playback_vector.buf[0];
625 nframes_t total = chaninfo->playback_vector.len[0] + chaninfo->playback_vector.len[1];
627 if (necessary_samples > total) {
628 cerr << "underrun for " << _name << endl;
634 memcpy ((char *) chaninfo->playback_wrap_buffer,
635 chaninfo->playback_vector.buf[0],
636 chaninfo->playback_vector.len[0] * sizeof (Sample));
637 memcpy (chaninfo->playback_wrap_buffer + chaninfo->playback_vector.len[0],
638 chaninfo->playback_vector.buf[1],
639 (necessary_samples - chaninfo->playback_vector.len[0])
642 chaninfo->current_playback_buffer = chaninfo->playback_wrap_buffer;
647 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
648 process_varispeed_playback(nframes, c);
650 playback_distance = nframes;
653 _speed = _target_speed;
664 /* we're exiting with failure, so ::commit will not
665 be called. unlock the state lock.
668 commit_should_unlock = false;
676 AudioDiskstream::process_varispeed_playback(nframes_t nframes, boost::shared_ptr<ChannelList> c)
678 ChannelList::iterator chan;
680 interpolation.set_speed (_target_speed);
683 for (chan = c->begin(); chan != c->end(); ++chan, ++channel) {
684 ChannelInfo* chaninfo (*chan);
686 playback_distance = interpolation.interpolate (
687 channel, nframes, chaninfo->current_playback_buffer, chaninfo->speed_buffer);
689 chaninfo->current_playback_buffer = chaninfo->speed_buffer;
694 AudioDiskstream::commit (nframes_t /*nframes*/)
696 bool need_butler = false;
698 if (!_io || !_io->active()) {
702 if (_actual_speed < 0.0) {
703 playback_sample -= playback_distance;
705 playback_sample += playback_distance;
708 boost::shared_ptr<ChannelList> c = channels.reader();
709 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
711 (*chan)->playback_buf->increment_read_ptr (playback_distance);
713 if (adjust_capture_position) {
714 (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
718 if (adjust_capture_position != 0) {
719 capture_captured += adjust_capture_position;
720 adjust_capture_position = 0;
724 if (_io && _io->active()) {
725 need_butler = c->front()->playback_buf->write_space() >= c->front()->playback_buf->bufsize() / 2;
730 if (_io && _io->active()) {
731 need_butler = c->front()->playback_buf->write_space() >= disk_io_chunk_frames
732 || c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
734 need_butler = c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
738 if (commit_should_unlock) {
748 AudioDiskstream::set_pending_overwrite (bool yn)
750 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
752 pending_overwrite = yn;
754 overwrite_frame = playback_sample;
755 overwrite_offset = channels.reader()->front()->playback_buf->get_read_ptr();
759 AudioDiskstream::overwrite_existing_buffers ()
761 boost::shared_ptr<ChannelList> c = channels.reader();
762 Sample* mixdown_buffer;
765 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
767 overwrite_queued = false;
769 /* assume all are the same size */
770 nframes_t size = c->front()->playback_buf->bufsize();
772 mixdown_buffer = new Sample[size];
773 gain_buffer = new float[size];
775 /* reduce size so that we can fill the buffer correctly. */
781 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
783 start = overwrite_frame;
784 nframes_t cnt = size;
786 /* to fill the buffer without resetting the playback sample, we need to
787 do it one or two chunks (normally two).
789 |----------------------------------------------------------------------|
793 |<- second chunk->||<----------------- first chunk ------------------>|
797 nframes_t to_read = size - overwrite_offset;
799 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, *chan, n, reversed)) {
800 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
801 _id, size, playback_sample) << endmsg;
809 if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer,
810 start, cnt, *chan, n, reversed)) {
811 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
812 _id, size, playback_sample) << endmsg;
821 pending_overwrite = false;
822 delete [] gain_buffer;
823 delete [] mixdown_buffer;
828 AudioDiskstream::seek (nframes_t frame, bool complete_refill)
832 ChannelList::iterator chan;
833 boost::shared_ptr<ChannelList> c = channels.reader();
835 Glib::Mutex::Lock lm (state_lock);
837 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
838 (*chan)->playback_buf->reset ();
839 (*chan)->capture_buf->reset ();
842 /* can't rec-enable in destructive mode if transport is before start */
844 if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
845 disengage_record_enable ();
848 playback_sample = frame;
851 if (complete_refill) {
852 while ((ret = do_refill_with_alloc ()) > 0) ;
854 ret = do_refill_with_alloc ();
861 AudioDiskstream::can_internal_playback_seek (nframes_t distance)
863 ChannelList::iterator chan;
864 boost::shared_ptr<ChannelList> c = channels.reader();
866 for (chan = c->begin(); chan != c->end(); ++chan) {
867 if ((*chan)->playback_buf->read_space() < distance) {
875 AudioDiskstream::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 (*chan)->playback_buf->increment_read_ptr (distance);
884 first_recordable_frame += distance;
885 playback_sample += distance;
891 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer, nframes_t& start, nframes_t cnt,
892 ChannelInfo* /*channel_info*/, int channel, bool reversed)
894 nframes_t this_read = 0;
896 nframes_t loop_end = 0;
897 nframes_t loop_start = 0;
898 nframes_t loop_length = 0;
899 nframes_t offset = 0;
902 /* XXX we don't currently play loops in reverse. not sure why */
906 /* Make the use of a Location atomic for this read operation.
908 Note: Locations don't get deleted, so all we care about
909 when I say "atomic" is that we are always pointing to
910 the same one and using a start/length values obtained
914 if ((loc = loop_location) != 0) {
915 loop_start = loc->start();
916 loop_end = loc->end();
917 loop_length = loop_end - loop_start;
920 /* if we are looping, ensure that the first frame we read is at the correct
921 position within the loop.
924 if (loc && start >= loop_end) {
925 //cerr << "start adjusted from " << start;
926 start = loop_start + ((start - loop_start) % loop_length);
927 //cerr << "to " << start << endl;
930 //cerr << "start is " << start << " loopstart: " << loop_start << " loopend: " << loop_end << endl;
939 /* take any loop into account. we can't read past the end of the loop. */
941 if (loc && (loop_end - start < cnt)) {
942 this_read = loop_end - start;
943 //cerr << "reloop true: thisread: " << this_read << " cnt: " << cnt << endl;
950 if (this_read == 0) {
954 this_read = min(cnt,this_read);
956 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
957 error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), _id, this_read,
962 _read_data_count = _playlist->read_data_count();
966 swap_by_ptr (buf, buf + this_read - 1);
970 /* if we read to the end of the loop, go back to the beginning */
987 AudioDiskstream::do_refill_with_alloc ()
989 Sample* mix_buf = new Sample[disk_io_chunk_frames];
990 float* gain_buf = new float[disk_io_chunk_frames];
992 int ret = _do_refill(mix_buf, gain_buf);
1001 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer)
1005 RingBufferNPT<Sample>::rw_vector vector;
1006 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1007 nframes_t total_space;
1008 nframes_t zero_fill;
1010 ChannelList::iterator i;
1011 boost::shared_ptr<ChannelList> c = channels.reader();
1018 assert(mixdown_buffer);
1019 assert(gain_buffer);
1026 c->front()->playback_buf->get_write_vector (&vector);
1028 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1032 /* if there are 2+ chunks of disk i/o possible for
1033 this track, let the caller know so that it can arrange
1034 for us to be called again, ASAP.
1037 if (total_space >= (_slaved?3:2) * disk_io_chunk_frames) {
1041 /* if we're running close to normal speed and there isn't enough
1042 space to do disk_io_chunk_frames of I/O, then don't bother.
1044 at higher speeds, just do it because the sync between butler
1045 and audio thread may not be good enough.
1048 if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1052 /* when slaved, don't try to get too close to the read pointer. this
1053 leaves space for the buffer reversal to have something useful to
1057 if (_slaved && total_space < (c->front()->playback_buf->bufsize() / 2)) {
1061 /* never do more than disk_io_chunk_frames worth of disk input per call (limit doesn't apply for memset) */
1063 total_space = min (disk_io_chunk_frames, total_space);
1067 if (file_frame == 0) {
1069 /* at start: nothing to do but fill with silence */
1071 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1073 ChannelInfo* chan (*i);
1074 chan->playback_buf->get_write_vector (&vector);
1075 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1076 if (vector.len[1]) {
1077 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1079 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1084 if (file_frame < total_space) {
1086 /* too close to the start: read what we can,
1087 and then zero fill the rest
1090 zero_fill = total_space - file_frame;
1091 total_space = file_frame;
1101 if (file_frame == max_frames) {
1103 /* at end: nothing to do but fill with silence */
1105 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1107 ChannelInfo* chan (*i);
1108 chan->playback_buf->get_write_vector (&vector);
1109 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1110 if (vector.len[1]) {
1111 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1113 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1118 if (file_frame > max_frames - total_space) {
1120 /* to close to the end: read what we can, and zero fill the rest */
1122 zero_fill = total_space - (max_frames - file_frame);
1123 total_space = max_frames - file_frame;
1130 nframes_t file_frame_tmp = 0;
1132 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1134 ChannelInfo* chan (*i);
1137 nframes_t len1, len2;
1139 chan->playback_buf->get_write_vector (&vector);
1141 if (vector.len[0] > disk_io_chunk_frames) {
1143 /* we're not going to fill the first chunk, so certainly do not bother with the
1144 other part. it won't be connected with the part we do fill, as in:
1146 .... => writable space
1147 ++++ => readable space
1148 ^^^^ => 1 x disk_io_chunk_frames that would be filled
1150 |......|+++++++++++++|...............................|
1155 So, just pretend that the buf1 part isn't there.
1165 file_frame_tmp = file_frame;
1167 buf1 = vector.buf[0];
1168 len1 = vector.len[0];
1169 buf2 = vector.buf[1];
1170 len2 = vector.len[1];
1172 to_read = min (ts, len1);
1173 to_read = min (to_read, disk_io_chunk_frames);
1177 if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1182 chan->playback_buf->increment_write_ptr (to_read);
1186 to_read = min (ts, len2);
1190 /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1191 so read some or all of vector.len[1] as well.
1194 if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1199 chan->playback_buf->increment_write_ptr (to_read);
1208 file_frame = file_frame_tmp;
1215 /** Flush pending data to disk.
1217 * Important note: this function will write *AT MOST* disk_io_chunk_frames
1218 * of data to disk. it will never write more than that. If it writes that
1219 * much and there is more than that waiting to be written, it will return 1,
1220 * otherwise 0 on success or -1 on failure.
1222 * If there is less than disk_io_chunk_frames to be written, no data will be
1223 * written at all unless @a force_flush is true.
1226 AudioDiskstream::do_flush (RunContext /*context*/, bool force_flush)
1230 RingBufferNPT<Sample>::rw_vector vector;
1231 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1234 _write_data_count = 0;
1236 transvec.buf[0] = 0;
1237 transvec.buf[1] = 0;
1241 boost::shared_ptr<ChannelList> c = channels.reader();
1242 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1244 (*chan)->capture_buf->get_read_vector (&vector);
1246 total = vector.len[0] + vector.len[1];
1248 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1252 /* if there are 2+ chunks of disk i/o possible for
1253 this track, let the caller know so that it can arrange
1254 for us to be called again, ASAP.
1256 if we are forcing a flush, then if there is* any* extra
1257 work, let the caller know.
1259 if we are no longer recording and there is any extra work,
1260 let the caller know too.
1263 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1267 to_write = min (disk_io_chunk_frames, (nframes_t) vector.len[0]);
1269 // check the transition buffer when recording destructive
1270 // important that we get this after the capture buf
1272 if (destructive()) {
1273 (*chan)->capture_transition_buf->get_read_vector(&transvec);
1274 size_t transcount = transvec.len[0] + transvec.len[1];
1275 bool have_start = false;
1278 for (ti=0; ti < transcount; ++ti) {
1279 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1281 if (captrans.type == CaptureStart) {
1282 // by definition, the first data we got above represents the given capture pos
1284 (*chan)->write_source->mark_capture_start (captrans.capture_val);
1285 (*chan)->curr_capture_cnt = 0;
1289 else if (captrans.type == CaptureEnd) {
1291 // capture end, the capture_val represents total frames in capture
1293 if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1295 // shorten to make the write a perfect fit
1296 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
1298 if (nto_write < to_write) {
1299 ret = 1; // should we?
1301 to_write = nto_write;
1303 (*chan)->write_source->mark_capture_end ();
1305 // increment past this transition, but go no further
1310 // actually ends just beyond this chunk, so force more work
1318 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1322 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1323 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1327 (*chan)->capture_buf->increment_read_ptr (to_write);
1328 (*chan)->curr_capture_cnt += to_write;
1330 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1332 /* we wrote all of vector.len[0] but it wasn't an entire
1333 disk_io_chunk_frames of data, so arrange for some part
1334 of vector.len[1] to be flushed to disk as well.
1337 to_write = min ((nframes_t)(disk_io_chunk_frames - to_write), (nframes_t) vector.len[1]);
1339 if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1340 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1344 _write_data_count += (*chan)->write_source->write_data_count();
1346 (*chan)->capture_buf->increment_read_ptr (to_write);
1347 (*chan)->curr_capture_cnt += to_write;
1356 AudioDiskstream::transport_stopped (struct tm& when, time_t twhen, bool abort_capture)
1358 uint32_t buffer_position;
1359 bool more_work = true;
1361 boost::shared_ptr<AudioRegion> region;
1362 nframes_t total_capture;
1364 SourceList::iterator src;
1365 ChannelList::iterator chan;
1366 vector<CaptureInfo*>::iterator ci;
1367 boost::shared_ptr<ChannelList> c = channels.reader();
1369 bool mark_write_completed = false;
1371 finish_capture (true, c);
1373 /* butler is already stopped, but there may be work to do
1374 to flush remaining data to disk.
1377 while (more_work && !err) {
1378 switch (do_flush (TransportContext, true)) {
1385 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1390 /* XXX is there anything we can do if err != 0 ? */
1391 Glib::Mutex::Lock lm (capture_info_lock);
1393 if (capture_info.empty()) {
1397 if (abort_capture) {
1399 if (destructive()) {
1403 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1405 if ((*chan)->write_source) {
1407 (*chan)->write_source->mark_for_remove ();
1408 (*chan)->write_source->drop_references ();
1409 (*chan)->write_source.reset ();
1412 /* new source set up in "out" below */
1418 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1419 total_capture += (*ci)->frames;
1422 /* figure out the name for this take */
1424 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1426 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1430 s->update_header (capture_info.front()->start, when, twhen);
1431 s->set_captured_for (_name);
1432 s->mark_immutable ();
1433 if (Config->get_auto_analyse_audio()) {
1434 Analyser::queue_source_for_analysis (s, true);
1439 /* destructive tracks have a single, never changing region */
1441 if (destructive()) {
1443 /* send a signal that any UI can pick up to do the right thing. there is
1444 a small problem here in that a UI may need the peak data to be ready
1445 for the data that was recorded and this isn't interlocked with that
1446 process. this problem is deferred to the UI.
1449 _playlist->Modified();
1453 string whole_file_region_name;
1454 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1456 /* Register a new region with the Session that
1457 describes the entire source. Do this first
1458 so that any sub-regions will obviously be
1459 children of this one (later!)
1463 boost::shared_ptr<Region> rx (RegionFactory::create (srcs,
1464 c->front()->write_source->last_capture_start_frame(), total_capture,
1465 whole_file_region_name, 0,
1466 Region::Flag (Region::DefaultFlags|Region::Automatic|Region::WholeFile)));
1468 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1469 region->special_set_position (capture_info.front()->start);
1473 catch (failed_constructor& err) {
1474 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1478 _last_capture_regions.push_back (region);
1480 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1482 XMLNode &before = _playlist->get_state();
1483 _playlist->freeze ();
1485 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1489 _session.region_name (region_name, whole_file_region_name, false);
1491 // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->frames << " add region " << region_name << endl;
1494 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, buffer_position, (*ci)->frames, region_name));
1495 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1498 catch (failed_constructor& err) {
1499 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1500 continue; /* XXX is this OK? */
1503 region->GoingAway.connect (bind (mem_fun (*this, &Diskstream::remove_region_from_last_capture), boost::weak_ptr<Region>(region)));
1505 _last_capture_regions.push_back (region);
1507 i_am_the_modifier++;
1508 _playlist->add_region (region, (*ci)->start, 1, non_layered());
1509 i_am_the_modifier--;
1511 buffer_position += (*ci)->frames;
1515 XMLNode &after = _playlist->get_state();
1516 _session.add_command (new MementoCommand<Playlist>(*_playlist, &before, &after));
1519 mark_write_completed = true;
1522 reset_write_sources (mark_write_completed);
1526 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1530 capture_info.clear ();
1531 capture_start_frame = 0;
1535 AudioDiskstream::transport_looped (nframes_t transport_frame)
1537 if (was_recording) {
1538 // all we need to do is finish this capture, with modified capture length
1539 boost::shared_ptr<ChannelList> c = channels.reader();
1541 // adjust the capture length knowing that the data will be recorded to disk
1542 // only necessary after the first loop where we're recording
1543 if (capture_info.size() == 0) {
1544 capture_captured += _capture_offset;
1546 if (_alignment_style == ExistingMaterial) {
1547 capture_captured += _session.worst_output_latency();
1549 capture_captured += _roll_delay;
1553 finish_capture (true, c);
1555 // the next region will start recording via the normal mechanism
1556 // we'll set the start position to the current transport pos
1557 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1558 capture_start_frame = transport_frame;
1559 first_recordable_frame = transport_frame; // mild lie
1560 last_recordable_frame = max_frames;
1561 was_recording = true;
1563 if (recordable() && destructive()) {
1564 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1566 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1567 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1569 if (transvec.len[0] > 0) {
1570 transvec.buf[0]->type = CaptureStart;
1571 transvec.buf[0]->capture_val = capture_start_frame;
1572 (*chan)->capture_transition_buf->increment_write_ptr(1);
1576 fatal << X_("programming error: capture_transition_buf is full on rec loop! inconceivable!")
1586 AudioDiskstream::finish_capture (bool /*rec_monitors_input*/, boost::shared_ptr<ChannelList> c)
1588 was_recording = false;
1590 if (capture_captured == 0) {
1594 if (recordable() && destructive()) {
1595 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1597 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1598 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1600 if (transvec.len[0] > 0) {
1601 transvec.buf[0]->type = CaptureEnd;
1602 transvec.buf[0]->capture_val = capture_captured;
1603 (*chan)->capture_transition_buf->increment_write_ptr(1);
1607 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1613 CaptureInfo* ci = new CaptureInfo;
1615 ci->start = capture_start_frame;
1616 ci->frames = capture_captured;
1618 /* XXX theoretical race condition here. Need atomic exchange ?
1619 However, the circumstances when this is called right
1620 now (either on record-disable or transport_stopped)
1621 mean that no actual race exists. I think ...
1622 We now have a capture_info_lock, but it is only to be used
1623 to synchronize in the transport_stop and the capture info
1624 accessors, so that invalidation will not occur (both non-realtime).
1627 // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1629 capture_info.push_back (ci);
1630 capture_captured = 0;
1632 /* now we've finished a capture, reset first_recordable_frame for next time */
1633 first_recordable_frame = max_frames;
1637 AudioDiskstream::set_record_enabled (bool yn)
1639 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0) {
1643 /* can't rec-enable in destructive mode if transport is before start */
1645 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1649 if (yn && channels.reader()->front()->source == 0) {
1651 /* pick up connections not initiated *from* the IO object
1652 we're associated with.
1655 get_input_sources ();
1658 /* yes, i know that this not proof against race conditions, but its
1659 good enough. i think.
1662 if (record_enabled() != yn) {
1664 engage_record_enable ();
1666 disengage_record_enable ();
1672 AudioDiskstream::engage_record_enable ()
1674 bool rolling = _session.transport_speed() != 0.0f;
1675 boost::shared_ptr<ChannelList> c = channels.reader();
1677 g_atomic_int_set (&_record_enabled, 1);
1678 capturing_sources.clear ();
1680 if (Config->get_monitoring_model() == HardwareMonitoring) {
1682 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1683 if ((*chan)->source) {
1684 (*chan)->source->ensure_monitor_input (!(_session.config.get_auto_input() && rolling));
1686 capturing_sources.push_back ((*chan)->write_source);
1687 (*chan)->write_source->mark_streaming_write_started ();
1691 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1692 capturing_sources.push_back ((*chan)->write_source);
1693 (*chan)->write_source->mark_streaming_write_started ();
1697 RecordEnableChanged (); /* EMIT SIGNAL */
1701 AudioDiskstream::disengage_record_enable ()
1703 g_atomic_int_set (&_record_enabled, 0);
1704 boost::shared_ptr<ChannelList> c = channels.reader();
1705 if (Config->get_monitoring_model() == HardwareMonitoring) {
1706 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1707 if ((*chan)->source) {
1708 (*chan)->source->ensure_monitor_input (false);
1712 capturing_sources.clear ();
1713 RecordEnableChanged (); /* EMIT SIGNAL */
1717 AudioDiskstream::get_state ()
1719 XMLNode* node = new XMLNode ("AudioDiskstream");
1721 LocaleGuard lg (X_("POSIX"));
1722 boost::shared_ptr<ChannelList> c = channels.reader();
1724 node->add_property ("flags", enum_2_string (_flags));
1726 snprintf (buf, sizeof(buf), "%zd", c->size());
1727 node->add_property ("channels", buf);
1729 node->add_property ("playlist", _playlist->name());
1731 snprintf (buf, sizeof(buf), "%.12g", _visible_speed);
1732 node->add_property ("speed", buf);
1734 node->add_property("name", _name);
1735 id().print (buf, sizeof (buf));
1736 node->add_property("id", buf);
1738 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1740 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1741 XMLNode* cs_grandchild;
1743 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1744 cs_grandchild = new XMLNode (X_("file"));
1745 cs_grandchild->add_property (X_("path"), (*i)->path());
1746 cs_child->add_child_nocopy (*cs_grandchild);
1749 /* store the location where capture will start */
1753 if (_session.config.get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1754 snprintf (buf, sizeof (buf), "%" PRId64, pi->start());
1756 snprintf (buf, sizeof (buf), "%" PRIu32, _session.transport_frame());
1759 cs_child->add_property (X_("at"), buf);
1760 node->add_child_nocopy (*cs_child);
1764 node->add_child_copy (*_extra_xml);
1771 AudioDiskstream::set_state (const XMLNode& node, int /*version*/)
1773 const XMLProperty* prop;
1774 XMLNodeList nlist = node.children();
1775 XMLNodeIterator niter;
1776 uint32_t nchans = 1;
1777 XMLNode* capture_pending_node = 0;
1778 LocaleGuard lg (X_("POSIX"));
1780 in_set_state = true;
1782 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1783 if ((*niter)->name() == IO::state_node_name) {
1784 deprecated_io_node = new XMLNode (**niter);
1787 if ((*niter)->name() == X_("CapturingSources")) {
1788 capture_pending_node = *niter;
1792 /* prevent write sources from being created */
1794 in_set_state = true;
1796 if ((prop = node.property ("name")) != 0) {
1797 _name = prop->value();
1800 if (deprecated_io_node) {
1801 if ((prop = deprecated_io_node->property ("id")) != 0) {
1802 _id = prop->value ();
1805 if ((prop = node.property ("id")) != 0) {
1806 _id = prop->value ();
1810 if ((prop = node.property ("flags")) != 0) {
1811 _flags = Flag (string_2_enum (prop->value(), _flags));
1814 if ((prop = node.property ("channels")) != 0) {
1815 nchans = atoi (prop->value().c_str());
1818 // create necessary extra channels
1819 // we are always constructed with one and we always need one
1821 _n_channels.set(DataType::AUDIO, channels.reader()->size());
1823 if (nchans > _n_channels.n_audio()) {
1825 add_channel (nchans - _n_channels.n_audio());
1826 IO::PortCountChanged(_n_channels);
1828 } else if (nchans < _n_channels.n_audio()) {
1830 remove_channel (_n_channels.n_audio() - nchans);
1833 if ((prop = node.property ("playlist")) == 0) {
1838 bool had_playlist = (_playlist != 0);
1840 if (find_and_use_playlist (prop->value())) {
1844 if (!had_playlist) {
1845 _playlist->set_orig_diskstream_id (_id);
1848 if (!destructive() && capture_pending_node) {
1849 /* destructive streams have one and only one source per channel,
1850 and so they never end up in pending capture in any useful
1853 use_pending_capture_data (*capture_pending_node);
1858 if ((prop = node.property ("speed")) != 0) {
1859 double sp = atof (prop->value().c_str());
1861 if (realtime_set_speed (sp, false)) {
1862 non_realtime_set_speed ();
1866 in_set_state = false;
1868 /* make sure this is clear before we do anything else */
1870 capturing_sources.clear ();
1872 /* write sources are handled when we handle the input set
1873 up of the IO that owns this DS (::non_realtime_input_change())
1880 AudioDiskstream::use_new_write_source (uint32_t n)
1882 boost::shared_ptr<ChannelList> c = channels.reader();
1884 if (!recordable()) {
1888 if (n >= c->size()) {
1889 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
1893 ChannelInfo* chan = (*c)[n];
1895 if (chan->write_source) {
1896 chan->write_source->done_with_peakfile_writes ();
1897 chan->write_source->set_allow_remove_if_empty (true);
1898 chan->write_source.reset ();
1902 if ((chan->write_source = _session.create_audio_source_for_session (*this, n, destructive())) == 0) {
1903 throw failed_constructor();
1907 catch (failed_constructor &err) {
1908 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
1909 chan->write_source.reset ();
1913 /* do not remove destructive files even if they are empty */
1915 chan->write_source->set_allow_remove_if_empty (!destructive());
1921 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool /*force*/)
1923 ChannelList::iterator chan;
1924 boost::shared_ptr<ChannelList> c = channels.reader();
1927 if (!_session.writable() || !recordable()) {
1931 capturing_sources.clear ();
1933 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1934 if (!destructive()) {
1936 if ((*chan)->write_source && mark_write_complete) {
1937 (*chan)->write_source->mark_streaming_write_completed ();
1939 use_new_write_source (n);
1941 if (record_enabled()) {
1942 capturing_sources.push_back ((*chan)->write_source);
1946 if ((*chan)->write_source == 0) {
1947 use_new_write_source (n);
1952 if (destructive()) {
1954 /* we now have all our write sources set up, so create the
1955 playlist's single region.
1958 if (_playlist->empty()) {
1959 setup_destructive_playlist ();
1965 AudioDiskstream::rename_write_sources ()
1967 ChannelList::iterator chan;
1968 boost::shared_ptr<ChannelList> c = channels.reader();
1971 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1972 if ((*chan)->write_source != 0) {
1973 (*chan)->write_source->set_source_name (_name, destructive());
1974 /* XXX what to do if one of them fails ? */
1982 AudioDiskstream::set_block_size (nframes_t /*nframes*/)
1984 if (_session.get_block_size() > speed_buffer_size) {
1985 speed_buffer_size = _session.get_block_size();
1986 boost::shared_ptr<ChannelList> c = channels.reader();
1988 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1989 if ((*chan)->speed_buffer)
1990 delete [] (*chan)->speed_buffer;
1991 (*chan)->speed_buffer = new Sample[speed_buffer_size];
1994 allocate_temporary_buffers ();
1998 AudioDiskstream::allocate_temporary_buffers ()
2000 /* make sure the wrap buffer is at least large enough to deal
2001 with the speeds up to 1.2, to allow for micro-variation
2002 when slaving to MTC, SMPTE etc.
2005 double sp = max (fabsf (_actual_speed), 1.2f);
2006 nframes_t required_wrap_size = (nframes_t) floor (_session.get_block_size() * sp) + 1;
2008 if (required_wrap_size > wrap_buffer_size) {
2010 boost::shared_ptr<ChannelList> c = channels.reader();
2012 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2013 if ((*chan)->playback_wrap_buffer)
2014 delete [] (*chan)->playback_wrap_buffer;
2015 (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
2016 if ((*chan)->capture_wrap_buffer)
2017 delete [] (*chan)->capture_wrap_buffer;
2018 (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
2021 wrap_buffer_size = required_wrap_size;
2026 AudioDiskstream::monitor_input (bool yn)
2028 boost::shared_ptr<ChannelList> c = channels.reader();
2030 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2032 if ((*chan)->source) {
2033 (*chan)->source->ensure_monitor_input (yn);
2039 AudioDiskstream::set_align_style_from_io ()
2041 bool have_physical = false;
2047 get_input_sources ();
2049 boost::shared_ptr<ChannelList> c = channels.reader();
2051 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2052 if ((*chan)->source && (*chan)->source->flags() & JackPortIsPhysical) {
2053 have_physical = true;
2058 if (have_physical) {
2059 set_align_style (ExistingMaterial);
2061 set_align_style (CaptureTime);
2066 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2069 while (how_many--) {
2070 c->push_back (new ChannelInfo(_session.audio_diskstream_buffer_size(), speed_buffer_size, wrap_buffer_size));
2071 interpolation.add_channel_to (_session.audio_diskstream_buffer_size(), speed_buffer_size);
2074 _n_channels.set(DataType::AUDIO, c->size());
2080 AudioDiskstream::add_channel (uint32_t how_many)
2082 RCUWriter<ChannelList> writer (channels);
2083 boost::shared_ptr<ChannelList> c = writer.get_copy();
2085 return add_channel_to (c, how_many);
2089 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2091 while (how_many-- && !c->empty()) {
2092 // FIXME: crash (thread safe with RCU?)
2093 // memory leak, when disabled.... :(
2096 interpolation.remove_channel_from ();
2099 _n_channels.set(DataType::AUDIO, c->size());
2105 AudioDiskstream::remove_channel (uint32_t how_many)
2107 RCUWriter<ChannelList> writer (channels);
2108 boost::shared_ptr<ChannelList> c = writer.get_copy();
2110 return remove_channel_from (c, how_many);
2114 AudioDiskstream::playback_buffer_load () const
2116 boost::shared_ptr<ChannelList> c = channels.reader();
2118 return (float) ((double) c->front()->playback_buf->read_space()/
2119 (double) c->front()->playback_buf->bufsize());
2123 AudioDiskstream::capture_buffer_load () const
2125 boost::shared_ptr<ChannelList> c = channels.reader();
2127 return (float) ((double) c->front()->capture_buf->write_space()/
2128 (double) c->front()->capture_buf->bufsize());
2132 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2134 const XMLProperty* prop;
2135 XMLNodeList nlist = node.children();
2136 XMLNodeIterator niter;
2137 boost::shared_ptr<AudioFileSource> fs;
2138 boost::shared_ptr<AudioFileSource> first_fs;
2139 SourceList pending_sources;
2142 if ((prop = node.property (X_("at"))) == 0) {
2146 if (sscanf (prop->value().c_str(), "%" PRIu32, &position) != 1) {
2150 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2151 if ((*niter)->name() == X_("file")) {
2153 if ((prop = (*niter)->property (X_("path"))) == 0) {
2157 // This protects sessions from errant CapturingSources in stored sessions
2159 if (stat (prop->value().c_str(), &sbuf)) {
2164 fs = boost::dynamic_pointer_cast<AudioFileSource> (
2165 SourceFactory::createWritable (DataType::AUDIO, _session,
2166 prop->value(), true,
2167 false, _session.frame_rate()));
2170 catch (failed_constructor& err) {
2171 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2172 _name, prop->value())
2177 pending_sources.push_back (fs);
2179 if (first_fs == 0) {
2183 fs->set_captured_for (_name);
2187 if (pending_sources.size() == 0) {
2188 /* nothing can be done */
2192 if (pending_sources.size() != _n_channels.n_audio()) {
2193 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2198 boost::shared_ptr<AudioRegion> region;
2201 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (
2202 pending_sources, 0, first_fs->length(first_fs->timeline_position()),
2203 region_name_from_path (first_fs->name(), true), 0,
2204 Region::Flag (Region::DefaultFlags|Region::Automatic|Region::WholeFile)));
2205 region->special_set_position (0);
2208 catch (failed_constructor& err) {
2209 error << string_compose (
2210 _("%1: cannot create whole-file region from pending capture sources"),
2217 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (
2218 pending_sources, 0, first_fs->length(first_fs->timeline_position()),
2219 region_name_from_path (first_fs->name(), true)));
2222 catch (failed_constructor& err) {
2223 error << string_compose (_("%1: cannot create region from pending capture sources"),
2230 _playlist->add_region (region, position);
2236 AudioDiskstream::set_non_layered (bool yn)
2238 if (yn != non_layered()) {
2241 _flags = Flag (_flags | NonLayered);
2243 _flags = Flag (_flags & ~NonLayered);
2251 AudioDiskstream::set_destructive (bool yn)
2253 bool bounce_ignored;
2255 if (yn != destructive()) {
2258 /* requestor should already have checked this and
2259 bounced if necessary and desired
2261 if (!can_become_destructive (bounce_ignored)) {
2264 _flags = Flag (_flags | Destructive);
2265 use_destructive_playlist ();
2267 _flags = Flag (_flags & ~Destructive);
2268 reset_write_sources (true, true);
2276 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2279 requires_bounce = false;
2283 /* is there only one region ? */
2285 if (_playlist->n_regions() != 1) {
2286 requires_bounce = true;
2290 boost::shared_ptr<Region> first = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
2293 /* do the source(s) for the region cover the session start position ? */
2295 if (first->position() != _session.current_start_frame()) {
2296 if (first->start() > _session.current_start_frame()) {
2297 requires_bounce = true;
2302 /* is the source used by only 1 playlist ? */
2304 boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2308 if (afirst->source()->used() > 1) {
2309 requires_bounce = true;
2313 requires_bounce = false;
2317 AudioDiskstream::ChannelInfo::ChannelInfo (nframes_t bufsize, nframes_t speed_size, nframes_t wrap_size)
2321 current_capture_buffer = 0;
2322 current_playback_buffer = 0;
2323 curr_capture_cnt = 0;
2325 speed_buffer = new Sample[speed_size];
2326 playback_wrap_buffer = new Sample[wrap_size];
2327 capture_wrap_buffer = new Sample[wrap_size];
2329 playback_buf = new RingBufferNPT<Sample> (bufsize);
2330 capture_buf = new RingBufferNPT<Sample> (bufsize);
2331 capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2333 /* touch the ringbuffer buffers, which will cause
2334 them to be mapped into locked physical RAM if
2335 we're running with mlockall(). this doesn't do
2339 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2340 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2341 memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2344 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2347 write_source.reset ();
2350 delete [] speed_buffer;
2353 delete [] playback_wrap_buffer;
2354 playback_wrap_buffer = 0;
2356 delete [] capture_wrap_buffer;
2357 capture_wrap_buffer = 0;
2359 delete playback_buf;
2365 delete capture_transition_buf;
2366 capture_transition_buf = 0;