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>
55 #include <ardour/audio_buffer.h>
56 #include <ardour/session.h>
57 #include <ardour/io.h>
63 using namespace ARDOUR;
66 size_t AudioDiskstream::_working_buffers_size = 0;
67 Sample* AudioDiskstream::_mixdown_buffer = 0;
68 gain_t* AudioDiskstream::_gain_buffer = 0;
70 AudioDiskstream::AudioDiskstream (Session &sess, const string &name, Diskstream::Flag flag)
71 : Diskstream(sess, name, flag)
72 , deprecated_io_node(NULL)
73 , channels (new ChannelList)
75 /* prevent any write sources from being created */
85 AudioDiskstream::AudioDiskstream (Session& sess, const XMLNode& node)
86 : Diskstream(sess, node)
87 , deprecated_io_node(NULL)
88 , channels (new ChannelList)
93 if (set_state (node)) {
95 throw failed_constructor();
101 use_destructive_playlist ();
106 AudioDiskstream::init (Diskstream::Flag f)
110 /* there are no channels at this point, so these
111 two calls just get speed_buffer_size and wrap_buffer
112 size setup without duplicating their code.
115 set_block_size (_session.get_block_size());
116 allocate_temporary_buffers ();
119 assert(_n_channels == ChanCount(DataType::AUDIO, 1));
122 AudioDiskstream::~AudioDiskstream ()
127 RCUWriter<ChannelList> writer (channels);
128 boost::shared_ptr<ChannelList> c = writer.get_copy();
130 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
141 AudioDiskstream::allocate_working_buffers()
143 assert(disk_io_frames() > 0);
145 _working_buffers_size = disk_io_frames();
146 _mixdown_buffer = new Sample[_working_buffers_size];
147 _gain_buffer = new gain_t[_working_buffers_size];
151 AudioDiskstream::free_working_buffers()
153 delete [] _mixdown_buffer;
154 delete [] _gain_buffer;
155 _working_buffers_size = 0;
161 AudioDiskstream::non_realtime_input_change ()
164 Glib::Mutex::Lock lm (state_lock);
166 if (input_change_pending == NoChange) {
171 RCUWriter<ChannelList> writer (channels);
172 boost::shared_ptr<ChannelList> c = writer.get_copy();
174 _n_channels.set(DataType::AUDIO, c->size());
176 if (_io->n_inputs().n_audio() > _n_channels.n_audio()) {
177 add_channel_to (c, _io->n_inputs().n_audio() - _n_channels.n_audio());
178 } else if (_io->n_inputs().n_audio() < _n_channels.n_audio()) {
179 remove_channel_from (c, _n_channels.n_audio() - _io->n_inputs().n_audio());
183 get_input_sources ();
184 set_capture_offset ();
186 if (first_input_change) {
187 set_align_style (_persistent_alignment_style);
188 first_input_change = false;
190 set_align_style_from_io ();
193 input_change_pending = NoChange;
195 /* implicit unlock */
198 /* reset capture files */
200 reset_write_sources (false);
202 /* now refill channel buffers */
204 if (speed() != 1.0f || speed() != -1.0f) {
205 seek ((nframes_t) (_session.transport_frame() * (double) speed()));
207 seek (_session.transport_frame());
212 AudioDiskstream::non_realtime_locate (nframes_t location)
214 /* now refill channel buffers */
216 if (speed() != 1.0f || speed() != -1.0f) {
217 seek ((nframes_t) (location * (double) speed()));
224 AudioDiskstream::get_input_sources ()
226 boost::shared_ptr<ChannelList> c = channels.reader();
229 ChannelList::iterator chan;
230 uint32_t ni = _io->n_inputs().n_audio();
231 vector<string> connections;
233 for (n = 0, chan = c->begin(); chan != c->end() && n < ni; ++chan, ++n) {
235 connections.clear ();
237 if (_io->input(n)->get_connections (connections) == 0) {
239 if ((*chan)->source) {
240 // _source->disable_metering ();
246 (*chan)->source = dynamic_cast<AudioPort*>(_session.engine().get_port_by_name (connections[0]) );
252 AudioDiskstream::find_and_use_playlist (const string& name)
254 boost::shared_ptr<AudioPlaylist> playlist;
256 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (_session.playlist_by_name (name))) == 0) {
257 playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, name));
261 error << string_compose(_("AudioDiskstream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
265 return use_playlist (playlist);
269 AudioDiskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
271 assert(boost::dynamic_pointer_cast<AudioPlaylist>(playlist));
273 Diskstream::use_playlist(playlist);
279 AudioDiskstream::use_new_playlist ()
282 boost::shared_ptr<AudioPlaylist> playlist;
284 if (!in_set_state && destructive()) {
289 newname = Playlist::bump_name (_playlist->name(), _session);
291 newname = Playlist::bump_name (_name, _session);
294 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, newname, hidden()))) != 0) {
296 playlist->set_orig_diskstream_id (id());
297 return use_playlist (playlist);
305 AudioDiskstream::use_copy_playlist ()
307 assert(audio_playlist());
313 if (_playlist == 0) {
314 error << string_compose(_("AudioDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
319 boost::shared_ptr<AudioPlaylist> playlist;
321 newname = Playlist::bump_name (_playlist->name(), _session);
323 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist>(PlaylistFactory::create (audio_playlist(), newname))) != 0) {
324 playlist->set_orig_diskstream_id (id());
325 return use_playlist (playlist);
332 AudioDiskstream::setup_destructive_playlist ()
335 boost::shared_ptr<ChannelList> c = channels.reader();
337 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
338 srcs.push_back ((*chan)->write_source);
341 /* a single full-sized region */
343 boost::shared_ptr<Region> region (RegionFactory::create (srcs, 0, max_frames - srcs.front()->natural_position(), _name));
344 _playlist->add_region (region, srcs.front()->natural_position());
348 AudioDiskstream::use_destructive_playlist ()
350 /* this is called from the XML-based constructor or ::set_destructive. when called,
351 we already have a playlist and a region, but we need to
352 set up our sources for write. we use the sources associated
353 with the (presumed single, full-extent) region.
356 boost::shared_ptr<Region> rp = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
359 reset_write_sources (false, true);
363 boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
366 throw failed_constructor();
369 /* be sure to stretch the region out to the maximum length */
371 region->set_length (max_frames - region->position(), this);
374 ChannelList::iterator chan;
375 boost::shared_ptr<ChannelList> c = channels.reader();
377 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
378 (*chan)->write_source = boost::dynamic_pointer_cast<AudioFileSource>(region->source (n));
379 assert((*chan)->write_source);
380 (*chan)->write_source->set_allow_remove_if_empty (false);
382 /* this might be false if we switched modes, so force it */
384 (*chan)->write_source->set_destructive (true);
387 /* the source list will never be reset for a destructive track */
391 AudioDiskstream::check_record_status (nframes_t transport_frame, nframes_t nframes, bool can_record)
393 int possibly_recording;
396 const int transport_rolling = 0x4;
397 const int track_rec_enabled = 0x2;
398 const int global_rec_enabled = 0x1;
400 /* merge together the 3 factors that affect record status, and compute
404 rolling = _session.transport_speed() != 0.0f;
405 possibly_recording = (rolling << 2) | (record_enabled() << 1) | can_record;
406 change = possibly_recording ^ last_possibly_recording;
408 if (possibly_recording == last_possibly_recording) {
414 /* if per-track or global rec-enable turned on while the other was already on, we've started recording */
416 if (((change & track_rec_enabled) && record_enabled() && (!(change & global_rec_enabled) && can_record)) ||
417 ((change & global_rec_enabled) && can_record && (!(change & track_rec_enabled) && record_enabled()))) {
419 /* starting to record: compute first+last frames */
421 first_recordable_frame = transport_frame + _capture_offset;
422 last_recordable_frame = max_frames;
423 capture_start_frame = transport_frame;
425 if (!(last_possibly_recording & transport_rolling) && (possibly_recording & transport_rolling)) {
427 /* was stopped, now rolling (and recording) */
429 if (_alignment_style == ExistingMaterial) {
430 first_recordable_frame += _session.worst_output_latency();
432 first_recordable_frame += _roll_delay;
437 /* was rolling, but record state changed */
439 if (_alignment_style == ExistingMaterial) {
441 if (!Config->get_punch_in()) {
443 /* manual punch in happens at the correct transport frame
444 because the user hit a button. but to get alignment correct
445 we have to back up the position of the new region to the
446 appropriate spot given the roll delay.
449 capture_start_frame -= _roll_delay;
451 /* XXX paul notes (august 2005): i don't know why
455 first_recordable_frame += _capture_offset;
459 /* autopunch toggles recording at the precise
460 transport frame, and then the DS waits
461 to start recording for a time that depends
462 on the output latency.
465 first_recordable_frame += _session.worst_output_latency();
470 if (Config->get_punch_in()) {
471 first_recordable_frame += _roll_delay;
473 capture_start_frame -= _roll_delay;
479 if (recordable() && destructive()) {
480 boost::shared_ptr<ChannelList> c = channels.reader();
481 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
483 RingBufferNPT<CaptureTransition>::rw_vector transvec;
484 (*chan)->capture_transition_buf->get_write_vector(&transvec);
486 if (transvec.len[0] > 0) {
487 transvec.buf[0]->type = CaptureStart;
488 transvec.buf[0]->capture_val = capture_start_frame;
489 (*chan)->capture_transition_buf->increment_write_ptr(1);
493 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
499 } else if (!record_enabled() || !can_record) {
503 last_recordable_frame = transport_frame + _capture_offset;
505 if (_alignment_style == ExistingMaterial) {
506 last_recordable_frame += _session.worst_output_latency();
508 last_recordable_frame += _roll_delay;
512 last_possibly_recording = possibly_recording;
516 AudioDiskstream::process (nframes_t transport_frame, nframes_t nframes, nframes_t offset, bool can_record, bool rec_monitors_input)
519 boost::shared_ptr<ChannelList> c = channels.reader();
520 ChannelList::iterator chan;
522 nframes_t rec_offset = 0;
523 nframes_t rec_nframes = 0;
524 bool nominally_recording;
525 bool re = record_enabled ();
526 bool collect_playback = false;
528 /* if we've already processed the frames corresponding to this call,
529 just return. this allows multiple routes that are taking input
530 from this diskstream to call our ::process() method, but have
531 this stuff only happen once. more commonly, it allows both
532 the AudioTrack that is using this AudioDiskstream *and* the Session
533 to call process() without problems.
540 commit_should_unlock = false;
542 if (!_io || !_io->active()) {
547 check_record_status (transport_frame, nframes, can_record);
549 nominally_recording = (can_record && re);
556 /* This lock is held until the end of AudioDiskstream::commit, so these two functions
557 must always be called as a pair. The only exception is if this function
558 returns a non-zero value, in which case, ::commit should not be called.
561 // If we can't take the state lock return.
562 if (!state_lock.trylock()) {
565 commit_should_unlock = true;
566 adjust_capture_position = 0;
568 for (chan = c->begin(); chan != c->end(); ++chan) {
569 (*chan)->current_capture_buffer = 0;
570 (*chan)->current_playback_buffer = 0;
573 if (nominally_recording || (_session.get_record_enabled() && Config->get_punch_in())) {
576 // Safeguard against situations where process() goes haywire when autopunching and last_recordable_frame < first_recordable_frame
577 if (last_recordable_frame < first_recordable_frame) {
578 last_recordable_frame = max_frames;
581 ot = coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
588 case OverlapInternal:
589 /* ---------- recrange
592 rec_nframes = nframes;
597 /* |--------| recrange
600 rec_nframes = transport_frame + nframes - first_recordable_frame;
602 rec_offset = first_recordable_frame - transport_frame;
607 /* |--------| recrange
610 rec_nframes = last_recordable_frame - transport_frame;
614 case OverlapExternal:
615 /* |--------| recrange
616 -------------- transrange
618 rec_nframes = last_recordable_frame - first_recordable_frame;
619 rec_offset = first_recordable_frame - transport_frame;
623 if (rec_nframes && !was_recording) {
624 capture_captured = 0;
625 was_recording = true;
630 if (can_record && !_last_capture_regions.empty()) {
631 _last_capture_regions.clear ();
634 if (nominally_recording || rec_nframes) {
636 uint32_t limit = _io->n_inputs ().n_audio();
638 /* one or more ports could already have been removed from _io, but our
639 channel setup hasn't yet been updated. prevent us from trying to
640 use channels that correspond to missing ports. note that the
641 process callback (from which this is called) is always atomic
642 with respect to port removal/addition.
645 for (n = 0, chan = c->begin(); chan != c->end() && n < limit; ++chan, ++n) {
647 ChannelInfo* chaninfo (*chan);
649 chaninfo->capture_buf->get_write_vector (&chaninfo->capture_vector);
651 if (rec_nframes <= chaninfo->capture_vector.len[0]) {
653 chaninfo->current_capture_buffer = chaninfo->capture_vector.buf[0];
655 /* note: grab the entire port buffer, but only copy what we were supposed to for recording, and use
659 AudioPort* const ap = _io->audio_input(n);
661 assert(rec_nframes <= ap->get_audio_buffer( nframes, offset ).capacity());
662 memcpy (chaninfo->current_capture_buffer, ap->get_audio_buffer( nframes, offset ).data(rec_nframes, offset + rec_offset), sizeof (Sample) * rec_nframes);
666 nframes_t total = chaninfo->capture_vector.len[0] + chaninfo->capture_vector.len[1];
668 if (rec_nframes > total) {
673 AudioPort* const ap = _io->audio_input(n);
676 Sample* buf = ap->get_audio_buffer( nframes, offset ).data(nframes, offset);
677 nframes_t first = chaninfo->capture_vector.len[0];
679 memcpy (chaninfo->capture_wrap_buffer, buf, sizeof (Sample) * first);
680 memcpy (chaninfo->capture_vector.buf[0], buf, sizeof (Sample) * first);
681 memcpy (chaninfo->capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
682 memcpy (chaninfo->capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
684 chaninfo->current_capture_buffer = chaninfo->capture_wrap_buffer;
691 finish_capture (rec_monitors_input, c);
698 /* data will be written to disk */
700 if (rec_nframes == nframes && rec_offset == 0) {
702 for (chan = c->begin(); chan != c->end(); ++chan) {
703 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
706 playback_distance = nframes;
711 /* we can't use the capture buffer as the playback buffer, because
712 we recorded only a part of the current process' cycle data
716 collect_playback = true;
719 adjust_capture_position = rec_nframes;
721 } else if (nominally_recording) {
723 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
725 for (chan = c->begin(); chan != c->end(); ++chan) {
726 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
729 playback_distance = nframes;
733 collect_playback = true;
736 if (collect_playback) {
738 /* we're doing playback */
740 nframes_t necessary_samples;
742 /* no varispeed playback if we're recording, because the output .... TBD */
744 if (rec_nframes == 0 && _actual_speed != 1.0f) {
745 necessary_samples = (nframes_t) floor ((nframes * fabs (_actual_speed))) + 1;
747 necessary_samples = nframes;
750 for (chan = c->begin(); chan != c->end(); ++chan) {
751 (*chan)->playback_buf->get_read_vector (&(*chan)->playback_vector);
756 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
758 ChannelInfo* chaninfo (*chan);
760 if (necessary_samples <= chaninfo->playback_vector.len[0]) {
762 chaninfo->current_playback_buffer = chaninfo->playback_vector.buf[0];
765 nframes_t total = chaninfo->playback_vector.len[0] + chaninfo->playback_vector.len[1];
767 if (necessary_samples > total) {
768 cerr << "underrun for " << _name << endl;
774 memcpy ((char *) chaninfo->playback_wrap_buffer, chaninfo->playback_vector.buf[0],
775 chaninfo->playback_vector.len[0] * sizeof (Sample));
776 memcpy (chaninfo->playback_wrap_buffer + chaninfo->playback_vector.len[0], chaninfo->playback_vector.buf[1],
777 (necessary_samples - chaninfo->playback_vector.len[0]) * sizeof (Sample));
779 chaninfo->current_playback_buffer = chaninfo->playback_wrap_buffer;
784 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
785 process_varispeed_playback(nframes, c);
787 playback_distance = nframes;
801 /* we're exiting with failure, so ::commit will not
802 be called. unlock the state lock.
805 commit_should_unlock = false;
813 AudioDiskstream::process_varispeed_playback(nframes_t nframes, boost::shared_ptr<ChannelList> c)
815 ChannelList::iterator chan;
817 // the idea behind phase is that when the speed is not 1.0, we have to
818 // interpolate between samples and then we have to store where we thought we were.
819 // rather than being at sample N or N+1, we were at N+0.8792922
820 // so the "phase" element, if you want to think about this way,
821 // varies from 0 to 1, representing the "offset" between samples
822 uint64_t phase = last_phase;
827 // index in the input buffers
830 // Linearly interpolate into the speed buffer
831 // using 40.24 fixed point math
833 // Fixed point is just an integer with an implied scaling factor.
834 // In 40.24 the scaling factor is 2^24 = 16777216,
835 // so a value of 10*2^24 (in integer space) is equivalent to 10.0.
837 // The advantage is that addition and modulus [like x = (x + y) % 2^40]
838 // have no rounding errors and no drift, and just require a single integer add.
841 const int64_t fractional_part_mask = 0xFFFFFF;
842 const Sample binary_scaling_factor = 16777216.0f;
844 // phi = fixed point speed
845 if (phi != target_phi) {
846 phi_delta = ((int64_t)(target_phi - phi)) / nframes;
851 for (chan = c->begin(); chan != c->end(); ++chan) {
853 Sample fractional_phase_part;
854 ChannelInfo* chaninfo (*chan);
859 for (nframes_t outsample = 0; outsample < nframes; ++outsample) {
861 fractional_phase_part = (phase & fractional_part_mask) / binary_scaling_factor;
862 chaninfo->speed_buffer[outsample] =
863 chaninfo->current_playback_buffer[i] * (1.0f - fractional_phase_part) +
864 chaninfo->current_playback_buffer[i+1] * fractional_phase_part;
865 phase += phi + phi_delta;
868 chaninfo->current_playback_buffer = chaninfo->speed_buffer;
871 playback_distance = i; // + 1;
872 last_phase = (phase & fractional_part_mask);
876 AudioDiskstream::commit (nframes_t nframes)
878 bool need_butler = false;
880 if (!_io || !_io->active()) {
884 if (_actual_speed < 0.0) {
885 playback_sample -= playback_distance;
887 playback_sample += playback_distance;
890 boost::shared_ptr<ChannelList> c = channels.reader();
891 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
893 (*chan)->playback_buf->increment_read_ptr (playback_distance);
895 if (adjust_capture_position) {
896 (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
900 if (adjust_capture_position != 0) {
901 capture_captured += adjust_capture_position;
902 adjust_capture_position = 0;
906 if (_io && _io->active()) {
907 need_butler = c->front()->playback_buf->write_space() >= c->front()->playback_buf->bufsize() / 2;
912 if (_io && _io->active()) {
913 need_butler = c->front()->playback_buf->write_space() >= disk_io_chunk_frames
914 || c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
916 need_butler = c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
920 if (commit_should_unlock) {
930 AudioDiskstream::set_pending_overwrite (bool yn)
932 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
934 pending_overwrite = yn;
936 overwrite_frame = playback_sample;
937 overwrite_offset = channels.reader()->front()->playback_buf->get_read_ptr();
941 AudioDiskstream::overwrite_existing_buffers ()
943 boost::shared_ptr<ChannelList> c = channels.reader();
944 Sample* mixdown_buffer;
947 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
949 overwrite_queued = false;
951 /* assume all are the same size */
952 nframes_t size = c->front()->playback_buf->bufsize();
954 mixdown_buffer = new Sample[size];
955 gain_buffer = new float[size];
957 /* reduce size so that we can fill the buffer correctly. */
963 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
965 start = overwrite_frame;
966 nframes_t cnt = size;
968 /* to fill the buffer without resetting the playback sample, we need to
969 do it one or two chunks (normally two).
971 |----------------------------------------------------------------------|
975 |<- second chunk->||<----------------- first chunk ------------------>|
979 nframes_t to_read = size - overwrite_offset;
981 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, *chan, n, reversed)) {
982 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
983 _id, size, playback_sample) << endmsg;
991 if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer,
992 start, cnt, *chan, n, reversed)) {
993 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
994 _id, size, playback_sample) << endmsg;
1003 pending_overwrite = false;
1004 delete [] gain_buffer;
1005 delete [] mixdown_buffer;
1010 AudioDiskstream::seek (nframes_t frame, bool complete_refill)
1014 ChannelList::iterator chan;
1015 boost::shared_ptr<ChannelList> c = channels.reader();
1017 Glib::Mutex::Lock lm (state_lock);
1019 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1020 (*chan)->playback_buf->reset ();
1021 (*chan)->capture_buf->reset ();
1024 /* can't rec-enable in destructive mode if transport is before start */
1026 if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
1027 disengage_record_enable ();
1030 playback_sample = frame;
1033 if (complete_refill) {
1034 while ((ret = do_refill_with_alloc ()) > 0) ;
1036 ret = do_refill_with_alloc ();
1043 AudioDiskstream::can_internal_playback_seek (nframes_t distance)
1045 ChannelList::iterator chan;
1046 boost::shared_ptr<ChannelList> c = channels.reader();
1048 for (chan = c->begin(); chan != c->end(); ++chan) {
1049 if ((*chan)->playback_buf->read_space() < distance) {
1057 AudioDiskstream::internal_playback_seek (nframes_t distance)
1059 ChannelList::iterator chan;
1060 boost::shared_ptr<ChannelList> c = channels.reader();
1062 for (chan = c->begin(); chan != c->end(); ++chan) {
1063 (*chan)->playback_buf->increment_read_ptr (distance);
1066 first_recordable_frame += distance;
1067 playback_sample += distance;
1073 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer, nframes_t& start, nframes_t cnt,
1074 ChannelInfo* channel_info, int channel, bool reversed)
1076 nframes_t this_read = 0;
1077 bool reloop = false;
1078 nframes_t loop_end = 0;
1079 nframes_t loop_start = 0;
1080 nframes_t loop_length = 0;
1081 nframes_t offset = 0;
1084 /* XXX we don't currently play loops in reverse. not sure why */
1088 /* Make the use of a Location atomic for this read operation.
1090 Note: Locations don't get deleted, so all we care about
1091 when I say "atomic" is that we are always pointing to
1092 the same one and using a start/length values obtained
1096 if ((loc = loop_location) != 0) {
1097 loop_start = loc->start();
1098 loop_end = loc->end();
1099 loop_length = loop_end - loop_start;
1102 /* if we are looping, ensure that the first frame we read is at the correct
1103 position within the loop.
1106 if (loc && start >= loop_end) {
1107 //cerr << "start adjusted from " << start;
1108 start = loop_start + ((start - loop_start) % loop_length);
1109 //cerr << "to " << start << endl;
1112 //cerr << "start is " << start << " loopstart: " << loop_start << " loopend: " << loop_end << endl;
1121 /* take any loop into account. we can't read past the end of the loop. */
1123 if (loc && (loop_end - start < cnt)) {
1124 this_read = loop_end - start;
1125 //cerr << "reloop true: thisread: " << this_read << " cnt: " << cnt << endl;
1132 if (this_read == 0) {
1136 this_read = min(cnt,this_read);
1138 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
1139 error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), _id, this_read,
1144 _read_data_count = _playlist->read_data_count();
1148 swap_by_ptr (buf, buf + this_read - 1);
1152 /* if we read to the end of the loop, go back to the beginning */
1162 offset += this_read;
1169 AudioDiskstream::do_refill_with_alloc ()
1171 Sample* mix_buf = new Sample[disk_io_chunk_frames];
1172 float* gain_buf = new float[disk_io_chunk_frames];
1174 int ret = _do_refill(mix_buf, gain_buf);
1183 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer)
1187 RingBufferNPT<Sample>::rw_vector vector;
1188 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1189 nframes_t total_space;
1190 nframes_t zero_fill;
1192 ChannelList::iterator i;
1193 boost::shared_ptr<ChannelList> c = channels.reader();
1200 assert(mixdown_buffer);
1201 assert(gain_buffer);
1208 c->front()->playback_buf->get_write_vector (&vector);
1210 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1214 /* if there are 2+ chunks of disk i/o possible for
1215 this track, let the caller know so that it can arrange
1216 for us to be called again, ASAP.
1219 if (total_space >= (_slaved?3:2) * disk_io_chunk_frames) {
1223 /* if we're running close to normal speed and there isn't enough
1224 space to do disk_io_chunk_frames of I/O, then don't bother.
1226 at higher speeds, just do it because the sync between butler
1227 and audio thread may not be good enough.
1230 if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1234 /* when slaved, don't try to get too close to the read pointer. this
1235 leaves space for the buffer reversal to have something useful to
1239 if (_slaved && total_space < (c->front()->playback_buf->bufsize() / 2)) {
1243 /* never do more than disk_io_chunk_frames worth of disk input per call (limit doesn't apply for memset) */
1245 total_space = min (disk_io_chunk_frames, total_space);
1249 if (file_frame == 0) {
1251 /* at start: nothing to do but fill with silence */
1253 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1255 ChannelInfo* chan (*i);
1256 chan->playback_buf->get_write_vector (&vector);
1257 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1258 if (vector.len[1]) {
1259 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1261 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1266 if (file_frame < total_space) {
1268 /* too close to the start: read what we can,
1269 and then zero fill the rest
1272 zero_fill = total_space - file_frame;
1273 total_space = file_frame;
1283 if (file_frame == max_frames) {
1285 /* at end: nothing to do but fill with silence */
1287 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1289 ChannelInfo* chan (*i);
1290 chan->playback_buf->get_write_vector (&vector);
1291 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1292 if (vector.len[1]) {
1293 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1295 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1300 if (file_frame > max_frames - total_space) {
1302 /* to close to the end: read what we can, and zero fill the rest */
1304 zero_fill = total_space - (max_frames - file_frame);
1305 total_space = max_frames - file_frame;
1312 nframes_t file_frame_tmp = 0;
1314 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1316 ChannelInfo* chan (*i);
1319 nframes_t len1, len2;
1321 chan->playback_buf->get_write_vector (&vector);
1323 if (vector.len[0] > disk_io_chunk_frames) {
1325 /* we're not going to fill the first chunk, so certainly do not bother with the
1326 other part. it won't be connected with the part we do fill, as in:
1328 .... => writable space
1329 ++++ => readable space
1330 ^^^^ => 1 x disk_io_chunk_frames that would be filled
1332 |......|+++++++++++++|...............................|
1337 So, just pretend that the buf1 part isn't there.
1347 file_frame_tmp = file_frame;
1349 buf1 = vector.buf[0];
1350 len1 = vector.len[0];
1351 buf2 = vector.buf[1];
1352 len2 = vector.len[1];
1354 to_read = min (ts, len1);
1355 to_read = min (to_read, disk_io_chunk_frames);
1359 if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1364 chan->playback_buf->increment_write_ptr (to_read);
1368 to_read = min (ts, len2);
1372 /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1373 so read some or all of vector.len[1] as well.
1376 if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1381 chan->playback_buf->increment_write_ptr (to_read);
1390 file_frame = file_frame_tmp;
1397 /** Flush pending data to disk.
1399 * Important note: this function will write *AT MOST* disk_io_chunk_frames
1400 * of data to disk. it will never write more than that. If it writes that
1401 * much and there is more than that waiting to be written, it will return 1,
1402 * otherwise 0 on success or -1 on failure.
1404 * If there is less than disk_io_chunk_frames to be written, no data will be
1405 * written at all unless @a force_flush is true.
1408 AudioDiskstream::do_flush (RunContext context, bool force_flush)
1412 RingBufferNPT<Sample>::rw_vector vector;
1413 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1416 _write_data_count = 0;
1418 transvec.buf[0] = 0;
1419 transvec.buf[1] = 0;
1423 boost::shared_ptr<ChannelList> c = channels.reader();
1424 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1426 (*chan)->capture_buf->get_read_vector (&vector);
1428 total = vector.len[0] + vector.len[1];
1430 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1434 /* if there are 2+ chunks of disk i/o possible for
1435 this track, let the caller know so that it can arrange
1436 for us to be called again, ASAP.
1438 if we are forcing a flush, then if there is* any* extra
1439 work, let the caller know.
1441 if we are no longer recording and there is any extra work,
1442 let the caller know too.
1445 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1449 to_write = min (disk_io_chunk_frames, (nframes_t) vector.len[0]);
1451 // check the transition buffer when recording destructive
1452 // important that we get this after the capture buf
1454 if (destructive()) {
1455 (*chan)->capture_transition_buf->get_read_vector(&transvec);
1456 size_t transcount = transvec.len[0] + transvec.len[1];
1457 bool have_start = false;
1460 for (ti=0; ti < transcount; ++ti) {
1461 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1463 if (captrans.type == CaptureStart) {
1464 // by definition, the first data we got above represents the given capture pos
1466 (*chan)->write_source->mark_capture_start (captrans.capture_val);
1467 (*chan)->curr_capture_cnt = 0;
1471 else if (captrans.type == CaptureEnd) {
1473 // capture end, the capture_val represents total frames in capture
1475 if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1477 // shorten to make the write a perfect fit
1478 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
1480 if (nto_write < to_write) {
1481 ret = 1; // should we?
1483 to_write = nto_write;
1485 (*chan)->write_source->mark_capture_end ();
1487 // increment past this transition, but go no further
1492 // actually ends just beyond this chunk, so force more work
1500 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1504 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1505 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1509 (*chan)->capture_buf->increment_read_ptr (to_write);
1510 (*chan)->curr_capture_cnt += to_write;
1512 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1514 /* we wrote all of vector.len[0] but it wasn't an entire
1515 disk_io_chunk_frames of data, so arrange for some part
1516 of vector.len[1] to be flushed to disk as well.
1519 to_write = min ((nframes_t)(disk_io_chunk_frames - to_write), (nframes_t) vector.len[1]);
1521 if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1522 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1526 _write_data_count += (*chan)->write_source->write_data_count();
1528 (*chan)->capture_buf->increment_read_ptr (to_write);
1529 (*chan)->curr_capture_cnt += to_write;
1538 AudioDiskstream::transport_stopped (struct tm& when, time_t twhen, bool abort_capture)
1540 uint32_t buffer_position;
1541 bool more_work = true;
1543 boost::shared_ptr<AudioRegion> region;
1544 nframes_t total_capture;
1546 SourceList::iterator src;
1547 ChannelList::iterator chan;
1548 vector<CaptureInfo*>::iterator ci;
1549 boost::shared_ptr<ChannelList> c = channels.reader();
1551 bool mark_write_completed = false;
1553 finish_capture (true, c);
1555 /* butler is already stopped, but there may be work to do
1556 to flush remaining data to disk.
1559 while (more_work && !err) {
1560 switch (do_flush (TransportContext, true)) {
1567 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1572 /* XXX is there anything we can do if err != 0 ? */
1573 Glib::Mutex::Lock lm (capture_info_lock);
1575 if (capture_info.empty()) {
1579 if (abort_capture) {
1581 if (destructive()) {
1585 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1587 if ((*chan)->write_source) {
1589 (*chan)->write_source->mark_for_remove ();
1590 (*chan)->write_source->drop_references ();
1591 (*chan)->write_source.reset ();
1594 /* new source set up in "out" below */
1600 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1601 total_capture += (*ci)->frames;
1604 /* figure out the name for this take */
1606 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1608 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1612 s->update_header (capture_info.front()->start, when, twhen);
1613 s->set_captured_for (_name);
1614 s->mark_immutable ();
1615 if (Config->get_auto_analyse_audio()) {
1616 Analyser::queue_source_for_analysis (s, true);
1621 /* destructive tracks have a single, never changing region */
1623 if (destructive()) {
1625 /* send a signal that any UI can pick up to do the right thing. there is
1626 a small problem here in that a UI may need the peak data to be ready
1627 for the data that was recorded and this isn't interlocked with that
1628 process. this problem is deferred to the UI.
1631 _playlist->Modified();
1635 string whole_file_region_name;
1636 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1638 /* Register a new region with the Session that
1639 describes the entire source. Do this first
1640 so that any sub-regions will obviously be
1641 children of this one (later!)
1645 boost::shared_ptr<Region> rx (RegionFactory::create (srcs,
1646 c->front()->write_source->last_capture_start_frame(), total_capture,
1647 whole_file_region_name, 0,
1648 Region::Flag (Region::DefaultFlags|Region::Automatic|Region::WholeFile)));
1650 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1651 region->special_set_position (capture_info.front()->start);
1655 catch (failed_constructor& err) {
1656 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1660 _last_capture_regions.push_back (region);
1662 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1664 XMLNode &before = _playlist->get_state();
1665 _playlist->freeze ();
1667 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1671 _session.region_name (region_name, whole_file_region_name, false);
1673 // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->frames << " add region " << region_name << endl;
1676 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, buffer_position, (*ci)->frames, region_name));
1677 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1680 catch (failed_constructor& err) {
1681 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1682 continue; /* XXX is this OK? */
1685 region->GoingAway.connect (bind (mem_fun (*this, &Diskstream::remove_region_from_last_capture), boost::weak_ptr<Region>(region)));
1687 _last_capture_regions.push_back (region);
1689 i_am_the_modifier++;
1690 _playlist->add_region (region, (*ci)->start);
1691 i_am_the_modifier--;
1693 buffer_position += (*ci)->frames;
1697 XMLNode &after = _playlist->get_state();
1698 _session.add_command (new MementoCommand<Playlist>(*_playlist, &before, &after));
1701 mark_write_completed = true;
1704 reset_write_sources (mark_write_completed);
1708 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1712 capture_info.clear ();
1713 capture_start_frame = 0;
1717 AudioDiskstream::transport_looped (nframes_t transport_frame)
1719 if (was_recording) {
1720 // all we need to do is finish this capture, with modified capture length
1721 boost::shared_ptr<ChannelList> c = channels.reader();
1723 // adjust the capture length knowing that the data will be recorded to disk
1724 // only necessary after the first loop where we're recording
1725 if (capture_info.size() == 0) {
1726 capture_captured += _capture_offset;
1728 if (_alignment_style == ExistingMaterial) {
1729 capture_captured += _session.worst_output_latency();
1731 capture_captured += _roll_delay;
1735 finish_capture (true, c);
1737 // the next region will start recording via the normal mechanism
1738 // we'll set the start position to the current transport pos
1739 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1740 capture_start_frame = transport_frame;
1741 first_recordable_frame = transport_frame; // mild lie
1742 last_recordable_frame = max_frames;
1743 was_recording = true;
1745 if (recordable() && destructive()) {
1746 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1748 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1749 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1751 if (transvec.len[0] > 0) {
1752 transvec.buf[0]->type = CaptureStart;
1753 transvec.buf[0]->capture_val = capture_start_frame;
1754 (*chan)->capture_transition_buf->increment_write_ptr(1);
1758 fatal << X_("programming error: capture_transition_buf is full on rec loop! inconceivable!")
1768 AudioDiskstream::finish_capture (bool rec_monitors_input, boost::shared_ptr<ChannelList> c)
1770 was_recording = false;
1772 if (capture_captured == 0) {
1776 if (recordable() && destructive()) {
1777 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1779 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1780 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1782 if (transvec.len[0] > 0) {
1783 transvec.buf[0]->type = CaptureEnd;
1784 transvec.buf[0]->capture_val = capture_captured;
1785 (*chan)->capture_transition_buf->increment_write_ptr(1);
1789 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1795 CaptureInfo* ci = new CaptureInfo;
1797 ci->start = capture_start_frame;
1798 ci->frames = capture_captured;
1800 /* XXX theoretical race condition here. Need atomic exchange ?
1801 However, the circumstances when this is called right
1802 now (either on record-disable or transport_stopped)
1803 mean that no actual race exists. I think ...
1804 We now have a capture_info_lock, but it is only to be used
1805 to synchronize in the transport_stop and the capture info
1806 accessors, so that invalidation will not occur (both non-realtime).
1809 // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1811 capture_info.push_back (ci);
1812 capture_captured = 0;
1814 /* now we've finished a capture, reset first_recordable_frame for next time */
1815 first_recordable_frame = max_frames;
1819 AudioDiskstream::set_record_enabled (bool yn)
1821 if (!recordable() || !_session.record_enabling_legal() || _io->n_inputs().n_audio() == 0) {
1825 /* can't rec-enable in destructive mode if transport is before start */
1827 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1831 if (yn && channels.reader()->front()->source == 0) {
1833 /* pick up connections not initiated *from* the IO object
1834 we're associated with.
1837 get_input_sources ();
1840 /* yes, i know that this not proof against race conditions, but its
1841 good enough. i think.
1844 if (record_enabled() != yn) {
1846 engage_record_enable ();
1848 disengage_record_enable ();
1854 AudioDiskstream::engage_record_enable ()
1856 bool rolling = _session.transport_speed() != 0.0f;
1857 boost::shared_ptr<ChannelList> c = channels.reader();
1859 g_atomic_int_set (&_record_enabled, 1);
1860 capturing_sources.clear ();
1862 if (Config->get_monitoring_model() == HardwareMonitoring) {
1864 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1865 if ((*chan)->source) {
1866 (*chan)->source->ensure_monitor_input (!(Config->get_auto_input() && rolling));
1868 capturing_sources.push_back ((*chan)->write_source);
1869 (*chan)->write_source->mark_streaming_write_started ();
1873 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1874 capturing_sources.push_back ((*chan)->write_source);
1875 (*chan)->write_source->mark_streaming_write_started ();
1879 RecordEnableChanged (); /* EMIT SIGNAL */
1883 AudioDiskstream::disengage_record_enable ()
1885 g_atomic_int_set (&_record_enabled, 0);
1886 boost::shared_ptr<ChannelList> c = channels.reader();
1887 if (Config->get_monitoring_model() == HardwareMonitoring) {
1888 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1889 if ((*chan)->source) {
1890 (*chan)->source->ensure_monitor_input (false);
1894 capturing_sources.clear ();
1895 RecordEnableChanged (); /* EMIT SIGNAL */
1899 AudioDiskstream::get_state ()
1901 XMLNode* node = new XMLNode ("AudioDiskstream");
1903 LocaleGuard lg (X_("POSIX"));
1904 boost::shared_ptr<ChannelList> c = channels.reader();
1906 node->add_property ("flags", enum_2_string (_flags));
1908 snprintf (buf, sizeof(buf), "%zd", c->size());
1909 node->add_property ("channels", buf);
1911 node->add_property ("playlist", _playlist->name());
1913 snprintf (buf, sizeof(buf), "%.12g", _visible_speed);
1914 node->add_property ("speed", buf);
1916 node->add_property("name", _name);
1917 id().print (buf, sizeof (buf));
1918 node->add_property("id", buf);
1920 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1922 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1923 XMLNode* cs_grandchild;
1925 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1926 cs_grandchild = new XMLNode (X_("file"));
1927 cs_grandchild->add_property (X_("path"), (*i)->path());
1928 cs_child->add_child_nocopy (*cs_grandchild);
1931 /* store the location where capture will start */
1935 if (Config->get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1936 snprintf (buf, sizeof (buf), "%" PRIu32, pi->start());
1938 snprintf (buf, sizeof (buf), "%" PRIu32, _session.transport_frame());
1941 cs_child->add_property (X_("at"), buf);
1942 node->add_child_nocopy (*cs_child);
1946 node->add_child_copy (*_extra_xml);
1953 AudioDiskstream::set_state (const XMLNode& node)
1955 const XMLProperty* prop;
1956 XMLNodeList nlist = node.children();
1957 XMLNodeIterator niter;
1958 uint32_t nchans = 1;
1959 XMLNode* capture_pending_node = 0;
1960 LocaleGuard lg (X_("POSIX"));
1962 in_set_state = true;
1964 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1965 if ((*niter)->name() == IO::state_node_name) {
1966 deprecated_io_node = new XMLNode (**niter);
1969 if ((*niter)->name() == X_("CapturingSources")) {
1970 capture_pending_node = *niter;
1974 /* prevent write sources from being created */
1976 in_set_state = true;
1978 if ((prop = node.property ("name")) != 0) {
1979 _name = prop->value();
1982 if (deprecated_io_node) {
1983 if ((prop = deprecated_io_node->property ("id")) != 0) {
1984 _id = prop->value ();
1987 if ((prop = node.property ("id")) != 0) {
1988 _id = prop->value ();
1992 if ((prop = node.property ("flags")) != 0) {
1993 _flags = Flag (string_2_enum (prop->value(), _flags));
1996 if ((prop = node.property ("channels")) != 0) {
1997 nchans = atoi (prop->value().c_str());
2000 // create necessary extra channels
2001 // we are always constructed with one and we always need one
2003 _n_channels.set(DataType::AUDIO, channels.reader()->size());
2005 if (nchans > _n_channels.n_audio()) {
2007 add_channel (nchans - _n_channels.n_audio());
2008 IO::PortCountChanged(_n_channels);
2010 } else if (nchans < _n_channels.n_audio()) {
2012 remove_channel (_n_channels.n_audio() - nchans);
2015 if ((prop = node.property ("playlist")) == 0) {
2020 bool had_playlist = (_playlist != 0);
2022 if (find_and_use_playlist (prop->value())) {
2026 if (!had_playlist) {
2027 _playlist->set_orig_diskstream_id (_id);
2030 if (!destructive() && capture_pending_node) {
2031 /* destructive streams have one and only one source per channel,
2032 and so they never end up in pending capture in any useful
2035 use_pending_capture_data (*capture_pending_node);
2040 if ((prop = node.property ("speed")) != 0) {
2041 double sp = atof (prop->value().c_str());
2043 if (realtime_set_speed (sp, false)) {
2044 non_realtime_set_speed ();
2048 in_set_state = false;
2050 /* make sure this is clear before we do anything else */
2052 capturing_sources.clear ();
2054 /* write sources are handled when we handle the input set
2055 up of the IO that owns this DS (::non_realtime_input_change())
2062 AudioDiskstream::use_new_write_source (uint32_t n)
2064 boost::shared_ptr<ChannelList> c = channels.reader();
2066 if (!recordable()) {
2070 if (n >= c->size()) {
2071 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
2075 ChannelInfo* chan = (*c)[n];
2077 if (chan->write_source) {
2078 chan->write_source->done_with_peakfile_writes ();
2079 chan->write_source->set_allow_remove_if_empty (true);
2080 chan->write_source.reset ();
2084 if ((chan->write_source = _session.create_audio_source_for_session (*this, n, destructive())) == 0) {
2085 throw failed_constructor();
2089 catch (failed_constructor &err) {
2090 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
2091 chan->write_source.reset ();
2095 /* do not remove destructive files even if they are empty */
2097 chan->write_source->set_allow_remove_if_empty (!destructive());
2103 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool force)
2105 ChannelList::iterator chan;
2106 boost::shared_ptr<ChannelList> c = channels.reader();
2109 if (!recordable()) {
2113 capturing_sources.clear ();
2115 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
2116 if (!destructive()) {
2118 if ((*chan)->write_source && mark_write_complete) {
2119 (*chan)->write_source->mark_streaming_write_completed ();
2121 use_new_write_source (n);
2123 if (record_enabled()) {
2124 capturing_sources.push_back ((*chan)->write_source);
2128 if ((*chan)->write_source == 0) {
2129 use_new_write_source (n);
2134 if (destructive()) {
2136 /* we now have all our write sources set up, so create the
2137 playlist's single region.
2140 if (_playlist->empty()) {
2141 setup_destructive_playlist ();
2147 AudioDiskstream::rename_write_sources ()
2149 ChannelList::iterator chan;
2150 boost::shared_ptr<ChannelList> c = channels.reader();
2153 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
2154 if ((*chan)->write_source != 0) {
2155 (*chan)->write_source->set_source_name (_name, destructive());
2156 /* XXX what to do if one of them fails ? */
2164 AudioDiskstream::set_block_size (nframes_t nframes)
2166 if (_session.get_block_size() > speed_buffer_size) {
2167 speed_buffer_size = _session.get_block_size();
2168 boost::shared_ptr<ChannelList> c = channels.reader();
2170 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2171 if ((*chan)->speed_buffer) delete [] (*chan)->speed_buffer;
2172 (*chan)->speed_buffer = new Sample[speed_buffer_size];
2175 allocate_temporary_buffers ();
2179 AudioDiskstream::allocate_temporary_buffers ()
2181 /* make sure the wrap buffer is at least large enough to deal
2182 with the speeds up to 1.2, to allow for micro-variation
2183 when slaving to MTC, SMPTE etc.
2186 double sp = max (fabsf (_actual_speed), 1.2f);
2187 nframes_t required_wrap_size = (nframes_t) floor (_session.get_block_size() * sp) + 1;
2189 if (required_wrap_size > wrap_buffer_size) {
2191 boost::shared_ptr<ChannelList> c = channels.reader();
2193 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2194 if ((*chan)->playback_wrap_buffer) delete [] (*chan)->playback_wrap_buffer;
2195 (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
2196 if ((*chan)->capture_wrap_buffer) delete [] (*chan)->capture_wrap_buffer;
2197 (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
2200 wrap_buffer_size = required_wrap_size;
2205 AudioDiskstream::monitor_input (bool yn)
2207 boost::shared_ptr<ChannelList> c = channels.reader();
2209 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2211 if ((*chan)->source) {
2212 (*chan)->source->ensure_monitor_input (yn);
2218 AudioDiskstream::set_align_style_from_io ()
2220 bool have_physical = false;
2226 get_input_sources ();
2228 boost::shared_ptr<ChannelList> c = channels.reader();
2230 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2231 if ((*chan)->source && (*chan)->source->flags() & JackPortIsPhysical) {
2232 have_physical = true;
2237 if (have_physical) {
2238 set_align_style (ExistingMaterial);
2240 set_align_style (CaptureTime);
2245 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2247 while (how_many--) {
2248 c->push_back (new ChannelInfo(_session.audio_diskstream_buffer_size(), speed_buffer_size, wrap_buffer_size));
2251 _n_channels.set(DataType::AUDIO, c->size());
2257 AudioDiskstream::add_channel (uint32_t how_many)
2259 RCUWriter<ChannelList> writer (channels);
2260 boost::shared_ptr<ChannelList> c = writer.get_copy();
2262 return add_channel_to (c, how_many);
2266 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2268 while (how_many-- && !c->empty()) {
2273 _n_channels.set(DataType::AUDIO, c->size());
2279 AudioDiskstream::remove_channel (uint32_t how_many)
2281 RCUWriter<ChannelList> writer (channels);
2282 boost::shared_ptr<ChannelList> c = writer.get_copy();
2284 return remove_channel_from (c, how_many);
2288 AudioDiskstream::playback_buffer_load () const
2290 boost::shared_ptr<ChannelList> c = channels.reader();
2292 return (float) ((double) c->front()->playback_buf->read_space()/
2293 (double) c->front()->playback_buf->bufsize());
2297 AudioDiskstream::capture_buffer_load () const
2299 boost::shared_ptr<ChannelList> c = channels.reader();
2301 return (float) ((double) c->front()->capture_buf->write_space()/
2302 (double) c->front()->capture_buf->bufsize());
2306 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2308 const XMLProperty* prop;
2309 XMLNodeList nlist = node.children();
2310 XMLNodeIterator niter;
2311 boost::shared_ptr<AudioFileSource> fs;
2312 boost::shared_ptr<AudioFileSource> first_fs;
2313 SourceList pending_sources;
2316 if ((prop = node.property (X_("at"))) == 0) {
2320 if (sscanf (prop->value().c_str(), "%" PRIu32, &position) != 1) {
2324 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2325 if ((*niter)->name() == X_("file")) {
2327 if ((prop = (*niter)->property (X_("path"))) == 0) {
2331 // This protects sessions from errant CapturingSources in stored sessions
2333 if (stat (prop->value().c_str(), &sbuf)) {
2338 fs = boost::dynamic_pointer_cast<AudioFileSource> (
2339 SourceFactory::createWritable (DataType::AUDIO, _session,
2340 prop->value(), true,
2341 false, _session.frame_rate()));
2344 catch (failed_constructor& err) {
2345 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2346 _name, prop->value())
2351 pending_sources.push_back (fs);
2353 if (first_fs == 0) {
2357 fs->set_captured_for (_name);
2361 if (pending_sources.size() == 0) {
2362 /* nothing can be done */
2366 if (pending_sources.size() != _n_channels.n_audio()) {
2367 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2372 boost::shared_ptr<AudioRegion> region;
2375 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (
2376 pending_sources, 0, first_fs->length(),
2377 region_name_from_path (first_fs->name(), true), 0,
2378 Region::Flag (Region::DefaultFlags|Region::Automatic|Region::WholeFile)));
2379 region->special_set_position (0);
2382 catch (failed_constructor& err) {
2383 error << string_compose (
2384 _("%1: cannot create whole-file region from pending capture sources"),
2391 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (
2392 pending_sources, 0, first_fs->length(),
2393 region_name_from_path (first_fs->name(), true)));
2396 catch (failed_constructor& err) {
2397 error << string_compose (_("%1: cannot create region from pending capture sources"),
2404 _playlist->add_region (region, position);
2410 AudioDiskstream::set_destructive (bool yn)
2412 bool bounce_ignored;
2414 if (yn != destructive()) {
2417 /* requestor should already have checked this and
2418 bounced if necessary and desired
2420 if (!can_become_destructive (bounce_ignored)) {
2423 _flags = Flag (_flags | Destructive);
2424 use_destructive_playlist ();
2426 _flags = Flag (_flags & ~Destructive);
2427 reset_write_sources (true, true);
2435 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2438 requires_bounce = false;
2442 /* is there only one region ? */
2444 if (_playlist->n_regions() != 1) {
2445 requires_bounce = true;
2449 boost::shared_ptr<Region> first = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
2452 /* do the source(s) for the region cover the session start position ? */
2454 if (first->position() != _session.current_start_frame()) {
2455 if (first->start() > _session.current_start_frame()) {
2456 requires_bounce = true;
2461 /* is the source used by only 1 playlist ? */
2463 boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2467 if (afirst->source()->used() > 1) {
2468 requires_bounce = true;
2472 requires_bounce = false;
2476 AudioDiskstream::ChannelInfo::ChannelInfo (nframes_t bufsize, nframes_t speed_size, nframes_t wrap_size)
2480 current_capture_buffer = 0;
2481 current_playback_buffer = 0;
2482 curr_capture_cnt = 0;
2484 speed_buffer = new Sample[speed_size];
2485 playback_wrap_buffer = new Sample[wrap_size];
2486 capture_wrap_buffer = new Sample[wrap_size];
2488 playback_buf = new RingBufferNPT<Sample> (bufsize);
2489 capture_buf = new RingBufferNPT<Sample> (bufsize);
2490 capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2492 /* touch the ringbuffer buffers, which will cause
2493 them to be mapped into locked physical RAM if
2494 we're running with mlockall(). this doesn't do
2498 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2499 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2500 memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2503 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2506 write_source.reset ();
2509 delete [] speed_buffer;
2512 delete [] playback_wrap_buffer;
2513 playback_wrap_buffer = 0;
2515 delete [] capture_wrap_buffer;
2516 capture_wrap_buffer = 0;
2518 delete playback_buf;
2524 delete capture_transition_buf;
2525 capture_transition_buf = 0;