2 Copyright (C) 2000-2006 Paul Davis
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
33 #include <pbd/error.h>
34 #include <glibmm/thread.h>
35 #include <pbd/xml++.h>
36 #include <pbd/memento_command.h>
37 #include <pbd/enumwriter.h>
38 #include <pbd/stacktrace.h>
40 #include <ardour/ardour.h>
41 #include <ardour/audioengine.h>
42 #include <ardour/analyser.h>
43 #include <ardour/audio_diskstream.h>
44 #include <ardour/utils.h>
45 #include <ardour/configuration.h>
46 #include <ardour/audiofilesource.h>
47 #include <ardour/send.h>
48 #include <ardour/region_factory.h>
49 #include <ardour/audioplaylist.h>
50 #include <ardour/playlist_factory.h>
51 #include <ardour/cycle_timer.h>
52 #include <ardour/audioregion.h>
53 #include <ardour/audio_port.h>
54 #include <ardour/source_factory.h>
60 using namespace ARDOUR;
63 size_t AudioDiskstream::_working_buffers_size = 0;
64 Sample* AudioDiskstream::_mixdown_buffer = 0;
65 gain_t* AudioDiskstream::_gain_buffer = 0;
67 AudioDiskstream::AudioDiskstream (Session &sess, const string &name, Diskstream::Flag flag)
68 : Diskstream(sess, name, flag)
69 , deprecated_io_node(NULL)
70 , channels (new ChannelList)
72 /* prevent any write sources from being created */
82 AudioDiskstream::AudioDiskstream (Session& sess, const XMLNode& node)
83 : Diskstream(sess, node)
84 , deprecated_io_node(NULL)
85 , channels (new ChannelList)
90 if (set_state (node)) {
92 throw failed_constructor();
98 use_destructive_playlist ();
103 AudioDiskstream::init (Diskstream::Flag f)
107 /* there are no channels at this point, so these
108 two calls just get speed_buffer_size and wrap_buffer
109 size setup without duplicating their code.
112 set_block_size (_session.get_block_size());
113 allocate_temporary_buffers ();
116 assert(_n_channels == ChanCount(DataType::AUDIO, 1));
119 AudioDiskstream::~AudioDiskstream ()
124 RCUWriter<ChannelList> writer (channels);
125 boost::shared_ptr<ChannelList> c = writer.get_copy();
127 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
138 AudioDiskstream::allocate_working_buffers()
140 assert(disk_io_frames() > 0);
142 _working_buffers_size = disk_io_frames();
143 _mixdown_buffer = new Sample[_working_buffers_size];
144 _gain_buffer = new gain_t[_working_buffers_size];
148 AudioDiskstream::free_working_buffers()
150 delete [] _mixdown_buffer;
151 delete [] _gain_buffer;
152 _working_buffers_size = 0;
158 AudioDiskstream::non_realtime_input_change ()
161 Glib::Mutex::Lock lm (state_lock);
163 if (input_change_pending == NoChange) {
168 RCUWriter<ChannelList> writer (channels);
169 boost::shared_ptr<ChannelList> c = writer.get_copy();
171 _n_channels.set(DataType::AUDIO, c->size());
173 if (_io->n_inputs().n_audio() > _n_channels.n_audio()) {
174 add_channel_to (c, _io->n_inputs().n_audio() - _n_channels.n_audio());
175 } else if (_io->n_inputs().n_audio() < _n_channels.n_audio()) {
176 remove_channel_from (c, _n_channels.n_audio() - _io->n_inputs().n_audio());
180 get_input_sources ();
181 set_capture_offset ();
183 if (first_input_change) {
184 set_align_style (_persistent_alignment_style);
185 first_input_change = false;
187 set_align_style_from_io ();
190 input_change_pending = NoChange;
192 /* implicit unlock */
195 /* reset capture files */
197 reset_write_sources (false);
199 /* now refill channel buffers */
201 if (speed() != 1.0f || speed() != -1.0f) {
202 seek ((nframes_t) (_session.transport_frame() * (double) speed()));
204 seek (_session.transport_frame());
209 AudioDiskstream::non_realtime_locate (nframes_t location)
211 /* now refill channel buffers */
213 if (speed() != 1.0f || speed() != -1.0f) {
214 seek ((nframes_t) (location * (double) speed()));
221 AudioDiskstream::get_input_sources ()
223 boost::shared_ptr<ChannelList> c = channels.reader();
226 ChannelList::iterator chan;
227 uint32_t ni = _io->n_inputs().n_audio();
228 vector<string> connections;
230 for (n = 0, chan = c->begin(); chan != c->end() && n < ni; ++chan, ++n) {
232 connections.clear ();
234 if (_io->input(n)->get_connections (connections) == 0) {
236 if ((*chan)->source) {
237 // _source->disable_metering ();
243 (*chan)->source = dynamic_cast<AudioPort*>(_session.engine().get_port_by_name (connections[0]) );
249 AudioDiskstream::find_and_use_playlist (const string& name)
251 boost::shared_ptr<AudioPlaylist> playlist;
253 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (_session.playlist_by_name (name))) == 0) {
254 playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, name));
258 error << string_compose(_("AudioDiskstream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
262 return use_playlist (playlist);
266 AudioDiskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
268 assert(boost::dynamic_pointer_cast<AudioPlaylist>(playlist));
270 Diskstream::use_playlist(playlist);
276 AudioDiskstream::use_new_playlist ()
279 boost::shared_ptr<AudioPlaylist> playlist;
281 if (!in_set_state && destructive()) {
286 newname = Playlist::bump_name (_playlist->name(), _session);
288 newname = Playlist::bump_name (_name, _session);
291 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, newname, hidden()))) != 0) {
293 playlist->set_orig_diskstream_id (id());
294 return use_playlist (playlist);
302 AudioDiskstream::use_copy_playlist ()
304 assert(audio_playlist());
310 if (_playlist == 0) {
311 error << string_compose(_("AudioDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
316 boost::shared_ptr<AudioPlaylist> playlist;
318 newname = Playlist::bump_name (_playlist->name(), _session);
320 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist>(PlaylistFactory::create (audio_playlist(), newname))) != 0) {
321 playlist->set_orig_diskstream_id (id());
322 return use_playlist (playlist);
329 AudioDiskstream::setup_destructive_playlist ()
332 boost::shared_ptr<ChannelList> c = channels.reader();
334 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
335 srcs.push_back ((*chan)->write_source);
338 /* a single full-sized region */
340 boost::shared_ptr<Region> region (RegionFactory::create (srcs, 0, max_frames - srcs.front()->natural_position(), _name));
341 _playlist->add_region (region, srcs.front()->natural_position());
345 AudioDiskstream::use_destructive_playlist ()
347 /* this is called from the XML-based constructor or ::set_destructive. when called,
348 we already have a playlist and a region, but we need to
349 set up our sources for write. we use the sources associated
350 with the (presumed single, full-extent) region.
353 boost::shared_ptr<Region> rp = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
356 reset_write_sources (false, true);
360 boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
363 throw failed_constructor();
366 /* be sure to stretch the region out to the maximum length */
368 region->set_length (max_frames - region->position(), this);
371 ChannelList::iterator chan;
372 boost::shared_ptr<ChannelList> c = channels.reader();
374 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
375 (*chan)->write_source = boost::dynamic_pointer_cast<AudioFileSource>(region->source (n));
376 assert((*chan)->write_source);
377 (*chan)->write_source->set_allow_remove_if_empty (false);
379 /* this might be false if we switched modes, so force it */
381 (*chan)->write_source->set_destructive (true);
384 /* the source list will never be reset for a destructive track */
388 AudioDiskstream::check_record_status (nframes_t transport_frame, nframes_t nframes, bool can_record)
390 int possibly_recording;
393 const int transport_rolling = 0x4;
394 const int track_rec_enabled = 0x2;
395 const int global_rec_enabled = 0x1;
397 /* merge together the 3 factors that affect record status, and compute
401 rolling = _session.transport_speed() != 0.0f;
402 possibly_recording = (rolling << 2) | (record_enabled() << 1) | can_record;
403 change = possibly_recording ^ last_possibly_recording;
405 if (possibly_recording == last_possibly_recording) {
411 /* if per-track or global rec-enable turned on while the other was already on, we've started recording */
413 if (((change & track_rec_enabled) && record_enabled() && (!(change & global_rec_enabled) && can_record)) ||
414 ((change & global_rec_enabled) && can_record && (!(change & track_rec_enabled) && record_enabled()))) {
416 /* starting to record: compute first+last frames */
418 first_recordable_frame = transport_frame + _capture_offset;
419 last_recordable_frame = max_frames;
420 capture_start_frame = transport_frame;
422 if (!(last_possibly_recording & transport_rolling) && (possibly_recording & transport_rolling)) {
424 /* was stopped, now rolling (and recording) */
426 if (_alignment_style == ExistingMaterial) {
427 first_recordable_frame += _session.worst_output_latency();
429 first_recordable_frame += _roll_delay;
434 /* was rolling, but record state changed */
436 if (_alignment_style == ExistingMaterial) {
438 if (!Config->get_punch_in()) {
440 /* manual punch in happens at the correct transport frame
441 because the user hit a button. but to get alignment correct
442 we have to back up the position of the new region to the
443 appropriate spot given the roll delay.
446 capture_start_frame -= _roll_delay;
448 /* XXX paul notes (august 2005): i don't know why
452 first_recordable_frame += _capture_offset;
456 /* autopunch toggles recording at the precise
457 transport frame, and then the DS waits
458 to start recording for a time that depends
459 on the output latency.
462 first_recordable_frame += _session.worst_output_latency();
467 if (Config->get_punch_in()) {
468 first_recordable_frame += _roll_delay;
470 capture_start_frame -= _roll_delay;
476 if (recordable() && destructive()) {
477 boost::shared_ptr<ChannelList> c = channels.reader();
478 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
480 RingBufferNPT<CaptureTransition>::rw_vector transvec;
481 (*chan)->capture_transition_buf->get_write_vector(&transvec);
483 if (transvec.len[0] > 0) {
484 transvec.buf[0]->type = CaptureStart;
485 transvec.buf[0]->capture_val = capture_start_frame;
486 (*chan)->capture_transition_buf->increment_write_ptr(1);
490 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
496 } else if (!record_enabled() || !can_record) {
500 last_recordable_frame = transport_frame + _capture_offset;
502 if (_alignment_style == ExistingMaterial) {
503 last_recordable_frame += _session.worst_output_latency();
505 last_recordable_frame += _roll_delay;
509 last_possibly_recording = possibly_recording;
513 AudioDiskstream::process (nframes_t transport_frame, nframes_t nframes, nframes_t offset, bool can_record, bool rec_monitors_input)
516 boost::shared_ptr<ChannelList> c = channels.reader();
517 ChannelList::iterator chan;
519 nframes_t rec_offset = 0;
520 nframes_t rec_nframes = 0;
521 bool nominally_recording;
522 bool re = record_enabled ();
523 bool collect_playback = false;
525 /* if we've already processed the frames corresponding to this call,
526 just return. this allows multiple routes that are taking input
527 from this diskstream to call our ::process() method, but have
528 this stuff only happen once. more commonly, it allows both
529 the AudioTrack that is using this AudioDiskstream *and* the Session
530 to call process() without problems.
537 commit_should_unlock = false;
539 if (!_io || !_io->active()) {
544 check_record_status (transport_frame, nframes, can_record);
546 nominally_recording = (can_record && re);
553 /* This lock is held until the end of AudioDiskstream::commit, so these two functions
554 must always be called as a pair. The only exception is if this function
555 returns a non-zero value, in which case, ::commit should not be called.
558 // If we can't take the state lock return.
559 if (!state_lock.trylock()) {
562 commit_should_unlock = true;
563 adjust_capture_position = 0;
565 for (chan = c->begin(); chan != c->end(); ++chan) {
566 (*chan)->current_capture_buffer = 0;
567 (*chan)->current_playback_buffer = 0;
570 if (nominally_recording || (_session.get_record_enabled() && Config->get_punch_in())) {
573 // Safeguard against situations where process() goes haywire when autopunching and last_recordable_frame < first_recordable_frame
574 if (last_recordable_frame < first_recordable_frame) {
575 last_recordable_frame = max_frames;
578 ot = coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
585 case OverlapInternal:
586 /* ---------- recrange
589 rec_nframes = nframes;
594 /* |--------| recrange
597 rec_nframes = transport_frame + nframes - first_recordable_frame;
599 rec_offset = first_recordable_frame - transport_frame;
604 /* |--------| recrange
607 rec_nframes = last_recordable_frame - transport_frame;
611 case OverlapExternal:
612 /* |--------| recrange
613 -------------- transrange
615 rec_nframes = last_recordable_frame - first_recordable_frame;
616 rec_offset = first_recordable_frame - transport_frame;
620 if (rec_nframes && !was_recording) {
621 capture_captured = 0;
622 was_recording = true;
627 if (can_record && !_last_capture_regions.empty()) {
628 _last_capture_regions.clear ();
631 if (nominally_recording || rec_nframes) {
633 uint32_t limit = _io->n_inputs ().n_audio();
635 /* one or more ports could already have been removed from _io, but our
636 channel setup hasn't yet been updated. prevent us from trying to
637 use channels that correspond to missing ports. note that the
638 process callback (from which this is called) is always atomic
639 with respect to port removal/addition.
642 for (n = 0, chan = c->begin(); chan != c->end() && n < limit; ++chan, ++n) {
644 ChannelInfo* chaninfo (*chan);
646 chaninfo->capture_buf->get_write_vector (&chaninfo->capture_vector);
648 if (rec_nframes <= chaninfo->capture_vector.len[0]) {
650 chaninfo->current_capture_buffer = chaninfo->capture_vector.buf[0];
652 /* note: grab the entire port buffer, but only copy what we were supposed to for recording, and use
656 AudioPort* const ap = _io->audio_input(n);
658 assert(rec_nframes <= ap->get_audio_buffer().capacity());
659 memcpy (chaninfo->current_capture_buffer, ap->get_audio_buffer().data(rec_nframes, offset + rec_offset), sizeof (Sample) * rec_nframes);
663 nframes_t total = chaninfo->capture_vector.len[0] + chaninfo->capture_vector.len[1];
665 if (rec_nframes > total) {
670 AudioPort* const ap = _io->audio_input(n);
673 Sample* buf = ap->get_audio_buffer().data(nframes, offset);
674 nframes_t first = chaninfo->capture_vector.len[0];
676 memcpy (chaninfo->capture_wrap_buffer, buf, sizeof (Sample) * first);
677 memcpy (chaninfo->capture_vector.buf[0], buf, sizeof (Sample) * first);
678 memcpy (chaninfo->capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
679 memcpy (chaninfo->capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
681 chaninfo->current_capture_buffer = chaninfo->capture_wrap_buffer;
688 finish_capture (rec_monitors_input, c);
695 /* data will be written to disk */
697 if (rec_nframes == nframes && rec_offset == 0) {
699 for (chan = c->begin(); chan != c->end(); ++chan) {
700 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
703 playback_distance = nframes;
708 /* we can't use the capture buffer as the playback buffer, because
709 we recorded only a part of the current process' cycle data
713 collect_playback = true;
716 adjust_capture_position = rec_nframes;
718 } else if (nominally_recording) {
720 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
722 for (chan = c->begin(); chan != c->end(); ++chan) {
723 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
726 playback_distance = nframes;
730 collect_playback = true;
733 if (collect_playback) {
735 /* we're doing playback */
737 nframes_t necessary_samples;
739 /* no varispeed playback if we're recording, because the output .... TBD */
741 if (rec_nframes == 0 && _actual_speed != 1.0f) {
742 necessary_samples = (nframes_t) floor ((nframes * fabs (_actual_speed))) + 1;
744 necessary_samples = nframes;
747 for (chan = c->begin(); chan != c->end(); ++chan) {
748 (*chan)->playback_buf->get_read_vector (&(*chan)->playback_vector);
753 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
755 ChannelInfo* chaninfo (*chan);
757 if (necessary_samples <= chaninfo->playback_vector.len[0]) {
759 chaninfo->current_playback_buffer = chaninfo->playback_vector.buf[0];
762 nframes_t total = chaninfo->playback_vector.len[0] + chaninfo->playback_vector.len[1];
764 if (necessary_samples > total) {
765 cerr << "underrun for " << _name << endl;
771 memcpy ((char *) chaninfo->playback_wrap_buffer, chaninfo->playback_vector.buf[0],
772 chaninfo->playback_vector.len[0] * sizeof (Sample));
773 memcpy (chaninfo->playback_wrap_buffer + chaninfo->playback_vector.len[0], chaninfo->playback_vector.buf[1],
774 (necessary_samples - chaninfo->playback_vector.len[0]) * sizeof (Sample));
776 chaninfo->current_playback_buffer = chaninfo->playback_wrap_buffer;
781 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
783 uint64_t phase = last_phase;
787 // Linearly interpolate into the alt buffer
788 // using 40.24 fixp maths (swh)
790 if (phi != target_phi) {
791 phi_delta = ((int64_t)(target_phi - phi)) / nframes;
796 for (chan = c->begin(); chan != c->end(); ++chan) {
799 ChannelInfo* chaninfo (*chan);
804 for (nframes_t outsample = 0; outsample < nframes; ++outsample) {
806 fr = (phase & 0xFFFFFF) / 16777216.0f;
807 chaninfo->speed_buffer[outsample] =
808 chaninfo->current_playback_buffer[i] * (1.0f - fr) +
809 chaninfo->current_playback_buffer[i+1] * fr;
810 phase += phi + phi_delta;
813 chaninfo->current_playback_buffer = chaninfo->speed_buffer;
816 playback_distance = i; // + 1;
817 last_phase = (phase & 0xFFFFFF);
820 playback_distance = nframes;
834 /* we're exiting with failure, so ::commit will not
835 be called. unlock the state lock.
838 commit_should_unlock = false;
846 AudioDiskstream::commit (nframes_t nframes)
848 bool need_butler = false;
850 if (!_io || !_io->active()) {
854 if (_actual_speed < 0.0) {
855 playback_sample -= playback_distance;
857 playback_sample += playback_distance;
860 boost::shared_ptr<ChannelList> c = channels.reader();
861 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
863 (*chan)->playback_buf->increment_read_ptr (playback_distance);
865 if (adjust_capture_position) {
866 (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
870 if (adjust_capture_position != 0) {
871 capture_captured += adjust_capture_position;
872 adjust_capture_position = 0;
876 if (_io && _io->active()) {
877 need_butler = c->front()->playback_buf->write_space() >= c->front()->playback_buf->bufsize() / 2;
882 if (_io && _io->active()) {
883 need_butler = c->front()->playback_buf->write_space() >= disk_io_chunk_frames
884 || c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
886 need_butler = c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
890 if (commit_should_unlock) {
900 AudioDiskstream::set_pending_overwrite (bool yn)
902 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
904 pending_overwrite = yn;
906 overwrite_frame = playback_sample;
907 overwrite_offset = channels.reader()->front()->playback_buf->get_read_ptr();
911 AudioDiskstream::overwrite_existing_buffers ()
913 boost::shared_ptr<ChannelList> c = channels.reader();
914 Sample* mixdown_buffer;
917 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
919 overwrite_queued = false;
921 /* assume all are the same size */
922 nframes_t size = c->front()->playback_buf->bufsize();
924 mixdown_buffer = new Sample[size];
925 gain_buffer = new float[size];
927 /* reduce size so that we can fill the buffer correctly. */
933 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
935 start = overwrite_frame;
936 nframes_t cnt = size;
938 /* to fill the buffer without resetting the playback sample, we need to
939 do it one or two chunks (normally two).
941 |----------------------------------------------------------------------|
945 |<- second chunk->||<----------------- first chunk ------------------>|
949 nframes_t to_read = size - overwrite_offset;
951 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, *chan, n, reversed)) {
952 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
953 _id, size, playback_sample) << endmsg;
961 if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer,
962 start, cnt, *chan, n, reversed)) {
963 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
964 _id, size, playback_sample) << endmsg;
973 pending_overwrite = false;
974 delete [] gain_buffer;
975 delete [] mixdown_buffer;
980 AudioDiskstream::seek (nframes_t frame, bool complete_refill)
984 ChannelList::iterator chan;
985 boost::shared_ptr<ChannelList> c = channels.reader();
987 Glib::Mutex::Lock lm (state_lock);
989 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
990 (*chan)->playback_buf->reset ();
991 (*chan)->capture_buf->reset ();
994 /* can't rec-enable in destructive mode if transport is before start */
996 if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
997 disengage_record_enable ();
1000 playback_sample = frame;
1003 if (complete_refill) {
1004 while ((ret = do_refill_with_alloc ()) > 0) ;
1006 ret = do_refill_with_alloc ();
1013 AudioDiskstream::can_internal_playback_seek (nframes_t distance)
1015 ChannelList::iterator chan;
1016 boost::shared_ptr<ChannelList> c = channels.reader();
1018 for (chan = c->begin(); chan != c->end(); ++chan) {
1019 if ((*chan)->playback_buf->read_space() < distance) {
1027 AudioDiskstream::internal_playback_seek (nframes_t distance)
1029 ChannelList::iterator chan;
1030 boost::shared_ptr<ChannelList> c = channels.reader();
1032 for (chan = c->begin(); chan != c->end(); ++chan) {
1033 (*chan)->playback_buf->increment_read_ptr (distance);
1036 first_recordable_frame += distance;
1037 playback_sample += distance;
1043 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer, nframes_t& start, nframes_t cnt,
1044 ChannelInfo* channel_info, int channel, bool reversed)
1046 nframes_t this_read = 0;
1047 bool reloop = false;
1048 nframes_t loop_end = 0;
1049 nframes_t loop_start = 0;
1050 nframes_t loop_length = 0;
1051 nframes_t offset = 0;
1054 /* XXX we don't currently play loops in reverse. not sure why */
1058 /* Make the use of a Location atomic for this read operation.
1060 Note: Locations don't get deleted, so all we care about
1061 when I say "atomic" is that we are always pointing to
1062 the same one and using a start/length values obtained
1066 if ((loc = loop_location) != 0) {
1067 loop_start = loc->start();
1068 loop_end = loc->end();
1069 loop_length = loop_end - loop_start;
1072 /* if we are looping, ensure that the first frame we read is at the correct
1073 position within the loop.
1076 if (loc && start >= loop_end) {
1077 //cerr << "start adjusted from " << start;
1078 start = loop_start + ((start - loop_start) % loop_length);
1079 //cerr << "to " << start << endl;
1082 //cerr << "start is " << start << " loopstart: " << loop_start << " loopend: " << loop_end << endl;
1091 /* take any loop into account. we can't read past the end of the loop. */
1093 if (loc && (loop_end - start < cnt)) {
1094 this_read = loop_end - start;
1095 //cerr << "reloop true: thisread: " << this_read << " cnt: " << cnt << endl;
1102 if (this_read == 0) {
1106 this_read = min(cnt,this_read);
1108 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
1109 error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), _id, this_read,
1114 _read_data_count = _playlist->read_data_count();
1118 swap_by_ptr (buf, buf + this_read - 1);
1122 /* if we read to the end of the loop, go back to the beginning */
1132 offset += this_read;
1139 AudioDiskstream::do_refill_with_alloc ()
1141 Sample* mix_buf = new Sample[disk_io_chunk_frames];
1142 float* gain_buf = new float[disk_io_chunk_frames];
1144 int ret = _do_refill(mix_buf, gain_buf);
1153 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer)
1157 RingBufferNPT<Sample>::rw_vector vector;
1158 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1159 nframes_t total_space;
1160 nframes_t zero_fill;
1162 ChannelList::iterator i;
1163 boost::shared_ptr<ChannelList> c = channels.reader();
1170 assert(mixdown_buffer);
1171 assert(gain_buffer);
1178 c->front()->playback_buf->get_write_vector (&vector);
1180 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1184 /* if there are 2+ chunks of disk i/o possible for
1185 this track, let the caller know so that it can arrange
1186 for us to be called again, ASAP.
1189 if (total_space >= (_slaved?3:2) * disk_io_chunk_frames) {
1193 /* if we're running close to normal speed and there isn't enough
1194 space to do disk_io_chunk_frames of I/O, then don't bother.
1196 at higher speeds, just do it because the sync between butler
1197 and audio thread may not be good enough.
1200 if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1204 /* when slaved, don't try to get too close to the read pointer. this
1205 leaves space for the buffer reversal to have something useful to
1209 if (_slaved && total_space < (c->front()->playback_buf->bufsize() / 2)) {
1213 /* never do more than disk_io_chunk_frames worth of disk input per call (limit doesn't apply for memset) */
1215 total_space = min (disk_io_chunk_frames, total_space);
1219 if (file_frame == 0) {
1221 /* at start: nothing to do but fill with silence */
1223 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1225 ChannelInfo* chan (*i);
1226 chan->playback_buf->get_write_vector (&vector);
1227 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1228 if (vector.len[1]) {
1229 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1231 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1236 if (file_frame < total_space) {
1238 /* too close to the start: read what we can,
1239 and then zero fill the rest
1242 zero_fill = total_space - file_frame;
1243 total_space = file_frame;
1253 if (file_frame == max_frames) {
1255 /* at end: nothing to do but fill with silence */
1257 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1259 ChannelInfo* chan (*i);
1260 chan->playback_buf->get_write_vector (&vector);
1261 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1262 if (vector.len[1]) {
1263 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1265 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1270 if (file_frame > max_frames - total_space) {
1272 /* to close to the end: read what we can, and zero fill the rest */
1274 zero_fill = total_space - (max_frames - file_frame);
1275 total_space = max_frames - file_frame;
1282 nframes_t file_frame_tmp = 0;
1284 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1286 ChannelInfo* chan (*i);
1289 nframes_t len1, len2;
1291 chan->playback_buf->get_write_vector (&vector);
1293 if (vector.len[0] > disk_io_chunk_frames) {
1295 /* we're not going to fill the first chunk, so certainly do not bother with the
1296 other part. it won't be connected with the part we do fill, as in:
1298 .... => writable space
1299 ++++ => readable space
1300 ^^^^ => 1 x disk_io_chunk_frames that would be filled
1302 |......|+++++++++++++|...............................|
1307 So, just pretend that the buf1 part isn't there.
1317 file_frame_tmp = file_frame;
1319 buf1 = vector.buf[0];
1320 len1 = vector.len[0];
1321 buf2 = vector.buf[1];
1322 len2 = vector.len[1];
1324 to_read = min (ts, len1);
1325 to_read = min (to_read, disk_io_chunk_frames);
1329 if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1334 chan->playback_buf->increment_write_ptr (to_read);
1338 to_read = min (ts, len2);
1342 /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1343 so read some or all of vector.len[1] as well.
1346 if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1351 chan->playback_buf->increment_write_ptr (to_read);
1360 file_frame = file_frame_tmp;
1367 /** Flush pending data to disk.
1369 * Important note: this function will write *AT MOST* disk_io_chunk_frames
1370 * of data to disk. it will never write more than that. If it writes that
1371 * much and there is more than that waiting to be written, it will return 1,
1372 * otherwise 0 on success or -1 on failure.
1374 * If there is less than disk_io_chunk_frames to be written, no data will be
1375 * written at all unless @a force_flush is true.
1378 AudioDiskstream::do_flush (Session::RunContext context, bool force_flush)
1382 RingBufferNPT<Sample>::rw_vector vector;
1383 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1386 _write_data_count = 0;
1388 transvec.buf[0] = 0;
1389 transvec.buf[1] = 0;
1393 boost::shared_ptr<ChannelList> c = channels.reader();
1394 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1396 (*chan)->capture_buf->get_read_vector (&vector);
1398 total = vector.len[0] + vector.len[1];
1400 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1404 /* if there are 2+ chunks of disk i/o possible for
1405 this track, let the caller know so that it can arrange
1406 for us to be called again, ASAP.
1408 if we are forcing a flush, then if there is* any* extra
1409 work, let the caller know.
1411 if we are no longer recording and there is any extra work,
1412 let the caller know too.
1415 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1419 to_write = min (disk_io_chunk_frames, (nframes_t) vector.len[0]);
1421 // check the transition buffer when recording destructive
1422 // important that we get this after the capture buf
1424 if (destructive()) {
1425 (*chan)->capture_transition_buf->get_read_vector(&transvec);
1426 size_t transcount = transvec.len[0] + transvec.len[1];
1427 bool have_start = false;
1430 for (ti=0; ti < transcount; ++ti) {
1431 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1433 if (captrans.type == CaptureStart) {
1434 // by definition, the first data we got above represents the given capture pos
1436 (*chan)->write_source->mark_capture_start (captrans.capture_val);
1437 (*chan)->curr_capture_cnt = 0;
1441 else if (captrans.type == CaptureEnd) {
1443 // capture end, the capture_val represents total frames in capture
1445 if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1447 // shorten to make the write a perfect fit
1448 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
1450 if (nto_write < to_write) {
1451 ret = 1; // should we?
1453 to_write = nto_write;
1455 (*chan)->write_source->mark_capture_end ();
1457 // increment past this transition, but go no further
1462 // actually ends just beyond this chunk, so force more work
1470 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1474 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1475 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1479 (*chan)->capture_buf->increment_read_ptr (to_write);
1480 (*chan)->curr_capture_cnt += to_write;
1482 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1484 /* we wrote all of vector.len[0] but it wasn't an entire
1485 disk_io_chunk_frames of data, so arrange for some part
1486 of vector.len[1] to be flushed to disk as well.
1489 to_write = min ((nframes_t)(disk_io_chunk_frames - to_write), (nframes_t) vector.len[1]);
1491 if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1492 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1496 _write_data_count += (*chan)->write_source->write_data_count();
1498 (*chan)->capture_buf->increment_read_ptr (to_write);
1499 (*chan)->curr_capture_cnt += to_write;
1508 AudioDiskstream::transport_stopped (struct tm& when, time_t twhen, bool abort_capture)
1510 uint32_t buffer_position;
1511 bool more_work = true;
1513 boost::shared_ptr<AudioRegion> region;
1514 nframes_t total_capture;
1516 SourceList::iterator src;
1517 ChannelList::iterator chan;
1518 vector<CaptureInfo*>::iterator ci;
1519 boost::shared_ptr<ChannelList> c = channels.reader();
1521 bool mark_write_completed = false;
1523 finish_capture (true, c);
1525 /* butler is already stopped, but there may be work to do
1526 to flush remaining data to disk.
1529 while (more_work && !err) {
1530 switch (do_flush (Session::TransportContext, true)) {
1537 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1542 /* XXX is there anything we can do if err != 0 ? */
1543 Glib::Mutex::Lock lm (capture_info_lock);
1545 if (capture_info.empty()) {
1549 if (abort_capture) {
1551 if (destructive()) {
1555 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1557 if ((*chan)->write_source) {
1559 (*chan)->write_source->mark_for_remove ();
1560 (*chan)->write_source->drop_references ();
1561 (*chan)->write_source.reset ();
1564 /* new source set up in "out" below */
1570 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1571 total_capture += (*ci)->frames;
1574 /* figure out the name for this take */
1576 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1578 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1582 s->update_header (capture_info.front()->start, when, twhen);
1583 s->set_captured_for (_name);
1584 s->mark_immutable ();
1585 if (Config->get_auto_analyse_audio()) {
1586 Analyser::queue_source_for_analysis (s, true);
1591 /* destructive tracks have a single, never changing region */
1593 if (destructive()) {
1595 /* send a signal that any UI can pick up to do the right thing. there is
1596 a small problem here in that a UI may need the peak data to be ready
1597 for the data that was recorded and this isn't interlocked with that
1598 process. this problem is deferred to the UI.
1601 _playlist->Modified();
1605 string whole_file_region_name;
1606 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1608 /* Register a new region with the Session that
1609 describes the entire source. Do this first
1610 so that any sub-regions will obviously be
1611 children of this one (later!)
1615 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, c->front()->write_source->last_capture_start_frame(), total_capture,
1616 whole_file_region_name,
1617 0, AudioRegion::Flag (AudioRegion::DefaultFlags|AudioRegion::Automatic|AudioRegion::WholeFile)));
1619 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1620 region->special_set_position (capture_info.front()->start);
1624 catch (failed_constructor& err) {
1625 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1629 _last_capture_regions.push_back (region);
1631 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1633 XMLNode &before = _playlist->get_state();
1634 _playlist->freeze ();
1636 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1640 _session.region_name (region_name, whole_file_region_name, false);
1642 // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->frames << " add region " << region_name << endl;
1645 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, buffer_position, (*ci)->frames, region_name));
1646 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1649 catch (failed_constructor& err) {
1650 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1651 continue; /* XXX is this OK? */
1654 region->GoingAway.connect (bind (mem_fun (*this, &Diskstream::remove_region_from_last_capture), boost::weak_ptr<Region>(region)));
1656 _last_capture_regions.push_back (region);
1658 i_am_the_modifier++;
1659 _playlist->add_region (region, (*ci)->start);
1660 i_am_the_modifier--;
1662 buffer_position += (*ci)->frames;
1666 XMLNode &after = _playlist->get_state();
1667 _session.add_command (new MementoCommand<Playlist>(*_playlist, &before, &after));
1670 mark_write_completed = true;
1673 reset_write_sources (mark_write_completed);
1677 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1681 capture_info.clear ();
1682 capture_start_frame = 0;
1686 AudioDiskstream::transport_looped (nframes_t transport_frame)
1688 if (was_recording) {
1689 // all we need to do is finish this capture, with modified capture length
1690 boost::shared_ptr<ChannelList> c = channels.reader();
1692 // adjust the capture length knowing that the data will be recorded to disk
1693 // only necessary after the first loop where we're recording
1694 if (capture_info.size() == 0) {
1695 capture_captured += _capture_offset;
1697 if (_alignment_style == ExistingMaterial) {
1698 capture_captured += _session.worst_output_latency();
1700 capture_captured += _roll_delay;
1704 finish_capture (true, c);
1706 // the next region will start recording via the normal mechanism
1707 // we'll set the start position to the current transport pos
1708 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1709 capture_start_frame = transport_frame;
1710 first_recordable_frame = transport_frame; // mild lie
1711 last_recordable_frame = max_frames;
1712 was_recording = true;
1714 if (recordable() && destructive()) {
1715 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1717 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1718 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1720 if (transvec.len[0] > 0) {
1721 transvec.buf[0]->type = CaptureStart;
1722 transvec.buf[0]->capture_val = capture_start_frame;
1723 (*chan)->capture_transition_buf->increment_write_ptr(1);
1727 fatal << X_("programming error: capture_transition_buf is full on rec loop! inconceivable!")
1737 AudioDiskstream::finish_capture (bool rec_monitors_input, boost::shared_ptr<ChannelList> c)
1739 was_recording = false;
1741 if (capture_captured == 0) {
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 = CaptureEnd;
1753 transvec.buf[0]->capture_val = capture_captured;
1754 (*chan)->capture_transition_buf->increment_write_ptr(1);
1758 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1764 CaptureInfo* ci = new CaptureInfo;
1766 ci->start = capture_start_frame;
1767 ci->frames = capture_captured;
1769 /* XXX theoretical race condition here. Need atomic exchange ?
1770 However, the circumstances when this is called right
1771 now (either on record-disable or transport_stopped)
1772 mean that no actual race exists. I think ...
1773 We now have a capture_info_lock, but it is only to be used
1774 to synchronize in the transport_stop and the capture info
1775 accessors, so that invalidation will not occur (both non-realtime).
1778 // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1780 capture_info.push_back (ci);
1781 capture_captured = 0;
1783 /* now we've finished a capture, reset first_recordable_frame for next time */
1784 first_recordable_frame = max_frames;
1788 AudioDiskstream::set_record_enabled (bool yn)
1790 if (!recordable() || !_session.record_enabling_legal() || _io->n_inputs().n_audio() == 0) {
1794 /* can't rec-enable in destructive mode if transport is before start */
1796 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1800 if (yn && channels.reader()->front()->source == 0) {
1802 /* pick up connections not initiated *from* the IO object
1803 we're associated with.
1806 get_input_sources ();
1809 /* yes, i know that this not proof against race conditions, but its
1810 good enough. i think.
1813 if (record_enabled() != yn) {
1815 engage_record_enable ();
1817 disengage_record_enable ();
1823 AudioDiskstream::engage_record_enable ()
1825 bool rolling = _session.transport_speed() != 0.0f;
1826 boost::shared_ptr<ChannelList> c = channels.reader();
1828 g_atomic_int_set (&_record_enabled, 1);
1829 capturing_sources.clear ();
1831 if (Config->get_monitoring_model() == HardwareMonitoring) {
1833 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1834 if ((*chan)->source) {
1835 (*chan)->source->ensure_monitor_input (!(Config->get_auto_input() && rolling));
1837 capturing_sources.push_back ((*chan)->write_source);
1838 (*chan)->write_source->mark_streaming_write_started ();
1842 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1843 capturing_sources.push_back ((*chan)->write_source);
1844 (*chan)->write_source->mark_streaming_write_started ();
1848 RecordEnableChanged (); /* EMIT SIGNAL */
1852 AudioDiskstream::disengage_record_enable ()
1854 g_atomic_int_set (&_record_enabled, 0);
1855 boost::shared_ptr<ChannelList> c = channels.reader();
1856 if (Config->get_monitoring_model() == HardwareMonitoring) {
1857 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1858 if ((*chan)->source) {
1859 (*chan)->source->ensure_monitor_input (false);
1863 capturing_sources.clear ();
1864 RecordEnableChanged (); /* EMIT SIGNAL */
1868 AudioDiskstream::get_state ()
1870 XMLNode* node = new XMLNode ("AudioDiskstream");
1872 LocaleGuard lg (X_("POSIX"));
1873 boost::shared_ptr<ChannelList> c = channels.reader();
1875 node->add_property ("flags", enum_2_string (_flags));
1877 snprintf (buf, sizeof(buf), "%zd", c->size());
1878 node->add_property ("channels", buf);
1880 node->add_property ("playlist", _playlist->name());
1882 snprintf (buf, sizeof(buf), "%.12g", _visible_speed);
1883 node->add_property ("speed", buf);
1885 node->add_property("name", _name);
1886 id().print (buf, sizeof (buf));
1887 node->add_property("id", buf);
1889 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1891 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1892 XMLNode* cs_grandchild;
1894 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1895 cs_grandchild = new XMLNode (X_("file"));
1896 cs_grandchild->add_property (X_("path"), (*i)->path());
1897 cs_child->add_child_nocopy (*cs_grandchild);
1900 /* store the location where capture will start */
1904 if (Config->get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1905 snprintf (buf, sizeof (buf), "%" PRIu32, pi->start());
1907 snprintf (buf, sizeof (buf), "%" PRIu32, _session.transport_frame());
1910 cs_child->add_property (X_("at"), buf);
1911 node->add_child_nocopy (*cs_child);
1915 node->add_child_copy (*_extra_xml);
1922 AudioDiskstream::set_state (const XMLNode& node)
1924 const XMLProperty* prop;
1925 XMLNodeList nlist = node.children();
1926 XMLNodeIterator niter;
1927 uint32_t nchans = 1;
1928 XMLNode* capture_pending_node = 0;
1929 LocaleGuard lg (X_("POSIX"));
1931 in_set_state = true;
1933 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1934 if ((*niter)->name() == IO::state_node_name) {
1935 deprecated_io_node = new XMLNode (**niter);
1938 if ((*niter)->name() == X_("CapturingSources")) {
1939 capture_pending_node = *niter;
1943 /* prevent write sources from being created */
1945 in_set_state = true;
1947 if ((prop = node.property ("name")) != 0) {
1948 _name = prop->value();
1951 if (deprecated_io_node) {
1952 if ((prop = deprecated_io_node->property ("id")) != 0) {
1953 _id = prop->value ();
1956 if ((prop = node.property ("id")) != 0) {
1957 _id = prop->value ();
1961 if ((prop = node.property ("flags")) != 0) {
1962 _flags = Flag (string_2_enum (prop->value(), _flags));
1965 if ((prop = node.property ("channels")) != 0) {
1966 nchans = atoi (prop->value().c_str());
1969 // create necessary extra channels
1970 // we are always constructed with one and we always need one
1972 _n_channels.set(DataType::AUDIO, channels.reader()->size());
1974 if (nchans > _n_channels.n_audio()) {
1976 add_channel (nchans - _n_channels.n_audio());
1977 IO::PortCountChanged(_n_channels);
1979 } else if (nchans < _n_channels.n_audio()) {
1981 remove_channel (_n_channels.n_audio() - nchans);
1984 if ((prop = node.property ("playlist")) == 0) {
1989 bool had_playlist = (_playlist != 0);
1991 if (find_and_use_playlist (prop->value())) {
1995 if (!had_playlist) {
1996 _playlist->set_orig_diskstream_id (_id);
1999 if (!destructive() && capture_pending_node) {
2000 /* destructive streams have one and only one source per channel,
2001 and so they never end up in pending capture in any useful
2004 use_pending_capture_data (*capture_pending_node);
2009 if ((prop = node.property ("speed")) != 0) {
2010 double sp = atof (prop->value().c_str());
2012 if (realtime_set_speed (sp, false)) {
2013 non_realtime_set_speed ();
2017 in_set_state = false;
2019 /* make sure this is clear before we do anything else */
2021 capturing_sources.clear ();
2023 /* write sources are handled when we handle the input set
2024 up of the IO that owns this DS (::non_realtime_input_change())
2031 AudioDiskstream::use_new_write_source (uint32_t n)
2033 boost::shared_ptr<ChannelList> c = channels.reader();
2035 if (!recordable()) {
2039 if (n >= c->size()) {
2040 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
2044 ChannelInfo* chan = (*c)[n];
2046 if (chan->write_source) {
2047 chan->write_source->done_with_peakfile_writes ();
2048 chan->write_source->set_allow_remove_if_empty (true);
2049 chan->write_source.reset ();
2053 if ((chan->write_source = _session.create_audio_source_for_session (*this, n, destructive())) == 0) {
2054 throw failed_constructor();
2058 catch (failed_constructor &err) {
2059 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
2060 chan->write_source.reset ();
2064 /* do not remove destructive files even if they are empty */
2066 chan->write_source->set_allow_remove_if_empty (!destructive());
2072 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool force)
2074 ChannelList::iterator chan;
2075 boost::shared_ptr<ChannelList> c = channels.reader();
2078 if (!recordable()) {
2082 capturing_sources.clear ();
2084 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
2085 if (!destructive()) {
2087 if ((*chan)->write_source && mark_write_complete) {
2088 (*chan)->write_source->mark_streaming_write_completed ();
2090 use_new_write_source (n);
2092 if (record_enabled()) {
2093 capturing_sources.push_back ((*chan)->write_source);
2097 if ((*chan)->write_source == 0) {
2098 use_new_write_source (n);
2103 if (destructive()) {
2105 /* we now have all our write sources set up, so create the
2106 playlist's single region.
2109 if (_playlist->empty()) {
2110 setup_destructive_playlist ();
2116 AudioDiskstream::rename_write_sources ()
2118 ChannelList::iterator chan;
2119 boost::shared_ptr<ChannelList> c = channels.reader();
2122 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
2123 if ((*chan)->write_source != 0) {
2124 (*chan)->write_source->set_source_name (_name, destructive());
2125 /* XXX what to do if one of them fails ? */
2133 AudioDiskstream::set_block_size (nframes_t nframes)
2135 if (_session.get_block_size() > speed_buffer_size) {
2136 speed_buffer_size = _session.get_block_size();
2137 boost::shared_ptr<ChannelList> c = channels.reader();
2139 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2140 if ((*chan)->speed_buffer) delete [] (*chan)->speed_buffer;
2141 (*chan)->speed_buffer = new Sample[speed_buffer_size];
2144 allocate_temporary_buffers ();
2148 AudioDiskstream::allocate_temporary_buffers ()
2150 /* make sure the wrap buffer is at least large enough to deal
2151 with the speeds up to 1.2, to allow for micro-variation
2152 when slaving to MTC, SMPTE etc.
2155 double sp = max (fabsf (_actual_speed), 1.2f);
2156 nframes_t required_wrap_size = (nframes_t) floor (_session.get_block_size() * sp) + 1;
2158 if (required_wrap_size > wrap_buffer_size) {
2160 boost::shared_ptr<ChannelList> c = channels.reader();
2162 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2163 if ((*chan)->playback_wrap_buffer) delete [] (*chan)->playback_wrap_buffer;
2164 (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
2165 if ((*chan)->capture_wrap_buffer) delete [] (*chan)->capture_wrap_buffer;
2166 (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
2169 wrap_buffer_size = required_wrap_size;
2174 AudioDiskstream::monitor_input (bool yn)
2176 boost::shared_ptr<ChannelList> c = channels.reader();
2178 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2180 if ((*chan)->source) {
2181 (*chan)->source->ensure_monitor_input (yn);
2187 AudioDiskstream::set_align_style_from_io ()
2189 bool have_physical = false;
2195 get_input_sources ();
2197 boost::shared_ptr<ChannelList> c = channels.reader();
2199 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2200 if ((*chan)->source && (*chan)->source->flags() & JackPortIsPhysical) {
2201 have_physical = true;
2206 if (have_physical) {
2207 set_align_style (ExistingMaterial);
2209 set_align_style (CaptureTime);
2214 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2216 while (how_many--) {
2217 c->push_back (new ChannelInfo(_session.audio_diskstream_buffer_size(), speed_buffer_size, wrap_buffer_size));
2220 _n_channels.set(DataType::AUDIO, c->size());
2226 AudioDiskstream::add_channel (uint32_t how_many)
2228 RCUWriter<ChannelList> writer (channels);
2229 boost::shared_ptr<ChannelList> c = writer.get_copy();
2231 return add_channel_to (c, how_many);
2235 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2237 while (how_many-- && !c->empty()) {
2242 _n_channels.set(DataType::AUDIO, c->size());
2248 AudioDiskstream::remove_channel (uint32_t how_many)
2250 RCUWriter<ChannelList> writer (channels);
2251 boost::shared_ptr<ChannelList> c = writer.get_copy();
2253 return remove_channel_from (c, how_many);
2257 AudioDiskstream::playback_buffer_load () const
2259 boost::shared_ptr<ChannelList> c = channels.reader();
2261 return (float) ((double) c->front()->playback_buf->read_space()/
2262 (double) c->front()->playback_buf->bufsize());
2266 AudioDiskstream::capture_buffer_load () const
2268 boost::shared_ptr<ChannelList> c = channels.reader();
2270 return (float) ((double) c->front()->capture_buf->write_space()/
2271 (double) c->front()->capture_buf->bufsize());
2275 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2277 const XMLProperty* prop;
2278 XMLNodeList nlist = node.children();
2279 XMLNodeIterator niter;
2280 boost::shared_ptr<AudioFileSource> fs;
2281 boost::shared_ptr<AudioFileSource> first_fs;
2282 SourceList pending_sources;
2285 if ((prop = node.property (X_("at"))) == 0) {
2289 if (sscanf (prop->value().c_str(), "%" PRIu32, &position) != 1) {
2293 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2294 if ((*niter)->name() == X_("file")) {
2296 if ((prop = (*niter)->property (X_("path"))) == 0) {
2300 // This protects sessions from errant CapturingSources in stored sessions
2302 if (stat (prop->value().c_str(), &sbuf)) {
2307 fs = boost::dynamic_pointer_cast<AudioFileSource> (
2308 SourceFactory::createWritable (DataType::AUDIO, _session, prop->value(), false, _session.frame_rate()));
2311 catch (failed_constructor& err) {
2312 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2313 _name, prop->value())
2318 pending_sources.push_back (fs);
2320 if (first_fs == 0) {
2324 fs->set_captured_for (_name);
2328 if (pending_sources.size() == 0) {
2329 /* nothing can be done */
2333 if (pending_sources.size() != _n_channels.n_audio()) {
2334 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2339 boost::shared_ptr<AudioRegion> region;
2342 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, 0, first_fs->length(),
2343 region_name_from_path (first_fs->name(), true),
2344 0, AudioRegion::Flag (AudioRegion::DefaultFlags|AudioRegion::Automatic|AudioRegion::WholeFile)));
2345 region->special_set_position (0);
2348 catch (failed_constructor& err) {
2349 error << string_compose (_("%1: cannot create whole-file region from pending capture sources"),
2357 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, 0, first_fs->length(), region_name_from_path (first_fs->name(), true)));
2360 catch (failed_constructor& err) {
2361 error << string_compose (_("%1: cannot create region from pending capture sources"),
2368 _playlist->add_region (region, position);
2374 AudioDiskstream::set_destructive (bool yn)
2376 bool bounce_ignored;
2378 if (yn != destructive()) {
2381 /* requestor should already have checked this and
2382 bounced if necessary and desired
2384 if (!can_become_destructive (bounce_ignored)) {
2387 _flags = Flag (_flags | Destructive);
2388 use_destructive_playlist ();
2390 _flags = Flag (_flags & ~Destructive);
2391 reset_write_sources (true, true);
2399 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2402 requires_bounce = false;
2406 /* is there only one region ? */
2408 if (_playlist->n_regions() != 1) {
2409 requires_bounce = true;
2413 boost::shared_ptr<Region> first = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
2416 /* do the source(s) for the region cover the session start position ? */
2418 if (first->position() != _session.current_start_frame()) {
2419 if (first->start() > _session.current_start_frame()) {
2420 requires_bounce = true;
2425 /* is the source used by only 1 playlist ? */
2427 boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2431 if (afirst->source()->used() > 1) {
2432 requires_bounce = true;
2436 requires_bounce = false;
2440 AudioDiskstream::ChannelInfo::ChannelInfo (nframes_t bufsize, nframes_t speed_size, nframes_t wrap_size)
2444 current_capture_buffer = 0;
2445 current_playback_buffer = 0;
2446 curr_capture_cnt = 0;
2448 speed_buffer = new Sample[speed_size];
2449 playback_wrap_buffer = new Sample[wrap_size];
2450 capture_wrap_buffer = new Sample[wrap_size];
2452 playback_buf = new RingBufferNPT<Sample> (bufsize);
2453 capture_buf = new RingBufferNPT<Sample> (bufsize);
2454 capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2456 /* touch the ringbuffer buffers, which will cause
2457 them to be mapped into locked physical RAM if
2458 we're running with mlockall(). this doesn't do
2462 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2463 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2464 memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2467 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2470 write_source.reset ();
2474 delete [] speed_buffer;
2478 if (playback_wrap_buffer) {
2479 delete [] playback_wrap_buffer;
2480 playback_wrap_buffer = 0;
2483 if (capture_wrap_buffer) {
2484 delete [] capture_wrap_buffer;
2485 capture_wrap_buffer = 0;
2489 delete playback_buf;
2498 if (capture_transition_buf) {
2499 delete capture_transition_buf;
2500 capture_transition_buf = 0;