2 Copyright (C) 2000-2006 Paul Davis
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
33 #include <pbd/error.h>
34 #include <glibmm/thread.h>
35 #include <pbd/xml++.h>
36 #include <pbd/memento_command.h>
37 #include <pbd/enumwriter.h>
38 #include <pbd/stacktrace.h>
40 #include <ardour/ardour.h>
41 #include <ardour/audioengine.h>
42 #include <ardour/audio_diskstream.h>
43 #include <ardour/utils.h>
44 #include <ardour/configuration.h>
45 #include <ardour/audiofilesource.h>
46 #include <ardour/send.h>
47 #include <ardour/region_factory.h>
48 #include <ardour/audioplaylist.h>
49 #include <ardour/playlist_factory.h>
50 #include <ardour/cycle_timer.h>
51 #include <ardour/audioregion.h>
52 #include <ardour/audio_port.h>
53 #include <ardour/source_factory.h>
59 using namespace ARDOUR;
62 size_t AudioDiskstream::_working_buffers_size = 0;
63 Sample* AudioDiskstream::_mixdown_buffer = 0;
64 gain_t* AudioDiskstream::_gain_buffer = 0;
66 AudioDiskstream::AudioDiskstream (Session &sess, const string &name, Diskstream::Flag flag)
67 : Diskstream(sess, name, flag)
68 , deprecated_io_node(NULL)
69 , channels (new ChannelList)
71 /* prevent any write sources from being created */
81 AudioDiskstream::AudioDiskstream (Session& sess, const XMLNode& node)
82 : Diskstream(sess, node)
83 , deprecated_io_node(NULL)
84 , channels (new ChannelList)
89 if (set_state (node)) {
91 throw failed_constructor();
97 use_destructive_playlist ();
102 AudioDiskstream::init (Diskstream::Flag f)
106 /* there are no channels at this point, so these
107 two calls just get speed_buffer_size and wrap_buffer
108 size setup without duplicating their code.
111 set_block_size (_session.get_block_size());
112 allocate_temporary_buffers ();
115 assert(_n_channels == ChanCount(DataType::AUDIO, 1));
118 AudioDiskstream::~AudioDiskstream ()
123 RCUWriter<ChannelList> writer (channels);
124 boost::shared_ptr<ChannelList> c = writer.get_copy();
126 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
137 AudioDiskstream::allocate_working_buffers()
139 assert(disk_io_frames() > 0);
141 _working_buffers_size = disk_io_frames();
142 _mixdown_buffer = new Sample[_working_buffers_size];
143 _gain_buffer = new gain_t[_working_buffers_size];
147 AudioDiskstream::free_working_buffers()
149 delete [] _mixdown_buffer;
150 delete [] _gain_buffer;
151 _working_buffers_size = 0;
157 AudioDiskstream::non_realtime_input_change ()
160 Glib::Mutex::Lock lm (state_lock);
162 if (input_change_pending == NoChange) {
167 RCUWriter<ChannelList> writer (channels);
168 boost::shared_ptr<ChannelList> c = writer.get_copy();
170 _n_channels.set(DataType::AUDIO, c->size());
172 if (_io->n_inputs().n_audio() > _n_channels.n_audio()) {
173 add_channel_to (c, _io->n_inputs().n_audio() - _n_channels.n_audio());
174 } else if (_io->n_inputs().n_audio() < _n_channels.n_audio()) {
175 remove_channel_from (c, _n_channels.n_audio() - _io->n_inputs().n_audio());
179 get_input_sources ();
180 set_capture_offset ();
182 if (first_input_change) {
183 set_align_style (_persistent_alignment_style);
184 first_input_change = false;
186 set_align_style_from_io ();
189 input_change_pending = NoChange;
191 /* implicit unlock */
194 /* reset capture files */
196 reset_write_sources (false);
198 /* now refill channel buffers */
200 if (speed() != 1.0f || speed() != -1.0f) {
201 seek ((nframes_t) (_session.transport_frame() * (double) speed()));
203 seek (_session.transport_frame());
208 AudioDiskstream::get_input_sources ()
210 boost::shared_ptr<ChannelList> c = channels.reader();
213 ChannelList::iterator chan;
214 uint32_t ni = _io->n_inputs().n_audio();
215 vector<string> connections;
217 for (n = 0, chan = c->begin(); chan != c->end() && n < ni; ++chan, ++n) {
219 connections.clear ();
221 if (_io->input(n)->get_connections (connections) == 0) {
223 if ((*chan)->source) {
224 // _source->disable_metering ();
230 (*chan)->source = dynamic_cast<AudioPort*>(_session.engine().get_port_by_name (connections[0]) );
236 AudioDiskstream::find_and_use_playlist (const string& name)
238 boost::shared_ptr<AudioPlaylist> playlist;
240 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (_session.playlist_by_name (name))) == 0) {
241 playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, name));
245 error << string_compose(_("AudioDiskstream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
249 return use_playlist (playlist);
253 AudioDiskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
255 assert(boost::dynamic_pointer_cast<AudioPlaylist>(playlist));
257 Diskstream::use_playlist(playlist);
263 AudioDiskstream::use_new_playlist ()
266 boost::shared_ptr<AudioPlaylist> playlist;
268 if (!in_set_state && destructive()) {
273 newname = Playlist::bump_name (_playlist->name(), _session);
275 newname = Playlist::bump_name (_name, _session);
278 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, newname, hidden()))) != 0) {
280 playlist->set_orig_diskstream_id (id());
281 return use_playlist (playlist);
289 AudioDiskstream::use_copy_playlist ()
291 assert(audio_playlist());
297 if (_playlist == 0) {
298 error << string_compose(_("AudioDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
303 boost::shared_ptr<AudioPlaylist> playlist;
305 newname = Playlist::bump_name (_playlist->name(), _session);
307 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist>(PlaylistFactory::create (audio_playlist(), newname))) != 0) {
308 playlist->set_orig_diskstream_id (id());
309 return use_playlist (playlist);
316 AudioDiskstream::setup_destructive_playlist ()
319 boost::shared_ptr<ChannelList> c = channels.reader();
321 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
322 srcs.push_back ((*chan)->write_source);
325 /* a single full-sized region */
327 boost::shared_ptr<Region> region (RegionFactory::create (srcs, 0, max_frames - srcs.front()->natural_position(), _name));
328 _playlist->add_region (region, srcs.front()->natural_position());
332 AudioDiskstream::use_destructive_playlist ()
334 /* this is called from the XML-based constructor or ::set_destructive. when called,
335 we already have a playlist and a region, but we need to
336 set up our sources for write. we use the sources associated
337 with the (presumed single, full-extent) region.
340 boost::shared_ptr<Region> rp = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
343 reset_write_sources (false, true);
347 boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
350 throw failed_constructor();
353 /* be sure to stretch the region out to the maximum length */
355 region->set_length (max_frames - region->position(), this);
358 ChannelList::iterator chan;
359 boost::shared_ptr<ChannelList> c = channels.reader();
361 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
362 (*chan)->write_source = boost::dynamic_pointer_cast<AudioFileSource>(region->source (n));
363 assert((*chan)->write_source);
364 (*chan)->write_source->set_allow_remove_if_empty (false);
366 /* this might be false if we switched modes, so force it */
368 (*chan)->write_source->set_destructive (true);
371 /* the source list will never be reset for a destructive track */
375 AudioDiskstream::check_record_status (nframes_t transport_frame, nframes_t nframes, bool can_record)
377 int possibly_recording;
380 const int transport_rolling = 0x4;
381 const int track_rec_enabled = 0x2;
382 const int global_rec_enabled = 0x1;
384 /* merge together the 3 factors that affect record status, and compute
388 rolling = _session.transport_speed() != 0.0f;
389 possibly_recording = (rolling << 2) | (record_enabled() << 1) | can_record;
390 change = possibly_recording ^ last_possibly_recording;
392 if (possibly_recording == last_possibly_recording) {
398 /* if per-track or global rec-enable turned on while the other was already on, we've started recording */
400 if ((change & track_rec_enabled) && record_enabled() && (!(change & global_rec_enabled) && can_record) ||
401 ((change & global_rec_enabled) && can_record && (!(change & track_rec_enabled) && record_enabled()))) {
403 /* starting to record: compute first+last frames */
405 first_recordable_frame = transport_frame + _capture_offset;
406 last_recordable_frame = max_frames;
407 capture_start_frame = transport_frame;
409 if (!(last_possibly_recording & transport_rolling) && (possibly_recording & transport_rolling)) {
411 /* was stopped, now rolling (and recording) */
413 if (_alignment_style == ExistingMaterial) {
414 first_recordable_frame += _session.worst_output_latency();
416 first_recordable_frame += _roll_delay;
421 /* was rolling, but record state changed */
423 if (_alignment_style == ExistingMaterial) {
425 if (!Config->get_punch_in()) {
427 /* manual punch in happens at the correct transport frame
428 because the user hit a button. but to get alignment correct
429 we have to back up the position of the new region to the
430 appropriate spot given the roll delay.
433 capture_start_frame -= _roll_delay;
435 /* XXX paul notes (august 2005): i don't know why
439 first_recordable_frame += _capture_offset;
443 /* autopunch toggles recording at the precise
444 transport frame, and then the DS waits
445 to start recording for a time that depends
446 on the output latency.
449 first_recordable_frame += _session.worst_output_latency();
454 if (Config->get_punch_in()) {
455 first_recordable_frame += _roll_delay;
457 capture_start_frame -= _roll_delay;
463 if (recordable() && destructive()) {
464 boost::shared_ptr<ChannelList> c = channels.reader();
465 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
467 RingBufferNPT<CaptureTransition>::rw_vector transvec;
468 (*chan)->capture_transition_buf->get_write_vector(&transvec);
470 if (transvec.len[0] > 0) {
471 transvec.buf[0]->type = CaptureStart;
472 transvec.buf[0]->capture_val = capture_start_frame;
473 (*chan)->capture_transition_buf->increment_write_ptr(1);
477 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
483 } else if (!record_enabled() || !can_record) {
487 last_recordable_frame = transport_frame + _capture_offset;
489 if (_alignment_style == ExistingMaterial) {
490 last_recordable_frame += _session.worst_output_latency();
492 last_recordable_frame += _roll_delay;
496 last_possibly_recording = possibly_recording;
500 AudioDiskstream::process (nframes_t transport_frame, nframes_t nframes, nframes_t offset, bool can_record, bool rec_monitors_input)
503 boost::shared_ptr<ChannelList> c = channels.reader();
504 ChannelList::iterator chan;
506 nframes_t rec_offset = 0;
507 nframes_t rec_nframes = 0;
508 bool nominally_recording;
509 bool re = record_enabled ();
510 bool collect_playback = false;
512 /* if we've already processed the frames corresponding to this call,
513 just return. this allows multiple routes that are taking input
514 from this diskstream to call our ::process() method, but have
515 this stuff only happen once. more commonly, it allows both
516 the AudioTrack that is using this AudioDiskstream *and* the Session
517 to call process() without problems.
524 commit_should_unlock = false;
526 if (!_io->active()) {
531 check_record_status (transport_frame, nframes, can_record);
533 nominally_recording = (can_record && re);
540 /* This lock is held until the end of AudioDiskstream::commit, so these two functions
541 must always be called as a pair. The only exception is if this function
542 returns a non-zero value, in which case, ::commit should not be called.
545 // If we can't take the state lock return.
546 if (!state_lock.trylock()) {
549 commit_should_unlock = true;
550 adjust_capture_position = 0;
552 for (chan = c->begin(); chan != c->end(); ++chan) {
553 (*chan)->current_capture_buffer = 0;
554 (*chan)->current_playback_buffer = 0;
557 if (nominally_recording || (_session.get_record_enabled() && Config->get_punch_in())) {
560 // Safeguard against situations where process() goes haywire when autopunching and last_recordable_frame < first_recordable_frame
561 if (last_recordable_frame < first_recordable_frame) {
562 last_recordable_frame = max_frames;
565 ot = coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
572 case OverlapInternal:
573 /* ---------- recrange
576 rec_nframes = nframes;
581 /* |--------| recrange
584 rec_nframes = transport_frame + nframes - first_recordable_frame;
586 rec_offset = first_recordable_frame - transport_frame;
591 /* |--------| recrange
594 rec_nframes = last_recordable_frame - transport_frame;
598 case OverlapExternal:
599 /* |--------| recrange
600 -------------- transrange
602 rec_nframes = last_recordable_frame - first_recordable_frame;
603 rec_offset = first_recordable_frame - transport_frame;
607 if (rec_nframes && !was_recording) {
608 capture_captured = 0;
609 was_recording = true;
614 if (can_record && !_last_capture_regions.empty()) {
615 _last_capture_regions.clear ();
618 if (nominally_recording || rec_nframes) {
620 uint32_t limit = _io->n_inputs ().n_audio();
622 /* one or more ports could already have been removed from _io, but our
623 channel setup hasn't yet been updated. prevent us from trying to
624 use channels that correspond to missing ports. note that the
625 process callback (from which this is called) is always atomic
626 with respect to port removal/addition.
629 for (n = 0, chan = c->begin(); chan != c->end() && n < limit; ++chan, ++n) {
631 ChannelInfo* chaninfo (*chan);
633 chaninfo->capture_buf->get_write_vector (&chaninfo->capture_vector);
635 if (rec_nframes <= chaninfo->capture_vector.len[0]) {
637 chaninfo->current_capture_buffer = chaninfo->capture_vector.buf[0];
639 /* note: grab the entire port buffer, but only copy what we were supposed to for recording, and use
643 AudioPort* const ap = _io->audio_input(n);
645 assert(rec_nframes <= ap->get_audio_buffer().capacity());
646 memcpy (chaninfo->current_capture_buffer, ap->get_audio_buffer().data(rec_nframes, offset + rec_offset), sizeof (Sample) * rec_nframes);
650 nframes_t total = chaninfo->capture_vector.len[0] + chaninfo->capture_vector.len[1];
652 if (rec_nframes > total) {
657 AudioPort* const ap = _io->audio_input(n);
660 Sample* buf = ap->get_audio_buffer().data(nframes, offset);
661 nframes_t first = chaninfo->capture_vector.len[0];
663 memcpy (chaninfo->capture_wrap_buffer, buf, sizeof (Sample) * first);
664 memcpy (chaninfo->capture_vector.buf[0], buf, sizeof (Sample) * first);
665 memcpy (chaninfo->capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
666 memcpy (chaninfo->capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
668 chaninfo->current_capture_buffer = chaninfo->capture_wrap_buffer;
675 finish_capture (rec_monitors_input, c);
682 /* data will be written to disk */
684 if (rec_nframes == nframes && rec_offset == 0) {
686 for (chan = c->begin(); chan != c->end(); ++chan) {
687 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
690 playback_distance = nframes;
695 /* we can't use the capture buffer as the playback buffer, because
696 we recorded only a part of the current process' cycle data
700 collect_playback = true;
703 adjust_capture_position = rec_nframes;
705 } else if (nominally_recording) {
707 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
709 for (chan = c->begin(); chan != c->end(); ++chan) {
710 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
713 playback_distance = nframes;
717 collect_playback = true;
720 if (collect_playback) {
722 /* we're doing playback */
724 nframes_t necessary_samples;
726 /* no varispeed playback if we're recording, because the output .... TBD */
728 if (rec_nframes == 0 && _actual_speed != 1.0f) {
729 necessary_samples = (nframes_t) floor ((nframes * fabs (_actual_speed))) + 1;
731 necessary_samples = nframes;
734 for (chan = c->begin(); chan != c->end(); ++chan) {
735 (*chan)->playback_buf->get_read_vector (&(*chan)->playback_vector);
740 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
742 ChannelInfo* chaninfo (*chan);
744 if (necessary_samples <= chaninfo->playback_vector.len[0]) {
746 chaninfo->current_playback_buffer = chaninfo->playback_vector.buf[0];
749 nframes_t total = chaninfo->playback_vector.len[0] + chaninfo->playback_vector.len[1];
751 if (necessary_samples > total) {
752 cerr << "underrun for " << _name << endl;
758 memcpy ((char *) chaninfo->playback_wrap_buffer, chaninfo->playback_vector.buf[0],
759 chaninfo->playback_vector.len[0] * sizeof (Sample));
760 memcpy (chaninfo->playback_wrap_buffer + chaninfo->playback_vector.len[0], chaninfo->playback_vector.buf[1],
761 (necessary_samples - chaninfo->playback_vector.len[0]) * sizeof (Sample));
763 chaninfo->current_playback_buffer = chaninfo->playback_wrap_buffer;
768 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
770 uint64_t phase = last_phase;
774 // Linearly interpolate into the alt buffer
775 // using 40.24 fixp maths (swh)
777 if (phi != target_phi) {
778 phi_delta = ((int64_t)(target_phi - phi)) / nframes;
783 for (chan = c->begin(); chan != c->end(); ++chan) {
786 ChannelInfo* chaninfo (*chan);
791 for (nframes_t outsample = 0; outsample < nframes; ++outsample) {
793 fr = (phase & 0xFFFFFF) / 16777216.0f;
794 chaninfo->speed_buffer[outsample] =
795 chaninfo->current_playback_buffer[i] * (1.0f - fr) +
796 chaninfo->current_playback_buffer[i+1] * fr;
797 phase += phi + phi_delta;
800 chaninfo->current_playback_buffer = chaninfo->speed_buffer;
803 playback_distance = i; // + 1;
804 last_phase = (phase & 0xFFFFFF);
807 playback_distance = nframes;
821 /* we're exiting with failure, so ::commit will not
822 be called. unlock the state lock.
825 commit_should_unlock = false;
833 AudioDiskstream::commit (nframes_t nframes)
835 bool need_butler = false;
837 if (!_io->active()) {
841 if (_actual_speed < 0.0) {
842 playback_sample -= playback_distance;
844 playback_sample += playback_distance;
847 boost::shared_ptr<ChannelList> c = channels.reader();
848 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
850 (*chan)->playback_buf->increment_read_ptr (playback_distance);
852 if (adjust_capture_position) {
853 (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
857 if (adjust_capture_position != 0) {
858 capture_captured += adjust_capture_position;
859 adjust_capture_position = 0;
863 /*if (_io && _io->active()) {*/
864 need_butler = c->front()->playback_buf->write_space() >= c->front()->playback_buf->bufsize() / 2;
869 /*if (_io && _io->active()) {*/
870 need_butler = c->front()->playback_buf->write_space() >= disk_io_chunk_frames
871 || c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
873 need_butler = c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
877 if (commit_should_unlock) {
887 AudioDiskstream::set_pending_overwrite (bool yn)
889 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
891 pending_overwrite = yn;
893 overwrite_frame = playback_sample;
894 overwrite_offset = channels.reader()->front()->playback_buf->get_read_ptr();
898 AudioDiskstream::overwrite_existing_buffers ()
900 boost::shared_ptr<ChannelList> c = channels.reader();
901 Sample* mixdown_buffer;
904 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
906 overwrite_queued = false;
908 /* assume all are the same size */
909 nframes_t size = c->front()->playback_buf->bufsize();
911 mixdown_buffer = new Sample[size];
912 gain_buffer = new float[size];
914 /* reduce size so that we can fill the buffer correctly. */
920 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
922 start = overwrite_frame;
923 nframes_t cnt = size;
925 /* to fill the buffer without resetting the playback sample, we need to
926 do it one or two chunks (normally two).
928 |----------------------------------------------------------------------|
932 |<- second chunk->||<----------------- first chunk ------------------>|
936 nframes_t to_read = size - overwrite_offset;
938 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, *chan, n, reversed)) {
939 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
940 _id, size, playback_sample) << endmsg;
948 if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer,
949 start, cnt, *chan, n, reversed)) {
950 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
951 _id, size, playback_sample) << endmsg;
960 pending_overwrite = false;
961 delete [] gain_buffer;
962 delete [] mixdown_buffer;
967 AudioDiskstream::seek (nframes_t frame, bool complete_refill)
971 ChannelList::iterator chan;
972 boost::shared_ptr<ChannelList> c = channels.reader();
974 Glib::Mutex::Lock lm (state_lock);
976 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
977 (*chan)->playback_buf->reset ();
978 (*chan)->capture_buf->reset ();
981 /* can't rec-enable in destructive mode if transport is before start */
983 if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
984 disengage_record_enable ();
987 playback_sample = frame;
990 if (complete_refill) {
991 while ((ret = do_refill_with_alloc ()) > 0) ;
993 ret = do_refill_with_alloc ();
1000 AudioDiskstream::can_internal_playback_seek (nframes_t distance)
1002 ChannelList::iterator chan;
1003 boost::shared_ptr<ChannelList> c = channels.reader();
1005 for (chan = c->begin(); chan != c->end(); ++chan) {
1006 if ((*chan)->playback_buf->read_space() < distance) {
1014 AudioDiskstream::internal_playback_seek (nframes_t distance)
1016 ChannelList::iterator chan;
1017 boost::shared_ptr<ChannelList> c = channels.reader();
1019 for (chan = c->begin(); chan != c->end(); ++chan) {
1020 (*chan)->playback_buf->increment_read_ptr (distance);
1023 first_recordable_frame += distance;
1024 playback_sample += distance;
1030 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer, nframes_t& start, nframes_t cnt,
1031 ChannelInfo* channel_info, int channel, bool reversed)
1033 nframes_t this_read = 0;
1034 bool reloop = false;
1035 nframes_t loop_end = 0;
1036 nframes_t loop_start = 0;
1037 nframes_t loop_length = 0;
1038 nframes_t offset = 0;
1041 /* XXX we don't currently play loops in reverse. not sure why */
1045 /* Make the use of a Location atomic for this read operation.
1047 Note: Locations don't get deleted, so all we care about
1048 when I say "atomic" is that we are always pointing to
1049 the same one and using a start/length values obtained
1053 if ((loc = loop_location) != 0) {
1054 loop_start = loc->start();
1055 loop_end = loc->end();
1056 loop_length = loop_end - loop_start;
1059 /* if we are looping, ensure that the first frame we read is at the correct
1060 position within the loop.
1063 if (loc && start >= loop_end) {
1064 //cerr << "start adjusted from " << start;
1065 start = loop_start + ((start - loop_start) % loop_length);
1066 //cerr << "to " << start << endl;
1069 //cerr << "start is " << start << " loopstart: " << loop_start << " loopend: " << loop_end << endl;
1078 /* take any loop into account. we can't read past the end of the loop. */
1080 if (loc && (loop_end - start < cnt)) {
1081 this_read = loop_end - start;
1082 //cerr << "reloop true: thisread: " << this_read << " cnt: " << cnt << endl;
1089 if (this_read == 0) {
1093 this_read = min(cnt,this_read);
1095 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
1096 error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), _id, this_read,
1101 _read_data_count = _playlist->read_data_count();
1105 swap_by_ptr (buf, buf + this_read - 1);
1109 /* if we read to the end of the loop, go back to the beginning */
1119 offset += this_read;
1126 AudioDiskstream::do_refill_with_alloc ()
1128 Sample* mix_buf = new Sample[disk_io_chunk_frames];
1129 float* gain_buf = new float[disk_io_chunk_frames];
1131 int ret = _do_refill(mix_buf, gain_buf);
1140 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer)
1144 RingBufferNPT<Sample>::rw_vector vector;
1145 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1146 nframes_t total_space;
1147 nframes_t zero_fill;
1149 ChannelList::iterator i;
1150 boost::shared_ptr<ChannelList> c = channels.reader();
1157 assert(mixdown_buffer);
1158 assert(gain_buffer);
1165 c->front()->playback_buf->get_write_vector (&vector);
1167 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1171 /* if there are 2+ chunks of disk i/o possible for
1172 this track, let the caller know so that it can arrange
1173 for us to be called again, ASAP.
1176 if (total_space >= (_slaved?3:2) * disk_io_chunk_frames) {
1180 /* if we're running close to normal speed and there isn't enough
1181 space to do disk_io_chunk_frames of I/O, then don't bother.
1183 at higher speeds, just do it because the sync between butler
1184 and audio thread may not be good enough.
1187 if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1191 /* when slaved, don't try to get too close to the read pointer. this
1192 leaves space for the buffer reversal to have something useful to
1196 if (_slaved && total_space < (c->front()->playback_buf->bufsize() / 2)) {
1200 /* never do more than disk_io_chunk_frames worth of disk input per call (limit doesn't apply for memset) */
1202 total_space = min (disk_io_chunk_frames, total_space);
1206 if (file_frame == 0) {
1208 /* at start: nothing to do but fill with silence */
1210 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1212 ChannelInfo* chan (*i);
1213 chan->playback_buf->get_write_vector (&vector);
1214 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1215 if (vector.len[1]) {
1216 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1218 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1223 if (file_frame < total_space) {
1225 /* too close to the start: read what we can,
1226 and then zero fill the rest
1229 zero_fill = total_space - file_frame;
1230 total_space = file_frame;
1240 if (file_frame == max_frames) {
1242 /* at end: nothing to do but fill with silence */
1244 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1246 ChannelInfo* chan (*i);
1247 chan->playback_buf->get_write_vector (&vector);
1248 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1249 if (vector.len[1]) {
1250 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1252 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1257 if (file_frame > max_frames - total_space) {
1259 /* to close to the end: read what we can, and zero fill the rest */
1261 zero_fill = total_space - (max_frames - file_frame);
1262 total_space = max_frames - file_frame;
1269 nframes_t file_frame_tmp = 0;
1271 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1273 ChannelInfo* chan (*i);
1276 nframes_t len1, len2;
1278 chan->playback_buf->get_write_vector (&vector);
1280 if (vector.len[0] > disk_io_chunk_frames) {
1282 /* we're not going to fill the first chunk, so certainly do not bother with the
1283 other part. it won't be connected with the part we do fill, as in:
1285 .... => writable space
1286 ++++ => readable space
1287 ^^^^ => 1 x disk_io_chunk_frames that would be filled
1289 |......|+++++++++++++|...............................|
1294 So, just pretend that the buf1 part isn't there.
1304 file_frame_tmp = file_frame;
1306 buf1 = vector.buf[0];
1307 len1 = vector.len[0];
1308 buf2 = vector.buf[1];
1309 len2 = vector.len[1];
1311 to_read = min (ts, len1);
1312 to_read = min (to_read, disk_io_chunk_frames);
1316 if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1321 chan->playback_buf->increment_write_ptr (to_read);
1325 to_read = min (ts, len2);
1329 /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1330 so read some or all of vector.len[1] as well.
1333 if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1338 chan->playback_buf->increment_write_ptr (to_read);
1347 file_frame = file_frame_tmp;
1354 /** Flush pending data to disk.
1356 * Important note: this function will write *AT MOST* disk_io_chunk_frames
1357 * of data to disk. it will never write more than that. If it writes that
1358 * much and there is more than that waiting to be written, it will return 1,
1359 * otherwise 0 on success or -1 on failure.
1361 * If there is less than disk_io_chunk_frames to be written, no data will be
1362 * written at all unless @a force_flush is true.
1365 AudioDiskstream::do_flush (Session::RunContext context, bool force_flush)
1369 RingBufferNPT<Sample>::rw_vector vector;
1370 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1373 _write_data_count = 0;
1375 transvec.buf[0] = 0;
1376 transvec.buf[1] = 0;
1380 boost::shared_ptr<ChannelList> c = channels.reader();
1381 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1383 (*chan)->capture_buf->get_read_vector (&vector);
1385 total = vector.len[0] + vector.len[1];
1387 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1391 /* if there are 2+ chunks of disk i/o possible for
1392 this track, let the caller know so that it can arrange
1393 for us to be called again, ASAP.
1395 if we are forcing a flush, then if there is* any* extra
1396 work, let the caller know.
1398 if we are no longer recording and there is any extra work,
1399 let the caller know too.
1402 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1406 to_write = min (disk_io_chunk_frames, (nframes_t) vector.len[0]);
1408 // check the transition buffer when recording destructive
1409 // important that we get this after the capture buf
1411 if (destructive()) {
1412 (*chan)->capture_transition_buf->get_read_vector(&transvec);
1413 size_t transcount = transvec.len[0] + transvec.len[1];
1414 bool have_start = false;
1417 for (ti=0; ti < transcount; ++ti) {
1418 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1420 if (captrans.type == CaptureStart) {
1421 // by definition, the first data we got above represents the given capture pos
1423 (*chan)->write_source->mark_capture_start (captrans.capture_val);
1424 (*chan)->curr_capture_cnt = 0;
1428 else if (captrans.type == CaptureEnd) {
1430 // capture end, the capture_val represents total frames in capture
1432 if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1434 // shorten to make the write a perfect fit
1435 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
1437 if (nto_write < to_write) {
1438 ret = 1; // should we?
1440 to_write = nto_write;
1442 (*chan)->write_source->mark_capture_end ();
1444 // increment past this transition, but go no further
1449 // actually ends just beyond this chunk, so force more work
1457 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1461 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1462 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1466 (*chan)->capture_buf->increment_read_ptr (to_write);
1467 (*chan)->curr_capture_cnt += to_write;
1469 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1471 /* we wrote all of vector.len[0] but it wasn't an entire
1472 disk_io_chunk_frames of data, so arrange for some part
1473 of vector.len[1] to be flushed to disk as well.
1476 to_write = min ((nframes_t)(disk_io_chunk_frames - to_write), (nframes_t) vector.len[1]);
1478 if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1479 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1483 _write_data_count += (*chan)->write_source->write_data_count();
1485 (*chan)->capture_buf->increment_read_ptr (to_write);
1486 (*chan)->curr_capture_cnt += to_write;
1495 AudioDiskstream::transport_stopped (struct tm& when, time_t twhen, bool abort_capture)
1497 uint32_t buffer_position;
1498 bool more_work = true;
1500 boost::shared_ptr<AudioRegion> region;
1501 nframes_t total_capture;
1503 SourceList::iterator src;
1504 ChannelList::iterator chan;
1505 vector<CaptureInfo*>::iterator ci;
1506 boost::shared_ptr<ChannelList> c = channels.reader();
1508 bool mark_write_completed = false;
1510 finish_capture (true, c);
1512 /* butler is already stopped, but there may be work to do
1513 to flush remaining data to disk.
1516 while (more_work && !err) {
1517 switch (do_flush (Session::TransportContext, true)) {
1524 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1529 /* XXX is there anything we can do if err != 0 ? */
1530 Glib::Mutex::Lock lm (capture_info_lock);
1532 if (capture_info.empty()) {
1536 if (abort_capture) {
1538 if (destructive()) {
1542 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1544 if ((*chan)->write_source) {
1546 (*chan)->write_source->mark_for_remove ();
1547 (*chan)->write_source->drop_references ();
1548 (*chan)->write_source.reset ();
1551 /* new source set up in "out" below */
1557 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1558 total_capture += (*ci)->frames;
1561 /* figure out the name for this take */
1563 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1565 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1569 s->update_header (capture_info.front()->start, when, twhen);
1570 s->set_captured_for (_name);
1571 s->mark_immutable ();
1575 /* destructive tracks have a single, never changing region */
1577 if (destructive()) {
1579 /* send a signal that any UI can pick up to do the right thing. there is
1580 a small problem here in that a UI may need the peak data to be ready
1581 for the data that was recorded and this isn't interlocked with that
1582 process. this problem is deferred to the UI.
1585 _playlist->Modified();
1589 string whole_file_region_name;
1590 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1592 /* Register a new region with the Session that
1593 describes the entire source. Do this first
1594 so that any sub-regions will obviously be
1595 children of this one (later!)
1599 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, c->front()->write_source->last_capture_start_frame(), total_capture,
1600 whole_file_region_name,
1601 0, AudioRegion::Flag (AudioRegion::DefaultFlags|AudioRegion::Automatic|AudioRegion::WholeFile)));
1603 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1604 region->special_set_position (capture_info.front()->start);
1608 catch (failed_constructor& err) {
1609 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1613 _last_capture_regions.push_back (region);
1615 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1617 XMLNode &before = _playlist->get_state();
1618 _playlist->freeze ();
1620 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1624 _session.region_name (region_name, whole_file_region_name, false);
1626 // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->frames << " add region " << region_name << endl;
1629 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, buffer_position, (*ci)->frames, region_name));
1630 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1633 catch (failed_constructor& err) {
1634 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1635 continue; /* XXX is this OK? */
1638 region->GoingAway.connect (bind (mem_fun (*this, &Diskstream::remove_region_from_last_capture), boost::weak_ptr<Region>(region)));
1640 _last_capture_regions.push_back (region);
1642 i_am_the_modifier++;
1643 _playlist->add_region (region, (*ci)->start);
1644 i_am_the_modifier--;
1646 buffer_position += (*ci)->frames;
1650 XMLNode &after = _playlist->get_state();
1651 _session.add_command (new MementoCommand<Playlist>(*_playlist, &before, &after));
1654 mark_write_completed = true;
1657 reset_write_sources (mark_write_completed);
1661 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1665 capture_info.clear ();
1666 capture_start_frame = 0;
1670 AudioDiskstream::transport_looped (nframes_t transport_frame)
1672 if (was_recording) {
1673 // all we need to do is finish this capture, with modified capture length
1674 boost::shared_ptr<ChannelList> c = channels.reader();
1676 // adjust the capture length knowing that the data will be recorded to disk
1677 // only necessary after the first loop where we're recording
1678 if (capture_info.size() == 0) {
1679 capture_captured += _capture_offset;
1681 if (_alignment_style == ExistingMaterial) {
1682 capture_captured += _session.worst_output_latency();
1684 capture_captured += _roll_delay;
1688 finish_capture (true, c);
1690 // the next region will start recording via the normal mechanism
1691 // we'll set the start position to the current transport pos
1692 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1693 capture_start_frame = transport_frame;
1694 first_recordable_frame = transport_frame; // mild lie
1695 last_recordable_frame = max_frames;
1696 was_recording = true;
1698 if (recordable() && destructive()) {
1699 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1701 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1702 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1704 if (transvec.len[0] > 0) {
1705 transvec.buf[0]->type = CaptureStart;
1706 transvec.buf[0]->capture_val = capture_start_frame;
1707 (*chan)->capture_transition_buf->increment_write_ptr(1);
1711 fatal << X_("programming error: capture_transition_buf is full on rec loop! inconceivable!")
1721 AudioDiskstream::finish_capture (bool rec_monitors_input, boost::shared_ptr<ChannelList> c)
1723 was_recording = false;
1725 if (capture_captured == 0) {
1729 if (recordable() && destructive()) {
1730 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1732 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1733 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1735 if (transvec.len[0] > 0) {
1736 transvec.buf[0]->type = CaptureEnd;
1737 transvec.buf[0]->capture_val = capture_captured;
1738 (*chan)->capture_transition_buf->increment_write_ptr(1);
1742 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1748 CaptureInfo* ci = new CaptureInfo;
1750 ci->start = capture_start_frame;
1751 ci->frames = capture_captured;
1753 /* XXX theoretical race condition here. Need atomic exchange ?
1754 However, the circumstances when this is called right
1755 now (either on record-disable or transport_stopped)
1756 mean that no actual race exists. I think ...
1757 We now have a capture_info_lock, but it is only to be used
1758 to synchronize in the transport_stop and the capture info
1759 accessors, so that invalidation will not occur (both non-realtime).
1762 // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1764 capture_info.push_back (ci);
1765 capture_captured = 0;
1767 /* now we've finished a capture, reset first_recordable_frame for next time */
1768 first_recordable_frame = max_frames;
1772 AudioDiskstream::set_record_enabled (bool yn)
1774 if (!recordable() || !_session.record_enabling_legal() || _io->n_inputs().n_audio() == 0) {
1778 /* can't rec-enable in destructive mode if transport is before start */
1780 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1784 if (yn && channels.reader()->front()->source == 0) {
1786 /* pick up connections not initiated *from* the IO object
1787 we're associated with.
1790 get_input_sources ();
1793 /* yes, i know that this not proof against race conditions, but its
1794 good enough. i think.
1797 if (record_enabled() != yn) {
1799 engage_record_enable ();
1801 disengage_record_enable ();
1807 AudioDiskstream::engage_record_enable ()
1809 bool rolling = _session.transport_speed() != 0.0f;
1810 boost::shared_ptr<ChannelList> c = channels.reader();
1812 g_atomic_int_set (&_record_enabled, 1);
1813 capturing_sources.clear ();
1815 if (Config->get_monitoring_model() == HardwareMonitoring) {
1817 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1818 if ((*chan)->source) {
1819 (*chan)->source->ensure_monitor_input (!(Config->get_auto_input() && rolling));
1821 capturing_sources.push_back ((*chan)->write_source);
1822 (*chan)->write_source->mark_streaming_write_started ();
1826 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1827 capturing_sources.push_back ((*chan)->write_source);
1828 (*chan)->write_source->mark_streaming_write_started ();
1832 RecordEnableChanged (); /* EMIT SIGNAL */
1836 AudioDiskstream::disengage_record_enable ()
1838 g_atomic_int_set (&_record_enabled, 0);
1839 boost::shared_ptr<ChannelList> c = channels.reader();
1840 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1841 if (Config->get_monitoring_model() == HardwareMonitoring) {
1842 if ((*chan)->source) {
1843 (*chan)->source->ensure_monitor_input (false);
1847 capturing_sources.clear ();
1848 RecordEnableChanged (); /* EMIT SIGNAL */
1852 AudioDiskstream::get_state ()
1854 XMLNode* node = new XMLNode ("AudioDiskstream");
1856 LocaleGuard lg (X_("POSIX"));
1857 boost::shared_ptr<ChannelList> c = channels.reader();
1859 node->add_property ("flags", enum_2_string (_flags));
1861 snprintf (buf, sizeof(buf), "%zd", c->size());
1862 node->add_property ("channels", buf);
1864 node->add_property ("playlist", _playlist->name());
1866 snprintf (buf, sizeof(buf), "%.12g", _visible_speed);
1867 node->add_property ("speed", buf);
1869 node->add_property("name", _name);
1870 id().print (buf, sizeof (buf));
1871 node->add_property("id", buf);
1873 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1875 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1876 XMLNode* cs_grandchild;
1878 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1879 cs_grandchild = new XMLNode (X_("file"));
1880 cs_grandchild->add_property (X_("path"), (*i)->path());
1881 cs_child->add_child_nocopy (*cs_grandchild);
1884 /* store the location where capture will start */
1888 if (Config->get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1889 snprintf (buf, sizeof (buf), "%" PRIu32, pi->start());
1891 snprintf (buf, sizeof (buf), "%" PRIu32, _session.transport_frame());
1894 cs_child->add_property (X_("at"), buf);
1895 node->add_child_nocopy (*cs_child);
1899 node->add_child_copy (*_extra_xml);
1906 AudioDiskstream::set_state (const XMLNode& node)
1908 const XMLProperty* prop;
1909 XMLNodeList nlist = node.children();
1910 XMLNodeIterator niter;
1911 uint32_t nchans = 1;
1912 XMLNode* capture_pending_node = 0;
1913 LocaleGuard lg (X_("POSIX"));
1915 in_set_state = true;
1917 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1918 if ((*niter)->name() == IO::state_node_name) {
1919 deprecated_io_node = new XMLNode (**niter);
1922 if ((*niter)->name() == X_("CapturingSources")) {
1923 capture_pending_node = *niter;
1927 /* prevent write sources from being created */
1929 in_set_state = true;
1931 if ((prop = node.property ("name")) != 0) {
1932 _name = prop->value();
1935 if (deprecated_io_node) {
1936 if ((prop = deprecated_io_node->property ("id")) != 0) {
1937 _id = prop->value ();
1940 if ((prop = node.property ("id")) != 0) {
1941 _id = prop->value ();
1945 if ((prop = node.property ("flags")) != 0) {
1946 _flags = Flag (string_2_enum (prop->value(), _flags));
1949 if ((prop = node.property ("channels")) != 0) {
1950 nchans = atoi (prop->value().c_str());
1953 // create necessary extra channels
1954 // we are always constructed with one and we always need one
1956 _n_channels.set(DataType::AUDIO, channels.reader()->size());
1958 if (nchans > _n_channels.n_audio()) {
1960 add_channel (nchans - _n_channels.n_audio());
1961 IO::PortCountChanged(_n_channels);
1963 } else if (nchans < _n_channels.n_audio()) {
1965 remove_channel (_n_channels.n_audio() - nchans);
1968 if ((prop = node.property ("playlist")) == 0) {
1973 bool had_playlist = (_playlist != 0);
1975 if (find_and_use_playlist (prop->value())) {
1979 if (!had_playlist) {
1980 _playlist->set_orig_diskstream_id (_id);
1983 if (!destructive() && capture_pending_node) {
1984 /* destructive streams have one and only one source per channel,
1985 and so they never end up in pending capture in any useful
1988 use_pending_capture_data (*capture_pending_node);
1993 if ((prop = node.property ("speed")) != 0) {
1994 double sp = atof (prop->value().c_str());
1996 if (realtime_set_speed (sp, false)) {
1997 non_realtime_set_speed ();
2001 in_set_state = false;
2003 /* make sure this is clear before we do anything else */
2005 capturing_sources.clear ();
2007 /* write sources are handled when we handle the input set
2008 up of the IO that owns this DS (::non_realtime_input_change())
2015 AudioDiskstream::use_new_write_source (uint32_t n)
2017 boost::shared_ptr<ChannelList> c = channels.reader();
2019 if (!recordable()) {
2023 if (n >= c->size()) {
2024 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
2028 ChannelInfo* chan = (*c)[n];
2030 if (chan->write_source) {
2031 chan->write_source->done_with_peakfile_writes ();
2032 chan->write_source->set_allow_remove_if_empty (true);
2033 chan->write_source.reset ();
2037 if ((chan->write_source = _session.create_audio_source_for_session (*this, n, destructive())) == 0) {
2038 throw failed_constructor();
2042 catch (failed_constructor &err) {
2043 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
2044 chan->write_source.reset ();
2048 /* do not remove destructive files even if they are empty */
2050 chan->write_source->set_allow_remove_if_empty (!destructive());
2056 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool force)
2058 ChannelList::iterator chan;
2059 boost::shared_ptr<ChannelList> c = channels.reader();
2062 if (!recordable()) {
2066 capturing_sources.clear ();
2068 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
2069 if (!destructive()) {
2071 if ((*chan)->write_source && mark_write_complete) {
2072 (*chan)->write_source->mark_streaming_write_completed ();
2074 use_new_write_source (n);
2076 if (record_enabled()) {
2077 capturing_sources.push_back ((*chan)->write_source);
2081 if ((*chan)->write_source == 0) {
2082 use_new_write_source (n);
2087 if (destructive()) {
2089 /* we now have all our write sources set up, so create the
2090 playlist's single region.
2093 if (_playlist->empty()) {
2094 setup_destructive_playlist ();
2100 AudioDiskstream::rename_write_sources ()
2102 ChannelList::iterator chan;
2103 boost::shared_ptr<ChannelList> c = channels.reader();
2106 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
2107 if ((*chan)->write_source != 0) {
2108 (*chan)->write_source->set_source_name (_name, destructive());
2109 /* XXX what to do if one of them fails ? */
2117 AudioDiskstream::set_block_size (nframes_t nframes)
2119 if (_session.get_block_size() > speed_buffer_size) {
2120 speed_buffer_size = _session.get_block_size();
2121 boost::shared_ptr<ChannelList> c = channels.reader();
2123 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2124 if ((*chan)->speed_buffer) delete [] (*chan)->speed_buffer;
2125 (*chan)->speed_buffer = new Sample[speed_buffer_size];
2128 allocate_temporary_buffers ();
2132 AudioDiskstream::allocate_temporary_buffers ()
2134 /* make sure the wrap buffer is at least large enough to deal
2135 with the speeds up to 1.2, to allow for micro-variation
2136 when slaving to MTC, SMPTE etc.
2139 double sp = max (fabsf (_actual_speed), 1.2f);
2140 nframes_t required_wrap_size = (nframes_t) floor (_session.get_block_size() * sp) + 1;
2142 if (required_wrap_size > wrap_buffer_size) {
2144 boost::shared_ptr<ChannelList> c = channels.reader();
2146 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2147 if ((*chan)->playback_wrap_buffer) delete [] (*chan)->playback_wrap_buffer;
2148 (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
2149 if ((*chan)->capture_wrap_buffer) delete [] (*chan)->capture_wrap_buffer;
2150 (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
2153 wrap_buffer_size = required_wrap_size;
2158 AudioDiskstream::monitor_input (bool yn)
2160 boost::shared_ptr<ChannelList> c = channels.reader();
2162 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2164 if ((*chan)->source) {
2165 (*chan)->source->ensure_monitor_input (yn);
2171 AudioDiskstream::set_align_style_from_io ()
2173 bool have_physical = false;
2179 get_input_sources ();
2181 boost::shared_ptr<ChannelList> c = channels.reader();
2183 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2184 if ((*chan)->source && (*chan)->source->flags() & JackPortIsPhysical) {
2185 have_physical = true;
2190 if (have_physical) {
2191 set_align_style (ExistingMaterial);
2193 set_align_style (CaptureTime);
2198 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2200 while (how_many--) {
2201 c->push_back (new ChannelInfo(_session.diskstream_buffer_size(), speed_buffer_size, wrap_buffer_size));
2204 _n_channels.set(DataType::AUDIO, c->size());
2210 AudioDiskstream::add_channel (uint32_t how_many)
2212 RCUWriter<ChannelList> writer (channels);
2213 boost::shared_ptr<ChannelList> c = writer.get_copy();
2215 return add_channel_to (c, how_many);
2219 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2221 while (--how_many && !c->empty()) {
2226 _n_channels.set(DataType::AUDIO, c->size());
2232 AudioDiskstream::remove_channel (uint32_t how_many)
2234 RCUWriter<ChannelList> writer (channels);
2235 boost::shared_ptr<ChannelList> c = writer.get_copy();
2237 return remove_channel_from (c, how_many);
2241 AudioDiskstream::playback_buffer_load () const
2243 boost::shared_ptr<ChannelList> c = channels.reader();
2245 return (float) ((double) c->front()->playback_buf->read_space()/
2246 (double) c->front()->playback_buf->bufsize());
2250 AudioDiskstream::capture_buffer_load () const
2252 boost::shared_ptr<ChannelList> c = channels.reader();
2254 return (float) ((double) c->front()->capture_buf->write_space()/
2255 (double) c->front()->capture_buf->bufsize());
2259 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2261 const XMLProperty* prop;
2262 XMLNodeList nlist = node.children();
2263 XMLNodeIterator niter;
2264 boost::shared_ptr<AudioFileSource> fs;
2265 boost::shared_ptr<AudioFileSource> first_fs;
2266 SourceList pending_sources;
2269 if ((prop = node.property (X_("at"))) == 0) {
2273 if (sscanf (prop->value().c_str(), "%" PRIu32, &position) != 1) {
2277 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2278 if ((*niter)->name() == X_("file")) {
2280 if ((prop = (*niter)->property (X_("path"))) == 0) {
2284 // This protects sessions from errant CapturingSources in stored sessions
2286 if (stat (prop->value().c_str(), &sbuf)) {
2291 fs = boost::dynamic_pointer_cast<AudioFileSource> (
2292 SourceFactory::createWritable (DataType::AUDIO, _session, prop->value(), false, _session.frame_rate()));
2295 catch (failed_constructor& err) {
2296 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2297 _name, prop->value())
2302 pending_sources.push_back (fs);
2304 if (first_fs == 0) {
2308 fs->set_captured_for (_name);
2312 if (pending_sources.size() == 0) {
2313 /* nothing can be done */
2317 if (pending_sources.size() != _n_channels.n_audio()) {
2318 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2323 boost::shared_ptr<AudioRegion> region;
2326 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, 0, first_fs->length(),
2327 region_name_from_path (first_fs->name(), true),
2328 0, AudioRegion::Flag (AudioRegion::DefaultFlags|AudioRegion::Automatic|AudioRegion::WholeFile)));
2329 region->special_set_position (0);
2332 catch (failed_constructor& err) {
2333 error << string_compose (_("%1: cannot create whole-file region from pending capture sources"),
2341 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, 0, first_fs->length(), region_name_from_path (first_fs->name(), true)));
2344 catch (failed_constructor& err) {
2345 error << string_compose (_("%1: cannot create region from pending capture sources"),
2352 _playlist->add_region (region, position);
2358 AudioDiskstream::set_destructive (bool yn)
2360 bool bounce_ignored;
2362 if (yn != destructive()) {
2365 /* requestor should already have checked this and
2366 bounced if necessary and desired
2368 if (!can_become_destructive (bounce_ignored)) {
2371 _flags = Flag (_flags | Destructive);
2372 use_destructive_playlist ();
2374 _flags = Flag (_flags & ~Destructive);
2375 reset_write_sources (true, true);
2383 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2386 requires_bounce = false;
2390 /* is there only one region ? */
2392 if (_playlist->n_regions() != 1) {
2393 requires_bounce = true;
2397 boost::shared_ptr<Region> first = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
2400 /* do the source(s) for the region cover the session start position ? */
2402 if (first->position() != _session.current_start_frame()) {
2403 if (first->start() > _session.current_start_frame()) {
2404 requires_bounce = true;
2409 /* is the source used by only 1 playlist ? */
2411 boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2415 if (afirst->source()->used() > 1) {
2416 requires_bounce = true;
2420 requires_bounce = false;
2424 AudioDiskstream::ChannelInfo::ChannelInfo (nframes_t bufsize, nframes_t speed_size, nframes_t wrap_size)
2428 current_capture_buffer = 0;
2429 current_playback_buffer = 0;
2430 curr_capture_cnt = 0;
2432 speed_buffer = new Sample[speed_size];
2433 playback_wrap_buffer = new Sample[wrap_size];
2434 capture_wrap_buffer = new Sample[wrap_size];
2436 playback_buf = new RingBufferNPT<Sample> (bufsize);
2437 capture_buf = new RingBufferNPT<Sample> (bufsize);
2438 capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2440 /* touch the ringbuffer buffers, which will cause
2441 them to be mapped into locked physical RAM if
2442 we're running with mlockall(). this doesn't do
2446 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2447 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2448 memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2451 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2454 write_source.reset ();
2458 delete [] speed_buffer;
2462 if (playback_wrap_buffer) {
2463 delete [] playback_wrap_buffer;
2464 playback_wrap_buffer = 0;
2467 if (capture_wrap_buffer) {
2468 delete [] capture_wrap_buffer;
2469 capture_wrap_buffer = 0;
2473 delete playback_buf;
2482 if (capture_transition_buf) {
2483 delete capture_transition_buf;
2484 capture_transition_buf = 0;