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"
48 #include "ardour/audioplaylist.h"
49 #include "ardour/audioregion.h"
50 #include "ardour/butler.h"
51 #include "ardour/configuration.h"
52 #include "ardour/cycle_timer.h"
53 #include "ardour/debug.h"
54 #include "ardour/io.h"
55 #include "ardour/playlist_factory.h"
56 #include "ardour/region_factory.h"
57 #include "ardour/send.h"
58 #include "ardour/session.h"
59 #include "ardour/source_factory.h"
60 #include "ardour/utils.h"
61 #include "ardour/session_playlists.h"
67 using namespace ARDOUR;
70 size_t AudioDiskstream::_working_buffers_size = 0;
71 Sample* AudioDiskstream::_mixdown_buffer = 0;
72 gain_t* AudioDiskstream::_gain_buffer = 0;
74 AudioDiskstream::AudioDiskstream (Session &sess, const string &name, Diskstream::Flag flag)
75 : Diskstream(sess, name, flag)
76 , deprecated_io_node(NULL)
77 , channels (new ChannelList)
79 /* prevent any write sources from being created */
89 AudioDiskstream::AudioDiskstream (Session& sess, const XMLNode& node)
90 : Diskstream(sess, node)
91 , deprecated_io_node(NULL)
92 , channels (new ChannelList)
97 if (set_state (node, Stateful::loading_state_version)) {
99 throw failed_constructor();
102 in_set_state = false;
105 use_destructive_playlist ();
110 AudioDiskstream::init (Diskstream::Flag f)
114 /* there are no channels at this point, so these
115 two calls just get speed_buffer_size and wrap_buffer
116 size setup without duplicating their code.
119 set_block_size (_session.get_block_size());
120 allocate_temporary_buffers ();
123 assert(_n_channels == ChanCount(DataType::AUDIO, 1));
126 AudioDiskstream::~AudioDiskstream ()
128 DEBUG_TRACE (DEBUG::Destruction, string_compose ("Audio Diskstream %1 destructor\n", _name));
131 RCUWriter<ChannelList> writer (channels);
132 boost::shared_ptr<ChannelList> c = writer.get_copy();
134 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
145 AudioDiskstream::allocate_working_buffers()
147 assert(disk_io_frames() > 0);
149 _working_buffers_size = disk_io_frames();
150 _mixdown_buffer = new Sample[_working_buffers_size];
151 _gain_buffer = new gain_t[_working_buffers_size];
155 AudioDiskstream::free_working_buffers()
157 delete [] _mixdown_buffer;
158 delete [] _gain_buffer;
159 _working_buffers_size = 0;
165 AudioDiskstream::non_realtime_input_change ()
168 Glib::Mutex::Lock lm (state_lock);
170 if (input_change_pending == NoChange) {
175 RCUWriter<ChannelList> writer (channels);
176 boost::shared_ptr<ChannelList> c = writer.get_copy();
178 _n_channels.set(DataType::AUDIO, c->size());
180 if (_io->n_ports().n_audio() > _n_channels.n_audio()) {
181 add_channel_to (c, _io->n_ports().n_audio() - _n_channels.n_audio());
182 } else if (_io->n_ports().n_audio() < _n_channels.n_audio()) {
183 remove_channel_from (c, _n_channels.n_audio() - _io->n_ports().n_audio());
187 get_input_sources ();
188 set_capture_offset ();
190 if (first_input_change) {
191 set_align_style (_persistent_alignment_style);
192 first_input_change = false;
194 set_align_style_from_io ();
197 input_change_pending = NoChange;
199 /* implicit unlock */
202 /* reset capture files */
204 reset_write_sources (false);
206 /* now refill channel buffers */
208 if (speed() != 1.0f || speed() != -1.0f) {
209 seek ((nframes_t) (_session.transport_frame() * (double) speed()));
211 seek (_session.transport_frame());
216 AudioDiskstream::non_realtime_locate (nframes_t location)
218 /* now refill channel buffers */
220 if (speed() != 1.0f || speed() != -1.0f) {
221 seek ((nframes_t) (location * (double) speed()));
228 AudioDiskstream::get_input_sources ()
230 boost::shared_ptr<ChannelList> c = channels.reader();
233 ChannelList::iterator chan;
234 uint32_t ni = _io->n_ports().n_audio();
235 vector<string> connections;
237 for (n = 0, chan = c->begin(); chan != c->end() && n < ni; ++chan, ++n) {
239 connections.clear ();
241 if (_io->nth (n)->get_connections (connections) == 0) {
243 if ((*chan)->source) {
244 // _source->disable_metering ();
250 (*chan)->source = dynamic_cast<AudioPort*>(_session.engine().get_port_by_name (connections[0]) );
256 AudioDiskstream::find_and_use_playlist (const string& name)
258 boost::shared_ptr<AudioPlaylist> playlist;
260 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (_session.playlists->by_name (name))) == 0) {
261 playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, name));
265 error << string_compose(_("AudioDiskstream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
269 return use_playlist (playlist);
273 AudioDiskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
275 assert(boost::dynamic_pointer_cast<AudioPlaylist>(playlist));
277 Diskstream::use_playlist(playlist);
283 AudioDiskstream::use_new_playlist ()
286 boost::shared_ptr<AudioPlaylist> playlist;
288 if (!in_set_state && destructive()) {
293 newname = Playlist::bump_name (_playlist->name(), _session);
295 newname = Playlist::bump_name (_name, _session);
298 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, newname, hidden()))) != 0) {
300 playlist->set_orig_diskstream_id (id());
301 return use_playlist (playlist);
309 AudioDiskstream::use_copy_playlist ()
311 assert(audio_playlist());
317 if (_playlist == 0) {
318 error << string_compose(_("AudioDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
323 boost::shared_ptr<AudioPlaylist> playlist;
325 newname = Playlist::bump_name (_playlist->name(), _session);
327 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist>(PlaylistFactory::create (audio_playlist(), newname))) != 0) {
328 playlist->set_orig_diskstream_id (id());
329 return use_playlist (playlist);
336 AudioDiskstream::setup_destructive_playlist ()
339 boost::shared_ptr<ChannelList> c = channels.reader();
341 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
342 srcs.push_back ((*chan)->write_source);
345 /* a single full-sized region */
347 boost::shared_ptr<Region> region (RegionFactory::create (srcs, 0, max_frames - srcs.front()->natural_position(), _name));
348 _playlist->add_region (region, srcs.front()->natural_position());
352 AudioDiskstream::use_destructive_playlist ()
354 /* this is called from the XML-based constructor or ::set_destructive. when called,
355 we already have a playlist and a region, but we need to
356 set up our sources for write. we use the sources associated
357 with the (presumed single, full-extent) region.
360 boost::shared_ptr<Region> rp = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
363 reset_write_sources (false, true);
367 boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
370 throw failed_constructor();
373 /* be sure to stretch the region out to the maximum length */
375 region->set_length (max_frames - region->position(), this);
378 ChannelList::iterator chan;
379 boost::shared_ptr<ChannelList> c = channels.reader();
381 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
382 (*chan)->write_source = boost::dynamic_pointer_cast<AudioFileSource>(region->source (n));
383 assert((*chan)->write_source);
384 (*chan)->write_source->set_allow_remove_if_empty (false);
386 /* this might be false if we switched modes, so force it */
388 (*chan)->write_source->set_destructive (true);
391 /* the source list will never be reset for a destructive track */
395 AudioDiskstream::prepare_record_status(nframes_t capture_start_frame)
397 if (recordable() && destructive()) {
398 boost::shared_ptr<ChannelList> c = channels.reader();
399 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
401 RingBufferNPT<CaptureTransition>::rw_vector transvec;
402 (*chan)->capture_transition_buf->get_write_vector(&transvec);
404 if (transvec.len[0] > 0) {
405 transvec.buf[0]->type = CaptureStart;
406 transvec.buf[0]->capture_val = capture_start_frame;
407 (*chan)->capture_transition_buf->increment_write_ptr(1);
411 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
419 AudioDiskstream::process (nframes_t transport_frame, nframes_t nframes, bool can_record, bool rec_monitors_input)
422 boost::shared_ptr<ChannelList> c = channels.reader();
423 ChannelList::iterator chan;
425 nframes_t rec_offset = 0;
426 nframes_t rec_nframes = 0;
427 bool nominally_recording;
428 bool re = record_enabled ();
429 bool collect_playback = false;
431 /* if we've already processed the frames corresponding to this call,
432 just return. this allows multiple routes that are taking input
433 from this diskstream to call our ::process() method, but have
434 this stuff only happen once. more commonly, it allows both
435 the AudioTrack that is using this AudioDiskstream *and* the Session
436 to call process() without problems.
443 commit_should_unlock = false;
445 if (!_io || !_io->active()) {
450 check_record_status (transport_frame, nframes, can_record);
452 nominally_recording = (can_record && re);
459 /* This lock is held until the end of AudioDiskstream::commit, so these two functions
460 must always be called as a pair. The only exception is if this function
461 returns a non-zero value, in which case, ::commit should not be called.
464 // If we can't take the state lock return.
465 if (!state_lock.trylock()) {
468 commit_should_unlock = true;
469 adjust_capture_position = 0;
471 for (chan = c->begin(); chan != c->end(); ++chan) {
472 (*chan)->current_capture_buffer = 0;
473 (*chan)->current_playback_buffer = 0;
476 if (nominally_recording || (_session.get_record_enabled() && _session.config.get_punch_in())) {
477 // Safeguard against situations where process() goes haywire when autopunching and last_recordable_frame < first_recordable_frame
478 if (last_recordable_frame < first_recordable_frame) {
479 last_recordable_frame = max_frames;
482 OverlapType ot = coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
484 calculate_record_range(ot, transport_frame, nframes, rec_nframes, rec_offset);
486 if (rec_nframes && !was_recording) {
487 capture_captured = 0;
488 was_recording = true;
493 if (can_record && !_last_capture_regions.empty()) {
494 _last_capture_regions.clear ();
497 if (nominally_recording || rec_nframes) {
499 uint32_t limit = _io->n_ports ().n_audio();
501 /* one or more ports could already have been removed from _io, but our
502 channel setup hasn't yet been updated. prevent us from trying to
503 use channels that correspond to missing ports. note that the
504 process callback (from which this is called) is always atomic
505 with respect to port removal/addition.
508 for (n = 0, chan = c->begin(); chan != c->end() && n < limit; ++chan, ++n) {
510 ChannelInfo* chaninfo (*chan);
512 chaninfo->capture_buf->get_write_vector (&chaninfo->capture_vector);
514 if (rec_nframes <= chaninfo->capture_vector.len[0]) {
516 chaninfo->current_capture_buffer = chaninfo->capture_vector.buf[0];
518 /* note: grab the entire port buffer, but only copy what we were supposed to
519 for recording, and use rec_offset
522 AudioPort* const ap = _io->audio (n);
524 assert(rec_nframes <= ap->get_audio_buffer(nframes).capacity());
525 memcpy (chaninfo->current_capture_buffer, ap->get_audio_buffer (rec_nframes).data(rec_offset), sizeof (Sample) * rec_nframes);
530 nframes_t total = chaninfo->capture_vector.len[0] + chaninfo->capture_vector.len[1];
532 if (rec_nframes > total) {
537 AudioPort* const ap = _io->audio (n);
540 Sample* buf = ap->get_audio_buffer(nframes).data();
541 nframes_t first = chaninfo->capture_vector.len[0];
543 memcpy (chaninfo->capture_wrap_buffer, buf, sizeof (Sample) * first);
544 memcpy (chaninfo->capture_vector.buf[0], buf, sizeof (Sample) * first);
545 memcpy (chaninfo->capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
546 memcpy (chaninfo->capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
548 chaninfo->current_capture_buffer = chaninfo->capture_wrap_buffer;
555 finish_capture (rec_monitors_input, c);
562 /* data will be written to disk */
564 if (rec_nframes == nframes && rec_offset == 0) {
566 for (chan = c->begin(); chan != c->end(); ++chan) {
567 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
570 playback_distance = nframes;
575 /* we can't use the capture buffer as the playback buffer, because
576 we recorded only a part of the current process' cycle data
580 collect_playback = true;
583 adjust_capture_position = rec_nframes;
585 } else if (nominally_recording) {
587 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
589 for (chan = c->begin(); chan != c->end(); ++chan) {
590 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
593 playback_distance = nframes;
597 collect_playback = true;
600 if (collect_playback) {
602 /* we're doing playback */
604 nframes_t necessary_samples;
606 /* no varispeed playback if we're recording, because the output .... TBD */
608 if (rec_nframes == 0 && _actual_speed != 1.0f) {
609 necessary_samples = (nframes_t) floor ((nframes * fabs (_actual_speed))) + 1;
611 necessary_samples = nframes;
614 for (chan = c->begin(); chan != c->end(); ++chan) {
615 (*chan)->playback_buf->get_read_vector (&(*chan)->playback_vector);
620 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
622 ChannelInfo* chaninfo (*chan);
624 if (necessary_samples <= chaninfo->playback_vector.len[0]) {
626 chaninfo->current_playback_buffer = chaninfo->playback_vector.buf[0];
629 nframes_t total = chaninfo->playback_vector.len[0] + chaninfo->playback_vector.len[1];
631 if (necessary_samples > total) {
632 cerr << _name << " Need " << necessary_samples << " total = " << total << endl;
633 cerr << "underrun for " << _name << endl;
639 memcpy ((char *) chaninfo->playback_wrap_buffer,
640 chaninfo->playback_vector.buf[0],
641 chaninfo->playback_vector.len[0] * sizeof (Sample));
642 memcpy (chaninfo->playback_wrap_buffer + chaninfo->playback_vector.len[0],
643 chaninfo->playback_vector.buf[1],
644 (necessary_samples - chaninfo->playback_vector.len[0])
647 chaninfo->current_playback_buffer = chaninfo->playback_wrap_buffer;
652 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
653 process_varispeed_playback(nframes, c);
655 playback_distance = nframes;
658 _speed = _target_speed;
669 /* we're exiting with failure, so ::commit will not
670 be called. unlock the state lock.
673 commit_should_unlock = false;
681 AudioDiskstream::process_varispeed_playback(nframes_t nframes, boost::shared_ptr<ChannelList> c)
683 ChannelList::iterator chan;
685 interpolation.set_speed (_target_speed);
688 for (chan = c->begin(); chan != c->end(); ++chan, ++channel) {
689 ChannelInfo* chaninfo (*chan);
691 playback_distance = interpolation.interpolate (
692 channel, nframes, chaninfo->current_playback_buffer, chaninfo->speed_buffer);
694 chaninfo->current_playback_buffer = chaninfo->speed_buffer;
699 AudioDiskstream::commit (nframes_t /*nframes*/)
701 bool need_butler = false;
703 if (!_io || !_io->active()) {
707 if (_actual_speed < 0.0) {
708 playback_sample -= playback_distance;
710 playback_sample += playback_distance;
713 boost::shared_ptr<ChannelList> c = channels.reader();
714 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
716 (*chan)->playback_buf->increment_read_ptr (playback_distance);
718 if (adjust_capture_position) {
719 (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
723 if (adjust_capture_position != 0) {
724 capture_captured += adjust_capture_position;
725 adjust_capture_position = 0;
729 if (_io && _io->active()) {
730 need_butler = c->front()->playback_buf->write_space() >= c->front()->playback_buf->bufsize() / 2;
735 if (_io && _io->active()) {
736 need_butler = c->front()->playback_buf->write_space() >= disk_io_chunk_frames
737 || c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
739 need_butler = c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
743 if (commit_should_unlock) {
753 AudioDiskstream::set_pending_overwrite (bool yn)
755 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
757 pending_overwrite = yn;
759 overwrite_frame = playback_sample;
760 overwrite_offset = channels.reader()->front()->playback_buf->get_read_ptr();
764 AudioDiskstream::overwrite_existing_buffers ()
766 boost::shared_ptr<ChannelList> c = channels.reader();
767 Sample* mixdown_buffer;
770 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
772 overwrite_queued = false;
774 /* assume all are the same size */
775 nframes_t size = c->front()->playback_buf->bufsize();
777 mixdown_buffer = new Sample[size];
778 gain_buffer = new float[size];
780 /* reduce size so that we can fill the buffer correctly. */
786 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
788 start = overwrite_frame;
789 nframes_t cnt = size;
791 /* to fill the buffer without resetting the playback sample, we need to
792 do it one or two chunks (normally two).
794 |----------------------------------------------------------------------|
798 |<- second chunk->||<----------------- first chunk ------------------>|
802 nframes_t to_read = size - overwrite_offset;
804 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, *chan, n, reversed)) {
805 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
806 _id, size, playback_sample) << endmsg;
814 if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer,
815 start, cnt, *chan, n, reversed)) {
816 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
817 _id, size, playback_sample) << endmsg;
826 pending_overwrite = false;
827 delete [] gain_buffer;
828 delete [] mixdown_buffer;
833 AudioDiskstream::seek (nframes_t frame, bool complete_refill)
837 ChannelList::iterator chan;
838 boost::shared_ptr<ChannelList> c = channels.reader();
840 Glib::Mutex::Lock lm (state_lock);
842 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
843 (*chan)->playback_buf->reset ();
844 (*chan)->capture_buf->reset ();
847 /* can't rec-enable in destructive mode if transport is before start */
849 if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
850 disengage_record_enable ();
853 playback_sample = frame;
856 if (complete_refill) {
857 while ((ret = do_refill_with_alloc ()) > 0) ;
859 ret = do_refill_with_alloc ();
866 AudioDiskstream::can_internal_playback_seek (nframes_t distance)
868 ChannelList::iterator chan;
869 boost::shared_ptr<ChannelList> c = channels.reader();
871 for (chan = c->begin(); chan != c->end(); ++chan) {
872 if ((*chan)->playback_buf->read_space() < distance) {
880 AudioDiskstream::internal_playback_seek (nframes_t distance)
882 ChannelList::iterator chan;
883 boost::shared_ptr<ChannelList> c = channels.reader();
885 for (chan = c->begin(); chan != c->end(); ++chan) {
886 (*chan)->playback_buf->increment_read_ptr (distance);
889 first_recordable_frame += distance;
890 playback_sample += distance;
896 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer, nframes_t& start, nframes_t cnt,
897 ChannelInfo* /*channel_info*/, int channel, bool reversed)
899 nframes_t this_read = 0;
901 nframes_t loop_end = 0;
902 nframes_t loop_start = 0;
903 nframes_t loop_length = 0;
904 nframes_t offset = 0;
907 /* XXX we don't currently play loops in reverse. not sure why */
911 /* Make the use of a Location atomic for this read operation.
913 Note: Locations don't get deleted, so all we care about
914 when I say "atomic" is that we are always pointing to
915 the same one and using a start/length values obtained
919 if ((loc = loop_location) != 0) {
920 loop_start = loc->start();
921 loop_end = loc->end();
922 loop_length = loop_end - loop_start;
925 /* if we are looping, ensure that the first frame we read is at the correct
926 position within the loop.
929 if (loc && start >= loop_end) {
930 //cerr << "start adjusted from " << start;
931 start = loop_start + ((start - loop_start) % loop_length);
932 //cerr << "to " << start << endl;
935 //cerr << "start is " << start << " loopstart: " << loop_start << " loopend: " << loop_end << endl;
944 /* take any loop into account. we can't read past the end of the loop. */
946 if (loc && (loop_end - start < cnt)) {
947 this_read = loop_end - start;
948 //cerr << "reloop true: thisread: " << this_read << " cnt: " << cnt << endl;
955 if (this_read == 0) {
959 this_read = min(cnt,this_read);
961 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
962 error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), _id, this_read,
967 _read_data_count = _playlist->read_data_count();
971 swap_by_ptr (buf, buf + this_read - 1);
975 /* if we read to the end of the loop, go back to the beginning */
992 AudioDiskstream::do_refill_with_alloc ()
994 Sample* mix_buf = new Sample[disk_io_chunk_frames];
995 float* gain_buf = new float[disk_io_chunk_frames];
997 int ret = _do_refill(mix_buf, gain_buf);
1006 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer)
1010 RingBufferNPT<Sample>::rw_vector vector;
1011 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1012 nframes_t total_space;
1013 nframes_t zero_fill;
1015 ChannelList::iterator i;
1016 boost::shared_ptr<ChannelList> c = channels.reader();
1023 assert(mixdown_buffer);
1024 assert(gain_buffer);
1031 c->front()->playback_buf->get_write_vector (&vector);
1033 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1037 /* if there are 2+ chunks of disk i/o possible for
1038 this track, let the caller know so that it can arrange
1039 for us to be called again, ASAP.
1042 if (total_space >= (_slaved?3:2) * disk_io_chunk_frames) {
1046 /* if we're running close to normal speed and there isn't enough
1047 space to do disk_io_chunk_frames of I/O, then don't bother.
1049 at higher speeds, just do it because the sync between butler
1050 and audio thread may not be good enough.
1053 if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1057 /* when slaved, don't try to get too close to the read pointer. this
1058 leaves space for the buffer reversal to have something useful to
1062 if (_slaved && total_space < (c->front()->playback_buf->bufsize() / 2)) {
1066 /* never do more than disk_io_chunk_frames worth of disk input per call (limit doesn't apply for memset) */
1068 total_space = min (disk_io_chunk_frames, total_space);
1072 if (file_frame == 0) {
1074 /* at start: nothing to do but fill with silence */
1076 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1078 ChannelInfo* chan (*i);
1079 chan->playback_buf->get_write_vector (&vector);
1080 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1081 if (vector.len[1]) {
1082 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1084 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1089 if (file_frame < total_space) {
1091 /* too close to the start: read what we can,
1092 and then zero fill the rest
1095 zero_fill = total_space - file_frame;
1096 total_space = file_frame;
1106 if (file_frame == max_frames) {
1108 /* at end: nothing to do but fill with silence */
1110 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1112 ChannelInfo* chan (*i);
1113 chan->playback_buf->get_write_vector (&vector);
1114 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1115 if (vector.len[1]) {
1116 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1118 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1123 if (file_frame > max_frames - total_space) {
1125 /* to close to the end: read what we can, and zero fill the rest */
1127 zero_fill = total_space - (max_frames - file_frame);
1128 total_space = max_frames - file_frame;
1135 nframes_t file_frame_tmp = 0;
1137 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1139 ChannelInfo* chan (*i);
1142 nframes_t len1, len2;
1144 chan->playback_buf->get_write_vector (&vector);
1146 if (vector.len[0] > disk_io_chunk_frames) {
1148 /* we're not going to fill the first chunk, so certainly do not bother with the
1149 other part. it won't be connected with the part we do fill, as in:
1151 .... => writable space
1152 ++++ => readable space
1153 ^^^^ => 1 x disk_io_chunk_frames that would be filled
1155 |......|+++++++++++++|...............................|
1160 So, just pretend that the buf1 part isn't there.
1170 file_frame_tmp = file_frame;
1172 buf1 = vector.buf[0];
1173 len1 = vector.len[0];
1174 buf2 = vector.buf[1];
1175 len2 = vector.len[1];
1177 to_read = min (ts, len1);
1178 to_read = min (to_read, disk_io_chunk_frames);
1182 if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1187 chan->playback_buf->increment_write_ptr (to_read);
1191 to_read = min (ts, len2);
1195 /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1196 so read some or all of vector.len[1] as well.
1199 if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1204 chan->playback_buf->increment_write_ptr (to_read);
1213 file_frame = file_frame_tmp;
1220 /** Flush pending data to disk.
1222 * Important note: this function will write *AT MOST* disk_io_chunk_frames
1223 * of data to disk. it will never write more than that. If it writes that
1224 * much and there is more than that waiting to be written, it will return 1,
1225 * otherwise 0 on success or -1 on failure.
1227 * If there is less than disk_io_chunk_frames to be written, no data will be
1228 * written at all unless @a force_flush is true.
1231 AudioDiskstream::do_flush (RunContext /*context*/, bool force_flush)
1235 RingBufferNPT<Sample>::rw_vector vector;
1236 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1239 _write_data_count = 0;
1241 transvec.buf[0] = 0;
1242 transvec.buf[1] = 0;
1246 boost::shared_ptr<ChannelList> c = channels.reader();
1247 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1249 (*chan)->capture_buf->get_read_vector (&vector);
1251 total = vector.len[0] + vector.len[1];
1253 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1257 /* if there are 2+ chunks of disk i/o possible for
1258 this track, let the caller know so that it can arrange
1259 for us to be called again, ASAP.
1261 if we are forcing a flush, then if there is* any* extra
1262 work, let the caller know.
1264 if we are no longer recording and there is any extra work,
1265 let the caller know too.
1268 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1272 to_write = min (disk_io_chunk_frames, (nframes_t) vector.len[0]);
1274 // check the transition buffer when recording destructive
1275 // important that we get this after the capture buf
1277 if (destructive()) {
1278 (*chan)->capture_transition_buf->get_read_vector(&transvec);
1279 size_t transcount = transvec.len[0] + transvec.len[1];
1280 bool have_start = false;
1283 for (ti=0; ti < transcount; ++ti) {
1284 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1286 if (captrans.type == CaptureStart) {
1287 // by definition, the first data we got above represents the given capture pos
1289 (*chan)->write_source->mark_capture_start (captrans.capture_val);
1290 (*chan)->curr_capture_cnt = 0;
1294 else if (captrans.type == CaptureEnd) {
1296 // capture end, the capture_val represents total frames in capture
1298 if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1300 // shorten to make the write a perfect fit
1301 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
1303 if (nto_write < to_write) {
1304 ret = 1; // should we?
1306 to_write = nto_write;
1308 (*chan)->write_source->mark_capture_end ();
1310 // increment past this transition, but go no further
1315 // actually ends just beyond this chunk, so force more work
1323 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1327 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1328 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1332 (*chan)->capture_buf->increment_read_ptr (to_write);
1333 (*chan)->curr_capture_cnt += to_write;
1335 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1337 /* we wrote all of vector.len[0] but it wasn't an entire
1338 disk_io_chunk_frames of data, so arrange for some part
1339 of vector.len[1] to be flushed to disk as well.
1342 to_write = min ((nframes_t)(disk_io_chunk_frames - to_write), (nframes_t) vector.len[1]);
1344 if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1345 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1349 _write_data_count += (*chan)->write_source->write_data_count();
1351 (*chan)->capture_buf->increment_read_ptr (to_write);
1352 (*chan)->curr_capture_cnt += to_write;
1361 AudioDiskstream::transport_stopped (struct tm& when, time_t twhen, bool abort_capture)
1363 uint32_t buffer_position;
1364 bool more_work = true;
1366 boost::shared_ptr<AudioRegion> region;
1367 nframes_t total_capture;
1369 SourceList::iterator src;
1370 ChannelList::iterator chan;
1371 vector<CaptureInfo*>::iterator ci;
1372 boost::shared_ptr<ChannelList> c = channels.reader();
1374 bool mark_write_completed = false;
1376 finish_capture (true, c);
1378 /* butler is already stopped, but there may be work to do
1379 to flush remaining data to disk.
1382 while (more_work && !err) {
1383 switch (do_flush (TransportContext, true)) {
1390 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1395 /* XXX is there anything we can do if err != 0 ? */
1396 Glib::Mutex::Lock lm (capture_info_lock);
1398 if (capture_info.empty()) {
1402 if (abort_capture) {
1404 if (destructive()) {
1408 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1410 if ((*chan)->write_source) {
1412 (*chan)->write_source->mark_for_remove ();
1413 (*chan)->write_source->drop_references ();
1414 (*chan)->write_source.reset ();
1417 /* new source set up in "out" below */
1423 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1424 total_capture += (*ci)->frames;
1427 /* figure out the name for this take */
1429 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1431 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1435 s->update_header (capture_info.front()->start, when, twhen);
1436 s->set_captured_for (_name);
1437 s->mark_immutable ();
1438 if (Config->get_auto_analyse_audio()) {
1439 Analyser::queue_source_for_analysis (s, true);
1444 /* destructive tracks have a single, never changing region */
1446 if (destructive()) {
1448 /* send a signal that any UI can pick up to do the right thing. there is
1449 a small problem here in that a UI may need the peak data to be ready
1450 for the data that was recorded and this isn't interlocked with that
1451 process. this problem is deferred to the UI.
1454 _playlist->Modified();
1458 string whole_file_region_name;
1459 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1461 /* Register a new region with the Session that
1462 describes the entire source. Do this first
1463 so that any sub-regions will obviously be
1464 children of this one (later!)
1468 boost::shared_ptr<Region> rx (RegionFactory::create (srcs,
1469 c->front()->write_source->last_capture_start_frame(), total_capture,
1470 whole_file_region_name, 0,
1471 Region::Flag (Region::DefaultFlags|Region::Automatic|Region::WholeFile)));
1473 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1474 region->special_set_position (capture_info.front()->start);
1478 catch (failed_constructor& err) {
1479 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1483 _last_capture_regions.push_back (region);
1485 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1487 XMLNode &before = _playlist->get_state();
1488 _playlist->freeze ();
1490 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1494 _session.region_name (region_name, whole_file_region_name, false);
1496 // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->frames << " add region " << region_name << endl;
1499 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, buffer_position, (*ci)->frames, region_name));
1500 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1503 catch (failed_constructor& err) {
1504 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1505 continue; /* XXX is this OK? */
1508 region->GoingAway.connect_same_thread (*this, boost::bind (&Diskstream::remove_region_from_last_capture, this, boost::weak_ptr<Region>(region)));
1510 _last_capture_regions.push_back (region);
1512 i_am_the_modifier++;
1513 _playlist->add_region (region, (*ci)->start, 1, non_layered());
1514 i_am_the_modifier--;
1516 buffer_position += (*ci)->frames;
1520 XMLNode &after = _playlist->get_state();
1521 _session.add_command (new MementoCommand<Playlist>(*_playlist, &before, &after));
1524 mark_write_completed = true;
1527 reset_write_sources (mark_write_completed);
1531 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1535 capture_info.clear ();
1536 capture_start_frame = 0;
1540 AudioDiskstream::transport_looped (nframes_t transport_frame)
1542 if (was_recording) {
1543 // all we need to do is finish this capture, with modified capture length
1544 boost::shared_ptr<ChannelList> c = channels.reader();
1546 // adjust the capture length knowing that the data will be recorded to disk
1547 // only necessary after the first loop where we're recording
1548 if (capture_info.size() == 0) {
1549 capture_captured += _capture_offset;
1551 if (_alignment_style == ExistingMaterial) {
1552 capture_captured += _session.worst_output_latency();
1554 capture_captured += _roll_delay;
1558 finish_capture (true, c);
1560 // the next region will start recording via the normal mechanism
1561 // we'll set the start position to the current transport pos
1562 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1563 capture_start_frame = transport_frame;
1564 first_recordable_frame = transport_frame; // mild lie
1565 last_recordable_frame = max_frames;
1566 was_recording = true;
1568 if (recordable() && destructive()) {
1569 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1571 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1572 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1574 if (transvec.len[0] > 0) {
1575 transvec.buf[0]->type = CaptureStart;
1576 transvec.buf[0]->capture_val = capture_start_frame;
1577 (*chan)->capture_transition_buf->increment_write_ptr(1);
1581 fatal << X_("programming error: capture_transition_buf is full on rec loop! inconceivable!")
1591 AudioDiskstream::finish_capture (bool /*rec_monitors_input*/, boost::shared_ptr<ChannelList> c)
1593 was_recording = false;
1595 if (capture_captured == 0) {
1599 if (recordable() && destructive()) {
1600 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1602 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1603 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1605 if (transvec.len[0] > 0) {
1606 transvec.buf[0]->type = CaptureEnd;
1607 transvec.buf[0]->capture_val = capture_captured;
1608 (*chan)->capture_transition_buf->increment_write_ptr(1);
1612 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1618 CaptureInfo* ci = new CaptureInfo;
1620 ci->start = capture_start_frame;
1621 ci->frames = capture_captured;
1623 /* XXX theoretical race condition here. Need atomic exchange ?
1624 However, the circumstances when this is called right
1625 now (either on record-disable or transport_stopped)
1626 mean that no actual race exists. I think ...
1627 We now have a capture_info_lock, but it is only to be used
1628 to synchronize in the transport_stop and the capture info
1629 accessors, so that invalidation will not occur (both non-realtime).
1632 // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1634 capture_info.push_back (ci);
1635 capture_captured = 0;
1637 /* now we've finished a capture, reset first_recordable_frame for next time */
1638 first_recordable_frame = max_frames;
1642 AudioDiskstream::set_record_enabled (bool yn)
1644 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0) {
1648 /* can't rec-enable in destructive mode if transport is before start */
1650 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1654 /* yes, i know that this not proof against race conditions, but its
1655 good enough. i think.
1658 if (record_enabled() != yn) {
1660 engage_record_enable ();
1662 disengage_record_enable ();
1668 AudioDiskstream::engage_record_enable ()
1670 bool rolling = _session.transport_speed() != 0.0f;
1671 boost::shared_ptr<ChannelList> c = channels.reader();
1673 g_atomic_int_set (&_record_enabled, 1);
1674 capturing_sources.clear ();
1676 if (Config->get_monitoring_model() == HardwareMonitoring) {
1678 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1679 if ((*chan)->source) {
1680 (*chan)->source->ensure_monitor_input (!(_session.config.get_auto_input() && rolling));
1682 capturing_sources.push_back ((*chan)->write_source);
1683 (*chan)->write_source->mark_streaming_write_started ();
1687 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1688 capturing_sources.push_back ((*chan)->write_source);
1689 (*chan)->write_source->mark_streaming_write_started ();
1693 RecordEnableChanged (); /* EMIT SIGNAL */
1697 AudioDiskstream::disengage_record_enable ()
1699 g_atomic_int_set (&_record_enabled, 0);
1700 boost::shared_ptr<ChannelList> c = channels.reader();
1701 if (Config->get_monitoring_model() == HardwareMonitoring) {
1702 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1703 if ((*chan)->source) {
1704 (*chan)->source->ensure_monitor_input (false);
1708 capturing_sources.clear ();
1709 RecordEnableChanged (); /* EMIT SIGNAL */
1713 AudioDiskstream::get_state ()
1715 XMLNode* node = new XMLNode ("AudioDiskstream");
1717 LocaleGuard lg (X_("POSIX"));
1718 boost::shared_ptr<ChannelList> c = channels.reader();
1720 node->add_property ("flags", enum_2_string (_flags));
1722 snprintf (buf, sizeof(buf), "%zd", c->size());
1723 node->add_property ("channels", buf);
1725 node->add_property ("playlist", _playlist->name());
1727 snprintf (buf, sizeof(buf), "%.12g", _visible_speed);
1728 node->add_property ("speed", buf);
1730 node->add_property("name", _name);
1731 id().print (buf, sizeof (buf));
1732 node->add_property("id", buf);
1734 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1736 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1737 XMLNode* cs_grandchild;
1739 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1740 cs_grandchild = new XMLNode (X_("file"));
1741 cs_grandchild->add_property (X_("path"), (*i)->path());
1742 cs_child->add_child_nocopy (*cs_grandchild);
1745 /* store the location where capture will start */
1749 if (_session.config.get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1750 snprintf (buf, sizeof (buf), "%" PRId64, pi->start());
1752 snprintf (buf, sizeof (buf), "%" PRId64, _session.transport_frame());
1755 cs_child->add_property (X_("at"), buf);
1756 node->add_child_nocopy (*cs_child);
1760 node->add_child_copy (*_extra_xml);
1767 AudioDiskstream::set_state (const XMLNode& node, int /*version*/)
1769 const XMLProperty* prop;
1770 XMLNodeList nlist = node.children();
1771 XMLNodeIterator niter;
1772 uint32_t nchans = 1;
1773 XMLNode* capture_pending_node = 0;
1774 LocaleGuard lg (X_("POSIX"));
1776 in_set_state = true;
1778 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1779 if ((*niter)->name() == IO::state_node_name) {
1780 deprecated_io_node = new XMLNode (**niter);
1783 if ((*niter)->name() == X_("CapturingSources")) {
1784 capture_pending_node = *niter;
1788 /* prevent write sources from being created */
1790 in_set_state = true;
1792 if ((prop = node.property ("name")) != 0) {
1793 _name = prop->value();
1796 if (deprecated_io_node) {
1797 if ((prop = deprecated_io_node->property ("id")) != 0) {
1798 _id = prop->value ();
1801 if ((prop = node.property ("id")) != 0) {
1802 _id = prop->value ();
1806 if ((prop = node.property ("flags")) != 0) {
1807 _flags = Flag (string_2_enum (prop->value(), _flags));
1810 if ((prop = node.property ("channels")) != 0) {
1811 nchans = atoi (prop->value().c_str());
1814 // create necessary extra channels
1815 // we are always constructed with one and we always need one
1817 _n_channels.set(DataType::AUDIO, channels.reader()->size());
1819 if (nchans > _n_channels.n_audio()) {
1821 add_channel (nchans - _n_channels.n_audio());
1822 IO::PortCountChanged(_n_channels);
1824 } else if (nchans < _n_channels.n_audio()) {
1826 remove_channel (_n_channels.n_audio() - nchans);
1829 if ((prop = node.property ("playlist")) == 0) {
1834 bool had_playlist = (_playlist != 0);
1836 if (find_and_use_playlist (prop->value())) {
1840 if (!had_playlist) {
1841 _playlist->set_orig_diskstream_id (_id);
1844 if (!destructive() && capture_pending_node) {
1845 /* destructive streams have one and only one source per channel,
1846 and so they never end up in pending capture in any useful
1849 use_pending_capture_data (*capture_pending_node);
1854 if ((prop = node.property ("speed")) != 0) {
1855 double sp = atof (prop->value().c_str());
1857 if (realtime_set_speed (sp, false)) {
1858 non_realtime_set_speed ();
1862 in_set_state = false;
1864 /* make sure this is clear before we do anything else */
1866 capturing_sources.clear ();
1868 /* write sources are handled when we handle the input set
1869 up of the IO that owns this DS (::non_realtime_input_change())
1876 AudioDiskstream::use_new_write_source (uint32_t n)
1878 boost::shared_ptr<ChannelList> c = channels.reader();
1880 if (!recordable()) {
1884 if (n >= c->size()) {
1885 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
1889 ChannelInfo* chan = (*c)[n];
1891 if (chan->write_source) {
1892 chan->write_source->done_with_peakfile_writes ();
1893 chan->write_source->set_allow_remove_if_empty (true);
1894 chan->write_source.reset ();
1898 if ((chan->write_source = _session.create_audio_source_for_session (*this, n, destructive())) == 0) {
1899 throw failed_constructor();
1903 catch (failed_constructor &err) {
1904 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
1905 chan->write_source.reset ();
1909 /* do not remove destructive files even if they are empty */
1911 chan->write_source->set_allow_remove_if_empty (!destructive());
1913 /* until we write, this file is considered removable */
1915 chan->write_source->mark_for_remove ();
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, Timecode 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)
2068 while (how_many--) {
2069 c->push_back (new ChannelInfo(_session.butler()->audio_diskstream_buffer_size(), speed_buffer_size, wrap_buffer_size));
2070 interpolation.add_channel_to (_session.butler()->audio_diskstream_buffer_size(), speed_buffer_size);
2073 _n_channels.set(DataType::AUDIO, c->size());
2079 AudioDiskstream::add_channel (uint32_t how_many)
2081 RCUWriter<ChannelList> writer (channels);
2082 boost::shared_ptr<ChannelList> c = writer.get_copy();
2084 return add_channel_to (c, how_many);
2088 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2090 while (how_many-- && !c->empty()) {
2091 // FIXME: crash (thread safe with RCU?)
2092 // memory leak, when disabled.... :(
2095 interpolation.remove_channel_from ();
2098 _n_channels.set(DataType::AUDIO, c->size());
2104 AudioDiskstream::remove_channel (uint32_t how_many)
2106 RCUWriter<ChannelList> writer (channels);
2107 boost::shared_ptr<ChannelList> c = writer.get_copy();
2109 return remove_channel_from (c, how_many);
2113 AudioDiskstream::playback_buffer_load () const
2115 boost::shared_ptr<ChannelList> c = channels.reader();
2117 return (float) ((double) c->front()->playback_buf->read_space()/
2118 (double) c->front()->playback_buf->bufsize());
2122 AudioDiskstream::capture_buffer_load () const
2124 boost::shared_ptr<ChannelList> c = channels.reader();
2126 return (float) ((double) c->front()->capture_buf->write_space()/
2127 (double) c->front()->capture_buf->bufsize());
2131 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2133 const XMLProperty* prop;
2134 XMLNodeList nlist = node.children();
2135 XMLNodeIterator niter;
2136 boost::shared_ptr<AudioFileSource> fs;
2137 boost::shared_ptr<AudioFileSource> first_fs;
2138 SourceList pending_sources;
2141 if ((prop = node.property (X_("at"))) == 0) {
2145 if (sscanf (prop->value().c_str(), "%" PRIu32, &position) != 1) {
2149 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2150 if ((*niter)->name() == X_("file")) {
2152 if ((prop = (*niter)->property (X_("path"))) == 0) {
2156 // This protects sessions from errant CapturingSources in stored sessions
2158 if (stat (prop->value().c_str(), &sbuf)) {
2163 fs = boost::dynamic_pointer_cast<AudioFileSource> (
2164 SourceFactory::createWritable (DataType::AUDIO, _session,
2165 prop->value(), false, _session.frame_rate()));
2168 catch (failed_constructor& err) {
2169 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2170 _name, prop->value())
2175 pending_sources.push_back (fs);
2177 if (first_fs == 0) {
2181 fs->set_captured_for (_name);
2185 if (pending_sources.size() == 0) {
2186 /* nothing can be done */
2190 if (pending_sources.size() != _n_channels.n_audio()) {
2191 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2196 boost::shared_ptr<AudioRegion> region;
2199 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (
2200 pending_sources, 0, first_fs->length(first_fs->timeline_position()),
2201 region_name_from_path (first_fs->name(), true), 0,
2202 Region::Flag (Region::DefaultFlags|Region::Automatic|Region::WholeFile)));
2203 region->special_set_position (0);
2206 catch (failed_constructor& err) {
2207 error << string_compose (
2208 _("%1: cannot create whole-file region from pending capture sources"),
2215 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (
2216 pending_sources, 0, first_fs->length(first_fs->timeline_position()),
2217 region_name_from_path (first_fs->name(), true)));
2220 catch (failed_constructor& err) {
2221 error << string_compose (_("%1: cannot create region from pending capture sources"),
2228 _playlist->add_region (region, position);
2234 AudioDiskstream::set_non_layered (bool yn)
2236 if (yn != non_layered()) {
2239 _flags = Flag (_flags | NonLayered);
2241 _flags = Flag (_flags & ~NonLayered);
2249 AudioDiskstream::set_destructive (bool yn)
2251 bool bounce_ignored;
2253 if (yn != destructive()) {
2256 /* requestor should already have checked this and
2257 bounced if necessary and desired
2259 if (!can_become_destructive (bounce_ignored)) {
2262 _flags = Flag (_flags | Destructive);
2263 use_destructive_playlist ();
2265 _flags = Flag (_flags & ~Destructive);
2266 reset_write_sources (true, true);
2274 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2277 requires_bounce = false;
2281 /* is there only one region ? */
2283 if (_playlist->n_regions() != 1) {
2284 requires_bounce = true;
2288 boost::shared_ptr<Region> first = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
2291 /* do the source(s) for the region cover the session start position ? */
2293 if (first->position() != _session.current_start_frame()) {
2294 if (first->start() > _session.current_start_frame()) {
2295 requires_bounce = true;
2300 /* is the source used by only 1 playlist ? */
2302 boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2306 if (_session.playlists->source_use_count (afirst->source()) > 1) {
2307 requires_bounce = true;
2311 requires_bounce = false;
2315 AudioDiskstream::ChannelInfo::ChannelInfo (nframes_t bufsize, nframes_t speed_size, nframes_t wrap_size)
2319 current_capture_buffer = 0;
2320 current_playback_buffer = 0;
2321 curr_capture_cnt = 0;
2323 speed_buffer = new Sample[speed_size];
2324 playback_wrap_buffer = new Sample[wrap_size];
2325 capture_wrap_buffer = new Sample[wrap_size];
2327 playback_buf = new RingBufferNPT<Sample> (bufsize);
2328 capture_buf = new RingBufferNPT<Sample> (bufsize);
2329 capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2331 /* touch the ringbuffer buffers, which will cause
2332 them to be mapped into locked physical RAM if
2333 we're running with mlockall(). this doesn't do
2337 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2338 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2339 memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2342 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2345 write_source.reset ();
2348 delete [] speed_buffer;
2351 delete [] playback_wrap_buffer;
2352 playback_wrap_buffer = 0;
2354 delete [] capture_wrap_buffer;
2355 capture_wrap_buffer = 0;
2357 delete playback_buf;
2363 delete capture_transition_buf;
2364 capture_transition_buf = 0;