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 */
348 plist.add (Properties::name, _name.val());
349 plist.add (Properties::start, 0);
350 plist.add (Properties::length, max_frames - max_frames - srcs.front()->natural_position());
352 boost::shared_ptr<Region> region (RegionFactory::create (srcs, plist));
353 _playlist->add_region (region, srcs.front()->natural_position());
357 AudioDiskstream::use_destructive_playlist ()
359 /* this is called from the XML-based constructor or ::set_destructive. when called,
360 we already have a playlist and a region, but we need to
361 set up our sources for write. we use the sources associated
362 with the (presumed single, full-extent) region.
365 boost::shared_ptr<Region> rp = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
368 reset_write_sources (false, true);
372 boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
375 throw failed_constructor();
378 /* be sure to stretch the region out to the maximum length */
380 region->set_length (max_frames - region->position(), this);
383 ChannelList::iterator chan;
384 boost::shared_ptr<ChannelList> c = channels.reader();
386 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
387 (*chan)->write_source = boost::dynamic_pointer_cast<AudioFileSource>(region->source (n));
388 assert((*chan)->write_source);
389 (*chan)->write_source->set_allow_remove_if_empty (false);
391 /* this might be false if we switched modes, so force it */
393 (*chan)->write_source->set_destructive (true);
396 /* the source list will never be reset for a destructive track */
400 AudioDiskstream::prepare_record_status(nframes_t capture_start_frame)
402 if (recordable() && destructive()) {
403 boost::shared_ptr<ChannelList> c = channels.reader();
404 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
406 RingBufferNPT<CaptureTransition>::rw_vector transvec;
407 (*chan)->capture_transition_buf->get_write_vector(&transvec);
409 if (transvec.len[0] > 0) {
410 transvec.buf[0]->type = CaptureStart;
411 transvec.buf[0]->capture_val = capture_start_frame;
412 (*chan)->capture_transition_buf->increment_write_ptr(1);
416 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
424 AudioDiskstream::process (nframes_t transport_frame, nframes_t nframes, bool can_record, bool rec_monitors_input)
427 boost::shared_ptr<ChannelList> c = channels.reader();
428 ChannelList::iterator chan;
430 nframes_t rec_offset = 0;
431 nframes_t rec_nframes = 0;
432 bool nominally_recording;
433 bool re = record_enabled ();
434 bool collect_playback = false;
436 /* if we've already processed the frames corresponding to this call,
437 just return. this allows multiple routes that are taking input
438 from this diskstream to call our ::process() method, but have
439 this stuff only happen once. more commonly, it allows both
440 the AudioTrack that is using this AudioDiskstream *and* the Session
441 to call process() without problems.
448 commit_should_unlock = false;
450 if (!_io || !_io->active()) {
455 check_record_status (transport_frame, nframes, can_record);
457 nominally_recording = (can_record && re);
464 /* This lock is held until the end of AudioDiskstream::commit, so these two functions
465 must always be called as a pair. The only exception is if this function
466 returns a non-zero value, in which case, ::commit should not be called.
469 // If we can't take the state lock return.
470 if (!state_lock.trylock()) {
473 commit_should_unlock = true;
474 adjust_capture_position = 0;
476 for (chan = c->begin(); chan != c->end(); ++chan) {
477 (*chan)->current_capture_buffer = 0;
478 (*chan)->current_playback_buffer = 0;
481 if (nominally_recording || (_session.get_record_enabled() && _session.config.get_punch_in())) {
482 // Safeguard against situations where process() goes haywire when autopunching and last_recordable_frame < first_recordable_frame
483 if (last_recordable_frame < first_recordable_frame) {
484 last_recordable_frame = max_frames;
487 OverlapType ot = coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
489 calculate_record_range(ot, transport_frame, nframes, rec_nframes, rec_offset);
491 if (rec_nframes && !was_recording) {
492 capture_captured = 0;
493 was_recording = true;
498 if (can_record && !_last_capture_regions.empty()) {
499 _last_capture_regions.clear ();
502 if (nominally_recording || rec_nframes) {
504 uint32_t limit = _io->n_ports ().n_audio();
506 /* one or more ports could already have been removed from _io, but our
507 channel setup hasn't yet been updated. prevent us from trying to
508 use channels that correspond to missing ports. note that the
509 process callback (from which this is called) is always atomic
510 with respect to port removal/addition.
513 for (n = 0, chan = c->begin(); chan != c->end() && n < limit; ++chan, ++n) {
515 ChannelInfo* chaninfo (*chan);
517 chaninfo->capture_buf->get_write_vector (&chaninfo->capture_vector);
519 if (rec_nframes <= chaninfo->capture_vector.len[0]) {
521 chaninfo->current_capture_buffer = chaninfo->capture_vector.buf[0];
523 /* note: grab the entire port buffer, but only copy what we were supposed to
524 for recording, and use rec_offset
527 AudioPort* const ap = _io->audio (n);
529 assert(rec_nframes <= ap->get_audio_buffer(nframes).capacity());
530 memcpy (chaninfo->current_capture_buffer, ap->get_audio_buffer (rec_nframes).data(rec_offset), sizeof (Sample) * rec_nframes);
535 nframes_t total = chaninfo->capture_vector.len[0] + chaninfo->capture_vector.len[1];
537 if (rec_nframes > total) {
542 AudioPort* const ap = _io->audio (n);
545 Sample* buf = ap->get_audio_buffer(nframes).data();
546 nframes_t first = chaninfo->capture_vector.len[0];
548 memcpy (chaninfo->capture_wrap_buffer, buf, sizeof (Sample) * first);
549 memcpy (chaninfo->capture_vector.buf[0], buf, sizeof (Sample) * first);
550 memcpy (chaninfo->capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
551 memcpy (chaninfo->capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
553 chaninfo->current_capture_buffer = chaninfo->capture_wrap_buffer;
560 finish_capture (rec_monitors_input, c);
567 /* data will be written to disk */
569 if (rec_nframes == nframes && rec_offset == 0) {
571 for (chan = c->begin(); chan != c->end(); ++chan) {
572 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
575 playback_distance = nframes;
580 /* we can't use the capture buffer as the playback buffer, because
581 we recorded only a part of the current process' cycle data
585 collect_playback = true;
588 adjust_capture_position = rec_nframes;
590 } else if (nominally_recording) {
592 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
594 for (chan = c->begin(); chan != c->end(); ++chan) {
595 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
598 playback_distance = nframes;
602 collect_playback = true;
605 if (collect_playback) {
607 /* we're doing playback */
609 nframes_t necessary_samples;
611 /* no varispeed playback if we're recording, because the output .... TBD */
613 if (rec_nframes == 0 && _actual_speed != 1.0f) {
614 necessary_samples = (nframes_t) floor ((nframes * fabs (_actual_speed))) + 1;
616 necessary_samples = nframes;
619 for (chan = c->begin(); chan != c->end(); ++chan) {
620 (*chan)->playback_buf->get_read_vector (&(*chan)->playback_vector);
625 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
627 ChannelInfo* chaninfo (*chan);
629 if (necessary_samples <= chaninfo->playback_vector.len[0]) {
631 chaninfo->current_playback_buffer = chaninfo->playback_vector.buf[0];
634 nframes_t total = chaninfo->playback_vector.len[0] + chaninfo->playback_vector.len[1];
636 if (necessary_samples > total) {
637 cerr << _name << " Need " << necessary_samples << " total = " << total << endl;
638 cerr << "underrun for " << _name << endl;
644 memcpy ((char *) chaninfo->playback_wrap_buffer,
645 chaninfo->playback_vector.buf[0],
646 chaninfo->playback_vector.len[0] * sizeof (Sample));
647 memcpy (chaninfo->playback_wrap_buffer + chaninfo->playback_vector.len[0],
648 chaninfo->playback_vector.buf[1],
649 (necessary_samples - chaninfo->playback_vector.len[0])
652 chaninfo->current_playback_buffer = chaninfo->playback_wrap_buffer;
657 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
658 process_varispeed_playback(nframes, c);
660 playback_distance = nframes;
663 _speed = _target_speed;
674 /* we're exiting with failure, so ::commit will not
675 be called. unlock the state lock.
678 commit_should_unlock = false;
686 AudioDiskstream::process_varispeed_playback(nframes_t nframes, boost::shared_ptr<ChannelList> c)
688 ChannelList::iterator chan;
690 interpolation.set_speed (_target_speed);
693 for (chan = c->begin(); chan != c->end(); ++chan, ++channel) {
694 ChannelInfo* chaninfo (*chan);
696 playback_distance = interpolation.interpolate (
697 channel, nframes, chaninfo->current_playback_buffer, chaninfo->speed_buffer);
699 chaninfo->current_playback_buffer = chaninfo->speed_buffer;
704 AudioDiskstream::commit (nframes_t /*nframes*/)
706 bool need_butler = false;
708 if (!_io || !_io->active()) {
712 if (_actual_speed < 0.0) {
713 playback_sample -= playback_distance;
715 playback_sample += playback_distance;
718 boost::shared_ptr<ChannelList> c = channels.reader();
719 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
721 (*chan)->playback_buf->increment_read_ptr (playback_distance);
723 if (adjust_capture_position) {
724 (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
728 if (adjust_capture_position != 0) {
729 capture_captured += adjust_capture_position;
730 adjust_capture_position = 0;
734 if (_io && _io->active()) {
735 need_butler = c->front()->playback_buf->write_space() >= c->front()->playback_buf->bufsize() / 2;
740 if (_io && _io->active()) {
741 need_butler = c->front()->playback_buf->write_space() >= disk_io_chunk_frames
742 || c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
744 need_butler = c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
748 if (commit_should_unlock) {
758 AudioDiskstream::set_pending_overwrite (bool yn)
760 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
762 pending_overwrite = yn;
764 overwrite_frame = playback_sample;
765 overwrite_offset = channels.reader()->front()->playback_buf->get_read_ptr();
769 AudioDiskstream::overwrite_existing_buffers ()
771 boost::shared_ptr<ChannelList> c = channels.reader();
772 Sample* mixdown_buffer;
775 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
777 overwrite_queued = false;
779 /* assume all are the same size */
780 nframes_t size = c->front()->playback_buf->bufsize();
782 mixdown_buffer = new Sample[size];
783 gain_buffer = new float[size];
785 /* reduce size so that we can fill the buffer correctly. */
791 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
793 start = overwrite_frame;
794 nframes_t cnt = size;
796 /* to fill the buffer without resetting the playback sample, we need to
797 do it one or two chunks (normally two).
799 |----------------------------------------------------------------------|
803 |<- second chunk->||<----------------- first chunk ------------------>|
807 nframes_t to_read = size - overwrite_offset;
809 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, *chan, n, reversed)) {
810 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
811 _id, size, playback_sample) << endmsg;
819 if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer,
820 start, cnt, *chan, n, reversed)) {
821 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
822 _id, size, playback_sample) << endmsg;
831 pending_overwrite = false;
832 delete [] gain_buffer;
833 delete [] mixdown_buffer;
838 AudioDiskstream::seek (nframes_t frame, bool complete_refill)
842 ChannelList::iterator chan;
843 boost::shared_ptr<ChannelList> c = channels.reader();
845 Glib::Mutex::Lock lm (state_lock);
847 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
848 (*chan)->playback_buf->reset ();
849 (*chan)->capture_buf->reset ();
852 /* can't rec-enable in destructive mode if transport is before start */
854 if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
855 disengage_record_enable ();
858 playback_sample = frame;
861 if (complete_refill) {
862 while ((ret = do_refill_with_alloc ()) > 0) ;
864 ret = do_refill_with_alloc ();
871 AudioDiskstream::can_internal_playback_seek (nframes_t distance)
873 ChannelList::iterator chan;
874 boost::shared_ptr<ChannelList> c = channels.reader();
876 for (chan = c->begin(); chan != c->end(); ++chan) {
877 if ((*chan)->playback_buf->read_space() < distance) {
885 AudioDiskstream::internal_playback_seek (nframes_t distance)
887 ChannelList::iterator chan;
888 boost::shared_ptr<ChannelList> c = channels.reader();
890 for (chan = c->begin(); chan != c->end(); ++chan) {
891 (*chan)->playback_buf->increment_read_ptr (distance);
894 first_recordable_frame += distance;
895 playback_sample += distance;
901 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer, nframes_t& start, nframes_t cnt,
902 ChannelInfo* /*channel_info*/, int channel, bool reversed)
904 nframes_t this_read = 0;
906 nframes_t loop_end = 0;
907 nframes_t loop_start = 0;
908 nframes_t loop_length = 0;
909 nframes_t offset = 0;
912 /* XXX we don't currently play loops in reverse. not sure why */
916 /* Make the use of a Location atomic for this read operation.
918 Note: Locations don't get deleted, so all we care about
919 when I say "atomic" is that we are always pointing to
920 the same one and using a start/length values obtained
924 if ((loc = loop_location) != 0) {
925 loop_start = loc->start();
926 loop_end = loc->end();
927 loop_length = loop_end - loop_start;
930 /* if we are looping, ensure that the first frame we read is at the correct
931 position within the loop.
934 if (loc && start >= loop_end) {
935 //cerr << "start adjusted from " << start;
936 start = loop_start + ((start - loop_start) % loop_length);
937 //cerr << "to " << start << endl;
940 //cerr << "start is " << start << " loopstart: " << loop_start << " loopend: " << loop_end << endl;
949 /* take any loop into account. we can't read past the end of the loop. */
951 if (loc && (loop_end - start < cnt)) {
952 this_read = loop_end - start;
953 //cerr << "reloop true: thisread: " << this_read << " cnt: " << cnt << endl;
960 if (this_read == 0) {
964 this_read = min(cnt,this_read);
966 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
967 error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), _id, this_read,
972 _read_data_count = _playlist->read_data_count();
976 swap_by_ptr (buf, buf + this_read - 1);
980 /* if we read to the end of the loop, go back to the beginning */
997 AudioDiskstream::do_refill_with_alloc ()
999 Sample* mix_buf = new Sample[disk_io_chunk_frames];
1000 float* gain_buf = new float[disk_io_chunk_frames];
1002 int ret = _do_refill(mix_buf, gain_buf);
1011 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer)
1015 RingBufferNPT<Sample>::rw_vector vector;
1016 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1017 nframes_t total_space;
1018 nframes_t zero_fill;
1020 ChannelList::iterator i;
1021 boost::shared_ptr<ChannelList> c = channels.reader();
1028 assert(mixdown_buffer);
1029 assert(gain_buffer);
1036 c->front()->playback_buf->get_write_vector (&vector);
1038 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1042 /* if there are 2+ chunks of disk i/o possible for
1043 this track, let the caller know so that it can arrange
1044 for us to be called again, ASAP.
1047 if (total_space >= (_slaved?3:2) * disk_io_chunk_frames) {
1051 /* if we're running close to normal speed and there isn't enough
1052 space to do disk_io_chunk_frames of I/O, then don't bother.
1054 at higher speeds, just do it because the sync between butler
1055 and audio thread may not be good enough.
1058 if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1062 /* when slaved, don't try to get too close to the read pointer. this
1063 leaves space for the buffer reversal to have something useful to
1067 if (_slaved && total_space < (c->front()->playback_buf->bufsize() / 2)) {
1071 /* never do more than disk_io_chunk_frames worth of disk input per call (limit doesn't apply for memset) */
1073 total_space = min (disk_io_chunk_frames, total_space);
1077 if (file_frame == 0) {
1079 /* at start: nothing to do but fill with silence */
1081 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1083 ChannelInfo* chan (*i);
1084 chan->playback_buf->get_write_vector (&vector);
1085 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1086 if (vector.len[1]) {
1087 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1089 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1094 if (file_frame < total_space) {
1096 /* too close to the start: read what we can,
1097 and then zero fill the rest
1100 zero_fill = total_space - file_frame;
1101 total_space = file_frame;
1111 if (file_frame == max_frames) {
1113 /* at end: nothing to do but fill with silence */
1115 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1117 ChannelInfo* chan (*i);
1118 chan->playback_buf->get_write_vector (&vector);
1119 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1120 if (vector.len[1]) {
1121 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1123 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1128 if (file_frame > max_frames - total_space) {
1130 /* to close to the end: read what we can, and zero fill the rest */
1132 zero_fill = total_space - (max_frames - file_frame);
1133 total_space = max_frames - file_frame;
1140 nframes_t file_frame_tmp = 0;
1142 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1144 ChannelInfo* chan (*i);
1147 nframes_t len1, len2;
1149 chan->playback_buf->get_write_vector (&vector);
1151 if (vector.len[0] > disk_io_chunk_frames) {
1153 /* we're not going to fill the first chunk, so certainly do not bother with the
1154 other part. it won't be connected with the part we do fill, as in:
1156 .... => writable space
1157 ++++ => readable space
1158 ^^^^ => 1 x disk_io_chunk_frames that would be filled
1160 |......|+++++++++++++|...............................|
1165 So, just pretend that the buf1 part isn't there.
1175 file_frame_tmp = file_frame;
1177 buf1 = vector.buf[0];
1178 len1 = vector.len[0];
1179 buf2 = vector.buf[1];
1180 len2 = vector.len[1];
1182 to_read = min (ts, len1);
1183 to_read = min (to_read, disk_io_chunk_frames);
1187 if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1192 chan->playback_buf->increment_write_ptr (to_read);
1196 to_read = min (ts, len2);
1200 /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1201 so read some or all of vector.len[1] as well.
1204 if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1209 chan->playback_buf->increment_write_ptr (to_read);
1218 file_frame = file_frame_tmp;
1225 /** Flush pending data to disk.
1227 * Important note: this function will write *AT MOST* disk_io_chunk_frames
1228 * of data to disk. it will never write more than that. If it writes that
1229 * much and there is more than that waiting to be written, it will return 1,
1230 * otherwise 0 on success or -1 on failure.
1232 * If there is less than disk_io_chunk_frames to be written, no data will be
1233 * written at all unless @a force_flush is true.
1236 AudioDiskstream::do_flush (RunContext /*context*/, bool force_flush)
1240 RingBufferNPT<Sample>::rw_vector vector;
1241 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1244 _write_data_count = 0;
1246 transvec.buf[0] = 0;
1247 transvec.buf[1] = 0;
1251 boost::shared_ptr<ChannelList> c = channels.reader();
1252 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1254 (*chan)->capture_buf->get_read_vector (&vector);
1256 total = vector.len[0] + vector.len[1];
1258 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1262 /* if there are 2+ chunks of disk i/o possible for
1263 this track, let the caller know so that it can arrange
1264 for us to be called again, ASAP.
1266 if we are forcing a flush, then if there is* any* extra
1267 work, let the caller know.
1269 if we are no longer recording and there is any extra work,
1270 let the caller know too.
1273 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1277 to_write = min (disk_io_chunk_frames, (nframes_t) vector.len[0]);
1279 // check the transition buffer when recording destructive
1280 // important that we get this after the capture buf
1282 if (destructive()) {
1283 (*chan)->capture_transition_buf->get_read_vector(&transvec);
1284 size_t transcount = transvec.len[0] + transvec.len[1];
1285 bool have_start = false;
1288 for (ti=0; ti < transcount; ++ti) {
1289 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1291 if (captrans.type == CaptureStart) {
1292 // by definition, the first data we got above represents the given capture pos
1294 (*chan)->write_source->mark_capture_start (captrans.capture_val);
1295 (*chan)->curr_capture_cnt = 0;
1299 else if (captrans.type == CaptureEnd) {
1301 // capture end, the capture_val represents total frames in capture
1303 if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1305 // shorten to make the write a perfect fit
1306 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
1308 if (nto_write < to_write) {
1309 ret = 1; // should we?
1311 to_write = nto_write;
1313 (*chan)->write_source->mark_capture_end ();
1315 // increment past this transition, but go no further
1320 // actually ends just beyond this chunk, so force more work
1328 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1332 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1333 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1337 (*chan)->capture_buf->increment_read_ptr (to_write);
1338 (*chan)->curr_capture_cnt += to_write;
1340 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1342 /* we wrote all of vector.len[0] but it wasn't an entire
1343 disk_io_chunk_frames of data, so arrange for some part
1344 of vector.len[1] to be flushed to disk as well.
1347 to_write = min ((nframes_t)(disk_io_chunk_frames - to_write), (nframes_t) vector.len[1]);
1349 if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1350 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1354 _write_data_count += (*chan)->write_source->write_data_count();
1356 (*chan)->capture_buf->increment_read_ptr (to_write);
1357 (*chan)->curr_capture_cnt += to_write;
1366 AudioDiskstream::transport_stopped (struct tm& when, time_t twhen, bool abort_capture)
1368 uint32_t buffer_position;
1369 bool more_work = true;
1371 boost::shared_ptr<AudioRegion> region;
1372 nframes_t total_capture;
1374 SourceList::iterator src;
1375 ChannelList::iterator chan;
1376 vector<CaptureInfo*>::iterator ci;
1377 boost::shared_ptr<ChannelList> c = channels.reader();
1379 bool mark_write_completed = false;
1381 finish_capture (true, c);
1383 /* butler is already stopped, but there may be work to do
1384 to flush remaining data to disk.
1387 while (more_work && !err) {
1388 switch (do_flush (TransportContext, true)) {
1395 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1400 /* XXX is there anything we can do if err != 0 ? */
1401 Glib::Mutex::Lock lm (capture_info_lock);
1403 if (capture_info.empty()) {
1407 if (abort_capture) {
1409 if (destructive()) {
1413 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1415 if ((*chan)->write_source) {
1417 (*chan)->write_source->mark_for_remove ();
1418 (*chan)->write_source->drop_references ();
1419 (*chan)->write_source.reset ();
1422 /* new source set up in "out" below */
1428 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1429 total_capture += (*ci)->frames;
1432 /* figure out the name for this take */
1434 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1436 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1440 s->update_header (capture_info.front()->start, when, twhen);
1441 s->set_captured_for (_name.val());
1442 s->mark_immutable ();
1443 if (Config->get_auto_analyse_audio()) {
1444 Analyser::queue_source_for_analysis (s, true);
1449 /* destructive tracks have a single, never changing region */
1451 if (destructive()) {
1453 /* send a signal that any UI can pick up to do the right thing. there is
1454 a small problem here in that a UI may need the peak data to be ready
1455 for the data that was recorded and this isn't interlocked with that
1456 process. this problem is deferred to the UI.
1459 _playlist->LayeringChanged(); // XXX this may not get the UI to do the right thing
1463 string whole_file_region_name;
1464 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1466 /* Register a new region with the Session that
1467 describes the entire source. Do this first
1468 so that any sub-regions will obviously be
1469 children of this one (later!)
1475 plist.add (Properties::start, c->front()->write_source->last_capture_start_frame());
1476 plist.add (Properties::length, total_capture);
1477 plist.add (Properties::name, whole_file_region_name);
1479 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1480 rx->set_automatic (true);
1481 rx->set_whole_file (true);
1483 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1484 region->special_set_position (capture_info.front()->start);
1488 catch (failed_constructor& err) {
1489 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1493 _last_capture_regions.push_back (region);
1495 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1497 XMLNode &before = _playlist->get_state();
1498 _playlist->freeze ();
1500 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1504 _session.region_name (region_name, whole_file_region_name, false);
1506 // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->frames << " add region " << region_name << endl;
1512 plist.add (Properties::start, buffer_position);
1513 plist.add (Properties::length, (*ci)->frames);
1514 plist.add (Properties::name, region_name);
1516 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1517 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1520 catch (failed_constructor& err) {
1521 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1522 continue; /* XXX is this OK? */
1525 region->DropReferences.connect_same_thread (*this, boost::bind (&Diskstream::remove_region_from_last_capture, this, boost::weak_ptr<Region>(region)));
1527 _last_capture_regions.push_back (region);
1529 i_am_the_modifier++;
1530 _playlist->add_region (region, (*ci)->start, 1, non_layered());
1531 i_am_the_modifier--;
1533 buffer_position += (*ci)->frames;
1537 XMLNode &after = _playlist->get_state();
1538 _session.add_command (new MementoCommand<Playlist>(*_playlist, &before, &after));
1541 mark_write_completed = true;
1544 reset_write_sources (mark_write_completed);
1548 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1552 capture_info.clear ();
1553 capture_start_frame = 0;
1557 AudioDiskstream::transport_looped (nframes_t transport_frame)
1559 if (was_recording) {
1560 // all we need to do is finish this capture, with modified capture length
1561 boost::shared_ptr<ChannelList> c = channels.reader();
1563 // adjust the capture length knowing that the data will be recorded to disk
1564 // only necessary after the first loop where we're recording
1565 if (capture_info.size() == 0) {
1566 capture_captured += _capture_offset;
1568 if (_alignment_style == ExistingMaterial) {
1569 capture_captured += _session.worst_output_latency();
1571 capture_captured += _roll_delay;
1575 finish_capture (true, c);
1577 // the next region will start recording via the normal mechanism
1578 // we'll set the start position to the current transport pos
1579 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1580 capture_start_frame = transport_frame;
1581 first_recordable_frame = transport_frame; // mild lie
1582 last_recordable_frame = max_frames;
1583 was_recording = true;
1585 if (recordable() && destructive()) {
1586 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1588 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1589 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1591 if (transvec.len[0] > 0) {
1592 transvec.buf[0]->type = CaptureStart;
1593 transvec.buf[0]->capture_val = capture_start_frame;
1594 (*chan)->capture_transition_buf->increment_write_ptr(1);
1598 fatal << X_("programming error: capture_transition_buf is full on rec loop! inconceivable!")
1608 AudioDiskstream::finish_capture (bool /*rec_monitors_input*/, boost::shared_ptr<ChannelList> c)
1610 was_recording = false;
1612 if (capture_captured == 0) {
1616 if (recordable() && destructive()) {
1617 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1619 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1620 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1622 if (transvec.len[0] > 0) {
1623 transvec.buf[0]->type = CaptureEnd;
1624 transvec.buf[0]->capture_val = capture_captured;
1625 (*chan)->capture_transition_buf->increment_write_ptr(1);
1629 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1635 CaptureInfo* ci = new CaptureInfo;
1637 ci->start = capture_start_frame;
1638 ci->frames = capture_captured;
1640 /* XXX theoretical race condition here. Need atomic exchange ?
1641 However, the circumstances when this is called right
1642 now (either on record-disable or transport_stopped)
1643 mean that no actual race exists. I think ...
1644 We now have a capture_info_lock, but it is only to be used
1645 to synchronize in the transport_stop and the capture info
1646 accessors, so that invalidation will not occur (both non-realtime).
1649 // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1651 capture_info.push_back (ci);
1652 capture_captured = 0;
1654 /* now we've finished a capture, reset first_recordable_frame for next time */
1655 first_recordable_frame = max_frames;
1659 AudioDiskstream::set_record_enabled (bool yn)
1661 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0) {
1665 /* can't rec-enable in destructive mode if transport is before start */
1667 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1671 /* yes, i know that this not proof against race conditions, but its
1672 good enough. i think.
1675 if (record_enabled() != yn) {
1677 engage_record_enable ();
1679 disengage_record_enable ();
1685 AudioDiskstream::engage_record_enable ()
1687 bool rolling = _session.transport_speed() != 0.0f;
1688 boost::shared_ptr<ChannelList> c = channels.reader();
1690 g_atomic_int_set (&_record_enabled, 1);
1691 capturing_sources.clear ();
1693 if (Config->get_monitoring_model() == HardwareMonitoring) {
1695 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1696 if ((*chan)->source) {
1697 (*chan)->source->ensure_monitor_input (!(_session.config.get_auto_input() && rolling));
1699 capturing_sources.push_back ((*chan)->write_source);
1700 (*chan)->write_source->mark_streaming_write_started ();
1704 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1705 capturing_sources.push_back ((*chan)->write_source);
1706 (*chan)->write_source->mark_streaming_write_started ();
1710 RecordEnableChanged (); /* EMIT SIGNAL */
1714 AudioDiskstream::disengage_record_enable ()
1716 g_atomic_int_set (&_record_enabled, 0);
1717 boost::shared_ptr<ChannelList> c = channels.reader();
1718 if (Config->get_monitoring_model() == HardwareMonitoring) {
1719 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1720 if ((*chan)->source) {
1721 (*chan)->source->ensure_monitor_input (false);
1725 capturing_sources.clear ();
1726 RecordEnableChanged (); /* EMIT SIGNAL */
1730 AudioDiskstream::get_state ()
1732 XMLNode* node = new XMLNode ("AudioDiskstream");
1734 LocaleGuard lg (X_("POSIX"));
1735 boost::shared_ptr<ChannelList> c = channels.reader();
1737 node->add_property ("flags", enum_2_string (_flags));
1739 snprintf (buf, sizeof(buf), "%zd", c->size());
1740 node->add_property ("channels", buf);
1742 node->add_property ("playlist", _playlist->name());
1744 snprintf (buf, sizeof(buf), "%.12g", _visible_speed);
1745 node->add_property ("speed", buf);
1747 node->add_property("name", _name);
1748 id().print (buf, sizeof (buf));
1749 node->add_property("id", buf);
1751 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1753 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1754 XMLNode* cs_grandchild;
1756 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1757 cs_grandchild = new XMLNode (X_("file"));
1758 cs_grandchild->add_property (X_("path"), (*i)->path());
1759 cs_child->add_child_nocopy (*cs_grandchild);
1762 /* store the location where capture will start */
1766 if (_session.config.get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1767 snprintf (buf, sizeof (buf), "%" PRId64, pi->start());
1769 snprintf (buf, sizeof (buf), "%" PRId64, _session.transport_frame());
1772 cs_child->add_property (X_("at"), buf);
1773 node->add_child_nocopy (*cs_child);
1777 node->add_child_copy (*_extra_xml);
1784 AudioDiskstream::set_state (const XMLNode& node, int /*version*/)
1786 const XMLProperty* prop;
1787 XMLNodeList nlist = node.children();
1788 XMLNodeIterator niter;
1789 uint32_t nchans = 1;
1790 XMLNode* capture_pending_node = 0;
1791 LocaleGuard lg (X_("POSIX"));
1793 in_set_state = true;
1795 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1796 if ((*niter)->name() == IO::state_node_name) {
1797 deprecated_io_node = new XMLNode (**niter);
1800 if ((*niter)->name() == X_("CapturingSources")) {
1801 capture_pending_node = *niter;
1805 /* prevent write sources from being created */
1807 in_set_state = true;
1809 if ((prop = node.property ("name")) != 0) {
1810 _name = prop->value();
1813 if (deprecated_io_node) {
1814 if ((prop = deprecated_io_node->property ("id")) != 0) {
1815 _id = prop->value ();
1818 if ((prop = node.property ("id")) != 0) {
1819 _id = prop->value ();
1823 if ((prop = node.property ("flags")) != 0) {
1824 _flags = Flag (string_2_enum (prop->value(), _flags));
1827 if ((prop = node.property ("channels")) != 0) {
1828 nchans = atoi (prop->value().c_str());
1831 // create necessary extra channels
1832 // we are always constructed with one and we always need one
1834 _n_channels.set(DataType::AUDIO, channels.reader()->size());
1836 if (nchans > _n_channels.n_audio()) {
1838 add_channel (nchans - _n_channels.n_audio());
1839 IO::PortCountChanged(_n_channels);
1841 } else if (nchans < _n_channels.n_audio()) {
1843 remove_channel (_n_channels.n_audio() - nchans);
1846 if ((prop = node.property ("playlist")) == 0) {
1851 bool had_playlist = (_playlist != 0);
1853 if (find_and_use_playlist (prop->value())) {
1857 if (!had_playlist) {
1858 _playlist->set_orig_diskstream_id (_id);
1861 if (!destructive() && capture_pending_node) {
1862 /* destructive streams have one and only one source per channel,
1863 and so they never end up in pending capture in any useful
1866 use_pending_capture_data (*capture_pending_node);
1871 if ((prop = node.property ("speed")) != 0) {
1872 double sp = atof (prop->value().c_str());
1874 if (realtime_set_speed (sp, false)) {
1875 non_realtime_set_speed ();
1879 in_set_state = false;
1881 /* make sure this is clear before we do anything else */
1883 capturing_sources.clear ();
1885 /* write sources are handled when we handle the input set
1886 up of the IO that owns this DS (::non_realtime_input_change())
1893 AudioDiskstream::use_new_write_source (uint32_t n)
1895 boost::shared_ptr<ChannelList> c = channels.reader();
1897 if (!recordable()) {
1901 if (n >= c->size()) {
1902 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
1906 ChannelInfo* chan = (*c)[n];
1908 if (chan->write_source) {
1909 chan->write_source->done_with_peakfile_writes ();
1910 chan->write_source->set_allow_remove_if_empty (true);
1911 chan->write_source.reset ();
1915 if ((chan->write_source = _session.create_audio_source_for_session (*this, n, destructive())) == 0) {
1916 throw failed_constructor();
1920 catch (failed_constructor &err) {
1921 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
1922 chan->write_source.reset ();
1926 /* do not remove destructive files even if they are empty */
1928 chan->write_source->set_allow_remove_if_empty (!destructive());
1930 /* until we write, this file is considered removable */
1932 chan->write_source->mark_for_remove ();
1938 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool /*force*/)
1940 ChannelList::iterator chan;
1941 boost::shared_ptr<ChannelList> c = channels.reader();
1944 if (!_session.writable() || !recordable()) {
1948 capturing_sources.clear ();
1950 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1951 if (!destructive()) {
1953 if ((*chan)->write_source && mark_write_complete) {
1954 (*chan)->write_source->mark_streaming_write_completed ();
1956 use_new_write_source (n);
1958 if (record_enabled()) {
1959 capturing_sources.push_back ((*chan)->write_source);
1963 if ((*chan)->write_source == 0) {
1964 use_new_write_source (n);
1969 if (destructive()) {
1971 /* we now have all our write sources set up, so create the
1972 playlist's single region.
1975 if (_playlist->empty()) {
1976 setup_destructive_playlist ();
1982 AudioDiskstream::rename_write_sources ()
1984 ChannelList::iterator chan;
1985 boost::shared_ptr<ChannelList> c = channels.reader();
1988 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1989 if ((*chan)->write_source != 0) {
1990 (*chan)->write_source->set_source_name (_name.val(), destructive());
1991 /* XXX what to do if one of them fails ? */
1999 AudioDiskstream::set_block_size (nframes_t /*nframes*/)
2001 if (_session.get_block_size() > speed_buffer_size) {
2002 speed_buffer_size = _session.get_block_size();
2003 boost::shared_ptr<ChannelList> c = channels.reader();
2005 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2006 if ((*chan)->speed_buffer)
2007 delete [] (*chan)->speed_buffer;
2008 (*chan)->speed_buffer = new Sample[speed_buffer_size];
2011 allocate_temporary_buffers ();
2015 AudioDiskstream::allocate_temporary_buffers ()
2017 /* make sure the wrap buffer is at least large enough to deal
2018 with the speeds up to 1.2, to allow for micro-variation
2019 when slaving to MTC, Timecode etc.
2022 double sp = max (fabsf (_actual_speed), 1.2f);
2023 nframes_t required_wrap_size = (nframes_t) floor (_session.get_block_size() * sp) + 1;
2025 if (required_wrap_size > wrap_buffer_size) {
2027 boost::shared_ptr<ChannelList> c = channels.reader();
2029 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2030 if ((*chan)->playback_wrap_buffer)
2031 delete [] (*chan)->playback_wrap_buffer;
2032 (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
2033 if ((*chan)->capture_wrap_buffer)
2034 delete [] (*chan)->capture_wrap_buffer;
2035 (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
2038 wrap_buffer_size = required_wrap_size;
2043 AudioDiskstream::monitor_input (bool yn)
2045 boost::shared_ptr<ChannelList> c = channels.reader();
2047 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2049 if ((*chan)->source) {
2050 (*chan)->source->ensure_monitor_input (yn);
2056 AudioDiskstream::set_align_style_from_io ()
2058 bool have_physical = false;
2064 get_input_sources ();
2066 boost::shared_ptr<ChannelList> c = channels.reader();
2068 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2069 if ((*chan)->source && (*chan)->source->flags() & JackPortIsPhysical) {
2070 have_physical = true;
2075 if (have_physical) {
2076 set_align_style (ExistingMaterial);
2078 set_align_style (CaptureTime);
2083 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2085 while (how_many--) {
2086 c->push_back (new ChannelInfo(_session.butler()->audio_diskstream_buffer_size(), speed_buffer_size, wrap_buffer_size));
2087 interpolation.add_channel_to (_session.butler()->audio_diskstream_buffer_size(), speed_buffer_size);
2090 _n_channels.set(DataType::AUDIO, c->size());
2096 AudioDiskstream::add_channel (uint32_t how_many)
2098 RCUWriter<ChannelList> writer (channels);
2099 boost::shared_ptr<ChannelList> c = writer.get_copy();
2101 return add_channel_to (c, how_many);
2105 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2107 while (how_many-- && !c->empty()) {
2108 // FIXME: crash (thread safe with RCU?)
2109 // memory leak, when disabled.... :(
2112 interpolation.remove_channel_from ();
2115 _n_channels.set(DataType::AUDIO, c->size());
2121 AudioDiskstream::remove_channel (uint32_t how_many)
2123 RCUWriter<ChannelList> writer (channels);
2124 boost::shared_ptr<ChannelList> c = writer.get_copy();
2126 return remove_channel_from (c, how_many);
2130 AudioDiskstream::playback_buffer_load () const
2132 boost::shared_ptr<ChannelList> c = channels.reader();
2134 return (float) ((double) c->front()->playback_buf->read_space()/
2135 (double) c->front()->playback_buf->bufsize());
2139 AudioDiskstream::capture_buffer_load () const
2141 boost::shared_ptr<ChannelList> c = channels.reader();
2143 return (float) ((double) c->front()->capture_buf->write_space()/
2144 (double) c->front()->capture_buf->bufsize());
2148 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2150 const XMLProperty* prop;
2151 XMLNodeList nlist = node.children();
2152 XMLNodeIterator niter;
2153 boost::shared_ptr<AudioFileSource> fs;
2154 boost::shared_ptr<AudioFileSource> first_fs;
2155 SourceList pending_sources;
2158 if ((prop = node.property (X_("at"))) == 0) {
2162 if (sscanf (prop->value().c_str(), "%" PRIu32, &position) != 1) {
2166 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2167 if ((*niter)->name() == X_("file")) {
2169 if ((prop = (*niter)->property (X_("path"))) == 0) {
2173 // This protects sessions from errant CapturingSources in stored sessions
2175 if (stat (prop->value().c_str(), &sbuf)) {
2180 fs = boost::dynamic_pointer_cast<AudioFileSource> (
2181 SourceFactory::createWritable (DataType::AUDIO, _session,
2182 prop->value(), false, _session.frame_rate()));
2185 catch (failed_constructor& err) {
2186 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2187 _name, prop->value())
2192 pending_sources.push_back (fs);
2194 if (first_fs == 0) {
2198 fs->set_captured_for (_name.val());
2202 if (pending_sources.size() == 0) {
2203 /* nothing can be done */
2207 if (pending_sources.size() != _n_channels.n_audio()) {
2208 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2213 boost::shared_ptr<AudioRegion> region;
2219 plist.add (Properties::start, 0);
2220 plist.add (Properties::length, first_fs->length (first_fs->timeline_position()));
2221 plist.add (Properties::name, region_name_from_path (first_fs->name(), true));
2223 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, plist));
2225 region->set_automatic (true);
2226 region->set_whole_file (true);
2227 region->special_set_position (0);
2230 catch (failed_constructor& err) {
2231 error << string_compose (
2232 _("%1: cannot create whole-file region from pending capture sources"),
2238 _playlist->add_region (region, position);
2244 AudioDiskstream::set_non_layered (bool yn)
2246 if (yn != non_layered()) {
2249 _flags = Flag (_flags | NonLayered);
2251 _flags = Flag (_flags & ~NonLayered);
2259 AudioDiskstream::set_destructive (bool yn)
2261 bool bounce_ignored;
2263 if (yn != destructive()) {
2266 /* requestor should already have checked this and
2267 bounced if necessary and desired
2269 if (!can_become_destructive (bounce_ignored)) {
2272 _flags = Flag (_flags | Destructive);
2273 use_destructive_playlist ();
2275 _flags = Flag (_flags & ~Destructive);
2276 reset_write_sources (true, true);
2284 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2287 requires_bounce = false;
2291 /* is there only one region ? */
2293 if (_playlist->n_regions() != 1) {
2294 requires_bounce = true;
2298 boost::shared_ptr<Region> first = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
2301 /* do the source(s) for the region cover the session start position ? */
2303 if (first->position() != _session.current_start_frame()) {
2304 if (first->start() > _session.current_start_frame()) {
2305 requires_bounce = true;
2310 /* is the source used by only 1 playlist ? */
2312 boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2316 if (_session.playlists->source_use_count (afirst->source()) > 1) {
2317 requires_bounce = true;
2321 requires_bounce = false;
2325 AudioDiskstream::ChannelInfo::ChannelInfo (nframes_t bufsize, nframes_t speed_size, nframes_t wrap_size)
2329 current_capture_buffer = 0;
2330 current_playback_buffer = 0;
2331 curr_capture_cnt = 0;
2333 speed_buffer = new Sample[speed_size];
2334 playback_wrap_buffer = new Sample[wrap_size];
2335 capture_wrap_buffer = new Sample[wrap_size];
2337 playback_buf = new RingBufferNPT<Sample> (bufsize);
2338 capture_buf = new RingBufferNPT<Sample> (bufsize);
2339 capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2341 /* touch the ringbuffer buffers, which will cause
2342 them to be mapped into locked physical RAM if
2343 we're running with mlockall(). this doesn't do
2347 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2348 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2349 memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2352 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2355 write_source.reset ();
2358 delete [] speed_buffer;
2361 delete [] playback_wrap_buffer;
2362 playback_wrap_buffer = 0;
2364 delete [] capture_wrap_buffer;
2365 capture_wrap_buffer = 0;
2367 delete playback_buf;
2373 delete capture_transition_buf;
2374 capture_transition_buf = 0;