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/analyser.h>
43 #include <ardour/audio_diskstream.h>
44 #include <ardour/utils.h>
45 #include <ardour/configuration.h>
46 #include <ardour/audiofilesource.h>
47 #include <ardour/send.h>
48 #include <ardour/region_factory.h>
49 #include <ardour/audioplaylist.h>
50 #include <ardour/playlist_factory.h>
51 #include <ardour/cycle_timer.h>
52 #include <ardour/audioregion.h>
53 #include <ardour/audio_port.h>
54 #include <ardour/source_factory.h>
60 using namespace ARDOUR;
63 size_t AudioDiskstream::_working_buffers_size = 0;
64 Sample* AudioDiskstream::_mixdown_buffer = 0;
65 gain_t* AudioDiskstream::_gain_buffer = 0;
67 AudioDiskstream::AudioDiskstream (Session &sess, const string &name, Diskstream::Flag flag)
68 : Diskstream(sess, name, flag)
69 , deprecated_io_node(NULL)
70 , channels (new ChannelList)
72 /* prevent any write sources from being created */
82 AudioDiskstream::AudioDiskstream (Session& sess, const XMLNode& node)
83 : Diskstream(sess, node)
84 , deprecated_io_node(NULL)
85 , channels (new ChannelList)
90 if (set_state (node)) {
92 throw failed_constructor();
98 use_destructive_playlist ();
103 AudioDiskstream::init (Diskstream::Flag f)
107 /* there are no channels at this point, so these
108 two calls just get speed_buffer_size and wrap_buffer
109 size setup without duplicating their code.
112 set_block_size (_session.get_block_size());
113 allocate_temporary_buffers ();
116 assert(_n_channels == ChanCount(DataType::AUDIO, 1));
119 AudioDiskstream::~AudioDiskstream ()
124 RCUWriter<ChannelList> writer (channels);
125 boost::shared_ptr<ChannelList> c = writer.get_copy();
127 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
138 AudioDiskstream::allocate_working_buffers()
140 assert(disk_io_frames() > 0);
142 _working_buffers_size = disk_io_frames();
143 _mixdown_buffer = new Sample[_working_buffers_size];
144 _gain_buffer = new gain_t[_working_buffers_size];
148 AudioDiskstream::free_working_buffers()
150 delete [] _mixdown_buffer;
151 delete [] _gain_buffer;
152 _working_buffers_size = 0;
158 AudioDiskstream::non_realtime_input_change ()
161 Glib::Mutex::Lock lm (state_lock);
163 if (input_change_pending == NoChange) {
168 RCUWriter<ChannelList> writer (channels);
169 boost::shared_ptr<ChannelList> c = writer.get_copy();
171 _n_channels.set(DataType::AUDIO, c->size());
173 if (_io->n_inputs().n_audio() > _n_channels.n_audio()) {
174 add_channel_to (c, _io->n_inputs().n_audio() - _n_channels.n_audio());
175 } else if (_io->n_inputs().n_audio() < _n_channels.n_audio()) {
176 remove_channel_from (c, _n_channels.n_audio() - _io->n_inputs().n_audio());
180 get_input_sources ();
181 set_capture_offset ();
183 if (first_input_change) {
184 set_align_style (_persistent_alignment_style);
185 first_input_change = false;
187 set_align_style_from_io ();
190 input_change_pending = NoChange;
192 /* implicit unlock */
195 /* reset capture files */
197 reset_write_sources (false);
199 /* now refill channel buffers */
201 if (speed() != 1.0f || speed() != -1.0f) {
202 seek ((nframes_t) (_session.transport_frame() * (double) speed()));
204 seek (_session.transport_frame());
209 AudioDiskstream::get_input_sources ()
211 boost::shared_ptr<ChannelList> c = channels.reader();
214 ChannelList::iterator chan;
215 uint32_t ni = _io->n_inputs().n_audio();
216 vector<string> connections;
218 for (n = 0, chan = c->begin(); chan != c->end() && n < ni; ++chan, ++n) {
220 connections.clear ();
222 if (_io->input(n)->get_connections (connections) == 0) {
224 if ((*chan)->source) {
225 // _source->disable_metering ();
231 (*chan)->source = dynamic_cast<AudioPort*>(_session.engine().get_port_by_name (connections[0]) );
237 AudioDiskstream::find_and_use_playlist (const string& name)
239 boost::shared_ptr<AudioPlaylist> playlist;
241 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (_session.playlist_by_name (name))) == 0) {
242 playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, name));
246 error << string_compose(_("AudioDiskstream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
250 return use_playlist (playlist);
254 AudioDiskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
256 assert(boost::dynamic_pointer_cast<AudioPlaylist>(playlist));
258 Diskstream::use_playlist(playlist);
264 AudioDiskstream::use_new_playlist ()
267 boost::shared_ptr<AudioPlaylist> playlist;
269 if (!in_set_state && destructive()) {
274 newname = Playlist::bump_name (_playlist->name(), _session);
276 newname = Playlist::bump_name (_name, _session);
279 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, newname, hidden()))) != 0) {
281 playlist->set_orig_diskstream_id (id());
282 return use_playlist (playlist);
290 AudioDiskstream::use_copy_playlist ()
292 assert(audio_playlist());
298 if (_playlist == 0) {
299 error << string_compose(_("AudioDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
304 boost::shared_ptr<AudioPlaylist> playlist;
306 newname = Playlist::bump_name (_playlist->name(), _session);
308 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist>(PlaylistFactory::create (audio_playlist(), newname))) != 0) {
309 playlist->set_orig_diskstream_id (id());
310 return use_playlist (playlist);
317 AudioDiskstream::setup_destructive_playlist ()
320 boost::shared_ptr<ChannelList> c = channels.reader();
322 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
323 srcs.push_back ((*chan)->write_source);
326 /* a single full-sized region */
328 boost::shared_ptr<Region> region (RegionFactory::create (srcs, 0, max_frames - srcs.front()->natural_position(), _name));
329 _playlist->add_region (region, srcs.front()->natural_position());
333 AudioDiskstream::use_destructive_playlist ()
335 /* this is called from the XML-based constructor or ::set_destructive. when called,
336 we already have a playlist and a region, but we need to
337 set up our sources for write. we use the sources associated
338 with the (presumed single, full-extent) region.
341 boost::shared_ptr<Region> rp = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
344 reset_write_sources (false, true);
348 boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
351 throw failed_constructor();
354 /* be sure to stretch the region out to the maximum length */
356 region->set_length (max_frames - region->position(), this);
359 ChannelList::iterator chan;
360 boost::shared_ptr<ChannelList> c = channels.reader();
362 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
363 (*chan)->write_source = boost::dynamic_pointer_cast<AudioFileSource>(region->source (n));
364 assert((*chan)->write_source);
365 (*chan)->write_source->set_allow_remove_if_empty (false);
367 /* this might be false if we switched modes, so force it */
369 (*chan)->write_source->set_destructive (true);
372 /* the source list will never be reset for a destructive track */
376 AudioDiskstream::check_record_status (nframes_t transport_frame, nframes_t nframes, bool can_record)
378 int possibly_recording;
381 const int transport_rolling = 0x4;
382 const int track_rec_enabled = 0x2;
383 const int global_rec_enabled = 0x1;
385 /* merge together the 3 factors that affect record status, and compute
389 rolling = _session.transport_speed() != 0.0f;
390 possibly_recording = (rolling << 2) | (record_enabled() << 1) | can_record;
391 change = possibly_recording ^ last_possibly_recording;
393 if (possibly_recording == last_possibly_recording) {
399 /* if per-track or global rec-enable turned on while the other was already on, we've started recording */
401 if (((change & track_rec_enabled) && record_enabled() && (!(change & global_rec_enabled) && can_record)) ||
402 (((change & global_rec_enabled) && can_record && (!(change & track_rec_enabled) && record_enabled())))) {
404 /* starting to record: compute first+last frames */
406 first_recordable_frame = transport_frame + _capture_offset;
407 last_recordable_frame = max_frames;
408 capture_start_frame = transport_frame;
410 if (!(last_possibly_recording & transport_rolling) && (possibly_recording & transport_rolling)) {
412 /* was stopped, now rolling (and recording) */
414 if (_alignment_style == ExistingMaterial) {
415 first_recordable_frame += _session.worst_output_latency();
417 first_recordable_frame += _roll_delay;
422 /* was rolling, but record state changed */
424 if (_alignment_style == ExistingMaterial) {
426 if (!Config->get_punch_in()) {
428 /* manual punch in happens at the correct transport frame
429 because the user hit a button. but to get alignment correct
430 we have to back up the position of the new region to the
431 appropriate spot given the roll delay.
434 capture_start_frame -= _roll_delay;
436 /* XXX paul notes (august 2005): i don't know why
440 first_recordable_frame += _capture_offset;
444 /* autopunch toggles recording at the precise
445 transport frame, and then the DS waits
446 to start recording for a time that depends
447 on the output latency.
450 first_recordable_frame += _session.worst_output_latency();
455 if (Config->get_punch_in()) {
456 first_recordable_frame += _roll_delay;
458 capture_start_frame -= _roll_delay;
464 if (recordable() && destructive()) {
465 boost::shared_ptr<ChannelList> c = channels.reader();
466 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
468 RingBufferNPT<CaptureTransition>::rw_vector transvec;
469 (*chan)->capture_transition_buf->get_write_vector(&transvec);
471 if (transvec.len[0] > 0) {
472 transvec.buf[0]->type = CaptureStart;
473 transvec.buf[0]->capture_val = capture_start_frame;
474 (*chan)->capture_transition_buf->increment_write_ptr(1);
478 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
484 } else if (!record_enabled() || !can_record) {
488 last_recordable_frame = transport_frame + _capture_offset;
490 if (_alignment_style == ExistingMaterial) {
491 last_recordable_frame += _session.worst_output_latency();
493 last_recordable_frame += _roll_delay;
497 last_possibly_recording = possibly_recording;
501 AudioDiskstream::process (nframes_t transport_frame, nframes_t nframes, nframes_t offset, bool can_record, bool rec_monitors_input)
504 boost::shared_ptr<ChannelList> c = channels.reader();
505 ChannelList::iterator chan;
507 nframes_t rec_offset = 0;
508 nframes_t rec_nframes = 0;
509 bool nominally_recording;
510 bool re = record_enabled ();
511 bool collect_playback = false;
513 /* if we've already processed the frames corresponding to this call,
514 just return. this allows multiple routes that are taking input
515 from this diskstream to call our ::process() method, but have
516 this stuff only happen once. more commonly, it allows both
517 the AudioTrack that is using this AudioDiskstream *and* the Session
518 to call process() without problems.
525 commit_should_unlock = false;
527 if (!_io->active()) {
532 check_record_status (transport_frame, nframes, can_record);
534 nominally_recording = (can_record && re);
541 /* This lock is held until the end of AudioDiskstream::commit, so these two functions
542 must always be called as a pair. The only exception is if this function
543 returns a non-zero value, in which case, ::commit should not be called.
546 // If we can't take the state lock return.
547 if (!state_lock.trylock()) {
550 commit_should_unlock = true;
551 adjust_capture_position = 0;
553 for (chan = c->begin(); chan != c->end(); ++chan) {
554 (*chan)->current_capture_buffer = 0;
555 (*chan)->current_playback_buffer = 0;
558 if (nominally_recording || (_session.get_record_enabled() && Config->get_punch_in())) {
561 // Safeguard against situations where process() goes haywire when autopunching and last_recordable_frame < first_recordable_frame
562 if (last_recordable_frame < first_recordable_frame) {
563 last_recordable_frame = max_frames;
566 ot = coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
573 case OverlapInternal:
574 /* ---------- recrange
577 rec_nframes = nframes;
582 /* |--------| recrange
585 rec_nframes = transport_frame + nframes - first_recordable_frame;
587 rec_offset = first_recordable_frame - transport_frame;
592 /* |--------| recrange
595 rec_nframes = last_recordable_frame - transport_frame;
599 case OverlapExternal:
600 /* |--------| recrange
601 -------------- transrange
603 rec_nframes = last_recordable_frame - first_recordable_frame;
604 rec_offset = first_recordable_frame - transport_frame;
608 if (rec_nframes && !was_recording) {
609 capture_captured = 0;
610 was_recording = true;
615 if (can_record && !_last_capture_regions.empty()) {
616 _last_capture_regions.clear ();
619 if (nominally_recording || rec_nframes) {
621 uint32_t limit = _io->n_inputs ().n_audio();
623 /* one or more ports could already have been removed from _io, but our
624 channel setup hasn't yet been updated. prevent us from trying to
625 use channels that correspond to missing ports. note that the
626 process callback (from which this is called) is always atomic
627 with respect to port removal/addition.
630 for (n = 0, chan = c->begin(); chan != c->end() && n < limit; ++chan, ++n) {
632 ChannelInfo* chaninfo (*chan);
634 chaninfo->capture_buf->get_write_vector (&chaninfo->capture_vector);
636 if (rec_nframes <= chaninfo->capture_vector.len[0]) {
638 chaninfo->current_capture_buffer = chaninfo->capture_vector.buf[0];
640 /* note: grab the entire port buffer, but only copy what we were supposed to for recording, and use
644 AudioPort* const ap = _io->audio_input(n);
646 assert(rec_nframes <= ap->get_audio_buffer().capacity());
647 memcpy (chaninfo->current_capture_buffer, ap->get_audio_buffer().data(rec_nframes, offset + rec_offset), sizeof (Sample) * rec_nframes);
651 nframes_t total = chaninfo->capture_vector.len[0] + chaninfo->capture_vector.len[1];
653 if (rec_nframes > total) {
658 AudioPort* const ap = _io->audio_input(n);
661 Sample* buf = ap->get_audio_buffer().data(nframes, offset);
662 nframes_t first = chaninfo->capture_vector.len[0];
664 memcpy (chaninfo->capture_wrap_buffer, buf, sizeof (Sample) * first);
665 memcpy (chaninfo->capture_vector.buf[0], buf, sizeof (Sample) * first);
666 memcpy (chaninfo->capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
667 memcpy (chaninfo->capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
669 chaninfo->current_capture_buffer = chaninfo->capture_wrap_buffer;
676 finish_capture (rec_monitors_input, c);
683 /* data will be written to disk */
685 if (rec_nframes == nframes && rec_offset == 0) {
687 for (chan = c->begin(); chan != c->end(); ++chan) {
688 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
691 playback_distance = nframes;
696 /* we can't use the capture buffer as the playback buffer, because
697 we recorded only a part of the current process' cycle data
701 collect_playback = true;
704 adjust_capture_position = rec_nframes;
706 } else if (nominally_recording) {
708 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
710 for (chan = c->begin(); chan != c->end(); ++chan) {
711 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
714 playback_distance = nframes;
718 collect_playback = true;
721 if (collect_playback) {
723 /* we're doing playback */
725 nframes_t necessary_samples;
727 /* no varispeed playback if we're recording, because the output .... TBD */
729 if (rec_nframes == 0 && _actual_speed != 1.0f) {
730 necessary_samples = (nframes_t) floor ((nframes * fabs (_actual_speed))) + 1;
732 necessary_samples = nframes;
735 for (chan = c->begin(); chan != c->end(); ++chan) {
736 (*chan)->playback_buf->get_read_vector (&(*chan)->playback_vector);
741 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
743 ChannelInfo* chaninfo (*chan);
745 if (necessary_samples <= chaninfo->playback_vector.len[0]) {
747 chaninfo->current_playback_buffer = chaninfo->playback_vector.buf[0];
750 nframes_t total = chaninfo->playback_vector.len[0] + chaninfo->playback_vector.len[1];
752 if (necessary_samples > total) {
753 cerr << "underrun for " << _name << endl;
759 memcpy ((char *) chaninfo->playback_wrap_buffer, chaninfo->playback_vector.buf[0],
760 chaninfo->playback_vector.len[0] * sizeof (Sample));
761 memcpy (chaninfo->playback_wrap_buffer + chaninfo->playback_vector.len[0], chaninfo->playback_vector.buf[1],
762 (necessary_samples - chaninfo->playback_vector.len[0]) * sizeof (Sample));
764 chaninfo->current_playback_buffer = chaninfo->playback_wrap_buffer;
769 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
771 uint64_t phase = last_phase;
775 // Linearly interpolate into the alt buffer
776 // using 40.24 fixp maths (swh)
778 if (phi != target_phi) {
779 phi_delta = ((int64_t)(target_phi - phi)) / nframes;
784 for (chan = c->begin(); chan != c->end(); ++chan) {
787 ChannelInfo* chaninfo (*chan);
792 for (nframes_t outsample = 0; outsample < nframes; ++outsample) {
794 fr = (phase & 0xFFFFFF) / 16777216.0f;
795 chaninfo->speed_buffer[outsample] =
796 chaninfo->current_playback_buffer[i] * (1.0f - fr) +
797 chaninfo->current_playback_buffer[i+1] * fr;
798 phase += phi + phi_delta;
801 chaninfo->current_playback_buffer = chaninfo->speed_buffer;
804 playback_distance = i; // + 1;
805 last_phase = (phase & 0xFFFFFF);
808 playback_distance = nframes;
822 /* we're exiting with failure, so ::commit will not
823 be called. unlock the state lock.
826 commit_should_unlock = false;
834 AudioDiskstream::commit (nframes_t nframes)
836 bool need_butler = false;
838 if (!_io->active()) {
842 if (_actual_speed < 0.0) {
843 playback_sample -= playback_distance;
845 playback_sample += playback_distance;
848 boost::shared_ptr<ChannelList> c = channels.reader();
849 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
851 (*chan)->playback_buf->increment_read_ptr (playback_distance);
853 if (adjust_capture_position) {
854 (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
858 if (adjust_capture_position != 0) {
859 capture_captured += adjust_capture_position;
860 adjust_capture_position = 0;
864 if (_io && _io->active()) {
865 need_butler = c->front()->playback_buf->write_space() >= c->front()->playback_buf->bufsize() / 2;
870 if (_io && _io->active()) {
871 need_butler = c->front()->playback_buf->write_space() >= disk_io_chunk_frames
872 || c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
874 need_butler = c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
878 if (commit_should_unlock) {
888 AudioDiskstream::set_pending_overwrite (bool yn)
890 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
892 pending_overwrite = yn;
894 overwrite_frame = playback_sample;
895 overwrite_offset = channels.reader()->front()->playback_buf->get_read_ptr();
899 AudioDiskstream::overwrite_existing_buffers ()
901 boost::shared_ptr<ChannelList> c = channels.reader();
902 Sample* mixdown_buffer;
905 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
907 overwrite_queued = false;
909 /* assume all are the same size */
910 nframes_t size = c->front()->playback_buf->bufsize();
912 mixdown_buffer = new Sample[size];
913 gain_buffer = new float[size];
915 /* reduce size so that we can fill the buffer correctly. */
921 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
923 start = overwrite_frame;
924 nframes_t cnt = size;
926 /* to fill the buffer without resetting the playback sample, we need to
927 do it one or two chunks (normally two).
929 |----------------------------------------------------------------------|
933 |<- second chunk->||<----------------- first chunk ------------------>|
937 nframes_t to_read = size - overwrite_offset;
939 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, *chan, n, reversed)) {
940 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
941 _id, size, playback_sample) << endmsg;
949 if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer,
950 start, cnt, *chan, n, reversed)) {
951 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
952 _id, size, playback_sample) << endmsg;
961 pending_overwrite = false;
962 delete [] gain_buffer;
963 delete [] mixdown_buffer;
968 AudioDiskstream::seek (nframes_t frame, bool complete_refill)
972 ChannelList::iterator chan;
973 boost::shared_ptr<ChannelList> c = channels.reader();
975 Glib::Mutex::Lock lm (state_lock);
977 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
978 (*chan)->playback_buf->reset ();
979 (*chan)->capture_buf->reset ();
982 /* can't rec-enable in destructive mode if transport is before start */
984 if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
985 disengage_record_enable ();
988 playback_sample = frame;
991 if (complete_refill) {
992 while ((ret = do_refill_with_alloc ()) > 0) ;
994 ret = do_refill_with_alloc ();
1001 AudioDiskstream::can_internal_playback_seek (nframes_t distance)
1003 ChannelList::iterator chan;
1004 boost::shared_ptr<ChannelList> c = channels.reader();
1006 for (chan = c->begin(); chan != c->end(); ++chan) {
1007 if ((*chan)->playback_buf->read_space() < distance) {
1015 AudioDiskstream::internal_playback_seek (nframes_t distance)
1017 ChannelList::iterator chan;
1018 boost::shared_ptr<ChannelList> c = channels.reader();
1020 for (chan = c->begin(); chan != c->end(); ++chan) {
1021 (*chan)->playback_buf->increment_read_ptr (distance);
1024 first_recordable_frame += distance;
1025 playback_sample += distance;
1031 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer, nframes_t& start, nframes_t cnt,
1032 ChannelInfo* channel_info, int channel, bool reversed)
1034 nframes_t this_read = 0;
1035 bool reloop = false;
1036 nframes_t loop_end = 0;
1037 nframes_t loop_start = 0;
1038 nframes_t loop_length = 0;
1039 nframes_t offset = 0;
1042 /* XXX we don't currently play loops in reverse. not sure why */
1046 /* Make the use of a Location atomic for this read operation.
1048 Note: Locations don't get deleted, so all we care about
1049 when I say "atomic" is that we are always pointing to
1050 the same one and using a start/length values obtained
1054 if ((loc = loop_location) != 0) {
1055 loop_start = loc->start();
1056 loop_end = loc->end();
1057 loop_length = loop_end - loop_start;
1060 /* if we are looping, ensure that the first frame we read is at the correct
1061 position within the loop.
1064 if (loc && start >= loop_end) {
1065 //cerr << "start adjusted from " << start;
1066 start = loop_start + ((start - loop_start) % loop_length);
1067 //cerr << "to " << start << endl;
1070 //cerr << "start is " << start << " loopstart: " << loop_start << " loopend: " << loop_end << endl;
1079 /* take any loop into account. we can't read past the end of the loop. */
1081 if (loc && (loop_end - start < cnt)) {
1082 this_read = loop_end - start;
1083 //cerr << "reloop true: thisread: " << this_read << " cnt: " << cnt << endl;
1090 if (this_read == 0) {
1094 this_read = min(cnt,this_read);
1096 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
1097 error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), _id, this_read,
1102 _read_data_count = _playlist->read_data_count();
1106 swap_by_ptr (buf, buf + this_read - 1);
1110 /* if we read to the end of the loop, go back to the beginning */
1120 offset += this_read;
1127 AudioDiskstream::do_refill_with_alloc ()
1129 Sample* mix_buf = new Sample[disk_io_chunk_frames];
1130 float* gain_buf = new float[disk_io_chunk_frames];
1132 int ret = _do_refill(mix_buf, gain_buf);
1141 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer)
1145 RingBufferNPT<Sample>::rw_vector vector;
1146 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1147 nframes_t total_space;
1148 nframes_t zero_fill;
1150 ChannelList::iterator i;
1151 boost::shared_ptr<ChannelList> c = channels.reader();
1158 assert(mixdown_buffer);
1159 assert(gain_buffer);
1166 c->front()->playback_buf->get_write_vector (&vector);
1168 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1172 /* if there are 2+ chunks of disk i/o possible for
1173 this track, let the caller know so that it can arrange
1174 for us to be called again, ASAP.
1177 if (total_space >= (_slaved?3:2) * disk_io_chunk_frames) {
1181 /* if we're running close to normal speed and there isn't enough
1182 space to do disk_io_chunk_frames of I/O, then don't bother.
1184 at higher speeds, just do it because the sync between butler
1185 and audio thread may not be good enough.
1188 if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1192 /* when slaved, don't try to get too close to the read pointer. this
1193 leaves space for the buffer reversal to have something useful to
1197 if (_slaved && total_space < (c->front()->playback_buf->bufsize() / 2)) {
1201 /* never do more than disk_io_chunk_frames worth of disk input per call (limit doesn't apply for memset) */
1203 total_space = min (disk_io_chunk_frames, total_space);
1207 if (file_frame == 0) {
1209 /* at start: nothing to do but fill with silence */
1211 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1213 ChannelInfo* chan (*i);
1214 chan->playback_buf->get_write_vector (&vector);
1215 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1216 if (vector.len[1]) {
1217 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1219 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1224 if (file_frame < total_space) {
1226 /* too close to the start: read what we can,
1227 and then zero fill the rest
1230 zero_fill = total_space - file_frame;
1231 total_space = file_frame;
1241 if (file_frame == max_frames) {
1243 /* at end: nothing to do but fill with silence */
1245 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1247 ChannelInfo* chan (*i);
1248 chan->playback_buf->get_write_vector (&vector);
1249 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1250 if (vector.len[1]) {
1251 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1253 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1258 if (file_frame > max_frames - total_space) {
1260 /* to close to the end: read what we can, and zero fill the rest */
1262 zero_fill = total_space - (max_frames - file_frame);
1263 total_space = max_frames - file_frame;
1270 nframes_t file_frame_tmp = 0;
1272 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1274 ChannelInfo* chan (*i);
1277 nframes_t len1, len2;
1279 chan->playback_buf->get_write_vector (&vector);
1281 if (vector.len[0] > disk_io_chunk_frames) {
1283 /* we're not going to fill the first chunk, so certainly do not bother with the
1284 other part. it won't be connected with the part we do fill, as in:
1286 .... => writable space
1287 ++++ => readable space
1288 ^^^^ => 1 x disk_io_chunk_frames that would be filled
1290 |......|+++++++++++++|...............................|
1295 So, just pretend that the buf1 part isn't there.
1305 file_frame_tmp = file_frame;
1307 buf1 = vector.buf[0];
1308 len1 = vector.len[0];
1309 buf2 = vector.buf[1];
1310 len2 = vector.len[1];
1312 to_read = min (ts, len1);
1313 to_read = min (to_read, disk_io_chunk_frames);
1317 if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1322 chan->playback_buf->increment_write_ptr (to_read);
1326 to_read = min (ts, len2);
1330 /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1331 so read some or all of vector.len[1] as well.
1334 if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1339 chan->playback_buf->increment_write_ptr (to_read);
1348 file_frame = file_frame_tmp;
1355 /** Flush pending data to disk.
1357 * Important note: this function will write *AT MOST* disk_io_chunk_frames
1358 * of data to disk. it will never write more than that. If it writes that
1359 * much and there is more than that waiting to be written, it will return 1,
1360 * otherwise 0 on success or -1 on failure.
1362 * If there is less than disk_io_chunk_frames to be written, no data will be
1363 * written at all unless @a force_flush is true.
1366 AudioDiskstream::do_flush (Session::RunContext context, bool force_flush)
1370 RingBufferNPT<Sample>::rw_vector vector;
1371 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1374 _write_data_count = 0;
1376 transvec.buf[0] = 0;
1377 transvec.buf[1] = 0;
1381 boost::shared_ptr<ChannelList> c = channels.reader();
1382 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1384 (*chan)->capture_buf->get_read_vector (&vector);
1386 total = vector.len[0] + vector.len[1];
1388 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1392 /* if there are 2+ chunks of disk i/o possible for
1393 this track, let the caller know so that it can arrange
1394 for us to be called again, ASAP.
1396 if we are forcing a flush, then if there is* any* extra
1397 work, let the caller know.
1399 if we are no longer recording and there is any extra work,
1400 let the caller know too.
1403 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1407 to_write = min (disk_io_chunk_frames, (nframes_t) vector.len[0]);
1409 // check the transition buffer when recording destructive
1410 // important that we get this after the capture buf
1412 if (destructive()) {
1413 (*chan)->capture_transition_buf->get_read_vector(&transvec);
1414 size_t transcount = transvec.len[0] + transvec.len[1];
1415 bool have_start = false;
1418 for (ti=0; ti < transcount; ++ti) {
1419 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1421 if (captrans.type == CaptureStart) {
1422 // by definition, the first data we got above represents the given capture pos
1424 (*chan)->write_source->mark_capture_start (captrans.capture_val);
1425 (*chan)->curr_capture_cnt = 0;
1429 else if (captrans.type == CaptureEnd) {
1431 // capture end, the capture_val represents total frames in capture
1433 if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1435 // shorten to make the write a perfect fit
1436 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
1438 if (nto_write < to_write) {
1439 ret = 1; // should we?
1441 to_write = nto_write;
1443 (*chan)->write_source->mark_capture_end ();
1445 // increment past this transition, but go no further
1450 // actually ends just beyond this chunk, so force more work
1458 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1462 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1463 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1467 (*chan)->capture_buf->increment_read_ptr (to_write);
1468 (*chan)->curr_capture_cnt += to_write;
1470 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1472 /* we wrote all of vector.len[0] but it wasn't an entire
1473 disk_io_chunk_frames of data, so arrange for some part
1474 of vector.len[1] to be flushed to disk as well.
1477 to_write = min ((nframes_t)(disk_io_chunk_frames - to_write), (nframes_t) vector.len[1]);
1479 if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1480 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1484 _write_data_count += (*chan)->write_source->write_data_count();
1486 (*chan)->capture_buf->increment_read_ptr (to_write);
1487 (*chan)->curr_capture_cnt += to_write;
1496 AudioDiskstream::transport_stopped (struct tm& when, time_t twhen, bool abort_capture)
1498 uint32_t buffer_position;
1499 bool more_work = true;
1501 boost::shared_ptr<AudioRegion> region;
1502 nframes_t total_capture;
1504 SourceList::iterator src;
1505 ChannelList::iterator chan;
1506 vector<CaptureInfo*>::iterator ci;
1507 boost::shared_ptr<ChannelList> c = channels.reader();
1509 bool mark_write_completed = false;
1511 finish_capture (true, c);
1513 /* butler is already stopped, but there may be work to do
1514 to flush remaining data to disk.
1517 while (more_work && !err) {
1518 switch (do_flush (Session::TransportContext, true)) {
1525 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1530 /* XXX is there anything we can do if err != 0 ? */
1531 Glib::Mutex::Lock lm (capture_info_lock);
1533 if (capture_info.empty()) {
1537 if (abort_capture) {
1539 if (destructive()) {
1543 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1545 if ((*chan)->write_source) {
1547 (*chan)->write_source->mark_for_remove ();
1548 (*chan)->write_source->drop_references ();
1549 (*chan)->write_source.reset ();
1552 /* new source set up in "out" below */
1558 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1559 total_capture += (*ci)->frames;
1562 /* figure out the name for this take */
1564 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1566 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1570 s->update_header (capture_info.front()->start, when, twhen);
1571 s->set_captured_for (_name);
1572 s->mark_immutable ();
1573 if (Config->get_auto_analyse_audio()) {
1574 Analyser::queue_source_for_analysis (s, true);
1579 /* destructive tracks have a single, never changing region */
1581 if (destructive()) {
1583 /* send a signal that any UI can pick up to do the right thing. there is
1584 a small problem here in that a UI may need the peak data to be ready
1585 for the data that was recorded and this isn't interlocked with that
1586 process. this problem is deferred to the UI.
1589 _playlist->Modified();
1593 string whole_file_region_name;
1594 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1596 /* Register a new region with the Session that
1597 describes the entire source. Do this first
1598 so that any sub-regions will obviously be
1599 children of this one (later!)
1603 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, c->front()->write_source->last_capture_start_frame(), total_capture,
1604 whole_file_region_name,
1605 0, AudioRegion::Flag (AudioRegion::DefaultFlags|AudioRegion::Automatic|AudioRegion::WholeFile)));
1607 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1608 region->special_set_position (capture_info.front()->start);
1612 catch (failed_constructor& err) {
1613 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1617 _last_capture_regions.push_back (region);
1619 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1621 XMLNode &before = _playlist->get_state();
1622 _playlist->freeze ();
1624 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1628 _session.region_name (region_name, whole_file_region_name, false);
1630 // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->frames << " add region " << region_name << endl;
1633 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, buffer_position, (*ci)->frames, region_name));
1634 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1637 catch (failed_constructor& err) {
1638 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1639 continue; /* XXX is this OK? */
1642 region->GoingAway.connect (bind (mem_fun (*this, &Diskstream::remove_region_from_last_capture), boost::weak_ptr<Region>(region)));
1644 _last_capture_regions.push_back (region);
1646 i_am_the_modifier++;
1647 _playlist->add_region (region, (*ci)->start);
1648 i_am_the_modifier--;
1650 buffer_position += (*ci)->frames;
1654 XMLNode &after = _playlist->get_state();
1655 _session.add_command (new MementoCommand<Playlist>(*_playlist, &before, &after));
1658 mark_write_completed = true;
1661 reset_write_sources (mark_write_completed);
1665 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1669 capture_info.clear ();
1670 capture_start_frame = 0;
1674 AudioDiskstream::transport_looped (nframes_t transport_frame)
1676 if (was_recording) {
1677 // all we need to do is finish this capture, with modified capture length
1678 boost::shared_ptr<ChannelList> c = channels.reader();
1680 // adjust the capture length knowing that the data will be recorded to disk
1681 // only necessary after the first loop where we're recording
1682 if (capture_info.size() == 0) {
1683 capture_captured += _capture_offset;
1685 if (_alignment_style == ExistingMaterial) {
1686 capture_captured += _session.worst_output_latency();
1688 capture_captured += _roll_delay;
1692 finish_capture (true, c);
1694 // the next region will start recording via the normal mechanism
1695 // we'll set the start position to the current transport pos
1696 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1697 capture_start_frame = transport_frame;
1698 first_recordable_frame = transport_frame; // mild lie
1699 last_recordable_frame = max_frames;
1700 was_recording = true;
1702 if (recordable() && destructive()) {
1703 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1705 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1706 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1708 if (transvec.len[0] > 0) {
1709 transvec.buf[0]->type = CaptureStart;
1710 transvec.buf[0]->capture_val = capture_start_frame;
1711 (*chan)->capture_transition_buf->increment_write_ptr(1);
1715 fatal << X_("programming error: capture_transition_buf is full on rec loop! inconceivable!")
1725 AudioDiskstream::finish_capture (bool rec_monitors_input, boost::shared_ptr<ChannelList> c)
1727 was_recording = false;
1729 if (capture_captured == 0) {
1733 if (recordable() && destructive()) {
1734 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1736 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1737 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1739 if (transvec.len[0] > 0) {
1740 transvec.buf[0]->type = CaptureEnd;
1741 transvec.buf[0]->capture_val = capture_captured;
1742 (*chan)->capture_transition_buf->increment_write_ptr(1);
1746 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1752 CaptureInfo* ci = new CaptureInfo;
1754 ci->start = capture_start_frame;
1755 ci->frames = capture_captured;
1757 /* XXX theoretical race condition here. Need atomic exchange ?
1758 However, the circumstances when this is called right
1759 now (either on record-disable or transport_stopped)
1760 mean that no actual race exists. I think ...
1761 We now have a capture_info_lock, but it is only to be used
1762 to synchronize in the transport_stop and the capture info
1763 accessors, so that invalidation will not occur (both non-realtime).
1766 // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1768 capture_info.push_back (ci);
1769 capture_captured = 0;
1771 /* now we've finished a capture, reset first_recordable_frame for next time */
1772 first_recordable_frame = max_frames;
1776 AudioDiskstream::set_record_enabled (bool yn)
1778 if (!recordable() || !_session.record_enabling_legal() || _io->n_inputs().n_audio() == 0) {
1782 /* can't rec-enable in destructive mode if transport is before start */
1784 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1788 if (yn && channels.reader()->front()->source == 0) {
1790 /* pick up connections not initiated *from* the IO object
1791 we're associated with.
1794 get_input_sources ();
1797 /* yes, i know that this not proof against race conditions, but its
1798 good enough. i think.
1801 if (record_enabled() != yn) {
1803 engage_record_enable ();
1805 disengage_record_enable ();
1811 AudioDiskstream::engage_record_enable ()
1813 bool rolling = _session.transport_speed() != 0.0f;
1814 boost::shared_ptr<ChannelList> c = channels.reader();
1816 g_atomic_int_set (&_record_enabled, 1);
1817 capturing_sources.clear ();
1819 if (Config->get_monitoring_model() == HardwareMonitoring) {
1821 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1822 if ((*chan)->source) {
1823 (*chan)->source->ensure_monitor_input (!(Config->get_auto_input() && rolling));
1825 capturing_sources.push_back ((*chan)->write_source);
1826 (*chan)->write_source->mark_streaming_write_started ();
1830 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1831 capturing_sources.push_back ((*chan)->write_source);
1832 (*chan)->write_source->mark_streaming_write_started ();
1836 RecordEnableChanged (); /* EMIT SIGNAL */
1840 AudioDiskstream::disengage_record_enable ()
1842 g_atomic_int_set (&_record_enabled, 0);
1843 boost::shared_ptr<ChannelList> c = channels.reader();
1844 if (Config->get_monitoring_model() == HardwareMonitoring) {
1845 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1846 if ((*chan)->source) {
1847 (*chan)->source->ensure_monitor_input (false);
1851 capturing_sources.clear ();
1852 RecordEnableChanged (); /* EMIT SIGNAL */
1856 AudioDiskstream::get_state ()
1858 XMLNode* node = new XMLNode ("AudioDiskstream");
1860 LocaleGuard lg (X_("POSIX"));
1861 boost::shared_ptr<ChannelList> c = channels.reader();
1863 node->add_property ("flags", enum_2_string (_flags));
1865 snprintf (buf, sizeof(buf), "%zd", c->size());
1866 node->add_property ("channels", buf);
1868 node->add_property ("playlist", _playlist->name());
1870 snprintf (buf, sizeof(buf), "%.12g", _visible_speed);
1871 node->add_property ("speed", buf);
1873 node->add_property("name", _name);
1874 id().print (buf, sizeof (buf));
1875 node->add_property("id", buf);
1877 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1879 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1880 XMLNode* cs_grandchild;
1882 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1883 cs_grandchild = new XMLNode (X_("file"));
1884 cs_grandchild->add_property (X_("path"), (*i)->path());
1885 cs_child->add_child_nocopy (*cs_grandchild);
1888 /* store the location where capture will start */
1892 if (Config->get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1893 snprintf (buf, sizeof (buf), "%" PRIu32, pi->start());
1895 snprintf (buf, sizeof (buf), "%" PRIu32, _session.transport_frame());
1898 cs_child->add_property (X_("at"), buf);
1899 node->add_child_nocopy (*cs_child);
1903 node->add_child_copy (*_extra_xml);
1910 AudioDiskstream::set_state (const XMLNode& node)
1912 const XMLProperty* prop;
1913 XMLNodeList nlist = node.children();
1914 XMLNodeIterator niter;
1915 uint32_t nchans = 1;
1916 XMLNode* capture_pending_node = 0;
1917 LocaleGuard lg (X_("POSIX"));
1919 in_set_state = true;
1921 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1922 if ((*niter)->name() == IO::state_node_name) {
1923 deprecated_io_node = new XMLNode (**niter);
1926 if ((*niter)->name() == X_("CapturingSources")) {
1927 capture_pending_node = *niter;
1931 /* prevent write sources from being created */
1933 in_set_state = true;
1935 if ((prop = node.property ("name")) != 0) {
1936 _name = prop->value();
1939 if (deprecated_io_node) {
1940 if ((prop = deprecated_io_node->property ("id")) != 0) {
1941 _id = prop->value ();
1944 if ((prop = node.property ("id")) != 0) {
1945 _id = prop->value ();
1949 if ((prop = node.property ("flags")) != 0) {
1950 _flags = Flag (string_2_enum (prop->value(), _flags));
1953 if ((prop = node.property ("channels")) != 0) {
1954 nchans = atoi (prop->value().c_str());
1957 // create necessary extra channels
1958 // we are always constructed with one and we always need one
1960 _n_channels.set(DataType::AUDIO, channels.reader()->size());
1962 if (nchans > _n_channels.n_audio()) {
1964 add_channel (nchans - _n_channels.n_audio());
1965 IO::PortCountChanged(_n_channels);
1967 } else if (nchans < _n_channels.n_audio()) {
1969 remove_channel (_n_channels.n_audio() - nchans);
1972 if ((prop = node.property ("playlist")) == 0) {
1977 bool had_playlist = (_playlist != 0);
1979 if (find_and_use_playlist (prop->value())) {
1983 if (!had_playlist) {
1984 _playlist->set_orig_diskstream_id (_id);
1987 if (!destructive() && capture_pending_node) {
1988 /* destructive streams have one and only one source per channel,
1989 and so they never end up in pending capture in any useful
1992 use_pending_capture_data (*capture_pending_node);
1997 if ((prop = node.property ("speed")) != 0) {
1998 double sp = atof (prop->value().c_str());
2000 if (realtime_set_speed (sp, false)) {
2001 non_realtime_set_speed ();
2005 in_set_state = false;
2007 /* make sure this is clear before we do anything else */
2009 capturing_sources.clear ();
2011 /* write sources are handled when we handle the input set
2012 up of the IO that owns this DS (::non_realtime_input_change())
2019 AudioDiskstream::use_new_write_source (uint32_t n)
2021 boost::shared_ptr<ChannelList> c = channels.reader();
2023 if (!recordable()) {
2027 if (n >= c->size()) {
2028 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
2032 ChannelInfo* chan = (*c)[n];
2034 if (chan->write_source) {
2035 chan->write_source->done_with_peakfile_writes ();
2036 chan->write_source->set_allow_remove_if_empty (true);
2037 chan->write_source.reset ();
2041 if ((chan->write_source = _session.create_audio_source_for_session (*this, n, destructive())) == 0) {
2042 throw failed_constructor();
2046 catch (failed_constructor &err) {
2047 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
2048 chan->write_source.reset ();
2052 /* do not remove destructive files even if they are empty */
2054 chan->write_source->set_allow_remove_if_empty (!destructive());
2060 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool force)
2062 ChannelList::iterator chan;
2063 boost::shared_ptr<ChannelList> c = channels.reader();
2066 if (!recordable()) {
2070 capturing_sources.clear ();
2072 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
2073 if (!destructive()) {
2075 if ((*chan)->write_source && mark_write_complete) {
2076 (*chan)->write_source->mark_streaming_write_completed ();
2078 use_new_write_source (n);
2080 if (record_enabled()) {
2081 capturing_sources.push_back ((*chan)->write_source);
2085 if ((*chan)->write_source == 0) {
2086 use_new_write_source (n);
2091 if (destructive()) {
2093 /* we now have all our write sources set up, so create the
2094 playlist's single region.
2097 if (_playlist->empty()) {
2098 setup_destructive_playlist ();
2104 AudioDiskstream::rename_write_sources ()
2106 ChannelList::iterator chan;
2107 boost::shared_ptr<ChannelList> c = channels.reader();
2110 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
2111 if ((*chan)->write_source != 0) {
2112 (*chan)->write_source->set_source_name (_name, destructive());
2113 /* XXX what to do if one of them fails ? */
2121 AudioDiskstream::set_block_size (nframes_t nframes)
2123 if (_session.get_block_size() > speed_buffer_size) {
2124 speed_buffer_size = _session.get_block_size();
2125 boost::shared_ptr<ChannelList> c = channels.reader();
2127 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2128 if ((*chan)->speed_buffer) delete [] (*chan)->speed_buffer;
2129 (*chan)->speed_buffer = new Sample[speed_buffer_size];
2132 allocate_temporary_buffers ();
2136 AudioDiskstream::allocate_temporary_buffers ()
2138 /* make sure the wrap buffer is at least large enough to deal
2139 with the speeds up to 1.2, to allow for micro-variation
2140 when slaving to MTC, SMPTE etc.
2143 double sp = max (fabsf (_actual_speed), 1.2f);
2144 nframes_t required_wrap_size = (nframes_t) floor (_session.get_block_size() * sp) + 1;
2146 if (required_wrap_size > wrap_buffer_size) {
2148 boost::shared_ptr<ChannelList> c = channels.reader();
2150 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2151 if ((*chan)->playback_wrap_buffer) delete [] (*chan)->playback_wrap_buffer;
2152 (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
2153 if ((*chan)->capture_wrap_buffer) delete [] (*chan)->capture_wrap_buffer;
2154 (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
2157 wrap_buffer_size = required_wrap_size;
2162 AudioDiskstream::monitor_input (bool yn)
2164 boost::shared_ptr<ChannelList> c = channels.reader();
2166 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2168 if ((*chan)->source) {
2169 (*chan)->source->ensure_monitor_input (yn);
2175 AudioDiskstream::set_align_style_from_io ()
2177 bool have_physical = false;
2183 get_input_sources ();
2185 boost::shared_ptr<ChannelList> c = channels.reader();
2187 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2188 if ((*chan)->source && (*chan)->source->flags() & JackPortIsPhysical) {
2189 have_physical = true;
2194 if (have_physical) {
2195 set_align_style (ExistingMaterial);
2197 set_align_style (CaptureTime);
2202 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2204 while (how_many--) {
2205 c->push_back (new ChannelInfo(_session.audio_diskstream_buffer_size(), speed_buffer_size, wrap_buffer_size));
2208 _n_channels.set(DataType::AUDIO, c->size());
2214 AudioDiskstream::add_channel (uint32_t how_many)
2216 RCUWriter<ChannelList> writer (channels);
2217 boost::shared_ptr<ChannelList> c = writer.get_copy();
2219 return add_channel_to (c, how_many);
2223 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2225 while (how_many-- && !c->empty()) {
2230 _n_channels.set(DataType::AUDIO, c->size());
2236 AudioDiskstream::remove_channel (uint32_t how_many)
2238 RCUWriter<ChannelList> writer (channels);
2239 boost::shared_ptr<ChannelList> c = writer.get_copy();
2241 return remove_channel_from (c, how_many);
2245 AudioDiskstream::playback_buffer_load () const
2247 boost::shared_ptr<ChannelList> c = channels.reader();
2249 return (float) ((double) c->front()->playback_buf->read_space()/
2250 (double) c->front()->playback_buf->bufsize());
2254 AudioDiskstream::capture_buffer_load () const
2256 boost::shared_ptr<ChannelList> c = channels.reader();
2258 return (float) ((double) c->front()->capture_buf->write_space()/
2259 (double) c->front()->capture_buf->bufsize());
2263 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2265 const XMLProperty* prop;
2266 XMLNodeList nlist = node.children();
2267 XMLNodeIterator niter;
2268 boost::shared_ptr<AudioFileSource> fs;
2269 boost::shared_ptr<AudioFileSource> first_fs;
2270 SourceList pending_sources;
2273 if ((prop = node.property (X_("at"))) == 0) {
2277 if (sscanf (prop->value().c_str(), "%" PRIu32, &position) != 1) {
2281 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2282 if ((*niter)->name() == X_("file")) {
2284 if ((prop = (*niter)->property (X_("path"))) == 0) {
2288 // This protects sessions from errant CapturingSources in stored sessions
2290 if (stat (prop->value().c_str(), &sbuf)) {
2295 fs = boost::dynamic_pointer_cast<AudioFileSource> (
2296 SourceFactory::createWritable (DataType::AUDIO, _session, prop->value(), false, _session.frame_rate()));
2299 catch (failed_constructor& err) {
2300 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2301 _name, prop->value())
2306 pending_sources.push_back (fs);
2308 if (first_fs == 0) {
2312 fs->set_captured_for (_name);
2316 if (pending_sources.size() == 0) {
2317 /* nothing can be done */
2321 if (pending_sources.size() != _n_channels.n_audio()) {
2322 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2327 boost::shared_ptr<AudioRegion> region;
2330 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, 0, first_fs->length(),
2331 region_name_from_path (first_fs->name(), true),
2332 0, AudioRegion::Flag (AudioRegion::DefaultFlags|AudioRegion::Automatic|AudioRegion::WholeFile)));
2333 region->special_set_position (0);
2336 catch (failed_constructor& err) {
2337 error << string_compose (_("%1: cannot create whole-file region from pending capture sources"),
2345 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, 0, first_fs->length(), region_name_from_path (first_fs->name(), true)));
2348 catch (failed_constructor& err) {
2349 error << string_compose (_("%1: cannot create region from pending capture sources"),
2356 _playlist->add_region (region, position);
2362 AudioDiskstream::set_destructive (bool yn)
2364 bool bounce_ignored;
2366 if (yn != destructive()) {
2369 /* requestor should already have checked this and
2370 bounced if necessary and desired
2372 if (!can_become_destructive (bounce_ignored)) {
2375 _flags = Flag (_flags | Destructive);
2376 use_destructive_playlist ();
2378 _flags = Flag (_flags & ~Destructive);
2379 reset_write_sources (true, true);
2387 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2390 requires_bounce = false;
2394 /* is there only one region ? */
2396 if (_playlist->n_regions() != 1) {
2397 requires_bounce = true;
2401 boost::shared_ptr<Region> first = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
2404 /* do the source(s) for the region cover the session start position ? */
2406 if (first->position() != _session.current_start_frame()) {
2407 if (first->start() > _session.current_start_frame()) {
2408 requires_bounce = true;
2413 /* is the source used by only 1 playlist ? */
2415 boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2419 if (afirst->source()->used() > 1) {
2420 requires_bounce = true;
2424 requires_bounce = false;
2428 AudioDiskstream::ChannelInfo::ChannelInfo (nframes_t bufsize, nframes_t speed_size, nframes_t wrap_size)
2432 current_capture_buffer = 0;
2433 current_playback_buffer = 0;
2434 curr_capture_cnt = 0;
2436 speed_buffer = new Sample[speed_size];
2437 playback_wrap_buffer = new Sample[wrap_size];
2438 capture_wrap_buffer = new Sample[wrap_size];
2440 playback_buf = new RingBufferNPT<Sample> (bufsize);
2441 capture_buf = new RingBufferNPT<Sample> (bufsize);
2442 capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2444 /* touch the ringbuffer buffers, which will cause
2445 them to be mapped into locked physical RAM if
2446 we're running with mlockall(). this doesn't do
2450 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2451 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2452 memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2455 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2458 write_source.reset ();
2462 delete [] speed_buffer;
2466 if (playback_wrap_buffer) {
2467 delete [] playback_wrap_buffer;
2468 playback_wrap_buffer = 0;
2471 if (capture_wrap_buffer) {
2472 delete [] capture_wrap_buffer;
2473 capture_wrap_buffer = 0;
2477 delete playback_buf;
2486 if (capture_transition_buf) {
2487 delete capture_transition_buf;
2488 capture_transition_buf = 0;