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/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"
47 #include "ardour/audioplaylist.h"
48 #include "ardour/audioregion.h"
49 #include "ardour/butler.h"
50 #include "ardour/configuration.h"
51 #include "ardour/cycle_timer.h"
52 #include "ardour/debug.h"
53 #include "ardour/io.h"
54 #include "ardour/playlist_factory.h"
55 #include "ardour/region_factory.h"
56 #include "ardour/send.h"
57 #include "ardour/session.h"
58 #include "ardour/source_factory.h"
59 #include "ardour/utils.h"
60 #include "ardour/session_playlists.h"
66 using namespace ARDOUR;
69 size_t AudioDiskstream::_working_buffers_size = 0;
70 Sample* AudioDiskstream::_mixdown_buffer = 0;
71 gain_t* AudioDiskstream::_gain_buffer = 0;
73 AudioDiskstream::AudioDiskstream (Session &sess, const string &name, Diskstream::Flag flag)
74 : Diskstream(sess, name, flag)
75 , deprecated_io_node(NULL)
76 , channels (new ChannelList)
78 /* prevent any write sources from being created */
88 AudioDiskstream::AudioDiskstream (Session& sess, const XMLNode& node)
89 : Diskstream(sess, node)
90 , deprecated_io_node(NULL)
91 , channels (new ChannelList)
96 if (set_state (node, Stateful::loading_state_version)) {
98 throw failed_constructor();
101 in_set_state = false;
104 use_destructive_playlist ();
109 AudioDiskstream::init (Diskstream::Flag f)
113 /* there are no channels at this point, so these
114 two calls just get speed_buffer_size and wrap_buffer
115 size setup without duplicating their code.
118 set_block_size (_session.get_block_size());
119 allocate_temporary_buffers ();
122 assert(_n_channels == ChanCount(DataType::AUDIO, 1));
125 AudioDiskstream::~AudioDiskstream ()
127 DEBUG_TRACE (DEBUG::Destruction, string_compose ("Audio Diskstream %1 destructor\n", _name));
132 RCUWriter<ChannelList> writer (channels);
133 boost::shared_ptr<ChannelList> c = writer.get_copy();
135 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
146 AudioDiskstream::allocate_working_buffers()
148 assert(disk_io_frames() > 0);
150 _working_buffers_size = disk_io_frames();
151 _mixdown_buffer = new Sample[_working_buffers_size];
152 _gain_buffer = new gain_t[_working_buffers_size];
156 AudioDiskstream::free_working_buffers()
158 delete [] _mixdown_buffer;
159 delete [] _gain_buffer;
160 _working_buffers_size = 0;
166 AudioDiskstream::non_realtime_input_change ()
169 Glib::Mutex::Lock lm (state_lock);
171 if (input_change_pending == NoChange) {
176 RCUWriter<ChannelList> writer (channels);
177 boost::shared_ptr<ChannelList> c = writer.get_copy();
179 _n_channels.set(DataType::AUDIO, c->size());
181 if (_io->n_ports().n_audio() > _n_channels.n_audio()) {
182 add_channel_to (c, _io->n_ports().n_audio() - _n_channels.n_audio());
183 } else if (_io->n_ports().n_audio() < _n_channels.n_audio()) {
184 remove_channel_from (c, _n_channels.n_audio() - _io->n_ports().n_audio());
188 get_input_sources ();
189 set_capture_offset ();
191 if (first_input_change) {
192 set_align_style (_persistent_alignment_style);
193 first_input_change = false;
195 set_align_style_from_io ();
198 input_change_pending = NoChange;
200 /* implicit unlock */
203 /* reset capture files */
205 reset_write_sources (false);
207 /* now refill channel buffers */
209 if (speed() != 1.0f || speed() != -1.0f) {
210 seek ((nframes_t) (_session.transport_frame() * (double) speed()));
212 seek (_session.transport_frame());
217 AudioDiskstream::non_realtime_locate (nframes_t location)
219 /* now refill channel buffers */
221 if (speed() != 1.0f || speed() != -1.0f) {
222 seek ((nframes_t) (location * (double) speed()));
229 AudioDiskstream::get_input_sources ()
231 boost::shared_ptr<ChannelList> c = channels.reader();
234 ChannelList::iterator chan;
235 uint32_t ni = _io->n_ports().n_audio();
236 vector<string> connections;
238 for (n = 0, chan = c->begin(); chan != c->end() && n < ni; ++chan, ++n) {
240 connections.clear ();
242 if (_io->nth (n)->get_connections (connections) == 0) {
244 if ((*chan)->source) {
245 // _source->disable_metering ();
251 (*chan)->source = dynamic_cast<AudioPort*>(_session.engine().get_port_by_name (connections[0]) );
257 AudioDiskstream::find_and_use_playlist (const string& name)
259 boost::shared_ptr<AudioPlaylist> playlist;
261 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (_session.playlists->by_name (name))) == 0) {
262 playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, name));
266 error << string_compose(_("AudioDiskstream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
270 return use_playlist (playlist);
274 AudioDiskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
276 assert(boost::dynamic_pointer_cast<AudioPlaylist>(playlist));
278 Diskstream::use_playlist(playlist);
284 AudioDiskstream::use_new_playlist ()
287 boost::shared_ptr<AudioPlaylist> playlist;
289 if (!in_set_state && destructive()) {
294 newname = Playlist::bump_name (_playlist->name(), _session);
296 newname = Playlist::bump_name (_name, _session);
299 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, newname, hidden()))) != 0) {
301 playlist->set_orig_diskstream_id (id());
302 return use_playlist (playlist);
310 AudioDiskstream::use_copy_playlist ()
312 assert(audio_playlist());
318 if (_playlist == 0) {
319 error << string_compose(_("AudioDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
324 boost::shared_ptr<AudioPlaylist> playlist;
326 newname = Playlist::bump_name (_playlist->name(), _session);
328 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist>(PlaylistFactory::create (audio_playlist(), newname))) != 0) {
329 playlist->set_orig_diskstream_id (id());
330 return use_playlist (playlist);
337 AudioDiskstream::setup_destructive_playlist ()
340 boost::shared_ptr<ChannelList> c = channels.reader();
342 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
343 srcs.push_back ((*chan)->write_source);
346 /* a single full-sized region */
348 boost::shared_ptr<Region> region (RegionFactory::create (srcs, 0, max_frames - srcs.front()->natural_position(), _name));
349 _playlist->add_region (region, srcs.front()->natural_position());
353 AudioDiskstream::use_destructive_playlist ()
355 /* this is called from the XML-based constructor or ::set_destructive. when called,
356 we already have a playlist and a region, but we need to
357 set up our sources for write. we use the sources associated
358 with the (presumed single, full-extent) region.
361 boost::shared_ptr<Region> rp = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
364 reset_write_sources (false, true);
368 boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
371 throw failed_constructor();
374 /* be sure to stretch the region out to the maximum length */
376 region->set_length (max_frames - region->position(), this);
379 ChannelList::iterator chan;
380 boost::shared_ptr<ChannelList> c = channels.reader();
382 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
383 (*chan)->write_source = boost::dynamic_pointer_cast<AudioFileSource>(region->source (n));
384 assert((*chan)->write_source);
385 (*chan)->write_source->set_allow_remove_if_empty (false);
387 /* this might be false if we switched modes, so force it */
389 (*chan)->write_source->set_destructive (true);
392 /* the source list will never be reset for a destructive track */
396 AudioDiskstream::prepare_record_status(nframes_t capture_start_frame)
398 if (recordable() && destructive()) {
399 boost::shared_ptr<ChannelList> c = channels.reader();
400 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
402 RingBufferNPT<CaptureTransition>::rw_vector transvec;
403 (*chan)->capture_transition_buf->get_write_vector(&transvec);
405 if (transvec.len[0] > 0) {
406 transvec.buf[0]->type = CaptureStart;
407 transvec.buf[0]->capture_val = capture_start_frame;
408 (*chan)->capture_transition_buf->increment_write_ptr(1);
412 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
420 AudioDiskstream::process (nframes_t transport_frame, nframes_t nframes, bool can_record, bool rec_monitors_input)
423 boost::shared_ptr<ChannelList> c = channels.reader();
424 ChannelList::iterator chan;
426 nframes_t rec_offset = 0;
427 nframes_t rec_nframes = 0;
428 bool nominally_recording;
429 bool re = record_enabled ();
430 bool collect_playback = false;
432 /* if we've already processed the frames corresponding to this call,
433 just return. this allows multiple routes that are taking input
434 from this diskstream to call our ::process() method, but have
435 this stuff only happen once. more commonly, it allows both
436 the AudioTrack that is using this AudioDiskstream *and* the Session
437 to call process() without problems.
444 commit_should_unlock = false;
446 if (!_io || !_io->active()) {
451 check_record_status (transport_frame, nframes, can_record);
453 nominally_recording = (can_record && re);
460 /* This lock is held until the end of AudioDiskstream::commit, so these two functions
461 must always be called as a pair. The only exception is if this function
462 returns a non-zero value, in which case, ::commit should not be called.
465 // If we can't take the state lock return.
466 if (!state_lock.trylock()) {
469 commit_should_unlock = true;
470 adjust_capture_position = 0;
472 for (chan = c->begin(); chan != c->end(); ++chan) {
473 (*chan)->current_capture_buffer = 0;
474 (*chan)->current_playback_buffer = 0;
477 if (nominally_recording || (_session.get_record_enabled() && _session.config.get_punch_in())) {
478 // Safeguard against situations where process() goes haywire when autopunching and last_recordable_frame < first_recordable_frame
479 if (last_recordable_frame < first_recordable_frame) {
480 last_recordable_frame = max_frames;
483 OverlapType ot = coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
485 calculate_record_range(ot, transport_frame, nframes, rec_nframes, rec_offset);
487 if (rec_nframes && !was_recording) {
488 capture_captured = 0;
489 was_recording = true;
494 if (can_record && !_last_capture_regions.empty()) {
495 _last_capture_regions.clear ();
498 if (nominally_recording || rec_nframes) {
500 uint32_t limit = _io->n_ports ().n_audio();
502 /* one or more ports could already have been removed from _io, but our
503 channel setup hasn't yet been updated. prevent us from trying to
504 use channels that correspond to missing ports. note that the
505 process callback (from which this is called) is always atomic
506 with respect to port removal/addition.
509 for (n = 0, chan = c->begin(); chan != c->end() && n < limit; ++chan, ++n) {
511 ChannelInfo* chaninfo (*chan);
513 chaninfo->capture_buf->get_write_vector (&chaninfo->capture_vector);
515 if (rec_nframes <= chaninfo->capture_vector.len[0]) {
517 chaninfo->current_capture_buffer = chaninfo->capture_vector.buf[0];
519 /* note: grab the entire port buffer, but only copy what we were supposed to
520 for recording, and use rec_offset
523 AudioPort* const ap = _io->audio (n);
525 assert(rec_nframes <= ap->get_audio_buffer(nframes).capacity());
526 memcpy (chaninfo->current_capture_buffer, ap->get_audio_buffer (rec_nframes).data(rec_offset), sizeof (Sample) * rec_nframes);
531 nframes_t total = chaninfo->capture_vector.len[0] + chaninfo->capture_vector.len[1];
533 if (rec_nframes > total) {
538 AudioPort* const ap = _io->audio (n);
541 Sample* buf = ap->get_audio_buffer(nframes).data();
542 nframes_t first = chaninfo->capture_vector.len[0];
544 memcpy (chaninfo->capture_wrap_buffer, buf, sizeof (Sample) * first);
545 memcpy (chaninfo->capture_vector.buf[0], buf, sizeof (Sample) * first);
546 memcpy (chaninfo->capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
547 memcpy (chaninfo->capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
549 chaninfo->current_capture_buffer = chaninfo->capture_wrap_buffer;
556 finish_capture (rec_monitors_input, c);
563 /* data will be written to disk */
565 if (rec_nframes == nframes && rec_offset == 0) {
567 for (chan = c->begin(); chan != c->end(); ++chan) {
568 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
571 playback_distance = nframes;
576 /* we can't use the capture buffer as the playback buffer, because
577 we recorded only a part of the current process' cycle data
581 collect_playback = true;
584 adjust_capture_position = rec_nframes;
586 } else if (nominally_recording) {
588 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
590 for (chan = c->begin(); chan != c->end(); ++chan) {
591 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
594 playback_distance = nframes;
598 collect_playback = true;
601 if (collect_playback) {
603 /* we're doing playback */
605 nframes_t necessary_samples;
607 /* no varispeed playback if we're recording, because the output .... TBD */
609 if (rec_nframes == 0 && _actual_speed != 1.0f) {
610 necessary_samples = (nframes_t) floor ((nframes * fabs (_actual_speed))) + 1;
612 necessary_samples = nframes;
615 for (chan = c->begin(); chan != c->end(); ++chan) {
616 (*chan)->playback_buf->get_read_vector (&(*chan)->playback_vector);
621 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
623 ChannelInfo* chaninfo (*chan);
625 if (necessary_samples <= chaninfo->playback_vector.len[0]) {
627 chaninfo->current_playback_buffer = chaninfo->playback_vector.buf[0];
630 nframes_t total = chaninfo->playback_vector.len[0] + chaninfo->playback_vector.len[1];
632 if (necessary_samples > total) {
633 cerr << _name << " Need " << necessary_samples << " total = " << total << endl;
634 cerr << "underrun for " << _name << endl;
640 memcpy ((char *) chaninfo->playback_wrap_buffer,
641 chaninfo->playback_vector.buf[0],
642 chaninfo->playback_vector.len[0] * sizeof (Sample));
643 memcpy (chaninfo->playback_wrap_buffer + chaninfo->playback_vector.len[0],
644 chaninfo->playback_vector.buf[1],
645 (necessary_samples - chaninfo->playback_vector.len[0])
648 chaninfo->current_playback_buffer = chaninfo->playback_wrap_buffer;
653 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
654 process_varispeed_playback(nframes, c);
656 playback_distance = nframes;
659 _speed = _target_speed;
670 /* we're exiting with failure, so ::commit will not
671 be called. unlock the state lock.
674 commit_should_unlock = false;
682 AudioDiskstream::process_varispeed_playback(nframes_t nframes, boost::shared_ptr<ChannelList> c)
684 ChannelList::iterator chan;
686 interpolation.set_speed (_target_speed);
689 for (chan = c->begin(); chan != c->end(); ++chan, ++channel) {
690 ChannelInfo* chaninfo (*chan);
692 playback_distance = interpolation.interpolate (
693 channel, nframes, chaninfo->current_playback_buffer, chaninfo->speed_buffer);
695 chaninfo->current_playback_buffer = chaninfo->speed_buffer;
700 AudioDiskstream::commit (nframes_t /*nframes*/)
702 bool need_butler = false;
704 if (!_io || !_io->active()) {
708 if (_actual_speed < 0.0) {
709 playback_sample -= playback_distance;
711 playback_sample += playback_distance;
714 boost::shared_ptr<ChannelList> c = channels.reader();
715 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
717 (*chan)->playback_buf->increment_read_ptr (playback_distance);
719 if (adjust_capture_position) {
720 (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
724 if (adjust_capture_position != 0) {
725 capture_captured += adjust_capture_position;
726 adjust_capture_position = 0;
730 if (_io && _io->active()) {
731 need_butler = c->front()->playback_buf->write_space() >= c->front()->playback_buf->bufsize() / 2;
736 if (_io && _io->active()) {
737 need_butler = c->front()->playback_buf->write_space() >= disk_io_chunk_frames
738 || c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
740 need_butler = c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
744 if (commit_should_unlock) {
754 AudioDiskstream::set_pending_overwrite (bool yn)
756 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
758 pending_overwrite = yn;
760 overwrite_frame = playback_sample;
761 overwrite_offset = channels.reader()->front()->playback_buf->get_read_ptr();
765 AudioDiskstream::overwrite_existing_buffers ()
767 boost::shared_ptr<ChannelList> c = channels.reader();
768 Sample* mixdown_buffer;
771 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
773 overwrite_queued = false;
775 /* assume all are the same size */
776 nframes_t size = c->front()->playback_buf->bufsize();
778 mixdown_buffer = new Sample[size];
779 gain_buffer = new float[size];
781 /* reduce size so that we can fill the buffer correctly. */
787 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
789 start = overwrite_frame;
790 nframes_t cnt = size;
792 /* to fill the buffer without resetting the playback sample, we need to
793 do it one or two chunks (normally two).
795 |----------------------------------------------------------------------|
799 |<- second chunk->||<----------------- first chunk ------------------>|
803 nframes_t to_read = size - overwrite_offset;
805 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, *chan, n, reversed)) {
806 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
807 _id, size, playback_sample) << endmsg;
815 if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer,
816 start, cnt, *chan, n, reversed)) {
817 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
818 _id, size, playback_sample) << endmsg;
827 pending_overwrite = false;
828 delete [] gain_buffer;
829 delete [] mixdown_buffer;
834 AudioDiskstream::seek (nframes_t frame, bool complete_refill)
838 ChannelList::iterator chan;
839 boost::shared_ptr<ChannelList> c = channels.reader();
841 Glib::Mutex::Lock lm (state_lock);
843 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
844 (*chan)->playback_buf->reset ();
845 (*chan)->capture_buf->reset ();
848 /* can't rec-enable in destructive mode if transport is before start */
850 if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
851 disengage_record_enable ();
854 playback_sample = frame;
857 if (complete_refill) {
858 while ((ret = do_refill_with_alloc ()) > 0) ;
860 ret = do_refill_with_alloc ();
867 AudioDiskstream::can_internal_playback_seek (nframes_t distance)
869 ChannelList::iterator chan;
870 boost::shared_ptr<ChannelList> c = channels.reader();
872 for (chan = c->begin(); chan != c->end(); ++chan) {
873 if ((*chan)->playback_buf->read_space() < distance) {
881 AudioDiskstream::internal_playback_seek (nframes_t distance)
883 ChannelList::iterator chan;
884 boost::shared_ptr<ChannelList> c = channels.reader();
886 for (chan = c->begin(); chan != c->end(); ++chan) {
887 (*chan)->playback_buf->increment_read_ptr (distance);
890 first_recordable_frame += distance;
891 playback_sample += distance;
897 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer, nframes_t& start, nframes_t cnt,
898 ChannelInfo* /*channel_info*/, int channel, bool reversed)
900 nframes_t this_read = 0;
902 nframes_t loop_end = 0;
903 nframes_t loop_start = 0;
904 nframes_t loop_length = 0;
905 nframes_t offset = 0;
908 /* XXX we don't currently play loops in reverse. not sure why */
912 /* Make the use of a Location atomic for this read operation.
914 Note: Locations don't get deleted, so all we care about
915 when I say "atomic" is that we are always pointing to
916 the same one and using a start/length values obtained
920 if ((loc = loop_location) != 0) {
921 loop_start = loc->start();
922 loop_end = loc->end();
923 loop_length = loop_end - loop_start;
926 /* if we are looping, ensure that the first frame we read is at the correct
927 position within the loop.
930 if (loc && start >= loop_end) {
931 //cerr << "start adjusted from " << start;
932 start = loop_start + ((start - loop_start) % loop_length);
933 //cerr << "to " << start << endl;
936 //cerr << "start is " << start << " loopstart: " << loop_start << " loopend: " << loop_end << endl;
945 /* take any loop into account. we can't read past the end of the loop. */
947 if (loc && (loop_end - start < cnt)) {
948 this_read = loop_end - start;
949 //cerr << "reloop true: thisread: " << this_read << " cnt: " << cnt << endl;
956 if (this_read == 0) {
960 this_read = min(cnt,this_read);
962 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
963 error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), _id, this_read,
968 _read_data_count = _playlist->read_data_count();
972 swap_by_ptr (buf, buf + this_read - 1);
976 /* if we read to the end of the loop, go back to the beginning */
993 AudioDiskstream::do_refill_with_alloc ()
995 Sample* mix_buf = new Sample[disk_io_chunk_frames];
996 float* gain_buf = new float[disk_io_chunk_frames];
998 int ret = _do_refill(mix_buf, gain_buf);
1007 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer)
1011 RingBufferNPT<Sample>::rw_vector vector;
1012 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1013 nframes_t total_space;
1014 nframes_t zero_fill;
1016 ChannelList::iterator i;
1017 boost::shared_ptr<ChannelList> c = channels.reader();
1024 assert(mixdown_buffer);
1025 assert(gain_buffer);
1032 c->front()->playback_buf->get_write_vector (&vector);
1034 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1038 /* if there are 2+ chunks of disk i/o possible for
1039 this track, let the caller know so that it can arrange
1040 for us to be called again, ASAP.
1043 if (total_space >= (_slaved?3:2) * disk_io_chunk_frames) {
1047 /* if we're running close to normal speed and there isn't enough
1048 space to do disk_io_chunk_frames of I/O, then don't bother.
1050 at higher speeds, just do it because the sync between butler
1051 and audio thread may not be good enough.
1054 if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1058 /* when slaved, don't try to get too close to the read pointer. this
1059 leaves space for the buffer reversal to have something useful to
1063 if (_slaved && total_space < (c->front()->playback_buf->bufsize() / 2)) {
1067 /* never do more than disk_io_chunk_frames worth of disk input per call (limit doesn't apply for memset) */
1069 total_space = min (disk_io_chunk_frames, total_space);
1073 if (file_frame == 0) {
1075 /* at start: nothing to do but fill with silence */
1077 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1079 ChannelInfo* chan (*i);
1080 chan->playback_buf->get_write_vector (&vector);
1081 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1082 if (vector.len[1]) {
1083 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1085 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1090 if (file_frame < total_space) {
1092 /* too close to the start: read what we can,
1093 and then zero fill the rest
1096 zero_fill = total_space - file_frame;
1097 total_space = file_frame;
1107 if (file_frame == max_frames) {
1109 /* at end: nothing to do but fill with silence */
1111 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1113 ChannelInfo* chan (*i);
1114 chan->playback_buf->get_write_vector (&vector);
1115 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1116 if (vector.len[1]) {
1117 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1119 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1124 if (file_frame > max_frames - total_space) {
1126 /* to close to the end: read what we can, and zero fill the rest */
1128 zero_fill = total_space - (max_frames - file_frame);
1129 total_space = max_frames - file_frame;
1136 nframes_t file_frame_tmp = 0;
1138 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1140 ChannelInfo* chan (*i);
1143 nframes_t len1, len2;
1145 chan->playback_buf->get_write_vector (&vector);
1147 if (vector.len[0] > disk_io_chunk_frames) {
1149 /* we're not going to fill the first chunk, so certainly do not bother with the
1150 other part. it won't be connected with the part we do fill, as in:
1152 .... => writable space
1153 ++++ => readable space
1154 ^^^^ => 1 x disk_io_chunk_frames that would be filled
1156 |......|+++++++++++++|...............................|
1161 So, just pretend that the buf1 part isn't there.
1171 file_frame_tmp = file_frame;
1173 buf1 = vector.buf[0];
1174 len1 = vector.len[0];
1175 buf2 = vector.buf[1];
1176 len2 = vector.len[1];
1178 to_read = min (ts, len1);
1179 to_read = min (to_read, disk_io_chunk_frames);
1183 if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1188 chan->playback_buf->increment_write_ptr (to_read);
1192 to_read = min (ts, len2);
1196 /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1197 so read some or all of vector.len[1] as well.
1200 if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1205 chan->playback_buf->increment_write_ptr (to_read);
1214 file_frame = file_frame_tmp;
1221 /** Flush pending data to disk.
1223 * Important note: this function will write *AT MOST* disk_io_chunk_frames
1224 * of data to disk. it will never write more than that. If it writes that
1225 * much and there is more than that waiting to be written, it will return 1,
1226 * otherwise 0 on success or -1 on failure.
1228 * If there is less than disk_io_chunk_frames to be written, no data will be
1229 * written at all unless @a force_flush is true.
1232 AudioDiskstream::do_flush (RunContext /*context*/, bool force_flush)
1236 RingBufferNPT<Sample>::rw_vector vector;
1237 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1240 _write_data_count = 0;
1242 transvec.buf[0] = 0;
1243 transvec.buf[1] = 0;
1247 boost::shared_ptr<ChannelList> c = channels.reader();
1248 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1250 (*chan)->capture_buf->get_read_vector (&vector);
1252 total = vector.len[0] + vector.len[1];
1254 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1258 /* if there are 2+ chunks of disk i/o possible for
1259 this track, let the caller know so that it can arrange
1260 for us to be called again, ASAP.
1262 if we are forcing a flush, then if there is* any* extra
1263 work, let the caller know.
1265 if we are no longer recording and there is any extra work,
1266 let the caller know too.
1269 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1273 to_write = min (disk_io_chunk_frames, (nframes_t) vector.len[0]);
1275 // check the transition buffer when recording destructive
1276 // important that we get this after the capture buf
1278 if (destructive()) {
1279 (*chan)->capture_transition_buf->get_read_vector(&transvec);
1280 size_t transcount = transvec.len[0] + transvec.len[1];
1281 bool have_start = false;
1284 for (ti=0; ti < transcount; ++ti) {
1285 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1287 if (captrans.type == CaptureStart) {
1288 // by definition, the first data we got above represents the given capture pos
1290 (*chan)->write_source->mark_capture_start (captrans.capture_val);
1291 (*chan)->curr_capture_cnt = 0;
1295 else if (captrans.type == CaptureEnd) {
1297 // capture end, the capture_val represents total frames in capture
1299 if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1301 // shorten to make the write a perfect fit
1302 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
1304 if (nto_write < to_write) {
1305 ret = 1; // should we?
1307 to_write = nto_write;
1309 (*chan)->write_source->mark_capture_end ();
1311 // increment past this transition, but go no further
1316 // actually ends just beyond this chunk, so force more work
1324 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1328 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1329 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1333 (*chan)->capture_buf->increment_read_ptr (to_write);
1334 (*chan)->curr_capture_cnt += to_write;
1336 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1338 /* we wrote all of vector.len[0] but it wasn't an entire
1339 disk_io_chunk_frames of data, so arrange for some part
1340 of vector.len[1] to be flushed to disk as well.
1343 to_write = min ((nframes_t)(disk_io_chunk_frames - to_write), (nframes_t) vector.len[1]);
1345 if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1346 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1350 _write_data_count += (*chan)->write_source->write_data_count();
1352 (*chan)->capture_buf->increment_read_ptr (to_write);
1353 (*chan)->curr_capture_cnt += to_write;
1362 AudioDiskstream::transport_stopped (struct tm& when, time_t twhen, bool abort_capture)
1364 uint32_t buffer_position;
1365 bool more_work = true;
1367 boost::shared_ptr<AudioRegion> region;
1368 nframes_t total_capture;
1370 SourceList::iterator src;
1371 ChannelList::iterator chan;
1372 vector<CaptureInfo*>::iterator ci;
1373 boost::shared_ptr<ChannelList> c = channels.reader();
1375 bool mark_write_completed = false;
1377 finish_capture (true, c);
1379 /* butler is already stopped, but there may be work to do
1380 to flush remaining data to disk.
1383 while (more_work && !err) {
1384 switch (do_flush (TransportContext, true)) {
1391 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1396 /* XXX is there anything we can do if err != 0 ? */
1397 Glib::Mutex::Lock lm (capture_info_lock);
1399 if (capture_info.empty()) {
1403 if (abort_capture) {
1405 if (destructive()) {
1409 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1411 if ((*chan)->write_source) {
1413 (*chan)->write_source->mark_for_remove ();
1414 (*chan)->write_source->drop_references ();
1415 (*chan)->write_source.reset ();
1418 /* new source set up in "out" below */
1424 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1425 total_capture += (*ci)->frames;
1428 /* figure out the name for this take */
1430 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1432 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1436 s->update_header (capture_info.front()->start, when, twhen);
1437 s->set_captured_for (_name);
1438 s->mark_immutable ();
1439 if (Config->get_auto_analyse_audio()) {
1440 Analyser::queue_source_for_analysis (s, true);
1445 /* destructive tracks have a single, never changing region */
1447 if (destructive()) {
1449 /* send a signal that any UI can pick up to do the right thing. there is
1450 a small problem here in that a UI may need the peak data to be ready
1451 for the data that was recorded and this isn't interlocked with that
1452 process. this problem is deferred to the UI.
1455 _playlist->Modified();
1459 string whole_file_region_name;
1460 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1462 /* Register a new region with the Session that
1463 describes the entire source. Do this first
1464 so that any sub-regions will obviously be
1465 children of this one (later!)
1469 boost::shared_ptr<Region> rx (RegionFactory::create (srcs,
1470 c->front()->write_source->last_capture_start_frame(), total_capture,
1471 whole_file_region_name, 0,
1472 Region::Flag (Region::DefaultFlags|Region::Automatic|Region::WholeFile)));
1474 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1475 region->special_set_position (capture_info.front()->start);
1479 catch (failed_constructor& err) {
1480 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1484 _last_capture_regions.push_back (region);
1486 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1488 XMLNode &before = _playlist->get_state();
1489 _playlist->freeze ();
1491 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1495 _session.region_name (region_name, whole_file_region_name, false);
1497 // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->frames << " add region " << region_name << endl;
1500 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, buffer_position, (*ci)->frames, region_name));
1501 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1504 catch (failed_constructor& err) {
1505 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1506 continue; /* XXX is this OK? */
1509 region->GoingAway.connect (sigc::bind (sigc::mem_fun (*this, &Diskstream::remove_region_from_last_capture), boost::weak_ptr<Region>(region)));
1511 _last_capture_regions.push_back (region);
1513 i_am_the_modifier++;
1514 _playlist->add_region (region, (*ci)->start, 1, non_layered());
1515 i_am_the_modifier--;
1517 buffer_position += (*ci)->frames;
1521 XMLNode &after = _playlist->get_state();
1522 _session.add_command (new MementoCommand<Playlist>(*_playlist, &before, &after));
1525 mark_write_completed = true;
1528 reset_write_sources (mark_write_completed);
1532 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1536 capture_info.clear ();
1537 capture_start_frame = 0;
1541 AudioDiskstream::transport_looped (nframes_t transport_frame)
1543 if (was_recording) {
1544 // all we need to do is finish this capture, with modified capture length
1545 boost::shared_ptr<ChannelList> c = channels.reader();
1547 // adjust the capture length knowing that the data will be recorded to disk
1548 // only necessary after the first loop where we're recording
1549 if (capture_info.size() == 0) {
1550 capture_captured += _capture_offset;
1552 if (_alignment_style == ExistingMaterial) {
1553 capture_captured += _session.worst_output_latency();
1555 capture_captured += _roll_delay;
1559 finish_capture (true, c);
1561 // the next region will start recording via the normal mechanism
1562 // we'll set the start position to the current transport pos
1563 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1564 capture_start_frame = transport_frame;
1565 first_recordable_frame = transport_frame; // mild lie
1566 last_recordable_frame = max_frames;
1567 was_recording = true;
1569 if (recordable() && destructive()) {
1570 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1572 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1573 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1575 if (transvec.len[0] > 0) {
1576 transvec.buf[0]->type = CaptureStart;
1577 transvec.buf[0]->capture_val = capture_start_frame;
1578 (*chan)->capture_transition_buf->increment_write_ptr(1);
1582 fatal << X_("programming error: capture_transition_buf is full on rec loop! inconceivable!")
1592 AudioDiskstream::finish_capture (bool /*rec_monitors_input*/, boost::shared_ptr<ChannelList> c)
1594 was_recording = false;
1596 if (capture_captured == 0) {
1600 if (recordable() && destructive()) {
1601 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1603 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1604 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1606 if (transvec.len[0] > 0) {
1607 transvec.buf[0]->type = CaptureEnd;
1608 transvec.buf[0]->capture_val = capture_captured;
1609 (*chan)->capture_transition_buf->increment_write_ptr(1);
1613 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1619 CaptureInfo* ci = new CaptureInfo;
1621 ci->start = capture_start_frame;
1622 ci->frames = capture_captured;
1624 /* XXX theoretical race condition here. Need atomic exchange ?
1625 However, the circumstances when this is called right
1626 now (either on record-disable or transport_stopped)
1627 mean that no actual race exists. I think ...
1628 We now have a capture_info_lock, but it is only to be used
1629 to synchronize in the transport_stop and the capture info
1630 accessors, so that invalidation will not occur (both non-realtime).
1633 // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1635 capture_info.push_back (ci);
1636 capture_captured = 0;
1638 /* now we've finished a capture, reset first_recordable_frame for next time */
1639 first_recordable_frame = max_frames;
1643 AudioDiskstream::set_record_enabled (bool yn)
1645 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0) {
1649 /* can't rec-enable in destructive mode if transport is before start */
1651 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1655 /* yes, i know that this not proof against race conditions, but its
1656 good enough. i think.
1659 if (record_enabled() != yn) {
1661 engage_record_enable ();
1663 disengage_record_enable ();
1669 AudioDiskstream::engage_record_enable ()
1671 bool rolling = _session.transport_speed() != 0.0f;
1672 boost::shared_ptr<ChannelList> c = channels.reader();
1674 g_atomic_int_set (&_record_enabled, 1);
1675 capturing_sources.clear ();
1677 if (Config->get_monitoring_model() == HardwareMonitoring) {
1679 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1680 if ((*chan)->source) {
1681 (*chan)->source->ensure_monitor_input (!(_session.config.get_auto_input() && rolling));
1683 capturing_sources.push_back ((*chan)->write_source);
1684 (*chan)->write_source->mark_streaming_write_started ();
1688 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1689 capturing_sources.push_back ((*chan)->write_source);
1690 (*chan)->write_source->mark_streaming_write_started ();
1694 RecordEnableChanged (); /* EMIT SIGNAL */
1698 AudioDiskstream::disengage_record_enable ()
1700 g_atomic_int_set (&_record_enabled, 0);
1701 boost::shared_ptr<ChannelList> c = channels.reader();
1702 if (Config->get_monitoring_model() == HardwareMonitoring) {
1703 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1704 if ((*chan)->source) {
1705 (*chan)->source->ensure_monitor_input (false);
1709 capturing_sources.clear ();
1710 RecordEnableChanged (); /* EMIT SIGNAL */
1714 AudioDiskstream::get_state ()
1716 XMLNode* node = new XMLNode ("AudioDiskstream");
1718 LocaleGuard lg (X_("POSIX"));
1719 boost::shared_ptr<ChannelList> c = channels.reader();
1721 node->add_property ("flags", enum_2_string (_flags));
1723 snprintf (buf, sizeof(buf), "%zd", c->size());
1724 node->add_property ("channels", buf);
1726 node->add_property ("playlist", _playlist->name());
1728 snprintf (buf, sizeof(buf), "%.12g", _visible_speed);
1729 node->add_property ("speed", buf);
1731 node->add_property("name", _name);
1732 id().print (buf, sizeof (buf));
1733 node->add_property("id", buf);
1735 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1737 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1738 XMLNode* cs_grandchild;
1740 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1741 cs_grandchild = new XMLNode (X_("file"));
1742 cs_grandchild->add_property (X_("path"), (*i)->path());
1743 cs_child->add_child_nocopy (*cs_grandchild);
1746 /* store the location where capture will start */
1750 if (_session.config.get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1751 snprintf (buf, sizeof (buf), "%" PRId64, pi->start());
1753 snprintf (buf, sizeof (buf), "%" PRId64, _session.transport_frame());
1756 cs_child->add_property (X_("at"), buf);
1757 node->add_child_nocopy (*cs_child);
1761 node->add_child_copy (*_extra_xml);
1768 AudioDiskstream::set_state (const XMLNode& node, int /*version*/)
1770 const XMLProperty* prop;
1771 XMLNodeList nlist = node.children();
1772 XMLNodeIterator niter;
1773 uint32_t nchans = 1;
1774 XMLNode* capture_pending_node = 0;
1775 LocaleGuard lg (X_("POSIX"));
1777 in_set_state = true;
1779 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1780 if ((*niter)->name() == IO::state_node_name) {
1781 deprecated_io_node = new XMLNode (**niter);
1784 if ((*niter)->name() == X_("CapturingSources")) {
1785 capture_pending_node = *niter;
1789 /* prevent write sources from being created */
1791 in_set_state = true;
1793 if ((prop = node.property ("name")) != 0) {
1794 _name = prop->value();
1797 if (deprecated_io_node) {
1798 if ((prop = deprecated_io_node->property ("id")) != 0) {
1799 _id = prop->value ();
1802 if ((prop = node.property ("id")) != 0) {
1803 _id = prop->value ();
1807 if ((prop = node.property ("flags")) != 0) {
1808 _flags = Flag (string_2_enum (prop->value(), _flags));
1811 if ((prop = node.property ("channels")) != 0) {
1812 nchans = atoi (prop->value().c_str());
1815 // create necessary extra channels
1816 // we are always constructed with one and we always need one
1818 _n_channels.set(DataType::AUDIO, channels.reader()->size());
1820 if (nchans > _n_channels.n_audio()) {
1822 add_channel (nchans - _n_channels.n_audio());
1823 IO::PortCountChanged(_n_channels);
1825 } else if (nchans < _n_channels.n_audio()) {
1827 remove_channel (_n_channels.n_audio() - nchans);
1830 if ((prop = node.property ("playlist")) == 0) {
1835 bool had_playlist = (_playlist != 0);
1837 if (find_and_use_playlist (prop->value())) {
1841 if (!had_playlist) {
1842 _playlist->set_orig_diskstream_id (_id);
1845 if (!destructive() && capture_pending_node) {
1846 /* destructive streams have one and only one source per channel,
1847 and so they never end up in pending capture in any useful
1850 use_pending_capture_data (*capture_pending_node);
1855 if ((prop = node.property ("speed")) != 0) {
1856 double sp = atof (prop->value().c_str());
1858 if (realtime_set_speed (sp, false)) {
1859 non_realtime_set_speed ();
1863 in_set_state = false;
1865 /* make sure this is clear before we do anything else */
1867 capturing_sources.clear ();
1869 /* write sources are handled when we handle the input set
1870 up of the IO that owns this DS (::non_realtime_input_change())
1877 AudioDiskstream::use_new_write_source (uint32_t n)
1879 boost::shared_ptr<ChannelList> c = channels.reader();
1881 if (!recordable()) {
1885 if (n >= c->size()) {
1886 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
1890 ChannelInfo* chan = (*c)[n];
1892 if (chan->write_source) {
1893 chan->write_source->done_with_peakfile_writes ();
1894 chan->write_source->set_allow_remove_if_empty (true);
1895 chan->write_source.reset ();
1899 if ((chan->write_source = _session.create_audio_source_for_session (*this, n, destructive())) == 0) {
1900 throw failed_constructor();
1904 catch (failed_constructor &err) {
1905 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
1906 chan->write_source.reset ();
1910 /* do not remove destructive files even if they are empty */
1912 chan->write_source->set_allow_remove_if_empty (!destructive());
1914 /* until we write, this file is considered removable */
1916 chan->write_source->mark_for_remove ();
1922 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool /*force*/)
1924 ChannelList::iterator chan;
1925 boost::shared_ptr<ChannelList> c = channels.reader();
1928 if (!_session.writable() || !recordable()) {
1932 capturing_sources.clear ();
1934 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1935 if (!destructive()) {
1937 if ((*chan)->write_source && mark_write_complete) {
1938 (*chan)->write_source->mark_streaming_write_completed ();
1940 use_new_write_source (n);
1942 if (record_enabled()) {
1943 capturing_sources.push_back ((*chan)->write_source);
1947 if ((*chan)->write_source == 0) {
1948 use_new_write_source (n);
1953 if (destructive()) {
1955 /* we now have all our write sources set up, so create the
1956 playlist's single region.
1959 if (_playlist->empty()) {
1960 setup_destructive_playlist ();
1966 AudioDiskstream::rename_write_sources ()
1968 ChannelList::iterator chan;
1969 boost::shared_ptr<ChannelList> c = channels.reader();
1972 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1973 if ((*chan)->write_source != 0) {
1974 (*chan)->write_source->set_source_name (_name, destructive());
1975 /* XXX what to do if one of them fails ? */
1983 AudioDiskstream::set_block_size (nframes_t /*nframes*/)
1985 if (_session.get_block_size() > speed_buffer_size) {
1986 speed_buffer_size = _session.get_block_size();
1987 boost::shared_ptr<ChannelList> c = channels.reader();
1989 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1990 if ((*chan)->speed_buffer)
1991 delete [] (*chan)->speed_buffer;
1992 (*chan)->speed_buffer = new Sample[speed_buffer_size];
1995 allocate_temporary_buffers ();
1999 AudioDiskstream::allocate_temporary_buffers ()
2001 /* make sure the wrap buffer is at least large enough to deal
2002 with the speeds up to 1.2, to allow for micro-variation
2003 when slaving to MTC, Timecode etc.
2006 double sp = max (fabsf (_actual_speed), 1.2f);
2007 nframes_t required_wrap_size = (nframes_t) floor (_session.get_block_size() * sp) + 1;
2009 if (required_wrap_size > wrap_buffer_size) {
2011 boost::shared_ptr<ChannelList> c = channels.reader();
2013 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2014 if ((*chan)->playback_wrap_buffer)
2015 delete [] (*chan)->playback_wrap_buffer;
2016 (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
2017 if ((*chan)->capture_wrap_buffer)
2018 delete [] (*chan)->capture_wrap_buffer;
2019 (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
2022 wrap_buffer_size = required_wrap_size;
2027 AudioDiskstream::monitor_input (bool yn)
2029 boost::shared_ptr<ChannelList> c = channels.reader();
2031 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2033 if ((*chan)->source) {
2034 (*chan)->source->ensure_monitor_input (yn);
2040 AudioDiskstream::set_align_style_from_io ()
2042 bool have_physical = false;
2048 get_input_sources ();
2050 boost::shared_ptr<ChannelList> c = channels.reader();
2052 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2053 if ((*chan)->source && (*chan)->source->flags() & JackPortIsPhysical) {
2054 have_physical = true;
2059 if (have_physical) {
2060 set_align_style (ExistingMaterial);
2062 set_align_style (CaptureTime);
2067 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2069 while (how_many--) {
2070 c->push_back (new ChannelInfo(_session.butler()->audio_diskstream_buffer_size(), speed_buffer_size, wrap_buffer_size));
2071 interpolation.add_channel_to (_session.butler()->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(), false, _session.frame_rate()));
2169 catch (failed_constructor& err) {
2170 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2171 _name, prop->value())
2176 pending_sources.push_back (fs);
2178 if (first_fs == 0) {
2182 fs->set_captured_for (_name);
2186 if (pending_sources.size() == 0) {
2187 /* nothing can be done */
2191 if (pending_sources.size() != _n_channels.n_audio()) {
2192 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2197 boost::shared_ptr<AudioRegion> region;
2200 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (
2201 pending_sources, 0, first_fs->length(first_fs->timeline_position()),
2202 region_name_from_path (first_fs->name(), true), 0,
2203 Region::Flag (Region::DefaultFlags|Region::Automatic|Region::WholeFile)));
2204 region->special_set_position (0);
2207 catch (failed_constructor& err) {
2208 error << string_compose (
2209 _("%1: cannot create whole-file region from pending capture sources"),
2216 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (
2217 pending_sources, 0, first_fs->length(first_fs->timeline_position()),
2218 region_name_from_path (first_fs->name(), true)));
2221 catch (failed_constructor& err) {
2222 error << string_compose (_("%1: cannot create region from pending capture sources"),
2229 _playlist->add_region (region, position);
2235 AudioDiskstream::set_non_layered (bool yn)
2237 if (yn != non_layered()) {
2240 _flags = Flag (_flags | NonLayered);
2242 _flags = Flag (_flags & ~NonLayered);
2250 AudioDiskstream::set_destructive (bool yn)
2252 bool bounce_ignored;
2254 if (yn != destructive()) {
2257 /* requestor should already have checked this and
2258 bounced if necessary and desired
2260 if (!can_become_destructive (bounce_ignored)) {
2263 _flags = Flag (_flags | Destructive);
2264 use_destructive_playlist ();
2266 _flags = Flag (_flags & ~Destructive);
2267 reset_write_sources (true, true);
2275 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2278 requires_bounce = false;
2282 /* is there only one region ? */
2284 if (_playlist->n_regions() != 1) {
2285 requires_bounce = true;
2289 boost::shared_ptr<Region> first = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
2292 /* do the source(s) for the region cover the session start position ? */
2294 if (first->position() != _session.current_start_frame()) {
2295 if (first->start() > _session.current_start_frame()) {
2296 requires_bounce = true;
2301 /* is the source used by only 1 playlist ? */
2303 boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2307 if (_session.playlists->source_use_count (afirst->source()) > 1) {
2308 requires_bounce = true;
2312 requires_bounce = false;
2316 AudioDiskstream::ChannelInfo::ChannelInfo (nframes_t bufsize, nframes_t speed_size, nframes_t wrap_size)
2320 current_capture_buffer = 0;
2321 current_playback_buffer = 0;
2322 curr_capture_cnt = 0;
2324 speed_buffer = new Sample[speed_size];
2325 playback_wrap_buffer = new Sample[wrap_size];
2326 capture_wrap_buffer = new Sample[wrap_size];
2328 playback_buf = new RingBufferNPT<Sample> (bufsize);
2329 capture_buf = new RingBufferNPT<Sample> (bufsize);
2330 capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2332 /* touch the ringbuffer buffers, which will cause
2333 them to be mapped into locked physical RAM if
2334 we're running with mlockall(). this doesn't do
2338 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2339 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2340 memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2343 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2346 write_source.reset ();
2349 delete [] speed_buffer;
2352 delete [] playback_wrap_buffer;
2353 playback_wrap_buffer = 0;
2355 delete [] capture_wrap_buffer;
2356 capture_wrap_buffer = 0;
2358 delete playback_buf;
2364 delete capture_transition_buf;
2365 capture_transition_buf = 0;