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"
65 using namespace ARDOUR;
68 size_t AudioDiskstream::_working_buffers_size = 0;
69 Sample* AudioDiskstream::_mixdown_buffer = 0;
70 gain_t* AudioDiskstream::_gain_buffer = 0;
72 AudioDiskstream::AudioDiskstream (Session &sess, const string &name, Diskstream::Flag flag)
73 : Diskstream(sess, name, flag)
74 , deprecated_io_node(NULL)
75 , channels (new ChannelList)
77 /* prevent any write sources from being created */
87 AudioDiskstream::AudioDiskstream (Session& sess, const XMLNode& node)
88 : Diskstream(sess, node)
89 , deprecated_io_node(NULL)
90 , channels (new ChannelList)
95 if (set_state (node, Stateful::loading_state_version)) {
97 throw failed_constructor();
100 in_set_state = false;
103 use_destructive_playlist ();
108 AudioDiskstream::init (Diskstream::Flag f)
112 /* there are no channels at this point, so these
113 two calls just get speed_buffer_size and wrap_buffer
114 size setup without duplicating their code.
117 set_block_size (_session.get_block_size());
118 allocate_temporary_buffers ();
121 assert(_n_channels == ChanCount(DataType::AUDIO, 1));
124 AudioDiskstream::~AudioDiskstream ()
126 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.playlist_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 (bind (mem_fun (*this, &Diskstream::remove_region_from_last_capture), 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 if (yn && channels.reader()->front()->source == 0) {
1656 /* pick up connections not initiated *from* the IO object
1657 we're associated with.
1660 get_input_sources ();
1663 /* yes, i know that this not proof against race conditions, but its
1664 good enough. i think.
1667 if (record_enabled() != yn) {
1669 engage_record_enable ();
1671 disengage_record_enable ();
1677 AudioDiskstream::engage_record_enable ()
1679 bool rolling = _session.transport_speed() != 0.0f;
1680 boost::shared_ptr<ChannelList> c = channels.reader();
1682 g_atomic_int_set (&_record_enabled, 1);
1683 capturing_sources.clear ();
1685 if (Config->get_monitoring_model() == HardwareMonitoring) {
1687 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1688 if ((*chan)->source) {
1689 (*chan)->source->ensure_monitor_input (!(_session.config.get_auto_input() && rolling));
1691 capturing_sources.push_back ((*chan)->write_source);
1692 (*chan)->write_source->mark_streaming_write_started ();
1696 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1697 capturing_sources.push_back ((*chan)->write_source);
1698 (*chan)->write_source->mark_streaming_write_started ();
1702 RecordEnableChanged (); /* EMIT SIGNAL */
1706 AudioDiskstream::disengage_record_enable ()
1708 g_atomic_int_set (&_record_enabled, 0);
1709 boost::shared_ptr<ChannelList> c = channels.reader();
1710 if (Config->get_monitoring_model() == HardwareMonitoring) {
1711 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1712 if ((*chan)->source) {
1713 (*chan)->source->ensure_monitor_input (false);
1717 capturing_sources.clear ();
1718 RecordEnableChanged (); /* EMIT SIGNAL */
1722 AudioDiskstream::get_state ()
1724 XMLNode* node = new XMLNode ("AudioDiskstream");
1726 LocaleGuard lg (X_("POSIX"));
1727 boost::shared_ptr<ChannelList> c = channels.reader();
1729 node->add_property ("flags", enum_2_string (_flags));
1731 snprintf (buf, sizeof(buf), "%zd", c->size());
1732 node->add_property ("channels", buf);
1734 node->add_property ("playlist", _playlist->name());
1736 snprintf (buf, sizeof(buf), "%.12g", _visible_speed);
1737 node->add_property ("speed", buf);
1739 node->add_property("name", _name);
1740 id().print (buf, sizeof (buf));
1741 node->add_property("id", buf);
1743 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1745 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1746 XMLNode* cs_grandchild;
1748 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1749 cs_grandchild = new XMLNode (X_("file"));
1750 cs_grandchild->add_property (X_("path"), (*i)->path());
1751 cs_child->add_child_nocopy (*cs_grandchild);
1754 /* store the location where capture will start */
1758 if (_session.config.get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1759 snprintf (buf, sizeof (buf), "%" PRId64, pi->start());
1761 snprintf (buf, sizeof (buf), "%" PRId64, _session.transport_frame());
1764 cs_child->add_property (X_("at"), buf);
1765 node->add_child_nocopy (*cs_child);
1769 node->add_child_copy (*_extra_xml);
1776 AudioDiskstream::set_state (const XMLNode& node, int /*version*/)
1778 const XMLProperty* prop;
1779 XMLNodeList nlist = node.children();
1780 XMLNodeIterator niter;
1781 uint32_t nchans = 1;
1782 XMLNode* capture_pending_node = 0;
1783 LocaleGuard lg (X_("POSIX"));
1785 in_set_state = true;
1787 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1788 if ((*niter)->name() == IO::state_node_name) {
1789 deprecated_io_node = new XMLNode (**niter);
1792 if ((*niter)->name() == X_("CapturingSources")) {
1793 capture_pending_node = *niter;
1797 /* prevent write sources from being created */
1799 in_set_state = true;
1801 if ((prop = node.property ("name")) != 0) {
1802 _name = prop->value();
1805 if (deprecated_io_node) {
1806 if ((prop = deprecated_io_node->property ("id")) != 0) {
1807 _id = prop->value ();
1810 if ((prop = node.property ("id")) != 0) {
1811 _id = prop->value ();
1815 if ((prop = node.property ("flags")) != 0) {
1816 _flags = Flag (string_2_enum (prop->value(), _flags));
1819 if ((prop = node.property ("channels")) != 0) {
1820 nchans = atoi (prop->value().c_str());
1823 // create necessary extra channels
1824 // we are always constructed with one and we always need one
1826 _n_channels.set(DataType::AUDIO, channels.reader()->size());
1828 if (nchans > _n_channels.n_audio()) {
1830 add_channel (nchans - _n_channels.n_audio());
1831 IO::PortCountChanged(_n_channels);
1833 } else if (nchans < _n_channels.n_audio()) {
1835 remove_channel (_n_channels.n_audio() - nchans);
1838 if ((prop = node.property ("playlist")) == 0) {
1843 bool had_playlist = (_playlist != 0);
1845 if (find_and_use_playlist (prop->value())) {
1849 if (!had_playlist) {
1850 _playlist->set_orig_diskstream_id (_id);
1853 if (!destructive() && capture_pending_node) {
1854 /* destructive streams have one and only one source per channel,
1855 and so they never end up in pending capture in any useful
1858 use_pending_capture_data (*capture_pending_node);
1863 if ((prop = node.property ("speed")) != 0) {
1864 double sp = atof (prop->value().c_str());
1866 if (realtime_set_speed (sp, false)) {
1867 non_realtime_set_speed ();
1871 in_set_state = false;
1873 /* make sure this is clear before we do anything else */
1875 capturing_sources.clear ();
1877 /* write sources are handled when we handle the input set
1878 up of the IO that owns this DS (::non_realtime_input_change())
1885 AudioDiskstream::use_new_write_source (uint32_t n)
1887 boost::shared_ptr<ChannelList> c = channels.reader();
1889 if (!recordable()) {
1893 if (n >= c->size()) {
1894 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
1898 ChannelInfo* chan = (*c)[n];
1900 if (chan->write_source) {
1901 chan->write_source->done_with_peakfile_writes ();
1902 chan->write_source->set_allow_remove_if_empty (true);
1903 chan->write_source.reset ();
1907 if ((chan->write_source = _session.create_audio_source_for_session (*this, n, destructive())) == 0) {
1908 throw failed_constructor();
1912 catch (failed_constructor &err) {
1913 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
1914 chan->write_source.reset ();
1918 /* do not remove destructive files even if they are empty */
1920 chan->write_source->set_allow_remove_if_empty (!destructive());
1922 /* until we write, this file is considered removable */
1924 chan->write_source->mark_for_remove ();
1925 cerr << "New write source " << chan->write_source->path() << " flags " << enum_2_string (chan->write_source->flags()) << endl;
1931 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool /*force*/)
1933 ChannelList::iterator chan;
1934 boost::shared_ptr<ChannelList> c = channels.reader();
1937 if (!_session.writable() || !recordable()) {
1941 capturing_sources.clear ();
1943 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1944 if (!destructive()) {
1946 if ((*chan)->write_source && mark_write_complete) {
1947 (*chan)->write_source->mark_streaming_write_completed ();
1949 use_new_write_source (n);
1951 if (record_enabled()) {
1952 capturing_sources.push_back ((*chan)->write_source);
1956 if ((*chan)->write_source == 0) {
1957 use_new_write_source (n);
1962 if (destructive()) {
1964 /* we now have all our write sources set up, so create the
1965 playlist's single region.
1968 if (_playlist->empty()) {
1969 setup_destructive_playlist ();
1975 AudioDiskstream::rename_write_sources ()
1977 ChannelList::iterator chan;
1978 boost::shared_ptr<ChannelList> c = channels.reader();
1981 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1982 if ((*chan)->write_source != 0) {
1983 (*chan)->write_source->set_source_name (_name, destructive());
1984 /* XXX what to do if one of them fails ? */
1992 AudioDiskstream::set_block_size (nframes_t /*nframes*/)
1994 if (_session.get_block_size() > speed_buffer_size) {
1995 speed_buffer_size = _session.get_block_size();
1996 boost::shared_ptr<ChannelList> c = channels.reader();
1998 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1999 if ((*chan)->speed_buffer)
2000 delete [] (*chan)->speed_buffer;
2001 (*chan)->speed_buffer = new Sample[speed_buffer_size];
2004 allocate_temporary_buffers ();
2008 AudioDiskstream::allocate_temporary_buffers ()
2010 /* make sure the wrap buffer is at least large enough to deal
2011 with the speeds up to 1.2, to allow for micro-variation
2012 when slaving to MTC, Timecode etc.
2015 double sp = max (fabsf (_actual_speed), 1.2f);
2016 nframes_t required_wrap_size = (nframes_t) floor (_session.get_block_size() * sp) + 1;
2018 if (required_wrap_size > wrap_buffer_size) {
2020 boost::shared_ptr<ChannelList> c = channels.reader();
2022 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2023 if ((*chan)->playback_wrap_buffer)
2024 delete [] (*chan)->playback_wrap_buffer;
2025 (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
2026 if ((*chan)->capture_wrap_buffer)
2027 delete [] (*chan)->capture_wrap_buffer;
2028 (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
2031 wrap_buffer_size = required_wrap_size;
2036 AudioDiskstream::monitor_input (bool yn)
2038 boost::shared_ptr<ChannelList> c = channels.reader();
2040 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2042 if ((*chan)->source) {
2043 (*chan)->source->ensure_monitor_input (yn);
2049 AudioDiskstream::set_align_style_from_io ()
2051 bool have_physical = false;
2057 get_input_sources ();
2059 boost::shared_ptr<ChannelList> c = channels.reader();
2061 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2062 if ((*chan)->source && (*chan)->source->flags() & JackPortIsPhysical) {
2063 have_physical = true;
2068 if (have_physical) {
2069 set_align_style (ExistingMaterial);
2071 set_align_style (CaptureTime);
2076 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2078 while (how_many--) {
2079 c->push_back (new ChannelInfo(_session.butler()->audio_diskstream_buffer_size(), speed_buffer_size, wrap_buffer_size));
2080 interpolation.add_channel_to (_session.butler()->audio_diskstream_buffer_size(), speed_buffer_size);
2083 _n_channels.set(DataType::AUDIO, c->size());
2089 AudioDiskstream::add_channel (uint32_t how_many)
2091 RCUWriter<ChannelList> writer (channels);
2092 boost::shared_ptr<ChannelList> c = writer.get_copy();
2094 return add_channel_to (c, how_many);
2098 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2100 while (how_many-- && !c->empty()) {
2101 // FIXME: crash (thread safe with RCU?)
2102 // memory leak, when disabled.... :(
2105 interpolation.remove_channel_from ();
2108 _n_channels.set(DataType::AUDIO, c->size());
2114 AudioDiskstream::remove_channel (uint32_t how_many)
2116 RCUWriter<ChannelList> writer (channels);
2117 boost::shared_ptr<ChannelList> c = writer.get_copy();
2119 return remove_channel_from (c, how_many);
2123 AudioDiskstream::playback_buffer_load () const
2125 boost::shared_ptr<ChannelList> c = channels.reader();
2127 return (float) ((double) c->front()->playback_buf->read_space()/
2128 (double) c->front()->playback_buf->bufsize());
2132 AudioDiskstream::capture_buffer_load () const
2134 boost::shared_ptr<ChannelList> c = channels.reader();
2136 return (float) ((double) c->front()->capture_buf->write_space()/
2137 (double) c->front()->capture_buf->bufsize());
2141 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2143 const XMLProperty* prop;
2144 XMLNodeList nlist = node.children();
2145 XMLNodeIterator niter;
2146 boost::shared_ptr<AudioFileSource> fs;
2147 boost::shared_ptr<AudioFileSource> first_fs;
2148 SourceList pending_sources;
2151 if ((prop = node.property (X_("at"))) == 0) {
2155 if (sscanf (prop->value().c_str(), "%" PRIu32, &position) != 1) {
2159 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2160 if ((*niter)->name() == X_("file")) {
2162 if ((prop = (*niter)->property (X_("path"))) == 0) {
2166 // This protects sessions from errant CapturingSources in stored sessions
2168 if (stat (prop->value().c_str(), &sbuf)) {
2173 fs = boost::dynamic_pointer_cast<AudioFileSource> (
2174 SourceFactory::createWritable (DataType::AUDIO, _session,
2175 prop->value(), true,
2176 false, _session.frame_rate()));
2179 catch (failed_constructor& err) {
2180 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2181 _name, prop->value())
2186 pending_sources.push_back (fs);
2188 if (first_fs == 0) {
2192 fs->set_captured_for (_name);
2196 if (pending_sources.size() == 0) {
2197 /* nothing can be done */
2201 if (pending_sources.size() != _n_channels.n_audio()) {
2202 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2207 boost::shared_ptr<AudioRegion> region;
2210 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (
2211 pending_sources, 0, first_fs->length(first_fs->timeline_position()),
2212 region_name_from_path (first_fs->name(), true), 0,
2213 Region::Flag (Region::DefaultFlags|Region::Automatic|Region::WholeFile)));
2214 region->special_set_position (0);
2217 catch (failed_constructor& err) {
2218 error << string_compose (
2219 _("%1: cannot create whole-file region from pending capture sources"),
2226 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (
2227 pending_sources, 0, first_fs->length(first_fs->timeline_position()),
2228 region_name_from_path (first_fs->name(), true)));
2231 catch (failed_constructor& err) {
2232 error << string_compose (_("%1: cannot create region from pending capture sources"),
2239 _playlist->add_region (region, position);
2245 AudioDiskstream::set_non_layered (bool yn)
2247 if (yn != non_layered()) {
2250 _flags = Flag (_flags | NonLayered);
2252 _flags = Flag (_flags & ~NonLayered);
2260 AudioDiskstream::set_destructive (bool yn)
2262 bool bounce_ignored;
2264 if (yn != destructive()) {
2267 /* requestor should already have checked this and
2268 bounced if necessary and desired
2270 if (!can_become_destructive (bounce_ignored)) {
2273 _flags = Flag (_flags | Destructive);
2274 use_destructive_playlist ();
2276 _flags = Flag (_flags & ~Destructive);
2277 reset_write_sources (true, true);
2285 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2288 requires_bounce = false;
2292 /* is there only one region ? */
2294 if (_playlist->n_regions() != 1) {
2295 requires_bounce = true;
2299 boost::shared_ptr<Region> first = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
2302 /* do the source(s) for the region cover the session start position ? */
2304 if (first->position() != _session.current_start_frame()) {
2305 if (first->start() > _session.current_start_frame()) {
2306 requires_bounce = true;
2311 /* is the source used by only 1 playlist ? */
2313 boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2317 if (_session.source_use_count (afirst->source()) > 1) {
2318 requires_bounce = true;
2322 requires_bounce = false;
2326 AudioDiskstream::ChannelInfo::ChannelInfo (nframes_t bufsize, nframes_t speed_size, nframes_t wrap_size)
2330 current_capture_buffer = 0;
2331 current_playback_buffer = 0;
2332 curr_capture_cnt = 0;
2334 speed_buffer = new Sample[speed_size];
2335 playback_wrap_buffer = new Sample[wrap_size];
2336 capture_wrap_buffer = new Sample[wrap_size];
2338 playback_buf = new RingBufferNPT<Sample> (bufsize);
2339 capture_buf = new RingBufferNPT<Sample> (bufsize);
2340 capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2342 /* touch the ringbuffer buffers, which will cause
2343 them to be mapped into locked physical RAM if
2344 we're running with mlockall(). this doesn't do
2348 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2349 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2350 memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2353 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2356 write_source.reset ();
2359 delete [] speed_buffer;
2362 delete [] playback_wrap_buffer;
2363 playback_wrap_buffer = 0;
2365 delete [] capture_wrap_buffer;
2366 capture_wrap_buffer = 0;
2368 delete playback_buf;
2374 delete capture_transition_buf;
2375 capture_transition_buf = 0;