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>
61 using namespace ARDOUR;
64 size_t AudioDiskstream::_working_buffers_size = 0;
65 Sample* AudioDiskstream::_mixdown_buffer = 0;
66 gain_t* AudioDiskstream::_gain_buffer = 0;
68 AudioDiskstream::AudioDiskstream (Session &sess, const string &name, Diskstream::Flag flag)
69 : Diskstream(sess, name, flag)
70 , deprecated_io_node(NULL)
71 , channels (new ChannelList)
73 /* prevent any write sources from being created */
83 AudioDiskstream::AudioDiskstream (Session& sess, const XMLNode& node)
84 : Diskstream(sess, node)
85 , deprecated_io_node(NULL)
86 , channels (new ChannelList)
91 if (set_state (node)) {
93 throw failed_constructor();
99 use_destructive_playlist ();
104 AudioDiskstream::init (Diskstream::Flag f)
108 /* there are no channels at this point, so these
109 two calls just get speed_buffer_size and wrap_buffer
110 size setup without duplicating their code.
113 set_block_size (_session.get_block_size());
114 allocate_temporary_buffers ();
117 assert(_n_channels == ChanCount(DataType::AUDIO, 1));
120 AudioDiskstream::~AudioDiskstream ()
125 RCUWriter<ChannelList> writer (channels);
126 boost::shared_ptr<ChannelList> c = writer.get_copy();
128 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
139 AudioDiskstream::allocate_working_buffers()
141 assert(disk_io_frames() > 0);
143 _working_buffers_size = disk_io_frames();
144 _mixdown_buffer = new Sample[_working_buffers_size];
145 _gain_buffer = new gain_t[_working_buffers_size];
149 AudioDiskstream::free_working_buffers()
151 delete [] _mixdown_buffer;
152 delete [] _gain_buffer;
153 _working_buffers_size = 0;
159 AudioDiskstream::non_realtime_input_change ()
162 Glib::Mutex::Lock lm (state_lock);
164 if (input_change_pending == NoChange) {
169 RCUWriter<ChannelList> writer (channels);
170 boost::shared_ptr<ChannelList> c = writer.get_copy();
172 _n_channels.set(DataType::AUDIO, c->size());
174 if (_io->n_inputs().n_audio() > _n_channels.n_audio()) {
175 add_channel_to (c, _io->n_inputs().n_audio() - _n_channels.n_audio());
176 } else if (_io->n_inputs().n_audio() < _n_channels.n_audio()) {
177 remove_channel_from (c, _n_channels.n_audio() - _io->n_inputs().n_audio());
181 get_input_sources ();
182 set_capture_offset ();
184 if (first_input_change) {
185 set_align_style (_persistent_alignment_style);
186 first_input_change = false;
188 set_align_style_from_io ();
191 input_change_pending = NoChange;
193 /* implicit unlock */
196 /* reset capture files */
198 reset_write_sources (false);
200 /* now refill channel buffers */
202 if (speed() != 1.0f || speed() != -1.0f) {
203 seek ((nframes_t) (_session.transport_frame() * (double) speed()));
205 seek (_session.transport_frame());
210 AudioDiskstream::non_realtime_locate (nframes_t location)
212 /* now refill channel buffers */
214 if (speed() != 1.0f || speed() != -1.0f) {
215 seek ((nframes_t) (location * (double) speed()));
222 AudioDiskstream::get_input_sources ()
224 boost::shared_ptr<ChannelList> c = channels.reader();
227 ChannelList::iterator chan;
228 uint32_t ni = _io->n_inputs().n_audio();
229 vector<string> connections;
231 for (n = 0, chan = c->begin(); chan != c->end() && n < ni; ++chan, ++n) {
233 connections.clear ();
235 if (_io->input(n)->get_connections (connections) == 0) {
237 if ((*chan)->source) {
238 // _source->disable_metering ();
244 (*chan)->source = dynamic_cast<AudioPort*>(_session.engine().get_port_by_name (connections[0]) );
250 AudioDiskstream::find_and_use_playlist (const string& name)
252 boost::shared_ptr<AudioPlaylist> playlist;
254 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (_session.playlist_by_name (name))) == 0) {
255 playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, name));
259 error << string_compose(_("AudioDiskstream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
263 return use_playlist (playlist);
267 AudioDiskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
269 assert(boost::dynamic_pointer_cast<AudioPlaylist>(playlist));
271 Diskstream::use_playlist(playlist);
277 AudioDiskstream::use_new_playlist ()
280 boost::shared_ptr<AudioPlaylist> playlist;
282 if (!in_set_state && destructive()) {
287 newname = Playlist::bump_name (_playlist->name(), _session);
289 newname = Playlist::bump_name (_name, _session);
292 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, newname, hidden()))) != 0) {
294 playlist->set_orig_diskstream_id (id());
295 return use_playlist (playlist);
303 AudioDiskstream::use_copy_playlist ()
305 assert(audio_playlist());
311 if (_playlist == 0) {
312 error << string_compose(_("AudioDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
317 boost::shared_ptr<AudioPlaylist> playlist;
319 newname = Playlist::bump_name (_playlist->name(), _session);
321 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist>(PlaylistFactory::create (audio_playlist(), newname))) != 0) {
322 playlist->set_orig_diskstream_id (id());
323 return use_playlist (playlist);
330 AudioDiskstream::setup_destructive_playlist ()
333 boost::shared_ptr<ChannelList> c = channels.reader();
335 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
336 srcs.push_back ((*chan)->write_source);
339 /* a single full-sized region */
341 boost::shared_ptr<Region> region (RegionFactory::create (srcs, 0, max_frames - srcs.front()->natural_position(), _name));
342 _playlist->add_region (region, srcs.front()->natural_position());
346 AudioDiskstream::use_destructive_playlist ()
348 /* this is called from the XML-based constructor or ::set_destructive. when called,
349 we already have a playlist and a region, but we need to
350 set up our sources for write. we use the sources associated
351 with the (presumed single, full-extent) region.
354 boost::shared_ptr<Region> rp = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
357 reset_write_sources (false, true);
361 boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
364 throw failed_constructor();
367 /* be sure to stretch the region out to the maximum length */
369 region->set_length (max_frames - region->position(), this);
372 ChannelList::iterator chan;
373 boost::shared_ptr<ChannelList> c = channels.reader();
375 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
376 (*chan)->write_source = boost::dynamic_pointer_cast<AudioFileSource>(region->source (n));
377 assert((*chan)->write_source);
378 (*chan)->write_source->set_allow_remove_if_empty (false);
380 /* this might be false if we switched modes, so force it */
382 (*chan)->write_source->set_destructive (true);
385 /* the source list will never be reset for a destructive track */
389 AudioDiskstream::check_record_status (nframes_t transport_frame, nframes_t nframes, bool can_record)
391 int possibly_recording;
394 const int transport_rolling = 0x4;
395 const int track_rec_enabled = 0x2;
396 const int global_rec_enabled = 0x1;
398 /* merge together the 3 factors that affect record status, and compute
402 rolling = _session.transport_speed() != 0.0f;
403 possibly_recording = (rolling << 2) | (record_enabled() << 1) | can_record;
404 change = possibly_recording ^ last_possibly_recording;
406 if (possibly_recording == last_possibly_recording) {
412 /* if per-track or global rec-enable turned on while the other was already on, we've started recording */
414 if (((change & track_rec_enabled) && record_enabled() && (!(change & global_rec_enabled) && can_record)) ||
415 ((change & global_rec_enabled) && can_record && (!(change & track_rec_enabled) && record_enabled()))) {
417 /* starting to record: compute first+last frames */
419 first_recordable_frame = transport_frame + _capture_offset;
420 last_recordable_frame = max_frames;
421 capture_start_frame = transport_frame;
423 if (!(last_possibly_recording & transport_rolling) && (possibly_recording & transport_rolling)) {
425 /* was stopped, now rolling (and recording) */
427 if (_alignment_style == ExistingMaterial) {
428 first_recordable_frame += _session.worst_output_latency();
430 first_recordable_frame += _roll_delay;
435 /* was rolling, but record state changed */
437 if (_alignment_style == ExistingMaterial) {
439 if (!Config->get_punch_in()) {
441 /* manual punch in happens at the correct transport frame
442 because the user hit a button. but to get alignment correct
443 we have to back up the position of the new region to the
444 appropriate spot given the roll delay.
447 capture_start_frame -= _roll_delay;
449 /* XXX paul notes (august 2005): i don't know why
453 first_recordable_frame += _capture_offset;
457 /* autopunch toggles recording at the precise
458 transport frame, and then the DS waits
459 to start recording for a time that depends
460 on the output latency.
463 first_recordable_frame += _session.worst_output_latency();
468 if (Config->get_punch_in()) {
469 first_recordable_frame += _roll_delay;
471 capture_start_frame -= _roll_delay;
477 if (recordable() && destructive()) {
478 boost::shared_ptr<ChannelList> c = channels.reader();
479 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
481 RingBufferNPT<CaptureTransition>::rw_vector transvec;
482 (*chan)->capture_transition_buf->get_write_vector(&transvec);
484 if (transvec.len[0] > 0) {
485 transvec.buf[0]->type = CaptureStart;
486 transvec.buf[0]->capture_val = capture_start_frame;
487 (*chan)->capture_transition_buf->increment_write_ptr(1);
491 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
497 } else if (!record_enabled() || !can_record) {
501 last_recordable_frame = transport_frame + _capture_offset;
503 if (_alignment_style == ExistingMaterial) {
504 last_recordable_frame += _session.worst_output_latency();
506 last_recordable_frame += _roll_delay;
510 last_possibly_recording = possibly_recording;
514 AudioDiskstream::process (nframes_t transport_frame, nframes_t nframes, nframes_t offset, bool can_record, bool rec_monitors_input)
517 boost::shared_ptr<ChannelList> c = channels.reader();
518 ChannelList::iterator chan;
520 nframes_t rec_offset = 0;
521 nframes_t rec_nframes = 0;
522 bool nominally_recording;
523 bool re = record_enabled ();
524 bool collect_playback = false;
526 /* if we've already processed the frames corresponding to this call,
527 just return. this allows multiple routes that are taking input
528 from this diskstream to call our ::process() method, but have
529 this stuff only happen once. more commonly, it allows both
530 the AudioTrack that is using this AudioDiskstream *and* the Session
531 to call process() without problems.
538 commit_should_unlock = false;
540 if (!_io || !_io->active()) {
545 check_record_status (transport_frame, nframes, can_record);
547 nominally_recording = (can_record && re);
554 /* This lock is held until the end of AudioDiskstream::commit, so these two functions
555 must always be called as a pair. The only exception is if this function
556 returns a non-zero value, in which case, ::commit should not be called.
559 // If we can't take the state lock return.
560 if (!state_lock.trylock()) {
563 commit_should_unlock = true;
564 adjust_capture_position = 0;
566 for (chan = c->begin(); chan != c->end(); ++chan) {
567 (*chan)->current_capture_buffer = 0;
568 (*chan)->current_playback_buffer = 0;
571 if (nominally_recording || (_session.get_record_enabled() && Config->get_punch_in())) {
574 // Safeguard against situations where process() goes haywire when autopunching and last_recordable_frame < first_recordable_frame
575 if (last_recordable_frame < first_recordable_frame) {
576 last_recordable_frame = max_frames;
579 ot = coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
586 case OverlapInternal:
587 /* ---------- recrange
590 rec_nframes = nframes;
595 /* |--------| recrange
598 rec_nframes = transport_frame + nframes - first_recordable_frame;
600 rec_offset = first_recordable_frame - transport_frame;
605 /* |--------| recrange
608 rec_nframes = last_recordable_frame - transport_frame;
612 case OverlapExternal:
613 /* |--------| recrange
614 -------------- transrange
616 rec_nframes = last_recordable_frame - first_recordable_frame;
617 rec_offset = first_recordable_frame - transport_frame;
621 if (rec_nframes && !was_recording) {
622 capture_captured = 0;
623 was_recording = true;
628 if (can_record && !_last_capture_regions.empty()) {
629 _last_capture_regions.clear ();
632 if (nominally_recording || rec_nframes) {
634 uint32_t limit = _io->n_inputs ().n_audio();
636 /* one or more ports could already have been removed from _io, but our
637 channel setup hasn't yet been updated. prevent us from trying to
638 use channels that correspond to missing ports. note that the
639 process callback (from which this is called) is always atomic
640 with respect to port removal/addition.
643 for (n = 0, chan = c->begin(); chan != c->end() && n < limit; ++chan, ++n) {
645 ChannelInfo* chaninfo (*chan);
647 chaninfo->capture_buf->get_write_vector (&chaninfo->capture_vector);
649 if (rec_nframes <= chaninfo->capture_vector.len[0]) {
651 chaninfo->current_capture_buffer = chaninfo->capture_vector.buf[0];
653 /* note: grab the entire port buffer, but only copy what we were supposed to for recording, and use
657 AudioPort* const ap = _io->audio_input(n);
659 assert(rec_nframes <= ap->get_audio_buffer( nframes, offset ).capacity());
660 memcpy (chaninfo->current_capture_buffer, ap->get_audio_buffer( nframes, offset ).data(rec_nframes, offset + rec_offset), sizeof (Sample) * rec_nframes);
664 nframes_t total = chaninfo->capture_vector.len[0] + chaninfo->capture_vector.len[1];
666 if (rec_nframes > total) {
671 AudioPort* const ap = _io->audio_input(n);
674 Sample* buf = ap->get_audio_buffer( nframes, offset ).data(nframes, offset);
675 nframes_t first = chaninfo->capture_vector.len[0];
677 memcpy (chaninfo->capture_wrap_buffer, buf, sizeof (Sample) * first);
678 memcpy (chaninfo->capture_vector.buf[0], buf, sizeof (Sample) * first);
679 memcpy (chaninfo->capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
680 memcpy (chaninfo->capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
682 chaninfo->current_capture_buffer = chaninfo->capture_wrap_buffer;
689 finish_capture (rec_monitors_input, c);
696 /* data will be written to disk */
698 if (rec_nframes == nframes && rec_offset == 0) {
700 for (chan = c->begin(); chan != c->end(); ++chan) {
701 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
704 playback_distance = nframes;
709 /* we can't use the capture buffer as the playback buffer, because
710 we recorded only a part of the current process' cycle data
714 collect_playback = true;
717 adjust_capture_position = rec_nframes;
719 } else if (nominally_recording) {
721 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
723 for (chan = c->begin(); chan != c->end(); ++chan) {
724 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
727 playback_distance = nframes;
731 collect_playback = true;
734 if (collect_playback) {
736 /* we're doing playback */
738 nframes_t necessary_samples;
740 /* no varispeed playback if we're recording, because the output .... TBD */
742 if (rec_nframes == 0 && _actual_speed != 1.0f) {
743 necessary_samples = (nframes_t) floor ((nframes * fabs (_actual_speed))) + 1;
745 necessary_samples = nframes;
748 for (chan = c->begin(); chan != c->end(); ++chan) {
749 (*chan)->playback_buf->get_read_vector (&(*chan)->playback_vector);
754 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
756 ChannelInfo* chaninfo (*chan);
758 if (necessary_samples <= chaninfo->playback_vector.len[0]) {
760 chaninfo->current_playback_buffer = chaninfo->playback_vector.buf[0];
763 nframes_t total = chaninfo->playback_vector.len[0] + chaninfo->playback_vector.len[1];
765 if (necessary_samples > total) {
766 cerr << "underrun for " << _name << endl;
772 memcpy ((char *) chaninfo->playback_wrap_buffer, chaninfo->playback_vector.buf[0],
773 chaninfo->playback_vector.len[0] * sizeof (Sample));
774 memcpy (chaninfo->playback_wrap_buffer + chaninfo->playback_vector.len[0], chaninfo->playback_vector.buf[1],
775 (necessary_samples - chaninfo->playback_vector.len[0]) * sizeof (Sample));
777 chaninfo->current_playback_buffer = chaninfo->playback_wrap_buffer;
782 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
783 process_varispeed_playback(nframes, c);
785 playback_distance = nframes;
799 /* we're exiting with failure, so ::commit will not
800 be called. unlock the state lock.
803 commit_should_unlock = false;
811 AudioDiskstream::process_varispeed_playback(nframes_t nframes, boost::shared_ptr<ChannelList> c)
813 ChannelList::iterator chan;
815 // the idea behind phase is that when the speed is not 1.0, we have to
816 // interpolate between samples and then we have to store where we thought we were.
817 // rather than being at sample N or N+1, we were at N+0.8792922
818 // so the "phase" element, if you want to think about this way,
819 // varies from 0 to 1, representing the "offset" between samples
820 uint64_t phase = last_phase;
825 // index in the input buffers
828 // Linearly interpolate into the speed buffer
829 // using 40.24 fixed point math
831 // Fixed point is just an integer with an implied scaling factor.
832 // In 40.24 the scaling factor is 2^24 = 16777216,
833 // so a value of 10*2^24 (in integer space) is equivalent to 10.0.
835 // The advantage is that addition and modulus [like x = (x + y) % 2^40]
836 // have no rounding errors and no drift, and just require a single integer add.
839 const int64_t fractional_part_mask = 0xFFFFFF;
840 const Sample binary_scaling_factor = 16777216.0f;
842 // phi = fixed point speed
843 if (phi != target_phi) {
844 phi_delta = ((int64_t)(target_phi - phi)) / nframes;
849 for (chan = c->begin(); chan != c->end(); ++chan) {
851 Sample fractional_phase_part;
852 ChannelInfo* chaninfo (*chan);
857 for (nframes_t outsample = 0; outsample < nframes; ++outsample) {
859 fractional_phase_part = (phase & fractional_part_mask) / binary_scaling_factor;
860 chaninfo->speed_buffer[outsample] =
861 chaninfo->current_playback_buffer[i] * (1.0f - fractional_phase_part) +
862 chaninfo->current_playback_buffer[i+1] * fractional_phase_part;
863 phase += phi + phi_delta;
866 chaninfo->current_playback_buffer = chaninfo->speed_buffer;
869 playback_distance = i; // + 1;
870 last_phase = (phase & fractional_part_mask);
874 AudioDiskstream::commit (nframes_t nframes)
876 bool need_butler = false;
878 if (!_io || !_io->active()) {
882 if (_actual_speed < 0.0) {
883 playback_sample -= playback_distance;
885 playback_sample += playback_distance;
888 boost::shared_ptr<ChannelList> c = channels.reader();
889 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
891 (*chan)->playback_buf->increment_read_ptr (playback_distance);
893 if (adjust_capture_position) {
894 (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
898 if (adjust_capture_position != 0) {
899 capture_captured += adjust_capture_position;
900 adjust_capture_position = 0;
904 if (_io && _io->active()) {
905 need_butler = c->front()->playback_buf->write_space() >= c->front()->playback_buf->bufsize() / 2;
910 if (_io && _io->active()) {
911 need_butler = c->front()->playback_buf->write_space() >= disk_io_chunk_frames
912 || c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
914 need_butler = c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
918 if (commit_should_unlock) {
928 AudioDiskstream::set_pending_overwrite (bool yn)
930 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
932 pending_overwrite = yn;
934 overwrite_frame = playback_sample;
935 overwrite_offset = channels.reader()->front()->playback_buf->get_read_ptr();
939 AudioDiskstream::overwrite_existing_buffers ()
941 boost::shared_ptr<ChannelList> c = channels.reader();
942 Sample* mixdown_buffer;
945 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
947 overwrite_queued = false;
949 /* assume all are the same size */
950 nframes_t size = c->front()->playback_buf->bufsize();
952 mixdown_buffer = new Sample[size];
953 gain_buffer = new float[size];
955 /* reduce size so that we can fill the buffer correctly. */
961 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
963 start = overwrite_frame;
964 nframes_t cnt = size;
966 /* to fill the buffer without resetting the playback sample, we need to
967 do it one or two chunks (normally two).
969 |----------------------------------------------------------------------|
973 |<- second chunk->||<----------------- first chunk ------------------>|
977 nframes_t to_read = size - overwrite_offset;
979 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, *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;
989 if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer,
990 start, cnt, *chan, n, reversed)) {
991 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
992 _id, size, playback_sample) << endmsg;
1001 pending_overwrite = false;
1002 delete [] gain_buffer;
1003 delete [] mixdown_buffer;
1008 AudioDiskstream::seek (nframes_t frame, bool complete_refill)
1012 ChannelList::iterator chan;
1013 boost::shared_ptr<ChannelList> c = channels.reader();
1015 Glib::Mutex::Lock lm (state_lock);
1017 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1018 (*chan)->playback_buf->reset ();
1019 (*chan)->capture_buf->reset ();
1022 /* can't rec-enable in destructive mode if transport is before start */
1024 if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
1025 disengage_record_enable ();
1028 playback_sample = frame;
1031 if (complete_refill) {
1032 while ((ret = do_refill_with_alloc ()) > 0) ;
1034 ret = do_refill_with_alloc ();
1041 AudioDiskstream::can_internal_playback_seek (nframes_t distance)
1043 ChannelList::iterator chan;
1044 boost::shared_ptr<ChannelList> c = channels.reader();
1046 for (chan = c->begin(); chan != c->end(); ++chan) {
1047 if ((*chan)->playback_buf->read_space() < distance) {
1055 AudioDiskstream::internal_playback_seek (nframes_t distance)
1057 ChannelList::iterator chan;
1058 boost::shared_ptr<ChannelList> c = channels.reader();
1060 for (chan = c->begin(); chan != c->end(); ++chan) {
1061 (*chan)->playback_buf->increment_read_ptr (distance);
1064 first_recordable_frame += distance;
1065 playback_sample += distance;
1071 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer, nframes_t& start, nframes_t cnt,
1072 ChannelInfo* channel_info, int channel, bool reversed)
1074 nframes_t this_read = 0;
1075 bool reloop = false;
1076 nframes_t loop_end = 0;
1077 nframes_t loop_start = 0;
1078 nframes_t loop_length = 0;
1079 nframes_t offset = 0;
1082 /* XXX we don't currently play loops in reverse. not sure why */
1086 /* Make the use of a Location atomic for this read operation.
1088 Note: Locations don't get deleted, so all we care about
1089 when I say "atomic" is that we are always pointing to
1090 the same one and using a start/length values obtained
1094 if ((loc = loop_location) != 0) {
1095 loop_start = loc->start();
1096 loop_end = loc->end();
1097 loop_length = loop_end - loop_start;
1100 /* if we are looping, ensure that the first frame we read is at the correct
1101 position within the loop.
1104 if (loc && start >= loop_end) {
1105 //cerr << "start adjusted from " << start;
1106 start = loop_start + ((start - loop_start) % loop_length);
1107 //cerr << "to " << start << endl;
1110 //cerr << "start is " << start << " loopstart: " << loop_start << " loopend: " << loop_end << endl;
1119 /* take any loop into account. we can't read past the end of the loop. */
1121 if (loc && (loop_end - start < cnt)) {
1122 this_read = loop_end - start;
1123 //cerr << "reloop true: thisread: " << this_read << " cnt: " << cnt << endl;
1130 if (this_read == 0) {
1134 this_read = min(cnt,this_read);
1136 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
1137 error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), _id, this_read,
1142 _read_data_count = _playlist->read_data_count();
1146 swap_by_ptr (buf, buf + this_read - 1);
1150 /* if we read to the end of the loop, go back to the beginning */
1160 offset += this_read;
1167 AudioDiskstream::do_refill_with_alloc ()
1169 Sample* mix_buf = new Sample[disk_io_chunk_frames];
1170 float* gain_buf = new float[disk_io_chunk_frames];
1172 int ret = _do_refill(mix_buf, gain_buf);
1181 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer)
1185 RingBufferNPT<Sample>::rw_vector vector;
1186 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1187 nframes_t total_space;
1188 nframes_t zero_fill;
1190 ChannelList::iterator i;
1191 boost::shared_ptr<ChannelList> c = channels.reader();
1198 assert(mixdown_buffer);
1199 assert(gain_buffer);
1206 c->front()->playback_buf->get_write_vector (&vector);
1208 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1212 /* if there are 2+ chunks of disk i/o possible for
1213 this track, let the caller know so that it can arrange
1214 for us to be called again, ASAP.
1217 if (total_space >= (_slaved?3:2) * disk_io_chunk_frames) {
1221 /* if we're running close to normal speed and there isn't enough
1222 space to do disk_io_chunk_frames of I/O, then don't bother.
1224 at higher speeds, just do it because the sync between butler
1225 and audio thread may not be good enough.
1228 if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1232 /* when slaved, don't try to get too close to the read pointer. this
1233 leaves space for the buffer reversal to have something useful to
1237 if (_slaved && total_space < (c->front()->playback_buf->bufsize() / 2)) {
1241 /* never do more than disk_io_chunk_frames worth of disk input per call (limit doesn't apply for memset) */
1243 total_space = min (disk_io_chunk_frames, total_space);
1247 if (file_frame == 0) {
1249 /* at start: nothing to do but fill with silence */
1251 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1253 ChannelInfo* chan (*i);
1254 chan->playback_buf->get_write_vector (&vector);
1255 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1256 if (vector.len[1]) {
1257 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1259 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1264 if (file_frame < total_space) {
1266 /* too close to the start: read what we can,
1267 and then zero fill the rest
1270 zero_fill = total_space - file_frame;
1271 total_space = file_frame;
1281 if (file_frame == max_frames) {
1283 /* at end: nothing to do but fill with silence */
1285 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1287 ChannelInfo* chan (*i);
1288 chan->playback_buf->get_write_vector (&vector);
1289 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1290 if (vector.len[1]) {
1291 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1293 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1298 if (file_frame > max_frames - total_space) {
1300 /* to close to the end: read what we can, and zero fill the rest */
1302 zero_fill = total_space - (max_frames - file_frame);
1303 total_space = max_frames - file_frame;
1310 nframes_t file_frame_tmp = 0;
1312 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1314 ChannelInfo* chan (*i);
1317 nframes_t len1, len2;
1319 chan->playback_buf->get_write_vector (&vector);
1321 if (vector.len[0] > disk_io_chunk_frames) {
1323 /* we're not going to fill the first chunk, so certainly do not bother with the
1324 other part. it won't be connected with the part we do fill, as in:
1326 .... => writable space
1327 ++++ => readable space
1328 ^^^^ => 1 x disk_io_chunk_frames that would be filled
1330 |......|+++++++++++++|...............................|
1335 So, just pretend that the buf1 part isn't there.
1345 file_frame_tmp = file_frame;
1347 buf1 = vector.buf[0];
1348 len1 = vector.len[0];
1349 buf2 = vector.buf[1];
1350 len2 = vector.len[1];
1352 to_read = min (ts, len1);
1353 to_read = min (to_read, disk_io_chunk_frames);
1357 if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1362 chan->playback_buf->increment_write_ptr (to_read);
1366 to_read = min (ts, len2);
1370 /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1371 so read some or all of vector.len[1] as well.
1374 if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1379 chan->playback_buf->increment_write_ptr (to_read);
1388 file_frame = file_frame_tmp;
1395 /** Flush pending data to disk.
1397 * Important note: this function will write *AT MOST* disk_io_chunk_frames
1398 * of data to disk. it will never write more than that. If it writes that
1399 * much and there is more than that waiting to be written, it will return 1,
1400 * otherwise 0 on success or -1 on failure.
1402 * If there is less than disk_io_chunk_frames to be written, no data will be
1403 * written at all unless @a force_flush is true.
1406 AudioDiskstream::do_flush (Session::RunContext context, bool force_flush)
1410 RingBufferNPT<Sample>::rw_vector vector;
1411 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1414 _write_data_count = 0;
1416 transvec.buf[0] = 0;
1417 transvec.buf[1] = 0;
1421 boost::shared_ptr<ChannelList> c = channels.reader();
1422 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1424 (*chan)->capture_buf->get_read_vector (&vector);
1426 total = vector.len[0] + vector.len[1];
1428 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1432 /* if there are 2+ chunks of disk i/o possible for
1433 this track, let the caller know so that it can arrange
1434 for us to be called again, ASAP.
1436 if we are forcing a flush, then if there is* any* extra
1437 work, let the caller know.
1439 if we are no longer recording and there is any extra work,
1440 let the caller know too.
1443 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1447 to_write = min (disk_io_chunk_frames, (nframes_t) vector.len[0]);
1449 // check the transition buffer when recording destructive
1450 // important that we get this after the capture buf
1452 if (destructive()) {
1453 (*chan)->capture_transition_buf->get_read_vector(&transvec);
1454 size_t transcount = transvec.len[0] + transvec.len[1];
1455 bool have_start = false;
1458 for (ti=0; ti < transcount; ++ti) {
1459 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1461 if (captrans.type == CaptureStart) {
1462 // by definition, the first data we got above represents the given capture pos
1464 (*chan)->write_source->mark_capture_start (captrans.capture_val);
1465 (*chan)->curr_capture_cnt = 0;
1469 else if (captrans.type == CaptureEnd) {
1471 // capture end, the capture_val represents total frames in capture
1473 if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1475 // shorten to make the write a perfect fit
1476 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
1478 if (nto_write < to_write) {
1479 ret = 1; // should we?
1481 to_write = nto_write;
1483 (*chan)->write_source->mark_capture_end ();
1485 // increment past this transition, but go no further
1490 // actually ends just beyond this chunk, so force more work
1498 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1502 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1503 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1507 (*chan)->capture_buf->increment_read_ptr (to_write);
1508 (*chan)->curr_capture_cnt += to_write;
1510 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1512 /* we wrote all of vector.len[0] but it wasn't an entire
1513 disk_io_chunk_frames of data, so arrange for some part
1514 of vector.len[1] to be flushed to disk as well.
1517 to_write = min ((nframes_t)(disk_io_chunk_frames - to_write), (nframes_t) vector.len[1]);
1519 if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1520 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1524 _write_data_count += (*chan)->write_source->write_data_count();
1526 (*chan)->capture_buf->increment_read_ptr (to_write);
1527 (*chan)->curr_capture_cnt += to_write;
1536 AudioDiskstream::transport_stopped (struct tm& when, time_t twhen, bool abort_capture)
1538 uint32_t buffer_position;
1539 bool more_work = true;
1541 boost::shared_ptr<AudioRegion> region;
1542 nframes_t total_capture;
1544 SourceList::iterator src;
1545 ChannelList::iterator chan;
1546 vector<CaptureInfo*>::iterator ci;
1547 boost::shared_ptr<ChannelList> c = channels.reader();
1549 bool mark_write_completed = false;
1551 finish_capture (true, c);
1553 /* butler is already stopped, but there may be work to do
1554 to flush remaining data to disk.
1557 while (more_work && !err) {
1558 switch (do_flush (Session::TransportContext, true)) {
1565 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1570 /* XXX is there anything we can do if err != 0 ? */
1571 Glib::Mutex::Lock lm (capture_info_lock);
1573 if (capture_info.empty()) {
1577 if (abort_capture) {
1579 if (destructive()) {
1583 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1585 if ((*chan)->write_source) {
1587 (*chan)->write_source->mark_for_remove ();
1588 (*chan)->write_source->drop_references ();
1589 (*chan)->write_source.reset ();
1592 /* new source set up in "out" below */
1598 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1599 total_capture += (*ci)->frames;
1602 /* figure out the name for this take */
1604 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1606 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1610 s->update_header (capture_info.front()->start, when, twhen);
1611 s->set_captured_for (_name);
1612 s->mark_immutable ();
1613 if (Config->get_auto_analyse_audio()) {
1614 Analyser::queue_source_for_analysis (s, true);
1619 /* destructive tracks have a single, never changing region */
1621 if (destructive()) {
1623 /* send a signal that any UI can pick up to do the right thing. there is
1624 a small problem here in that a UI may need the peak data to be ready
1625 for the data that was recorded and this isn't interlocked with that
1626 process. this problem is deferred to the UI.
1629 _playlist->Modified();
1633 string whole_file_region_name;
1634 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1636 /* Register a new region with the Session that
1637 describes the entire source. Do this first
1638 so that any sub-regions will obviously be
1639 children of this one (later!)
1643 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, c->front()->write_source->last_capture_start_frame(), total_capture,
1644 whole_file_region_name,
1645 0, AudioRegion::Flag (AudioRegion::DefaultFlags|AudioRegion::Automatic|AudioRegion::WholeFile)));
1647 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1648 region->special_set_position (capture_info.front()->start);
1652 catch (failed_constructor& err) {
1653 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1657 _last_capture_regions.push_back (region);
1659 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1661 XMLNode &before = _playlist->get_state();
1662 _playlist->freeze ();
1664 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1668 _session.region_name (region_name, whole_file_region_name, false);
1670 // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->frames << " add region " << region_name << endl;
1673 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, buffer_position, (*ci)->frames, region_name));
1674 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1677 catch (failed_constructor& err) {
1678 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1679 continue; /* XXX is this OK? */
1682 region->GoingAway.connect (bind (mem_fun (*this, &Diskstream::remove_region_from_last_capture), boost::weak_ptr<Region>(region)));
1684 _last_capture_regions.push_back (region);
1686 i_am_the_modifier++;
1687 _playlist->add_region (region, (*ci)->start);
1688 i_am_the_modifier--;
1690 buffer_position += (*ci)->frames;
1694 XMLNode &after = _playlist->get_state();
1695 _session.add_command (new MementoCommand<Playlist>(*_playlist, &before, &after));
1698 mark_write_completed = true;
1701 reset_write_sources (mark_write_completed);
1705 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1709 capture_info.clear ();
1710 capture_start_frame = 0;
1714 AudioDiskstream::transport_looped (nframes_t transport_frame)
1716 if (was_recording) {
1717 // all we need to do is finish this capture, with modified capture length
1718 boost::shared_ptr<ChannelList> c = channels.reader();
1720 // adjust the capture length knowing that the data will be recorded to disk
1721 // only necessary after the first loop where we're recording
1722 if (capture_info.size() == 0) {
1723 capture_captured += _capture_offset;
1725 if (_alignment_style == ExistingMaterial) {
1726 capture_captured += _session.worst_output_latency();
1728 capture_captured += _roll_delay;
1732 finish_capture (true, c);
1734 // the next region will start recording via the normal mechanism
1735 // we'll set the start position to the current transport pos
1736 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1737 capture_start_frame = transport_frame;
1738 first_recordable_frame = transport_frame; // mild lie
1739 last_recordable_frame = max_frames;
1740 was_recording = true;
1742 if (recordable() && destructive()) {
1743 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1745 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1746 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1748 if (transvec.len[0] > 0) {
1749 transvec.buf[0]->type = CaptureStart;
1750 transvec.buf[0]->capture_val = capture_start_frame;
1751 (*chan)->capture_transition_buf->increment_write_ptr(1);
1755 fatal << X_("programming error: capture_transition_buf is full on rec loop! inconceivable!")
1765 AudioDiskstream::finish_capture (bool rec_monitors_input, boost::shared_ptr<ChannelList> c)
1767 was_recording = false;
1769 if (capture_captured == 0) {
1773 if (recordable() && destructive()) {
1774 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1776 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1777 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1779 if (transvec.len[0] > 0) {
1780 transvec.buf[0]->type = CaptureEnd;
1781 transvec.buf[0]->capture_val = capture_captured;
1782 (*chan)->capture_transition_buf->increment_write_ptr(1);
1786 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1792 CaptureInfo* ci = new CaptureInfo;
1794 ci->start = capture_start_frame;
1795 ci->frames = capture_captured;
1797 /* XXX theoretical race condition here. Need atomic exchange ?
1798 However, the circumstances when this is called right
1799 now (either on record-disable or transport_stopped)
1800 mean that no actual race exists. I think ...
1801 We now have a capture_info_lock, but it is only to be used
1802 to synchronize in the transport_stop and the capture info
1803 accessors, so that invalidation will not occur (both non-realtime).
1806 // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1808 capture_info.push_back (ci);
1809 capture_captured = 0;
1811 /* now we've finished a capture, reset first_recordable_frame for next time */
1812 first_recordable_frame = max_frames;
1816 AudioDiskstream::set_record_enabled (bool yn)
1818 if (!recordable() || !_session.record_enabling_legal() || _io->n_inputs().n_audio() == 0) {
1822 /* can't rec-enable in destructive mode if transport is before start */
1824 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1828 if (yn && channels.reader()->front()->source == 0) {
1830 /* pick up connections not initiated *from* the IO object
1831 we're associated with.
1834 get_input_sources ();
1837 /* yes, i know that this not proof against race conditions, but its
1838 good enough. i think.
1841 if (record_enabled() != yn) {
1843 engage_record_enable ();
1845 disengage_record_enable ();
1851 AudioDiskstream::engage_record_enable ()
1853 bool rolling = _session.transport_speed() != 0.0f;
1854 boost::shared_ptr<ChannelList> c = channels.reader();
1856 g_atomic_int_set (&_record_enabled, 1);
1857 capturing_sources.clear ();
1859 if (Config->get_monitoring_model() == HardwareMonitoring) {
1861 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1862 if ((*chan)->source) {
1863 (*chan)->source->ensure_monitor_input (!(Config->get_auto_input() && rolling));
1865 capturing_sources.push_back ((*chan)->write_source);
1866 (*chan)->write_source->mark_streaming_write_started ();
1870 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1871 capturing_sources.push_back ((*chan)->write_source);
1872 (*chan)->write_source->mark_streaming_write_started ();
1876 RecordEnableChanged (); /* EMIT SIGNAL */
1880 AudioDiskstream::disengage_record_enable ()
1882 g_atomic_int_set (&_record_enabled, 0);
1883 boost::shared_ptr<ChannelList> c = channels.reader();
1884 if (Config->get_monitoring_model() == HardwareMonitoring) {
1885 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1886 if ((*chan)->source) {
1887 (*chan)->source->ensure_monitor_input (false);
1891 capturing_sources.clear ();
1892 RecordEnableChanged (); /* EMIT SIGNAL */
1896 AudioDiskstream::get_state ()
1898 XMLNode* node = new XMLNode ("AudioDiskstream");
1900 LocaleGuard lg (X_("POSIX"));
1901 boost::shared_ptr<ChannelList> c = channels.reader();
1903 node->add_property ("flags", enum_2_string (_flags));
1905 snprintf (buf, sizeof(buf), "%zd", c->size());
1906 node->add_property ("channels", buf);
1908 node->add_property ("playlist", _playlist->name());
1910 snprintf (buf, sizeof(buf), "%.12g", _visible_speed);
1911 node->add_property ("speed", buf);
1913 node->add_property("name", _name);
1914 id().print (buf, sizeof (buf));
1915 node->add_property("id", buf);
1917 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1919 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1920 XMLNode* cs_grandchild;
1922 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1923 cs_grandchild = new XMLNode (X_("file"));
1924 cs_grandchild->add_property (X_("path"), (*i)->path());
1925 cs_child->add_child_nocopy (*cs_grandchild);
1928 /* store the location where capture will start */
1932 if (Config->get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1933 snprintf (buf, sizeof (buf), "%" PRIu32, pi->start());
1935 snprintf (buf, sizeof (buf), "%" PRIu32, _session.transport_frame());
1938 cs_child->add_property (X_("at"), buf);
1939 node->add_child_nocopy (*cs_child);
1943 node->add_child_copy (*_extra_xml);
1950 AudioDiskstream::set_state (const XMLNode& node)
1952 const XMLProperty* prop;
1953 XMLNodeList nlist = node.children();
1954 XMLNodeIterator niter;
1955 uint32_t nchans = 1;
1956 XMLNode* capture_pending_node = 0;
1957 LocaleGuard lg (X_("POSIX"));
1959 in_set_state = true;
1961 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1962 if ((*niter)->name() == IO::state_node_name) {
1963 deprecated_io_node = new XMLNode (**niter);
1966 if ((*niter)->name() == X_("CapturingSources")) {
1967 capture_pending_node = *niter;
1971 /* prevent write sources from being created */
1973 in_set_state = true;
1975 if ((prop = node.property ("name")) != 0) {
1976 _name = prop->value();
1979 if (deprecated_io_node) {
1980 if ((prop = deprecated_io_node->property ("id")) != 0) {
1981 _id = prop->value ();
1984 if ((prop = node.property ("id")) != 0) {
1985 _id = prop->value ();
1989 if ((prop = node.property ("flags")) != 0) {
1990 _flags = Flag (string_2_enum (prop->value(), _flags));
1993 if ((prop = node.property ("channels")) != 0) {
1994 nchans = atoi (prop->value().c_str());
1997 // create necessary extra channels
1998 // we are always constructed with one and we always need one
2000 _n_channels.set(DataType::AUDIO, channels.reader()->size());
2002 if (nchans > _n_channels.n_audio()) {
2004 add_channel (nchans - _n_channels.n_audio());
2005 IO::PortCountChanged(_n_channels);
2007 } else if (nchans < _n_channels.n_audio()) {
2009 remove_channel (_n_channels.n_audio() - nchans);
2012 if ((prop = node.property ("playlist")) == 0) {
2017 bool had_playlist = (_playlist != 0);
2019 if (find_and_use_playlist (prop->value())) {
2023 if (!had_playlist) {
2024 _playlist->set_orig_diskstream_id (_id);
2027 if (!destructive() && capture_pending_node) {
2028 /* destructive streams have one and only one source per channel,
2029 and so they never end up in pending capture in any useful
2032 use_pending_capture_data (*capture_pending_node);
2037 if ((prop = node.property ("speed")) != 0) {
2038 double sp = atof (prop->value().c_str());
2040 if (realtime_set_speed (sp, false)) {
2041 non_realtime_set_speed ();
2045 in_set_state = false;
2047 /* make sure this is clear before we do anything else */
2049 capturing_sources.clear ();
2051 /* write sources are handled when we handle the input set
2052 up of the IO that owns this DS (::non_realtime_input_change())
2059 AudioDiskstream::use_new_write_source (uint32_t n)
2061 boost::shared_ptr<ChannelList> c = channels.reader();
2063 if (!recordable()) {
2067 if (n >= c->size()) {
2068 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
2072 ChannelInfo* chan = (*c)[n];
2074 if (chan->write_source) {
2075 chan->write_source->done_with_peakfile_writes ();
2076 chan->write_source->set_allow_remove_if_empty (true);
2077 chan->write_source.reset ();
2081 if ((chan->write_source = _session.create_audio_source_for_session (*this, n, destructive())) == 0) {
2082 throw failed_constructor();
2086 catch (failed_constructor &err) {
2087 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
2088 chan->write_source.reset ();
2092 /* do not remove destructive files even if they are empty */
2094 chan->write_source->set_allow_remove_if_empty (!destructive());
2100 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool force)
2102 ChannelList::iterator chan;
2103 boost::shared_ptr<ChannelList> c = channels.reader();
2106 if (!recordable()) {
2110 capturing_sources.clear ();
2112 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
2113 if (!destructive()) {
2115 if ((*chan)->write_source && mark_write_complete) {
2116 (*chan)->write_source->mark_streaming_write_completed ();
2118 use_new_write_source (n);
2120 if (record_enabled()) {
2121 capturing_sources.push_back ((*chan)->write_source);
2125 if ((*chan)->write_source == 0) {
2126 use_new_write_source (n);
2131 if (destructive()) {
2133 /* we now have all our write sources set up, so create the
2134 playlist's single region.
2137 if (_playlist->empty()) {
2138 setup_destructive_playlist ();
2144 AudioDiskstream::rename_write_sources ()
2146 ChannelList::iterator chan;
2147 boost::shared_ptr<ChannelList> c = channels.reader();
2150 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
2151 if ((*chan)->write_source != 0) {
2152 (*chan)->write_source->set_source_name (_name, destructive());
2153 /* XXX what to do if one of them fails ? */
2161 AudioDiskstream::set_block_size (nframes_t nframes)
2163 if (_session.get_block_size() > speed_buffer_size) {
2164 speed_buffer_size = _session.get_block_size();
2165 boost::shared_ptr<ChannelList> c = channels.reader();
2167 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2168 if ((*chan)->speed_buffer) delete [] (*chan)->speed_buffer;
2169 (*chan)->speed_buffer = new Sample[speed_buffer_size];
2172 allocate_temporary_buffers ();
2176 AudioDiskstream::allocate_temporary_buffers ()
2178 /* make sure the wrap buffer is at least large enough to deal
2179 with the speeds up to 1.2, to allow for micro-variation
2180 when slaving to MTC, SMPTE etc.
2183 double sp = max (fabsf (_actual_speed), 1.2f);
2184 nframes_t required_wrap_size = (nframes_t) floor (_session.get_block_size() * sp) + 1;
2186 if (required_wrap_size > wrap_buffer_size) {
2188 boost::shared_ptr<ChannelList> c = channels.reader();
2190 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2191 if ((*chan)->playback_wrap_buffer) delete [] (*chan)->playback_wrap_buffer;
2192 (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
2193 if ((*chan)->capture_wrap_buffer) delete [] (*chan)->capture_wrap_buffer;
2194 (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
2197 wrap_buffer_size = required_wrap_size;
2202 AudioDiskstream::monitor_input (bool yn)
2204 boost::shared_ptr<ChannelList> c = channels.reader();
2206 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2208 if ((*chan)->source) {
2209 (*chan)->source->ensure_monitor_input (yn);
2215 AudioDiskstream::set_align_style_from_io ()
2217 bool have_physical = false;
2223 get_input_sources ();
2225 boost::shared_ptr<ChannelList> c = channels.reader();
2227 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2228 if ((*chan)->source && (*chan)->source->flags() & JackPortIsPhysical) {
2229 have_physical = true;
2234 if (have_physical) {
2235 set_align_style (ExistingMaterial);
2237 set_align_style (CaptureTime);
2242 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2244 while (how_many--) {
2245 c->push_back (new ChannelInfo(_session.audio_diskstream_buffer_size(), speed_buffer_size, wrap_buffer_size));
2248 _n_channels.set(DataType::AUDIO, c->size());
2254 AudioDiskstream::add_channel (uint32_t how_many)
2256 RCUWriter<ChannelList> writer (channels);
2257 boost::shared_ptr<ChannelList> c = writer.get_copy();
2259 return add_channel_to (c, how_many);
2263 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2265 while (how_many-- && !c->empty()) {
2270 _n_channels.set(DataType::AUDIO, c->size());
2276 AudioDiskstream::remove_channel (uint32_t how_many)
2278 RCUWriter<ChannelList> writer (channels);
2279 boost::shared_ptr<ChannelList> c = writer.get_copy();
2281 return remove_channel_from (c, how_many);
2285 AudioDiskstream::playback_buffer_load () const
2287 boost::shared_ptr<ChannelList> c = channels.reader();
2289 return (float) ((double) c->front()->playback_buf->read_space()/
2290 (double) c->front()->playback_buf->bufsize());
2294 AudioDiskstream::capture_buffer_load () const
2296 boost::shared_ptr<ChannelList> c = channels.reader();
2298 return (float) ((double) c->front()->capture_buf->write_space()/
2299 (double) c->front()->capture_buf->bufsize());
2303 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2305 const XMLProperty* prop;
2306 XMLNodeList nlist = node.children();
2307 XMLNodeIterator niter;
2308 boost::shared_ptr<AudioFileSource> fs;
2309 boost::shared_ptr<AudioFileSource> first_fs;
2310 SourceList pending_sources;
2313 if ((prop = node.property (X_("at"))) == 0) {
2317 if (sscanf (prop->value().c_str(), "%" PRIu32, &position) != 1) {
2321 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2322 if ((*niter)->name() == X_("file")) {
2324 if ((prop = (*niter)->property (X_("path"))) == 0) {
2328 // This protects sessions from errant CapturingSources in stored sessions
2330 if (stat (prop->value().c_str(), &sbuf)) {
2335 fs = boost::dynamic_pointer_cast<AudioFileSource> (
2336 SourceFactory::createWritable (DataType::AUDIO, _session, prop->value(), false, _session.frame_rate()));
2339 catch (failed_constructor& err) {
2340 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2341 _name, prop->value())
2346 pending_sources.push_back (fs);
2348 if (first_fs == 0) {
2352 fs->set_captured_for (_name);
2356 if (pending_sources.size() == 0) {
2357 /* nothing can be done */
2361 if (pending_sources.size() != _n_channels.n_audio()) {
2362 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2367 boost::shared_ptr<AudioRegion> region;
2370 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, 0, first_fs->length(),
2371 region_name_from_path (first_fs->name(), true),
2372 0, AudioRegion::Flag (AudioRegion::DefaultFlags|AudioRegion::Automatic|AudioRegion::WholeFile)));
2373 region->special_set_position (0);
2376 catch (failed_constructor& err) {
2377 error << string_compose (_("%1: cannot create whole-file region from pending capture sources"),
2385 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, 0, first_fs->length(), region_name_from_path (first_fs->name(), true)));
2388 catch (failed_constructor& err) {
2389 error << string_compose (_("%1: cannot create region from pending capture sources"),
2396 _playlist->add_region (region, position);
2402 AudioDiskstream::set_destructive (bool yn)
2404 bool bounce_ignored;
2406 if (yn != destructive()) {
2409 /* requestor should already have checked this and
2410 bounced if necessary and desired
2412 if (!can_become_destructive (bounce_ignored)) {
2415 _flags = Flag (_flags | Destructive);
2416 use_destructive_playlist ();
2418 _flags = Flag (_flags & ~Destructive);
2419 reset_write_sources (true, true);
2427 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2430 requires_bounce = false;
2434 /* is there only one region ? */
2436 if (_playlist->n_regions() != 1) {
2437 requires_bounce = true;
2441 boost::shared_ptr<Region> first = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
2444 /* do the source(s) for the region cover the session start position ? */
2446 if (first->position() != _session.current_start_frame()) {
2447 if (first->start() > _session.current_start_frame()) {
2448 requires_bounce = true;
2453 /* is the source used by only 1 playlist ? */
2455 boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2459 if (afirst->source()->used() > 1) {
2460 requires_bounce = true;
2464 requires_bounce = false;
2468 AudioDiskstream::ChannelInfo::ChannelInfo (nframes_t bufsize, nframes_t speed_size, nframes_t wrap_size)
2472 current_capture_buffer = 0;
2473 current_playback_buffer = 0;
2474 curr_capture_cnt = 0;
2476 speed_buffer = new Sample[speed_size];
2477 playback_wrap_buffer = new Sample[wrap_size];
2478 capture_wrap_buffer = new Sample[wrap_size];
2480 playback_buf = new RingBufferNPT<Sample> (bufsize);
2481 capture_buf = new RingBufferNPT<Sample> (bufsize);
2482 capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2484 /* touch the ringbuffer buffers, which will cause
2485 them to be mapped into locked physical RAM if
2486 we're running with mlockall(). this doesn't do
2490 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2491 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2492 memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2495 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2498 write_source.reset ();
2501 delete [] speed_buffer;
2504 delete [] playback_wrap_buffer;
2505 playback_wrap_buffer = 0;
2507 delete [] capture_wrap_buffer;
2508 capture_wrap_buffer = 0;
2510 delete playback_buf;
2516 delete capture_transition_buf;
2517 capture_transition_buf = 0;