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::non_realtime_locate (nframes_t location)
211 /* now refill channel buffers */
213 if (speed() != 1.0f || speed() != -1.0f) {
214 seek ((nframes_t) (location * (double) speed()));
221 AudioDiskstream::get_input_sources ()
223 boost::shared_ptr<ChannelList> c = channels.reader();
226 ChannelList::iterator chan;
227 uint32_t ni = _io->n_inputs().n_audio();
228 vector<string> connections;
230 for (n = 0, chan = c->begin(); chan != c->end() && n < ni; ++chan, ++n) {
232 connections.clear ();
234 if (_io->input(n)->get_connections (connections) == 0) {
236 if ((*chan)->source) {
237 // _source->disable_metering ();
243 (*chan)->source = dynamic_cast<AudioPort*>(_session.engine().get_port_by_name (connections[0]) );
249 AudioDiskstream::find_and_use_playlist (const string& name)
251 boost::shared_ptr<AudioPlaylist> playlist;
253 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (_session.playlist_by_name (name))) == 0) {
254 playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, name));
258 error << string_compose(_("AudioDiskstream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
262 return use_playlist (playlist);
266 AudioDiskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
268 assert(boost::dynamic_pointer_cast<AudioPlaylist>(playlist));
270 Diskstream::use_playlist(playlist);
276 AudioDiskstream::use_new_playlist ()
279 boost::shared_ptr<AudioPlaylist> playlist;
281 if (!in_set_state && destructive()) {
286 newname = Playlist::bump_name (_playlist->name(), _session);
288 newname = Playlist::bump_name (_name, _session);
291 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, newname, hidden()))) != 0) {
293 playlist->set_orig_diskstream_id (id());
294 return use_playlist (playlist);
302 AudioDiskstream::use_copy_playlist ()
304 assert(audio_playlist());
310 if (_playlist == 0) {
311 error << string_compose(_("AudioDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
316 boost::shared_ptr<AudioPlaylist> playlist;
318 newname = Playlist::bump_name (_playlist->name(), _session);
320 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist>(PlaylistFactory::create (audio_playlist(), newname))) != 0) {
321 playlist->set_orig_diskstream_id (id());
322 return use_playlist (playlist);
329 AudioDiskstream::setup_destructive_playlist ()
332 boost::shared_ptr<ChannelList> c = channels.reader();
334 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
335 srcs.push_back ((*chan)->write_source);
338 /* a single full-sized region */
340 boost::shared_ptr<Region> region (RegionFactory::create (srcs, 0, max_frames - srcs.front()->natural_position(), _name));
341 _playlist->add_region (region, srcs.front()->natural_position());
345 AudioDiskstream::use_destructive_playlist ()
347 /* this is called from the XML-based constructor or ::set_destructive. when called,
348 we already have a playlist and a region, but we need to
349 set up our sources for write. we use the sources associated
350 with the (presumed single, full-extent) region.
353 boost::shared_ptr<Region> rp = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
356 reset_write_sources (false, true);
360 boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
363 throw failed_constructor();
366 /* be sure to stretch the region out to the maximum length */
368 region->set_length (max_frames - region->position(), this);
371 ChannelList::iterator chan;
372 boost::shared_ptr<ChannelList> c = channels.reader();
374 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
375 (*chan)->write_source = boost::dynamic_pointer_cast<AudioFileSource>(region->source (n));
376 assert((*chan)->write_source);
377 (*chan)->write_source->set_allow_remove_if_empty (false);
379 /* this might be false if we switched modes, so force it */
381 (*chan)->write_source->set_destructive (true);
384 /* the source list will never be reset for a destructive track */
388 AudioDiskstream::check_record_status (nframes_t transport_frame, nframes_t nframes, bool can_record)
390 int possibly_recording;
393 const int transport_rolling = 0x4;
394 const int track_rec_enabled = 0x2;
395 const int global_rec_enabled = 0x1;
397 /* merge together the 3 factors that affect record status, and compute
401 rolling = _session.transport_speed() != 0.0f;
402 possibly_recording = (rolling << 2) | (record_enabled() << 1) | can_record;
403 change = possibly_recording ^ last_possibly_recording;
405 if (possibly_recording == last_possibly_recording) {
411 /* if per-track or global rec-enable turned on while the other was already on, we've started recording */
413 if (((change & track_rec_enabled) && record_enabled() && (!(change & global_rec_enabled) && can_record)) ||
414 ((change & global_rec_enabled) && can_record && (!(change & track_rec_enabled) && record_enabled()))) {
416 /* starting to record: compute first+last frames */
418 first_recordable_frame = transport_frame + _capture_offset;
419 last_recordable_frame = max_frames;
420 capture_start_frame = transport_frame;
422 if (!(last_possibly_recording & transport_rolling) && (possibly_recording & transport_rolling)) {
424 /* was stopped, now rolling (and recording) */
426 if (_alignment_style == ExistingMaterial) {
427 first_recordable_frame += _session.worst_output_latency();
429 first_recordable_frame += _roll_delay;
434 /* was rolling, but record state changed */
436 if (_alignment_style == ExistingMaterial) {
438 if (!Config->get_punch_in()) {
440 /* manual punch in happens at the correct transport frame
441 because the user hit a button. but to get alignment correct
442 we have to back up the position of the new region to the
443 appropriate spot given the roll delay.
446 capture_start_frame -= _roll_delay;
448 /* XXX paul notes (august 2005): i don't know why
452 first_recordable_frame += _capture_offset;
456 /* autopunch toggles recording at the precise
457 transport frame, and then the DS waits
458 to start recording for a time that depends
459 on the output latency.
462 first_recordable_frame += _session.worst_output_latency();
467 if (Config->get_punch_in()) {
468 first_recordable_frame += _roll_delay;
470 capture_start_frame -= _roll_delay;
476 if (recordable() && destructive()) {
477 boost::shared_ptr<ChannelList> c = channels.reader();
478 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
480 RingBufferNPT<CaptureTransition>::rw_vector transvec;
481 (*chan)->capture_transition_buf->get_write_vector(&transvec);
483 if (transvec.len[0] > 0) {
484 transvec.buf[0]->type = CaptureStart;
485 transvec.buf[0]->capture_val = capture_start_frame;
486 (*chan)->capture_transition_buf->increment_write_ptr(1);
490 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
496 } else if (!record_enabled() || !can_record) {
500 last_recordable_frame = transport_frame + _capture_offset;
502 if (_alignment_style == ExistingMaterial) {
503 last_recordable_frame += _session.worst_output_latency();
505 last_recordable_frame += _roll_delay;
509 last_possibly_recording = possibly_recording;
513 AudioDiskstream::process (nframes_t transport_frame, nframes_t nframes, nframes_t offset, bool can_record, bool rec_monitors_input)
516 boost::shared_ptr<ChannelList> c = channels.reader();
517 ChannelList::iterator chan;
519 nframes_t rec_offset = 0;
520 nframes_t rec_nframes = 0;
521 bool nominally_recording;
522 bool re = record_enabled ();
523 bool collect_playback = false;
525 /* if we've already processed the frames corresponding to this call,
526 just return. this allows multiple routes that are taking input
527 from this diskstream to call our ::process() method, but have
528 this stuff only happen once. more commonly, it allows both
529 the AudioTrack that is using this AudioDiskstream *and* the Session
530 to call process() without problems.
537 commit_should_unlock = false;
539 if (!_io || !_io->active()) {
544 check_record_status (transport_frame, nframes, can_record);
546 nominally_recording = (can_record && re);
553 /* This lock is held until the end of AudioDiskstream::commit, so these two functions
554 must always be called as a pair. The only exception is if this function
555 returns a non-zero value, in which case, ::commit should not be called.
558 // If we can't take the state lock return.
559 if (!state_lock.trylock()) {
562 commit_should_unlock = true;
563 adjust_capture_position = 0;
565 for (chan = c->begin(); chan != c->end(); ++chan) {
566 (*chan)->current_capture_buffer = 0;
567 (*chan)->current_playback_buffer = 0;
570 if (nominally_recording || (_session.get_record_enabled() && Config->get_punch_in())) {
573 // Safeguard against situations where process() goes haywire when autopunching and last_recordable_frame < first_recordable_frame
574 if (last_recordable_frame < first_recordable_frame) {
575 last_recordable_frame = max_frames;
578 ot = coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
585 case OverlapInternal:
586 /* ---------- recrange
589 rec_nframes = nframes;
594 /* |--------| recrange
597 rec_nframes = transport_frame + nframes - first_recordable_frame;
599 rec_offset = first_recordable_frame - transport_frame;
604 /* |--------| recrange
607 rec_nframes = last_recordable_frame - transport_frame;
611 case OverlapExternal:
612 /* |--------| recrange
613 -------------- transrange
615 rec_nframes = last_recordable_frame - first_recordable_frame;
616 rec_offset = first_recordable_frame - transport_frame;
620 if (rec_nframes && !was_recording) {
621 capture_captured = 0;
622 was_recording = true;
627 if (can_record && !_last_capture_regions.empty()) {
628 _last_capture_regions.clear ();
631 if (nominally_recording || rec_nframes) {
633 uint32_t limit = _io->n_inputs ().n_audio();
635 /* one or more ports could already have been removed from _io, but our
636 channel setup hasn't yet been updated. prevent us from trying to
637 use channels that correspond to missing ports. note that the
638 process callback (from which this is called) is always atomic
639 with respect to port removal/addition.
642 for (n = 0, chan = c->begin(); chan != c->end() && n < limit; ++chan, ++n) {
644 ChannelInfo* chaninfo (*chan);
646 chaninfo->capture_buf->get_write_vector (&chaninfo->capture_vector);
648 if (rec_nframes <= chaninfo->capture_vector.len[0]) {
650 chaninfo->current_capture_buffer = chaninfo->capture_vector.buf[0];
652 /* note: grab the entire port buffer, but only copy what we were supposed to for recording, and use
656 AudioPort* const ap = _io->audio_input(n);
658 assert(rec_nframes <= ap->get_audio_buffer( nframes, offset ).capacity());
659 memcpy (chaninfo->current_capture_buffer, ap->get_audio_buffer( nframes, offset ).data(rec_nframes, offset + rec_offset), sizeof (Sample) * rec_nframes);
663 nframes_t total = chaninfo->capture_vector.len[0] + chaninfo->capture_vector.len[1];
665 if (rec_nframes > total) {
670 AudioPort* const ap = _io->audio_input(n);
673 Sample* buf = ap->get_audio_buffer( nframes, offset ).data(nframes, offset);
674 nframes_t first = chaninfo->capture_vector.len[0];
676 memcpy (chaninfo->capture_wrap_buffer, buf, sizeof (Sample) * first);
677 memcpy (chaninfo->capture_vector.buf[0], buf, sizeof (Sample) * first);
678 memcpy (chaninfo->capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
679 memcpy (chaninfo->capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
681 chaninfo->current_capture_buffer = chaninfo->capture_wrap_buffer;
688 finish_capture (rec_monitors_input, c);
695 /* data will be written to disk */
697 if (rec_nframes == nframes && rec_offset == 0) {
699 for (chan = c->begin(); chan != c->end(); ++chan) {
700 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
703 playback_distance = nframes;
708 /* we can't use the capture buffer as the playback buffer, because
709 we recorded only a part of the current process' cycle data
713 collect_playback = true;
716 adjust_capture_position = rec_nframes;
718 } else if (nominally_recording) {
720 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
722 for (chan = c->begin(); chan != c->end(); ++chan) {
723 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
726 playback_distance = nframes;
730 collect_playback = true;
733 if (collect_playback) {
735 /* we're doing playback */
737 nframes_t necessary_samples;
739 /* no varispeed playback if we're recording, because the output .... TBD */
741 if (rec_nframes == 0 && _actual_speed != 1.0f) {
742 necessary_samples = (nframes_t) floor ((nframes * fabs (_actual_speed))) + 1;
744 necessary_samples = nframes;
747 for (chan = c->begin(); chan != c->end(); ++chan) {
748 (*chan)->playback_buf->get_read_vector (&(*chan)->playback_vector);
753 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
755 ChannelInfo* chaninfo (*chan);
757 if (necessary_samples <= chaninfo->playback_vector.len[0]) {
759 chaninfo->current_playback_buffer = chaninfo->playback_vector.buf[0];
762 nframes_t total = chaninfo->playback_vector.len[0] + chaninfo->playback_vector.len[1];
764 if (necessary_samples > total) {
765 cerr << "underrun for " << _name << endl;
771 memcpy ((char *) chaninfo->playback_wrap_buffer, chaninfo->playback_vector.buf[0],
772 chaninfo->playback_vector.len[0] * sizeof (Sample));
773 memcpy (chaninfo->playback_wrap_buffer + chaninfo->playback_vector.len[0], chaninfo->playback_vector.buf[1],
774 (necessary_samples - chaninfo->playback_vector.len[0]) * sizeof (Sample));
776 chaninfo->current_playback_buffer = chaninfo->playback_wrap_buffer;
781 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
783 // the idea behind phase is that when the speed is not 1.0, we have to
784 // interpolate between samples and then we have to store where we thought we were.
785 // rather than being at sample N or N+1, we were at N+0.8792922
786 // so the "phase" element, if you want to think about this way,
787 // varies from 0 to 1, representing the "offset" between samples
788 uint64_t phase = last_phase;
792 // Linearly interpolate into the alt buffer
793 // using 40.24 fixp maths
795 // Fixedpoint is just an integer with an implied scaling factor.
796 // In 40.24 the scaling factor is 2^24 = 16777216,
797 // so a value of 10*2^24 (in integer space) is equivalent to 10.0.
799 // The advantage is that addition and modulus [like x = (x + y) % 2^40]
800 // has no rounding errors and no drift, and just requires a single integer add.
803 const int64_t fractional_part_mask = 0xFFFFFF;
804 const Sample binary_scaling_factor = 16777216.0f;
806 // phi = fixed point speed
807 if (phi != target_phi) {
808 phi_delta = ((int64_t)(target_phi - phi)) / nframes;
813 for (chan = c->begin(); chan != c->end(); ++chan) {
815 Sample fractional_part;
816 ChannelInfo* chaninfo (*chan);
821 for (nframes_t outsample = 0; outsample < nframes; ++outsample) {
823 fractional_part = (phase & fractional_part_mask) / binary_scaling_factor;
824 chaninfo->speed_buffer[outsample] =
825 chaninfo->current_playback_buffer[i] * (1.0f - fractional_part) +
826 chaninfo->current_playback_buffer[i+1] * fractional_part;
827 phase += phi + phi_delta;
830 chaninfo->current_playback_buffer = chaninfo->speed_buffer;
833 playback_distance = i; // + 1;
834 last_phase = (phase & fractional_part_mask);
837 playback_distance = nframes;
851 /* we're exiting with failure, so ::commit will not
852 be called. unlock the state lock.
855 commit_should_unlock = false;
863 AudioDiskstream::commit (nframes_t nframes)
865 bool need_butler = false;
867 if (!_io || !_io->active()) {
871 if (_actual_speed < 0.0) {
872 playback_sample -= playback_distance;
874 playback_sample += playback_distance;
877 boost::shared_ptr<ChannelList> c = channels.reader();
878 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
880 (*chan)->playback_buf->increment_read_ptr (playback_distance);
882 if (adjust_capture_position) {
883 (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
887 if (adjust_capture_position != 0) {
888 capture_captured += adjust_capture_position;
889 adjust_capture_position = 0;
893 if (_io && _io->active()) {
894 need_butler = c->front()->playback_buf->write_space() >= c->front()->playback_buf->bufsize() / 2;
899 if (_io && _io->active()) {
900 need_butler = c->front()->playback_buf->write_space() >= disk_io_chunk_frames
901 || c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
903 need_butler = c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
907 if (commit_should_unlock) {
917 AudioDiskstream::set_pending_overwrite (bool yn)
919 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
921 pending_overwrite = yn;
923 overwrite_frame = playback_sample;
924 overwrite_offset = channels.reader()->front()->playback_buf->get_read_ptr();
928 AudioDiskstream::overwrite_existing_buffers ()
930 boost::shared_ptr<ChannelList> c = channels.reader();
931 Sample* mixdown_buffer;
934 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
936 overwrite_queued = false;
938 /* assume all are the same size */
939 nframes_t size = c->front()->playback_buf->bufsize();
941 mixdown_buffer = new Sample[size];
942 gain_buffer = new float[size];
944 /* reduce size so that we can fill the buffer correctly. */
950 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
952 start = overwrite_frame;
953 nframes_t cnt = size;
955 /* to fill the buffer without resetting the playback sample, we need to
956 do it one or two chunks (normally two).
958 |----------------------------------------------------------------------|
962 |<- second chunk->||<----------------- first chunk ------------------>|
966 nframes_t to_read = size - overwrite_offset;
968 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, *chan, n, reversed)) {
969 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
970 _id, size, playback_sample) << endmsg;
978 if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer,
979 start, cnt, *chan, n, reversed)) {
980 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
981 _id, size, playback_sample) << endmsg;
990 pending_overwrite = false;
991 delete [] gain_buffer;
992 delete [] mixdown_buffer;
997 AudioDiskstream::seek (nframes_t frame, bool complete_refill)
1001 ChannelList::iterator chan;
1002 boost::shared_ptr<ChannelList> c = channels.reader();
1004 Glib::Mutex::Lock lm (state_lock);
1006 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1007 (*chan)->playback_buf->reset ();
1008 (*chan)->capture_buf->reset ();
1011 /* can't rec-enable in destructive mode if transport is before start */
1013 if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
1014 disengage_record_enable ();
1017 playback_sample = frame;
1020 if (complete_refill) {
1021 while ((ret = do_refill_with_alloc ()) > 0) ;
1023 ret = do_refill_with_alloc ();
1030 AudioDiskstream::can_internal_playback_seek (nframes_t distance)
1032 ChannelList::iterator chan;
1033 boost::shared_ptr<ChannelList> c = channels.reader();
1035 for (chan = c->begin(); chan != c->end(); ++chan) {
1036 if ((*chan)->playback_buf->read_space() < distance) {
1044 AudioDiskstream::internal_playback_seek (nframes_t distance)
1046 ChannelList::iterator chan;
1047 boost::shared_ptr<ChannelList> c = channels.reader();
1049 for (chan = c->begin(); chan != c->end(); ++chan) {
1050 (*chan)->playback_buf->increment_read_ptr (distance);
1053 first_recordable_frame += distance;
1054 playback_sample += distance;
1060 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer, nframes_t& start, nframes_t cnt,
1061 ChannelInfo* channel_info, int channel, bool reversed)
1063 nframes_t this_read = 0;
1064 bool reloop = false;
1065 nframes_t loop_end = 0;
1066 nframes_t loop_start = 0;
1067 nframes_t loop_length = 0;
1068 nframes_t offset = 0;
1071 /* XXX we don't currently play loops in reverse. not sure why */
1075 /* Make the use of a Location atomic for this read operation.
1077 Note: Locations don't get deleted, so all we care about
1078 when I say "atomic" is that we are always pointing to
1079 the same one and using a start/length values obtained
1083 if ((loc = loop_location) != 0) {
1084 loop_start = loc->start();
1085 loop_end = loc->end();
1086 loop_length = loop_end - loop_start;
1089 /* if we are looping, ensure that the first frame we read is at the correct
1090 position within the loop.
1093 if (loc && start >= loop_end) {
1094 //cerr << "start adjusted from " << start;
1095 start = loop_start + ((start - loop_start) % loop_length);
1096 //cerr << "to " << start << endl;
1099 //cerr << "start is " << start << " loopstart: " << loop_start << " loopend: " << loop_end << endl;
1108 /* take any loop into account. we can't read past the end of the loop. */
1110 if (loc && (loop_end - start < cnt)) {
1111 this_read = loop_end - start;
1112 //cerr << "reloop true: thisread: " << this_read << " cnt: " << cnt << endl;
1119 if (this_read == 0) {
1123 this_read = min(cnt,this_read);
1125 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
1126 error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), _id, this_read,
1131 _read_data_count = _playlist->read_data_count();
1135 swap_by_ptr (buf, buf + this_read - 1);
1139 /* if we read to the end of the loop, go back to the beginning */
1149 offset += this_read;
1156 AudioDiskstream::do_refill_with_alloc ()
1158 Sample* mix_buf = new Sample[disk_io_chunk_frames];
1159 float* gain_buf = new float[disk_io_chunk_frames];
1161 int ret = _do_refill(mix_buf, gain_buf);
1170 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer)
1174 RingBufferNPT<Sample>::rw_vector vector;
1175 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1176 nframes_t total_space;
1177 nframes_t zero_fill;
1179 ChannelList::iterator i;
1180 boost::shared_ptr<ChannelList> c = channels.reader();
1187 assert(mixdown_buffer);
1188 assert(gain_buffer);
1195 c->front()->playback_buf->get_write_vector (&vector);
1197 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1201 /* if there are 2+ chunks of disk i/o possible for
1202 this track, let the caller know so that it can arrange
1203 for us to be called again, ASAP.
1206 if (total_space >= (_slaved?3:2) * disk_io_chunk_frames) {
1210 /* if we're running close to normal speed and there isn't enough
1211 space to do disk_io_chunk_frames of I/O, then don't bother.
1213 at higher speeds, just do it because the sync between butler
1214 and audio thread may not be good enough.
1217 if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1221 /* when slaved, don't try to get too close to the read pointer. this
1222 leaves space for the buffer reversal to have something useful to
1226 if (_slaved && total_space < (c->front()->playback_buf->bufsize() / 2)) {
1230 /* never do more than disk_io_chunk_frames worth of disk input per call (limit doesn't apply for memset) */
1232 total_space = min (disk_io_chunk_frames, total_space);
1236 if (file_frame == 0) {
1238 /* at start: nothing to do but fill with silence */
1240 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1242 ChannelInfo* chan (*i);
1243 chan->playback_buf->get_write_vector (&vector);
1244 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1245 if (vector.len[1]) {
1246 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1248 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1253 if (file_frame < total_space) {
1255 /* too close to the start: read what we can,
1256 and then zero fill the rest
1259 zero_fill = total_space - file_frame;
1260 total_space = file_frame;
1270 if (file_frame == max_frames) {
1272 /* at end: nothing to do but fill with silence */
1274 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1276 ChannelInfo* chan (*i);
1277 chan->playback_buf->get_write_vector (&vector);
1278 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1279 if (vector.len[1]) {
1280 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1282 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1287 if (file_frame > max_frames - total_space) {
1289 /* to close to the end: read what we can, and zero fill the rest */
1291 zero_fill = total_space - (max_frames - file_frame);
1292 total_space = max_frames - file_frame;
1299 nframes_t file_frame_tmp = 0;
1301 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1303 ChannelInfo* chan (*i);
1306 nframes_t len1, len2;
1308 chan->playback_buf->get_write_vector (&vector);
1310 if (vector.len[0] > disk_io_chunk_frames) {
1312 /* we're not going to fill the first chunk, so certainly do not bother with the
1313 other part. it won't be connected with the part we do fill, as in:
1315 .... => writable space
1316 ++++ => readable space
1317 ^^^^ => 1 x disk_io_chunk_frames that would be filled
1319 |......|+++++++++++++|...............................|
1324 So, just pretend that the buf1 part isn't there.
1334 file_frame_tmp = file_frame;
1336 buf1 = vector.buf[0];
1337 len1 = vector.len[0];
1338 buf2 = vector.buf[1];
1339 len2 = vector.len[1];
1341 to_read = min (ts, len1);
1342 to_read = min (to_read, disk_io_chunk_frames);
1346 if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1351 chan->playback_buf->increment_write_ptr (to_read);
1355 to_read = min (ts, len2);
1359 /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1360 so read some or all of vector.len[1] as well.
1363 if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1368 chan->playback_buf->increment_write_ptr (to_read);
1377 file_frame = file_frame_tmp;
1384 /** Flush pending data to disk.
1386 * Important note: this function will write *AT MOST* disk_io_chunk_frames
1387 * of data to disk. it will never write more than that. If it writes that
1388 * much and there is more than that waiting to be written, it will return 1,
1389 * otherwise 0 on success or -1 on failure.
1391 * If there is less than disk_io_chunk_frames to be written, no data will be
1392 * written at all unless @a force_flush is true.
1395 AudioDiskstream::do_flush (Session::RunContext context, bool force_flush)
1399 RingBufferNPT<Sample>::rw_vector vector;
1400 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1403 _write_data_count = 0;
1405 transvec.buf[0] = 0;
1406 transvec.buf[1] = 0;
1410 boost::shared_ptr<ChannelList> c = channels.reader();
1411 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1413 (*chan)->capture_buf->get_read_vector (&vector);
1415 total = vector.len[0] + vector.len[1];
1417 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1421 /* if there are 2+ chunks of disk i/o possible for
1422 this track, let the caller know so that it can arrange
1423 for us to be called again, ASAP.
1425 if we are forcing a flush, then if there is* any* extra
1426 work, let the caller know.
1428 if we are no longer recording and there is any extra work,
1429 let the caller know too.
1432 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1436 to_write = min (disk_io_chunk_frames, (nframes_t) vector.len[0]);
1438 // check the transition buffer when recording destructive
1439 // important that we get this after the capture buf
1441 if (destructive()) {
1442 (*chan)->capture_transition_buf->get_read_vector(&transvec);
1443 size_t transcount = transvec.len[0] + transvec.len[1];
1444 bool have_start = false;
1447 for (ti=0; ti < transcount; ++ti) {
1448 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1450 if (captrans.type == CaptureStart) {
1451 // by definition, the first data we got above represents the given capture pos
1453 (*chan)->write_source->mark_capture_start (captrans.capture_val);
1454 (*chan)->curr_capture_cnt = 0;
1458 else if (captrans.type == CaptureEnd) {
1460 // capture end, the capture_val represents total frames in capture
1462 if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1464 // shorten to make the write a perfect fit
1465 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
1467 if (nto_write < to_write) {
1468 ret = 1; // should we?
1470 to_write = nto_write;
1472 (*chan)->write_source->mark_capture_end ();
1474 // increment past this transition, but go no further
1479 // actually ends just beyond this chunk, so force more work
1487 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1491 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1492 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1496 (*chan)->capture_buf->increment_read_ptr (to_write);
1497 (*chan)->curr_capture_cnt += to_write;
1499 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1501 /* we wrote all of vector.len[0] but it wasn't an entire
1502 disk_io_chunk_frames of data, so arrange for some part
1503 of vector.len[1] to be flushed to disk as well.
1506 to_write = min ((nframes_t)(disk_io_chunk_frames - to_write), (nframes_t) vector.len[1]);
1508 if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1509 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1513 _write_data_count += (*chan)->write_source->write_data_count();
1515 (*chan)->capture_buf->increment_read_ptr (to_write);
1516 (*chan)->curr_capture_cnt += to_write;
1525 AudioDiskstream::transport_stopped (struct tm& when, time_t twhen, bool abort_capture)
1527 uint32_t buffer_position;
1528 bool more_work = true;
1530 boost::shared_ptr<AudioRegion> region;
1531 nframes_t total_capture;
1533 SourceList::iterator src;
1534 ChannelList::iterator chan;
1535 vector<CaptureInfo*>::iterator ci;
1536 boost::shared_ptr<ChannelList> c = channels.reader();
1538 bool mark_write_completed = false;
1540 finish_capture (true, c);
1542 /* butler is already stopped, but there may be work to do
1543 to flush remaining data to disk.
1546 while (more_work && !err) {
1547 switch (do_flush (Session::TransportContext, true)) {
1554 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1559 /* XXX is there anything we can do if err != 0 ? */
1560 Glib::Mutex::Lock lm (capture_info_lock);
1562 if (capture_info.empty()) {
1566 if (abort_capture) {
1568 if (destructive()) {
1572 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1574 if ((*chan)->write_source) {
1576 (*chan)->write_source->mark_for_remove ();
1577 (*chan)->write_source->drop_references ();
1578 (*chan)->write_source.reset ();
1581 /* new source set up in "out" below */
1587 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1588 total_capture += (*ci)->frames;
1591 /* figure out the name for this take */
1593 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1595 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1599 s->update_header (capture_info.front()->start, when, twhen);
1600 s->set_captured_for (_name);
1601 s->mark_immutable ();
1602 if (Config->get_auto_analyse_audio()) {
1603 Analyser::queue_source_for_analysis (s, true);
1608 /* destructive tracks have a single, never changing region */
1610 if (destructive()) {
1612 /* send a signal that any UI can pick up to do the right thing. there is
1613 a small problem here in that a UI may need the peak data to be ready
1614 for the data that was recorded and this isn't interlocked with that
1615 process. this problem is deferred to the UI.
1618 _playlist->Modified();
1622 string whole_file_region_name;
1623 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1625 /* Register a new region with the Session that
1626 describes the entire source. Do this first
1627 so that any sub-regions will obviously be
1628 children of this one (later!)
1632 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, c->front()->write_source->last_capture_start_frame(), total_capture,
1633 whole_file_region_name,
1634 0, AudioRegion::Flag (AudioRegion::DefaultFlags|AudioRegion::Automatic|AudioRegion::WholeFile)));
1636 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1637 region->special_set_position (capture_info.front()->start);
1641 catch (failed_constructor& err) {
1642 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1646 _last_capture_regions.push_back (region);
1648 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1650 XMLNode &before = _playlist->get_state();
1651 _playlist->freeze ();
1653 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1657 _session.region_name (region_name, whole_file_region_name, false);
1659 // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->frames << " add region " << region_name << endl;
1662 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, buffer_position, (*ci)->frames, region_name));
1663 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1666 catch (failed_constructor& err) {
1667 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1668 continue; /* XXX is this OK? */
1671 region->GoingAway.connect (bind (mem_fun (*this, &Diskstream::remove_region_from_last_capture), boost::weak_ptr<Region>(region)));
1673 _last_capture_regions.push_back (region);
1675 i_am_the_modifier++;
1676 _playlist->add_region (region, (*ci)->start);
1677 i_am_the_modifier--;
1679 buffer_position += (*ci)->frames;
1683 XMLNode &after = _playlist->get_state();
1684 _session.add_command (new MementoCommand<Playlist>(*_playlist, &before, &after));
1687 mark_write_completed = true;
1690 reset_write_sources (mark_write_completed);
1694 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1698 capture_info.clear ();
1699 capture_start_frame = 0;
1703 AudioDiskstream::transport_looped (nframes_t transport_frame)
1705 if (was_recording) {
1706 // all we need to do is finish this capture, with modified capture length
1707 boost::shared_ptr<ChannelList> c = channels.reader();
1709 // adjust the capture length knowing that the data will be recorded to disk
1710 // only necessary after the first loop where we're recording
1711 if (capture_info.size() == 0) {
1712 capture_captured += _capture_offset;
1714 if (_alignment_style == ExistingMaterial) {
1715 capture_captured += _session.worst_output_latency();
1717 capture_captured += _roll_delay;
1721 finish_capture (true, c);
1723 // the next region will start recording via the normal mechanism
1724 // we'll set the start position to the current transport pos
1725 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1726 capture_start_frame = transport_frame;
1727 first_recordable_frame = transport_frame; // mild lie
1728 last_recordable_frame = max_frames;
1729 was_recording = true;
1731 if (recordable() && destructive()) {
1732 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1734 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1735 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1737 if (transvec.len[0] > 0) {
1738 transvec.buf[0]->type = CaptureStart;
1739 transvec.buf[0]->capture_val = capture_start_frame;
1740 (*chan)->capture_transition_buf->increment_write_ptr(1);
1744 fatal << X_("programming error: capture_transition_buf is full on rec loop! inconceivable!")
1754 AudioDiskstream::finish_capture (bool rec_monitors_input, boost::shared_ptr<ChannelList> c)
1756 was_recording = false;
1758 if (capture_captured == 0) {
1762 if (recordable() && destructive()) {
1763 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1765 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1766 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1768 if (transvec.len[0] > 0) {
1769 transvec.buf[0]->type = CaptureEnd;
1770 transvec.buf[0]->capture_val = capture_captured;
1771 (*chan)->capture_transition_buf->increment_write_ptr(1);
1775 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1781 CaptureInfo* ci = new CaptureInfo;
1783 ci->start = capture_start_frame;
1784 ci->frames = capture_captured;
1786 /* XXX theoretical race condition here. Need atomic exchange ?
1787 However, the circumstances when this is called right
1788 now (either on record-disable or transport_stopped)
1789 mean that no actual race exists. I think ...
1790 We now have a capture_info_lock, but it is only to be used
1791 to synchronize in the transport_stop and the capture info
1792 accessors, so that invalidation will not occur (both non-realtime).
1795 // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1797 capture_info.push_back (ci);
1798 capture_captured = 0;
1800 /* now we've finished a capture, reset first_recordable_frame for next time */
1801 first_recordable_frame = max_frames;
1805 AudioDiskstream::set_record_enabled (bool yn)
1807 if (!recordable() || !_session.record_enabling_legal() || _io->n_inputs().n_audio() == 0) {
1811 /* can't rec-enable in destructive mode if transport is before start */
1813 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1817 if (yn && channels.reader()->front()->source == 0) {
1819 /* pick up connections not initiated *from* the IO object
1820 we're associated with.
1823 get_input_sources ();
1826 /* yes, i know that this not proof against race conditions, but its
1827 good enough. i think.
1830 if (record_enabled() != yn) {
1832 engage_record_enable ();
1834 disengage_record_enable ();
1840 AudioDiskstream::engage_record_enable ()
1842 bool rolling = _session.transport_speed() != 0.0f;
1843 boost::shared_ptr<ChannelList> c = channels.reader();
1845 g_atomic_int_set (&_record_enabled, 1);
1846 capturing_sources.clear ();
1848 if (Config->get_monitoring_model() == HardwareMonitoring) {
1850 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1851 if ((*chan)->source) {
1852 (*chan)->source->ensure_monitor_input (!(Config->get_auto_input() && rolling));
1854 capturing_sources.push_back ((*chan)->write_source);
1855 (*chan)->write_source->mark_streaming_write_started ();
1859 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1860 capturing_sources.push_back ((*chan)->write_source);
1861 (*chan)->write_source->mark_streaming_write_started ();
1865 RecordEnableChanged (); /* EMIT SIGNAL */
1869 AudioDiskstream::disengage_record_enable ()
1871 g_atomic_int_set (&_record_enabled, 0);
1872 boost::shared_ptr<ChannelList> c = channels.reader();
1873 if (Config->get_monitoring_model() == HardwareMonitoring) {
1874 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1875 if ((*chan)->source) {
1876 (*chan)->source->ensure_monitor_input (false);
1880 capturing_sources.clear ();
1881 RecordEnableChanged (); /* EMIT SIGNAL */
1885 AudioDiskstream::get_state ()
1887 XMLNode* node = new XMLNode ("AudioDiskstream");
1889 LocaleGuard lg (X_("POSIX"));
1890 boost::shared_ptr<ChannelList> c = channels.reader();
1892 node->add_property ("flags", enum_2_string (_flags));
1894 snprintf (buf, sizeof(buf), "%zd", c->size());
1895 node->add_property ("channels", buf);
1897 node->add_property ("playlist", _playlist->name());
1899 snprintf (buf, sizeof(buf), "%.12g", _visible_speed);
1900 node->add_property ("speed", buf);
1902 node->add_property("name", _name);
1903 id().print (buf, sizeof (buf));
1904 node->add_property("id", buf);
1906 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1908 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1909 XMLNode* cs_grandchild;
1911 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1912 cs_grandchild = new XMLNode (X_("file"));
1913 cs_grandchild->add_property (X_("path"), (*i)->path());
1914 cs_child->add_child_nocopy (*cs_grandchild);
1917 /* store the location where capture will start */
1921 if (Config->get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1922 snprintf (buf, sizeof (buf), "%" PRIu32, pi->start());
1924 snprintf (buf, sizeof (buf), "%" PRIu32, _session.transport_frame());
1927 cs_child->add_property (X_("at"), buf);
1928 node->add_child_nocopy (*cs_child);
1932 node->add_child_copy (*_extra_xml);
1939 AudioDiskstream::set_state (const XMLNode& node)
1941 const XMLProperty* prop;
1942 XMLNodeList nlist = node.children();
1943 XMLNodeIterator niter;
1944 uint32_t nchans = 1;
1945 XMLNode* capture_pending_node = 0;
1946 LocaleGuard lg (X_("POSIX"));
1948 in_set_state = true;
1950 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1951 if ((*niter)->name() == IO::state_node_name) {
1952 deprecated_io_node = new XMLNode (**niter);
1955 if ((*niter)->name() == X_("CapturingSources")) {
1956 capture_pending_node = *niter;
1960 /* prevent write sources from being created */
1962 in_set_state = true;
1964 if ((prop = node.property ("name")) != 0) {
1965 _name = prop->value();
1968 if (deprecated_io_node) {
1969 if ((prop = deprecated_io_node->property ("id")) != 0) {
1970 _id = prop->value ();
1973 if ((prop = node.property ("id")) != 0) {
1974 _id = prop->value ();
1978 if ((prop = node.property ("flags")) != 0) {
1979 _flags = Flag (string_2_enum (prop->value(), _flags));
1982 if ((prop = node.property ("channels")) != 0) {
1983 nchans = atoi (prop->value().c_str());
1986 // create necessary extra channels
1987 // we are always constructed with one and we always need one
1989 _n_channels.set(DataType::AUDIO, channels.reader()->size());
1991 if (nchans > _n_channels.n_audio()) {
1993 add_channel (nchans - _n_channels.n_audio());
1994 IO::PortCountChanged(_n_channels);
1996 } else if (nchans < _n_channels.n_audio()) {
1998 remove_channel (_n_channels.n_audio() - nchans);
2001 if ((prop = node.property ("playlist")) == 0) {
2006 bool had_playlist = (_playlist != 0);
2008 if (find_and_use_playlist (prop->value())) {
2012 if (!had_playlist) {
2013 _playlist->set_orig_diskstream_id (_id);
2016 if (!destructive() && capture_pending_node) {
2017 /* destructive streams have one and only one source per channel,
2018 and so they never end up in pending capture in any useful
2021 use_pending_capture_data (*capture_pending_node);
2026 if ((prop = node.property ("speed")) != 0) {
2027 double sp = atof (prop->value().c_str());
2029 if (realtime_set_speed (sp, false)) {
2030 non_realtime_set_speed ();
2034 in_set_state = false;
2036 /* make sure this is clear before we do anything else */
2038 capturing_sources.clear ();
2040 /* write sources are handled when we handle the input set
2041 up of the IO that owns this DS (::non_realtime_input_change())
2048 AudioDiskstream::use_new_write_source (uint32_t n)
2050 boost::shared_ptr<ChannelList> c = channels.reader();
2052 if (!recordable()) {
2056 if (n >= c->size()) {
2057 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
2061 ChannelInfo* chan = (*c)[n];
2063 if (chan->write_source) {
2064 chan->write_source->done_with_peakfile_writes ();
2065 chan->write_source->set_allow_remove_if_empty (true);
2066 chan->write_source.reset ();
2070 if ((chan->write_source = _session.create_audio_source_for_session (*this, n, destructive())) == 0) {
2071 throw failed_constructor();
2075 catch (failed_constructor &err) {
2076 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
2077 chan->write_source.reset ();
2081 /* do not remove destructive files even if they are empty */
2083 chan->write_source->set_allow_remove_if_empty (!destructive());
2089 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool force)
2091 ChannelList::iterator chan;
2092 boost::shared_ptr<ChannelList> c = channels.reader();
2095 if (!recordable()) {
2099 capturing_sources.clear ();
2101 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
2102 if (!destructive()) {
2104 if ((*chan)->write_source && mark_write_complete) {
2105 (*chan)->write_source->mark_streaming_write_completed ();
2107 use_new_write_source (n);
2109 if (record_enabled()) {
2110 capturing_sources.push_back ((*chan)->write_source);
2114 if ((*chan)->write_source == 0) {
2115 use_new_write_source (n);
2120 if (destructive()) {
2122 /* we now have all our write sources set up, so create the
2123 playlist's single region.
2126 if (_playlist->empty()) {
2127 setup_destructive_playlist ();
2133 AudioDiskstream::rename_write_sources ()
2135 ChannelList::iterator chan;
2136 boost::shared_ptr<ChannelList> c = channels.reader();
2139 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
2140 if ((*chan)->write_source != 0) {
2141 (*chan)->write_source->set_source_name (_name, destructive());
2142 /* XXX what to do if one of them fails ? */
2150 AudioDiskstream::set_block_size (nframes_t nframes)
2152 if (_session.get_block_size() > speed_buffer_size) {
2153 speed_buffer_size = _session.get_block_size();
2154 boost::shared_ptr<ChannelList> c = channels.reader();
2156 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2157 if ((*chan)->speed_buffer) delete [] (*chan)->speed_buffer;
2158 (*chan)->speed_buffer = new Sample[speed_buffer_size];
2161 allocate_temporary_buffers ();
2165 AudioDiskstream::allocate_temporary_buffers ()
2167 /* make sure the wrap buffer is at least large enough to deal
2168 with the speeds up to 1.2, to allow for micro-variation
2169 when slaving to MTC, SMPTE etc.
2172 double sp = max (fabsf (_actual_speed), 1.2f);
2173 nframes_t required_wrap_size = (nframes_t) floor (_session.get_block_size() * sp) + 1;
2175 if (required_wrap_size > wrap_buffer_size) {
2177 boost::shared_ptr<ChannelList> c = channels.reader();
2179 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2180 if ((*chan)->playback_wrap_buffer) delete [] (*chan)->playback_wrap_buffer;
2181 (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
2182 if ((*chan)->capture_wrap_buffer) delete [] (*chan)->capture_wrap_buffer;
2183 (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
2186 wrap_buffer_size = required_wrap_size;
2191 AudioDiskstream::monitor_input (bool yn)
2193 boost::shared_ptr<ChannelList> c = channels.reader();
2195 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2197 if ((*chan)->source) {
2198 (*chan)->source->ensure_monitor_input (yn);
2204 AudioDiskstream::set_align_style_from_io ()
2206 bool have_physical = false;
2212 get_input_sources ();
2214 boost::shared_ptr<ChannelList> c = channels.reader();
2216 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2217 if ((*chan)->source && (*chan)->source->flags() & JackPortIsPhysical) {
2218 have_physical = true;
2223 if (have_physical) {
2224 set_align_style (ExistingMaterial);
2226 set_align_style (CaptureTime);
2231 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2233 while (how_many--) {
2234 c->push_back (new ChannelInfo(_session.audio_diskstream_buffer_size(), speed_buffer_size, wrap_buffer_size));
2237 _n_channels.set(DataType::AUDIO, c->size());
2243 AudioDiskstream::add_channel (uint32_t how_many)
2245 RCUWriter<ChannelList> writer (channels);
2246 boost::shared_ptr<ChannelList> c = writer.get_copy();
2248 return add_channel_to (c, how_many);
2252 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2254 while (how_many-- && !c->empty()) {
2259 _n_channels.set(DataType::AUDIO, c->size());
2265 AudioDiskstream::remove_channel (uint32_t how_many)
2267 RCUWriter<ChannelList> writer (channels);
2268 boost::shared_ptr<ChannelList> c = writer.get_copy();
2270 return remove_channel_from (c, how_many);
2274 AudioDiskstream::playback_buffer_load () const
2276 boost::shared_ptr<ChannelList> c = channels.reader();
2278 return (float) ((double) c->front()->playback_buf->read_space()/
2279 (double) c->front()->playback_buf->bufsize());
2283 AudioDiskstream::capture_buffer_load () const
2285 boost::shared_ptr<ChannelList> c = channels.reader();
2287 return (float) ((double) c->front()->capture_buf->write_space()/
2288 (double) c->front()->capture_buf->bufsize());
2292 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2294 const XMLProperty* prop;
2295 XMLNodeList nlist = node.children();
2296 XMLNodeIterator niter;
2297 boost::shared_ptr<AudioFileSource> fs;
2298 boost::shared_ptr<AudioFileSource> first_fs;
2299 SourceList pending_sources;
2302 if ((prop = node.property (X_("at"))) == 0) {
2306 if (sscanf (prop->value().c_str(), "%" PRIu32, &position) != 1) {
2310 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2311 if ((*niter)->name() == X_("file")) {
2313 if ((prop = (*niter)->property (X_("path"))) == 0) {
2317 // This protects sessions from errant CapturingSources in stored sessions
2319 if (stat (prop->value().c_str(), &sbuf)) {
2324 fs = boost::dynamic_pointer_cast<AudioFileSource> (
2325 SourceFactory::createWritable (DataType::AUDIO, _session, prop->value(), false, _session.frame_rate()));
2328 catch (failed_constructor& err) {
2329 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2330 _name, prop->value())
2335 pending_sources.push_back (fs);
2337 if (first_fs == 0) {
2341 fs->set_captured_for (_name);
2345 if (pending_sources.size() == 0) {
2346 /* nothing can be done */
2350 if (pending_sources.size() != _n_channels.n_audio()) {
2351 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2356 boost::shared_ptr<AudioRegion> region;
2359 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, 0, first_fs->length(),
2360 region_name_from_path (first_fs->name(), true),
2361 0, AudioRegion::Flag (AudioRegion::DefaultFlags|AudioRegion::Automatic|AudioRegion::WholeFile)));
2362 region->special_set_position (0);
2365 catch (failed_constructor& err) {
2366 error << string_compose (_("%1: cannot create whole-file region from pending capture sources"),
2374 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, 0, first_fs->length(), region_name_from_path (first_fs->name(), true)));
2377 catch (failed_constructor& err) {
2378 error << string_compose (_("%1: cannot create region from pending capture sources"),
2385 _playlist->add_region (region, position);
2391 AudioDiskstream::set_destructive (bool yn)
2393 bool bounce_ignored;
2395 if (yn != destructive()) {
2398 /* requestor should already have checked this and
2399 bounced if necessary and desired
2401 if (!can_become_destructive (bounce_ignored)) {
2404 _flags = Flag (_flags | Destructive);
2405 use_destructive_playlist ();
2407 _flags = Flag (_flags & ~Destructive);
2408 reset_write_sources (true, true);
2416 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2419 requires_bounce = false;
2423 /* is there only one region ? */
2425 if (_playlist->n_regions() != 1) {
2426 requires_bounce = true;
2430 boost::shared_ptr<Region> first = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
2433 /* do the source(s) for the region cover the session start position ? */
2435 if (first->position() != _session.current_start_frame()) {
2436 if (first->start() > _session.current_start_frame()) {
2437 requires_bounce = true;
2442 /* is the source used by only 1 playlist ? */
2444 boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2448 if (afirst->source()->used() > 1) {
2449 requires_bounce = true;
2453 requires_bounce = false;
2457 AudioDiskstream::ChannelInfo::ChannelInfo (nframes_t bufsize, nframes_t speed_size, nframes_t wrap_size)
2461 current_capture_buffer = 0;
2462 current_playback_buffer = 0;
2463 curr_capture_cnt = 0;
2465 speed_buffer = new Sample[speed_size];
2466 playback_wrap_buffer = new Sample[wrap_size];
2467 capture_wrap_buffer = new Sample[wrap_size];
2469 playback_buf = new RingBufferNPT<Sample> (bufsize);
2470 capture_buf = new RingBufferNPT<Sample> (bufsize);
2471 capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2473 /* touch the ringbuffer buffers, which will cause
2474 them to be mapped into locked physical RAM if
2475 we're running with mlockall(). this doesn't do
2479 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2480 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2481 memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2484 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2487 write_source.reset ();
2490 delete [] speed_buffer;
2493 delete [] playback_wrap_buffer;
2494 playback_wrap_buffer = 0;
2496 delete [] capture_wrap_buffer;
2497 capture_wrap_buffer = 0;
2499 delete playback_buf;
2505 delete capture_transition_buf;
2506 capture_transition_buf = 0;