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 <pbd/basename.h>
35 #include <glibmm/thread.h>
36 #include <pbd/xml++.h>
37 #include <pbd/memento_command.h>
38 #include <pbd/enumwriter.h>
39 #include <pbd/stacktrace.h>
41 #include <ardour/ardour.h>
42 #include <ardour/audioengine.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/source_factory.h>
59 using namespace ARDOUR;
62 size_t AudioDiskstream::_working_buffers_size = 0;
63 Sample* AudioDiskstream::_mixdown_buffer = 0;
64 gain_t* AudioDiskstream::_gain_buffer = 0;
66 AudioDiskstream::AudioDiskstream (Session &sess, const string &name, Diskstream::Flag flag)
67 : Diskstream(sess, name, flag)
68 , deprecated_io_node(NULL)
69 , channels (new ChannelList)
71 /* prevent any write sources from being created */
81 AudioDiskstream::AudioDiskstream (Session& sess, const XMLNode& node)
82 : Diskstream(sess, node)
83 , deprecated_io_node(NULL)
84 , channels (new ChannelList)
89 if (set_state (node)) {
91 throw failed_constructor();
97 use_destructive_playlist ();
102 AudioDiskstream::init (Diskstream::Flag f)
106 /* there are no channels at this point, so these
107 two calls just get speed_buffer_size and wrap_buffer
108 size setup without duplicating their code.
111 set_block_size (_session.get_block_size());
112 allocate_temporary_buffers ();
115 assert(_n_channels == 1);
118 AudioDiskstream::~AudioDiskstream ()
123 RCUWriter<ChannelList> writer (channels);
124 boost::shared_ptr<ChannelList> c = writer.get_copy();
126 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
137 AudioDiskstream::allocate_working_buffers()
139 assert(disk_io_frames() > 0);
141 _working_buffers_size = disk_io_frames();
142 _mixdown_buffer = new Sample[_working_buffers_size];
143 _gain_buffer = new gain_t[_working_buffers_size];
147 AudioDiskstream::free_working_buffers()
149 delete [] _mixdown_buffer;
150 delete [] _gain_buffer;
151 _working_buffers_size = 0;
157 AudioDiskstream::non_realtime_input_change ()
160 Glib::Mutex::Lock lm (state_lock);
162 if (input_change_pending == NoChange) {
167 RCUWriter<ChannelList> writer (channels);
168 boost::shared_ptr<ChannelList> c = writer.get_copy();
170 _n_channels = c->size();
172 if (_io->n_inputs() > _n_channels) {
173 add_channel_to (c, _io->n_inputs() - _n_channels);
174 } else if (_io->n_inputs() < _n_channels) {
175 remove_channel_from (c, _n_channels - _io->n_inputs());
179 get_input_sources ();
180 set_capture_offset ();
182 if (first_input_change) {
183 set_align_style (_persistent_alignment_style);
184 first_input_change = false;
186 set_align_style_from_io ();
189 input_change_pending = NoChange;
191 /* implicit unlock */
194 /* reset capture files */
196 reset_write_sources (false);
198 /* now refill channel buffers */
200 if (speed() != 1.0f || speed() != -1.0f) {
201 seek ((nframes_t) (_session.transport_frame() * (double) speed()));
203 seek (_session.transport_frame());
208 AudioDiskstream::get_input_sources ()
210 boost::shared_ptr<ChannelList> c = channels.reader();
213 ChannelList::iterator chan;
214 uint32_t ni = _io->n_inputs();
216 for (n = 0, chan = c->begin(); chan != c->end() && n < ni; ++chan, ++n) {
218 const char **connections = _io->input(n)->get_connections ();
220 if (connections == 0 || connections[0] == 0) {
222 if ((*chan)->source) {
223 // _source->disable_metering ();
229 (*chan)->source = _session.engine().get_port_by_name (connections[0]);
239 AudioDiskstream::find_and_use_playlist (const string& name)
241 boost::shared_ptr<AudioPlaylist> playlist;
243 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (_session.playlist_by_name (name))) == 0) {
244 playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (_session, name));
248 error << string_compose(_("AudioDiskstream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
252 return use_playlist (playlist);
256 AudioDiskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
258 assert(boost::dynamic_pointer_cast<AudioPlaylist>(playlist));
260 Diskstream::use_playlist(playlist);
266 AudioDiskstream::use_new_playlist ()
269 boost::shared_ptr<AudioPlaylist> playlist;
271 if (!in_set_state && destructive()) {
276 newname = Playlist::bump_name (_playlist->name(), _session);
278 newname = Playlist::bump_name (_name, _session);
281 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (_session, newname, hidden()))) != 0) {
283 playlist->set_orig_diskstream_id (id());
284 return use_playlist (playlist);
292 AudioDiskstream::use_copy_playlist ()
294 assert(audio_playlist());
300 if (_playlist == 0) {
301 error << string_compose(_("AudioDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
306 boost::shared_ptr<AudioPlaylist> playlist;
308 newname = Playlist::bump_name (_playlist->name(), _session);
310 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist>(PlaylistFactory::create (audio_playlist(), newname))) != 0) {
311 playlist->set_orig_diskstream_id (id());
312 return use_playlist (playlist);
319 AudioDiskstream::setup_destructive_playlist ()
322 boost::shared_ptr<ChannelList> c = channels.reader();
324 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
325 srcs.push_back ((*chan)->write_source);
328 /* a single full-sized region */
330 boost::shared_ptr<Region> region (RegionFactory::create (srcs, 0, max_frames - srcs.front()->natural_position(), _name));
331 _playlist->add_region (region, srcs.front()->natural_position());
335 AudioDiskstream::use_destructive_playlist ()
337 /* this is called from the XML-based constructor or ::set_destructive. when called,
338 we already have a playlist and a region, but we need to
339 set up our sources for write. we use the sources associated
340 with the (presumed single, full-extent) region.
343 boost::shared_ptr<Region> rp = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
346 reset_write_sources (false, true);
350 boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
353 throw failed_constructor();
356 /* be sure to stretch the region out to the maximum length */
358 region->set_length (max_frames - region->position(), this);
361 ChannelList::iterator chan;
362 boost::shared_ptr<ChannelList> c = channels.reader();
364 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
365 (*chan)->write_source = boost::dynamic_pointer_cast<AudioFileSource>(region->source (n));
366 assert((*chan)->write_source);
367 (*chan)->write_source->set_allow_remove_if_empty (false);
369 /* this might be false if we switched modes, so force it */
371 (*chan)->write_source->set_destructive (true);
374 /* the source list will never be reset for a destructive track */
378 AudioDiskstream::check_record_status (nframes_t transport_frame, nframes_t nframes, bool can_record)
380 int possibly_recording;
383 const int transport_rolling = 0x4;
384 const int track_rec_enabled = 0x2;
385 const int global_rec_enabled = 0x1;
387 /* merge together the 3 factors that affect record status, and compute
391 rolling = _session.transport_speed() != 0.0f;
392 possibly_recording = (rolling << 2) | (record_enabled() << 1) | can_record;
393 change = possibly_recording ^ last_possibly_recording;
395 if (possibly_recording == last_possibly_recording) {
401 /* if per-track or global rec-enable turned on while the other was already on, we've started recording */
403 if ((change & track_rec_enabled) && record_enabled() && (!(change & global_rec_enabled) && can_record) ||
404 ((change & global_rec_enabled) && can_record && (!(change & track_rec_enabled) && record_enabled()))) {
406 /* starting to record: compute first+last frames */
408 first_recordable_frame = transport_frame + _capture_offset;
409 last_recordable_frame = max_frames;
410 capture_start_frame = transport_frame;
412 if (!(last_possibly_recording & transport_rolling) && (possibly_recording & transport_rolling)) {
414 /* was stopped, now rolling (and recording) */
416 if (_alignment_style == ExistingMaterial) {
417 first_recordable_frame += _session.worst_output_latency();
419 first_recordable_frame += _roll_delay;
424 /* was rolling, but record state changed */
426 if (_alignment_style == ExistingMaterial) {
428 if (!Config->get_punch_in()) {
430 /* manual punch in happens at the correct transport frame
431 because the user hit a button. but to get alignment correct
432 we have to back up the position of the new region to the
433 appropriate spot given the roll delay.
436 capture_start_frame -= _roll_delay;
438 /* XXX paul notes (august 2005): i don't know why
442 first_recordable_frame += _capture_offset;
446 /* autopunch toggles recording at the precise
447 transport frame, and then the DS waits
448 to start recording for a time that depends
449 on the output latency.
452 first_recordable_frame += _session.worst_output_latency();
457 if (Config->get_punch_in()) {
458 first_recordable_frame += _roll_delay;
460 capture_start_frame -= _roll_delay;
466 if (_flags & Recordable) {
467 boost::shared_ptr<ChannelList> c = channels.reader();
468 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
470 RingBufferNPT<CaptureTransition>::rw_vector transvec;
471 (*chan)->capture_transition_buf->get_write_vector(&transvec);
473 if (transvec.len[0] > 0) {
474 transvec.buf[0]->type = CaptureStart;
475 transvec.buf[0]->capture_val = capture_start_frame;
476 (*chan)->capture_transition_buf->increment_write_ptr(1);
480 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
486 } else if (!record_enabled() || !can_record) {
490 last_recordable_frame = transport_frame + _capture_offset;
492 if (_alignment_style == ExistingMaterial) {
493 last_recordable_frame += _session.worst_output_latency();
495 last_recordable_frame += _roll_delay;
499 last_possibly_recording = possibly_recording;
503 AudioDiskstream::process (nframes_t transport_frame, nframes_t nframes, nframes_t offset, bool can_record, bool rec_monitors_input)
506 boost::shared_ptr<ChannelList> c = channels.reader();
507 ChannelList::iterator chan;
509 nframes_t rec_offset = 0;
510 nframes_t rec_nframes = 0;
511 bool nominally_recording;
512 bool re = record_enabled ();
513 bool collect_playback = false;
515 /* if we've already processed the frames corresponding to this call,
516 just return. this allows multiple routes that are taking input
517 from this diskstream to call our ::process() method, but have
518 this stuff only happen once. more commonly, it allows both
519 the AudioTrack that is using this AudioDiskstream *and* the Session
520 to call process() without problems.
527 check_record_status (transport_frame, nframes, can_record);
529 nominally_recording = (can_record && re);
536 /* This lock is held until the end of AudioDiskstream::commit, so these two functions
537 must always be called as a pair. The only exception is if this function
538 returns a non-zero value, in which case, ::commit should not be called.
541 // If we can't take the state lock return.
542 if (!state_lock.trylock()) {
546 adjust_capture_position = 0;
548 for (chan = c->begin(); chan != c->end(); ++chan) {
549 (*chan)->current_capture_buffer = 0;
550 (*chan)->current_playback_buffer = 0;
553 if (nominally_recording || (_session.get_record_enabled() && Config->get_punch_in())) {
556 ot = coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
563 case OverlapInternal:
564 /* ---------- recrange
567 rec_nframes = nframes;
572 /* |--------| recrange
575 rec_nframes = transport_frame + nframes - first_recordable_frame;
577 rec_offset = first_recordable_frame - transport_frame;
582 /* |--------| recrange
585 rec_nframes = last_recordable_frame - transport_frame;
589 case OverlapExternal:
590 /* |--------| recrange
591 -------------- transrange
593 rec_nframes = last_recordable_frame - last_recordable_frame;
594 rec_offset = first_recordable_frame - transport_frame;
598 if (rec_nframes && !was_recording) {
599 capture_captured = 0;
600 was_recording = true;
605 if (can_record && !_last_capture_regions.empty()) {
606 _last_capture_regions.clear ();
609 if (nominally_recording || rec_nframes) {
611 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
613 ChannelInfo* chaninfo (*chan);
615 chaninfo->capture_buf->get_write_vector (&chaninfo->capture_vector);
617 if (rec_nframes <= chaninfo->capture_vector.len[0]) {
619 chaninfo->current_capture_buffer = chaninfo->capture_vector.buf[0];
621 /* note: grab the entire port buffer, but only copy what we were supposed to for recording, and use
625 memcpy (chaninfo->current_capture_buffer, _io->input(n)->get_buffer (rec_nframes) + offset + rec_offset, sizeof (Sample) * rec_nframes);
629 nframes_t total = chaninfo->capture_vector.len[0] + chaninfo->capture_vector.len[1];
631 if (rec_nframes > total) {
636 Sample* buf = _io->input (n)->get_buffer (nframes) + offset;
637 nframes_t first = chaninfo->capture_vector.len[0];
639 memcpy (chaninfo->capture_wrap_buffer, buf, sizeof (Sample) * first);
640 memcpy (chaninfo->capture_vector.buf[0], buf, sizeof (Sample) * first);
641 memcpy (chaninfo->capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
642 memcpy (chaninfo->capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
644 chaninfo->current_capture_buffer = chaninfo->capture_wrap_buffer;
651 finish_capture (rec_monitors_input, c);
658 /* data will be written to disk */
660 if (rec_nframes == nframes && rec_offset == 0) {
662 for (chan = c->begin(); chan != c->end(); ++chan) {
663 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
666 playback_distance = nframes;
671 /* we can't use the capture buffer as the playback buffer, because
672 we recorded only a part of the current process' cycle data
676 collect_playback = true;
679 adjust_capture_position = rec_nframes;
681 } else if (nominally_recording) {
683 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
685 for (chan = c->begin(); chan != c->end(); ++chan) {
686 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
689 playback_distance = nframes;
693 collect_playback = true;
696 if (collect_playback) {
698 /* we're doing playback */
700 nframes_t necessary_samples;
702 /* no varispeed playback if we're recording, because the output .... TBD */
704 if (rec_nframes == 0 && _actual_speed != 1.0f) {
705 necessary_samples = (nframes_t) floor ((nframes * fabs (_actual_speed))) + 1;
707 necessary_samples = nframes;
710 for (chan = c->begin(); chan != c->end(); ++chan) {
711 (*chan)->playback_buf->get_read_vector (&(*chan)->playback_vector);
716 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
718 ChannelInfo* chaninfo (*chan);
720 if (necessary_samples <= chaninfo->playback_vector.len[0]) {
722 chaninfo->current_playback_buffer = chaninfo->playback_vector.buf[0];
725 nframes_t total = chaninfo->playback_vector.len[0] + chaninfo->playback_vector.len[1];
727 if (necessary_samples > total) {
733 memcpy ((char *) chaninfo->playback_wrap_buffer, chaninfo->playback_vector.buf[0],
734 chaninfo->playback_vector.len[0] * sizeof (Sample));
735 memcpy (chaninfo->playback_wrap_buffer + chaninfo->playback_vector.len[0], chaninfo->playback_vector.buf[1],
736 (necessary_samples - chaninfo->playback_vector.len[0]) * sizeof (Sample));
738 chaninfo->current_playback_buffer = chaninfo->playback_wrap_buffer;
743 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
745 uint64_t phase = last_phase;
748 // Linearly interpolate into the alt buffer
749 // using 40.24 fixp maths (swh)
751 for (chan = c->begin(); chan != c->end(); ++chan) {
754 ChannelInfo* chaninfo (*chan);
759 for (nframes_t outsample = 0; outsample < nframes; ++outsample) {
761 fr = (phase & 0xFFFFFF) / 16777216.0f;
762 chaninfo->speed_buffer[outsample] =
763 chaninfo->current_playback_buffer[i] * (1.0f - fr) +
764 chaninfo->current_playback_buffer[i+1] * fr;
768 chaninfo->current_playback_buffer = chaninfo->speed_buffer;
771 playback_distance = i + 1;
772 last_phase = (phase & 0xFFFFFF);
775 playback_distance = nframes;
787 /* we're exiting with failure, so ::commit will not
788 be called. unlock the state lock.
798 AudioDiskstream::commit (nframes_t nframes)
800 bool need_butler = false;
802 if (_actual_speed < 0.0) {
803 playback_sample -= playback_distance;
805 playback_sample += playback_distance;
808 boost::shared_ptr<ChannelList> c = channels.reader();
809 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
811 (*chan)->playback_buf->increment_read_ptr (playback_distance);
813 if (adjust_capture_position) {
814 (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
818 if (adjust_capture_position != 0) {
819 capture_captured += adjust_capture_position;
820 adjust_capture_position = 0;
824 need_butler = c->front()->playback_buf->write_space() >= c->front()->playback_buf->bufsize() / 2;
826 need_butler = c->front()->playback_buf->write_space() >= disk_io_chunk_frames
827 || c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
837 AudioDiskstream::set_pending_overwrite (bool yn)
839 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
841 pending_overwrite = yn;
843 overwrite_frame = playback_sample;
844 overwrite_offset = channels.reader()->front()->playback_buf->get_read_ptr();
848 AudioDiskstream::overwrite_existing_buffers ()
850 boost::shared_ptr<ChannelList> c = channels.reader();
851 Sample* mixdown_buffer;
854 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
856 overwrite_queued = false;
858 /* assume all are the same size */
859 nframes_t size = c->front()->playback_buf->bufsize();
861 mixdown_buffer = new Sample[size];
862 gain_buffer = new float[size];
864 /* reduce size so that we can fill the buffer correctly. */
870 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
872 start = overwrite_frame;
873 nframes_t cnt = size;
875 /* to fill the buffer without resetting the playback sample, we need to
876 do it one or two chunks (normally two).
878 |----------------------------------------------------------------------|
882 |<- second chunk->||<----------------- first chunk ------------------>|
886 nframes_t to_read = size - overwrite_offset;
888 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, *chan, n, reversed)) {
889 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
890 _id, size, playback_sample) << endmsg;
898 if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer,
899 start, cnt, *chan, n, reversed)) {
900 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
901 _id, size, playback_sample) << endmsg;
910 pending_overwrite = false;
911 delete [] gain_buffer;
912 delete [] mixdown_buffer;
917 AudioDiskstream::seek (nframes_t frame, bool complete_refill)
921 ChannelList::iterator chan;
922 boost::shared_ptr<ChannelList> c = channels.reader();
924 Glib::Mutex::Lock lm (state_lock);
926 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
927 (*chan)->playback_buf->reset ();
928 (*chan)->capture_buf->reset ();
931 /* can't rec-enable in destructive mode if transport is before start */
933 if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
934 disengage_record_enable ();
937 playback_sample = frame;
940 if (complete_refill) {
941 while ((ret = do_refill_with_alloc ()) > 0) ;
943 ret = do_refill_with_alloc ();
950 AudioDiskstream::can_internal_playback_seek (nframes_t distance)
952 ChannelList::iterator chan;
953 boost::shared_ptr<ChannelList> c = channels.reader();
955 for (chan = c->begin(); chan != c->end(); ++chan) {
956 if ((*chan)->playback_buf->read_space() < distance) {
964 AudioDiskstream::internal_playback_seek (nframes_t distance)
966 ChannelList::iterator chan;
967 boost::shared_ptr<ChannelList> c = channels.reader();
969 for (chan = c->begin(); chan != c->end(); ++chan) {
970 (*chan)->playback_buf->increment_read_ptr (distance);
973 first_recordable_frame += distance;
974 playback_sample += distance;
980 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer, nframes_t& start, nframes_t cnt,
981 ChannelInfo* channel_info, int channel, bool reversed)
983 nframes_t this_read = 0;
985 nframes_t loop_end = 0;
986 nframes_t loop_start = 0;
987 nframes_t loop_length = 0;
988 nframes_t offset = 0;
991 /* XXX we don't currently play loops in reverse. not sure why */
995 /* Make the use of a Location atomic for this read operation.
997 Note: Locations don't get deleted, so all we care about
998 when I say "atomic" is that we are always pointing to
999 the same one and using a start/length values obtained
1003 if ((loc = loop_location) != 0) {
1004 loop_start = loc->start();
1005 loop_end = loc->end();
1006 loop_length = loop_end - loop_start;
1009 /* if we are looping, ensure that the first frame we read is at the correct
1010 position within the loop.
1013 if (loc && start >= loop_end) {
1014 //cerr << "start adjusted from " << start;
1015 start = loop_start + ((start - loop_start) % loop_length);
1016 //cerr << "to " << start << endl;
1019 //cerr << "start is " << start << " loopstart: " << loop_start << " loopend: " << loop_end << endl;
1028 /* take any loop into account. we can't read past the end of the loop. */
1030 if (loc && (loop_end - start < cnt)) {
1031 this_read = loop_end - start;
1032 //cerr << "reloop true: thisread: " << this_read << " cnt: " << cnt << endl;
1039 if (this_read == 0) {
1043 this_read = min(cnt,this_read);
1045 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
1046 error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), _id, this_read,
1051 _read_data_count = _playlist->read_data_count();
1055 swap_by_ptr (buf, buf + this_read - 1);
1059 /* if we read to the end of the loop, go back to the beginning */
1069 offset += this_read;
1076 AudioDiskstream::do_refill_with_alloc ()
1078 Sample* mix_buf = new Sample[disk_io_chunk_frames];
1079 float* gain_buf = new float[disk_io_chunk_frames];
1081 int ret = _do_refill(mix_buf, gain_buf);
1090 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer)
1094 RingBufferNPT<Sample>::rw_vector vector;
1095 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1096 nframes_t total_space;
1097 nframes_t zero_fill;
1099 ChannelList::iterator i;
1100 boost::shared_ptr<ChannelList> c = channels.reader();
1107 assert(mixdown_buffer);
1108 assert(gain_buffer);
1115 c->front()->playback_buf->get_write_vector (&vector);
1117 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1121 /* if there are 2+ chunks of disk i/o possible for
1122 this track, let the caller know so that it can arrange
1123 for us to be called again, ASAP.
1126 if (total_space >= (_slaved?3:2) * disk_io_chunk_frames) {
1130 /* if we're running close to normal speed and there isn't enough
1131 space to do disk_io_chunk_frames of I/O, then don't bother.
1133 at higher speeds, just do it because the sync between butler
1134 and audio thread may not be good enough.
1137 if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1141 /* when slaved, don't try to get too close to the read pointer. this
1142 leaves space for the buffer reversal to have something useful to
1146 if (_slaved && total_space < (c->front()->playback_buf->bufsize() / 2)) {
1150 /* never do more than disk_io_chunk_frames worth of disk input per call (limit doesn't apply for memset) */
1152 total_space = min (disk_io_chunk_frames, total_space);
1156 if (file_frame == 0) {
1158 /* at start: nothing to do but fill with silence */
1160 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1162 ChannelInfo* chan (*i);
1163 chan->playback_buf->get_write_vector (&vector);
1164 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1165 if (vector.len[1]) {
1166 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1168 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1173 if (file_frame < total_space) {
1175 /* too close to the start: read what we can,
1176 and then zero fill the rest
1179 zero_fill = total_space - file_frame;
1180 total_space = file_frame;
1190 if (file_frame == max_frames) {
1192 /* at end: nothing to do but fill with silence */
1194 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1196 ChannelInfo* chan (*i);
1197 chan->playback_buf->get_write_vector (&vector);
1198 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1199 if (vector.len[1]) {
1200 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1202 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1207 if (file_frame > max_frames - total_space) {
1209 /* to close to the end: read what we can, and zero fill the rest */
1211 zero_fill = total_space - (max_frames - file_frame);
1212 total_space = max_frames - file_frame;
1219 nframes_t file_frame_tmp = 0;
1221 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1223 ChannelInfo* chan (*i);
1226 nframes_t len1, len2;
1228 chan->playback_buf->get_write_vector (&vector);
1230 if (vector.len[0] > disk_io_chunk_frames) {
1232 /* we're not going to fill the first chunk, so certainly do not bother with the
1233 other part. it won't be connected with the part we do fill, as in:
1235 .... => writable space
1236 ++++ => readable space
1237 ^^^^ => 1 x disk_io_chunk_frames that would be filled
1239 |......|+++++++++++++|...............................|
1244 So, just pretend that the buf1 part isn't there.
1254 file_frame_tmp = file_frame;
1256 buf1 = vector.buf[0];
1257 len1 = vector.len[0];
1258 buf2 = vector.buf[1];
1259 len2 = vector.len[1];
1261 to_read = min (ts, len1);
1262 to_read = min (to_read, disk_io_chunk_frames);
1266 if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1271 chan->playback_buf->increment_write_ptr (to_read);
1275 to_read = min (ts, len2);
1279 /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1280 so read some or all of vector.len[1] as well.
1283 if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1288 chan->playback_buf->increment_write_ptr (to_read);
1297 file_frame = file_frame_tmp;
1304 /** Flush pending data to disk.
1306 * Important note: this function will write *AT MOST* disk_io_chunk_frames
1307 * of data to disk. it will never write more than that. If it writes that
1308 * much and there is more than that waiting to be written, it will return 1,
1309 * otherwise 0 on success or -1 on failure.
1311 * If there is less than disk_io_chunk_frames to be written, no data will be
1312 * written at all unless @a force_flush is true.
1315 AudioDiskstream::do_flush (Session::RunContext context, bool force_flush)
1319 RingBufferNPT<Sample>::rw_vector vector;
1320 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1323 _write_data_count = 0;
1325 transvec.buf[0] = 0;
1326 transvec.buf[1] = 0;
1330 boost::shared_ptr<ChannelList> c = channels.reader();
1331 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1333 (*chan)->capture_buf->get_read_vector (&vector);
1335 total = vector.len[0] + vector.len[1];
1337 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1341 /* if there are 2+ chunks of disk i/o possible for
1342 this track, let the caller know so that it can arrange
1343 for us to be called again, ASAP.
1345 if we are forcing a flush, then if there is* any* extra
1346 work, let the caller know.
1348 if we are no longer recording and there is any extra work,
1349 let the caller know too.
1352 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1356 to_write = min (disk_io_chunk_frames, (nframes_t) vector.len[0]);
1358 // check the transition buffer when recording destructive
1359 // important that we get this after the capture buf
1361 if (destructive()) {
1362 (*chan)->capture_transition_buf->get_read_vector(&transvec);
1363 size_t transcount = transvec.len[0] + transvec.len[1];
1364 bool have_start = false;
1367 for (ti=0; ti < transcount; ++ti) {
1368 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1370 if (captrans.type == CaptureStart) {
1371 // by definition, the first data we got above represents the given capture pos
1373 (*chan)->write_source->mark_capture_start (captrans.capture_val);
1374 (*chan)->curr_capture_cnt = 0;
1378 else if (captrans.type == CaptureEnd) {
1380 // capture end, the capture_val represents total frames in capture
1382 if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1384 // shorten to make the write a perfect fit
1385 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
1387 if (nto_write < to_write) {
1388 ret = 1; // should we?
1390 to_write = nto_write;
1392 (*chan)->write_source->mark_capture_end ();
1394 // increment past this transition, but go no further
1399 // actually ends just beyond this chunk, so force more work
1407 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1411 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1412 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1416 (*chan)->capture_buf->increment_read_ptr (to_write);
1417 (*chan)->curr_capture_cnt += to_write;
1419 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1421 /* we wrote all of vector.len[0] but it wasn't an entire
1422 disk_io_chunk_frames of data, so arrange for some part
1423 of vector.len[1] to be flushed to disk as well.
1426 to_write = min ((nframes_t)(disk_io_chunk_frames - to_write), (nframes_t) vector.len[1]);
1428 if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1429 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1433 _write_data_count += (*chan)->write_source->write_data_count();
1435 (*chan)->capture_buf->increment_read_ptr (to_write);
1436 (*chan)->curr_capture_cnt += to_write;
1445 AudioDiskstream::transport_stopped (struct tm& when, time_t twhen, bool abort_capture)
1447 uint32_t buffer_position;
1448 bool more_work = true;
1450 boost::shared_ptr<AudioRegion> region;
1451 nframes_t total_capture;
1453 SourceList::iterator src;
1454 ChannelList::iterator chan;
1455 vector<CaptureInfo*>::iterator ci;
1456 boost::shared_ptr<ChannelList> c = channels.reader();
1458 bool mark_write_completed = false;
1460 finish_capture (true, c);
1462 /* butler is already stopped, but there may be work to do
1463 to flush remaining data to disk.
1466 while (more_work && !err) {
1467 switch (do_flush (Session::TransportContext, true)) {
1474 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1479 /* XXX is there anything we can do if err != 0 ? */
1480 Glib::Mutex::Lock lm (capture_info_lock);
1482 if (capture_info.empty()) {
1486 if (abort_capture) {
1488 if (destructive()) {
1492 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1494 if ((*chan)->write_source) {
1496 (*chan)->write_source->mark_for_remove ();
1497 (*chan)->write_source->drop_references ();
1498 (*chan)->write_source.reset ();
1501 /* new source set up in "out" below */
1507 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1508 total_capture += (*ci)->frames;
1511 /* figure out the name for this take */
1513 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1515 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1519 s->update_header (capture_info.front()->start, when, twhen);
1520 s->set_captured_for (_name);
1521 s->mark_immutable ();
1525 /* destructive tracks have a single, never changing region */
1527 if (destructive()) {
1529 /* send a signal that any UI can pick up to do the right thing. there is
1530 a small problem here in that a UI may need the peak data to be ready
1531 for the data that was recorded and this isn't interlocked with that
1532 process. this problem is deferred to the UI.
1535 _playlist->Modified();
1539 string whole_file_region_name;
1540 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1542 /* Register a new region with the Session that
1543 describes the entire source. Do this first
1544 so that any sub-regions will obviously be
1545 children of this one (later!)
1549 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, c->front()->write_source->last_capture_start_frame(), total_capture,
1550 whole_file_region_name,
1551 0, AudioRegion::Flag (AudioRegion::DefaultFlags|AudioRegion::Automatic|AudioRegion::WholeFile)));
1553 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1554 region->special_set_position (capture_info.front()->start);
1558 catch (failed_constructor& err) {
1559 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1563 _last_capture_regions.push_back (region);
1565 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1567 XMLNode &before = _playlist->get_state();
1568 _playlist->freeze ();
1570 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1574 _session.region_name (region_name, whole_file_region_name, false);
1576 // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->frames << " add region " << region_name << endl;
1579 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, buffer_position, (*ci)->frames, region_name));
1580 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1583 catch (failed_constructor& err) {
1584 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1585 continue; /* XXX is this OK? */
1588 region->GoingAway.connect (bind (mem_fun (*this, &Diskstream::remove_region_from_last_capture), boost::weak_ptr<Region>(region)));
1590 _last_capture_regions.push_back (region);
1592 i_am_the_modifier++;
1593 _playlist->add_region (region, (*ci)->start);
1594 i_am_the_modifier--;
1596 buffer_position += (*ci)->frames;
1600 XMLNode &after = _playlist->get_state();
1601 _session.add_command (new MementoCommand<Playlist>(*_playlist, &before, &after));
1604 mark_write_completed = true;
1607 reset_write_sources (mark_write_completed);
1611 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1615 capture_info.clear ();
1616 capture_start_frame = 0;
1620 AudioDiskstream::finish_capture (bool rec_monitors_input, boost::shared_ptr<ChannelList> c)
1622 was_recording = false;
1624 if (capture_captured == 0) {
1628 if (recordable() && destructive()) {
1629 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1631 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1632 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1635 if (transvec.len[0] > 0) {
1636 transvec.buf[0]->type = CaptureEnd;
1637 transvec.buf[0]->capture_val = capture_captured;
1638 (*chan)->capture_transition_buf->increment_write_ptr(1);
1642 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1648 CaptureInfo* ci = new CaptureInfo;
1650 ci->start = capture_start_frame;
1651 ci->frames = capture_captured;
1653 /* XXX theoretical race condition here. Need atomic exchange ?
1654 However, the circumstances when this is called right
1655 now (either on record-disable or transport_stopped)
1656 mean that no actual race exists. I think ...
1657 We now have a capture_info_lock, but it is only to be used
1658 to synchronize in the transport_stop and the capture info
1659 accessors, so that invalidation will not occur (both non-realtime).
1662 // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1664 capture_info.push_back (ci);
1665 capture_captured = 0;
1669 AudioDiskstream::set_record_enabled (bool yn)
1671 if (!recordable() || !_session.record_enabling_legal() || _io->n_inputs() == 0) {
1675 /* can't rec-enable in destructive mode if transport is before start */
1677 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1681 if (yn && channels.reader()->front()->source == 0) {
1683 /* pick up connections not initiated *from* the IO object
1684 we're associated with.
1687 get_input_sources ();
1690 /* yes, i know that this not proof against race conditions, but its
1691 good enough. i think.
1694 if (record_enabled() != yn) {
1696 engage_record_enable ();
1698 disengage_record_enable ();
1704 AudioDiskstream::engage_record_enable ()
1706 bool rolling = _session.transport_speed() != 0.0f;
1707 boost::shared_ptr<ChannelList> c = channels.reader();
1709 g_atomic_int_set (&_record_enabled, 1);
1710 capturing_sources.clear ();
1712 if (Config->get_monitoring_model() == HardwareMonitoring) {
1714 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1715 if ((*chan)->source) {
1716 (*chan)->source->ensure_monitor_input (!(Config->get_auto_input() && rolling));
1718 capturing_sources.push_back ((*chan)->write_source);
1722 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1723 capturing_sources.push_back ((*chan)->write_source);
1727 RecordEnableChanged (); /* EMIT SIGNAL */
1731 AudioDiskstream::disengage_record_enable ()
1733 g_atomic_int_set (&_record_enabled, 0);
1734 boost::shared_ptr<ChannelList> c = channels.reader();
1735 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1736 if (Config->get_monitoring_model() == HardwareMonitoring) {
1737 if ((*chan)->source) {
1738 (*chan)->source->ensure_monitor_input (false);
1742 capturing_sources.clear ();
1743 RecordEnableChanged (); /* EMIT SIGNAL */
1747 AudioDiskstream::get_state ()
1749 XMLNode* node = new XMLNode ("AudioDiskstream");
1751 LocaleGuard lg (X_("POSIX"));
1752 boost::shared_ptr<ChannelList> c = channels.reader();
1754 node->add_property ("flags", enum_2_string (_flags));
1756 snprintf (buf, sizeof(buf), "%zd", c->size());
1757 node->add_property ("channels", buf);
1759 node->add_property ("playlist", _playlist->name());
1761 snprintf (buf, sizeof(buf), "%.12g", _visible_speed);
1762 node->add_property ("speed", buf);
1764 node->add_property("name", _name);
1765 id().print (buf, sizeof (buf));
1766 node->add_property("id", buf);
1768 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1770 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1771 XMLNode* cs_grandchild;
1773 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1774 cs_grandchild = new XMLNode (X_("file"));
1775 cs_grandchild->add_property (X_("path"), (*i)->path());
1776 cs_child->add_child_nocopy (*cs_grandchild);
1779 /* store the location where capture will start */
1783 if (Config->get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1784 snprintf (buf, sizeof (buf), "%" PRIu32, pi->start());
1786 snprintf (buf, sizeof (buf), "%" PRIu32, _session.transport_frame());
1789 cs_child->add_property (X_("at"), buf);
1790 node->add_child_nocopy (*cs_child);
1794 node->add_child_copy (*_extra_xml);
1801 AudioDiskstream::set_state (const XMLNode& node)
1803 const XMLProperty* prop;
1804 XMLNodeList nlist = node.children();
1805 XMLNodeIterator niter;
1806 uint32_t nchans = 1;
1807 XMLNode* capture_pending_node = 0;
1808 LocaleGuard lg (X_("POSIX"));
1810 in_set_state = true;
1812 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1813 if ((*niter)->name() == IO::state_node_name) {
1814 deprecated_io_node = new XMLNode (**niter);
1817 if ((*niter)->name() == X_("CapturingSources")) {
1818 capture_pending_node = *niter;
1822 /* prevent write sources from being created */
1824 in_set_state = true;
1826 if ((prop = node.property ("name")) != 0) {
1827 _name = prop->value();
1830 if (deprecated_io_node) {
1831 if ((prop = deprecated_io_node->property ("id")) != 0) {
1832 _id = prop->value ();
1835 if ((prop = node.property ("id")) != 0) {
1836 _id = prop->value ();
1840 if ((prop = node.property ("flags")) != 0) {
1841 _flags = Flag (string_2_enum (prop->value(), _flags));
1844 if ((prop = node.property ("channels")) != 0) {
1845 nchans = atoi (prop->value().c_str());
1848 // create necessary extra channels
1849 // we are always constructed with one and we always need one
1851 _n_channels = channels.reader()->size();
1853 if (nchans > _n_channels) {
1855 add_channel (nchans - _n_channels);
1857 } else if (nchans < _n_channels) {
1859 remove_channel (_n_channels - nchans);
1862 if ((prop = node.property ("playlist")) == 0) {
1867 bool had_playlist = (_playlist != 0);
1869 if (find_and_use_playlist (prop->value())) {
1873 if (!had_playlist) {
1874 _playlist->set_orig_diskstream_id (_id);
1877 if (!destructive() && capture_pending_node) {
1878 /* destructive streams have one and only one source per channel,
1879 and so they never end up in pending capture in any useful
1882 use_pending_capture_data (*capture_pending_node);
1887 if ((prop = node.property ("speed")) != 0) {
1888 double sp = atof (prop->value().c_str());
1890 if (realtime_set_speed (sp, false)) {
1891 non_realtime_set_speed ();
1895 in_set_state = false;
1897 /* make sure this is clear before we do anything else */
1899 capturing_sources.clear ();
1901 /* write sources are handled when we handle the input set
1902 up of the IO that owns this DS (::non_realtime_input_change())
1905 in_set_state = false;
1911 AudioDiskstream::use_new_write_source (uint32_t n)
1913 boost::shared_ptr<ChannelList> c = channels.reader();
1915 if (!recordable()) {
1919 if (n >= c->size()) {
1920 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
1924 ChannelInfo* chan = (*c)[n];
1926 if (chan->write_source) {
1927 chan->write_source->done_with_peakfile_writes ();
1928 chan->write_source->set_allow_remove_if_empty (true);
1929 chan->write_source.reset ();
1933 if ((chan->write_source = _session.create_audio_source_for_session (*this, n, destructive())) == 0) {
1934 throw failed_constructor();
1938 catch (failed_constructor &err) {
1939 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
1940 chan->write_source.reset ();
1944 /* do not remove destructive files even if they are empty */
1946 chan->write_source->set_allow_remove_if_empty (!destructive());
1952 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool force)
1954 ChannelList::iterator chan;
1955 boost::shared_ptr<ChannelList> c = channels.reader();
1958 if (!recordable()) {
1962 capturing_sources.clear ();
1964 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1965 if (!destructive()) {
1967 if ((*chan)->write_source && mark_write_complete) {
1968 (*chan)->write_source->mark_streaming_write_completed ();
1970 use_new_write_source (n);
1972 if (record_enabled()) {
1973 capturing_sources.push_back ((*chan)->write_source);
1977 if ((*chan)->write_source == 0) {
1978 use_new_write_source (n);
1983 if (destructive()) {
1985 /* we now have all our write sources set up, so create the
1986 playlist's single region.
1989 if (_playlist->empty()) {
1990 setup_destructive_playlist ();
1996 AudioDiskstream::rename_write_sources ()
1998 ChannelList::iterator chan;
1999 boost::shared_ptr<ChannelList> c = channels.reader();
2002 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
2003 if ((*chan)->write_source != 0) {
2004 (*chan)->write_source->set_name (_name, destructive());
2005 /* XXX what to do if one of them fails ? */
2013 AudioDiskstream::set_block_size (nframes_t nframes)
2015 if (_session.get_block_size() > speed_buffer_size) {
2016 speed_buffer_size = _session.get_block_size();
2017 boost::shared_ptr<ChannelList> c = channels.reader();
2019 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2020 if ((*chan)->speed_buffer) delete [] (*chan)->speed_buffer;
2021 (*chan)->speed_buffer = new Sample[speed_buffer_size];
2024 allocate_temporary_buffers ();
2028 AudioDiskstream::allocate_temporary_buffers ()
2030 /* make sure the wrap buffer is at least large enough to deal
2031 with the speeds up to 1.2, to allow for micro-variation
2032 when slaving to MTC, SMPTE etc.
2035 double sp = max (fabsf (_actual_speed), 1.2f);
2036 nframes_t required_wrap_size = (nframes_t) floor (_session.get_block_size() * sp) + 1;
2038 if (required_wrap_size > wrap_buffer_size) {
2040 boost::shared_ptr<ChannelList> c = channels.reader();
2042 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2043 if ((*chan)->playback_wrap_buffer) delete [] (*chan)->playback_wrap_buffer;
2044 (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
2045 if ((*chan)->capture_wrap_buffer) delete [] (*chan)->capture_wrap_buffer;
2046 (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
2049 wrap_buffer_size = required_wrap_size;
2054 AudioDiskstream::monitor_input (bool yn)
2056 boost::shared_ptr<ChannelList> c = channels.reader();
2058 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2060 if ((*chan)->source) {
2061 (*chan)->source->ensure_monitor_input (yn);
2067 AudioDiskstream::set_align_style_from_io ()
2069 bool have_physical = false;
2075 get_input_sources ();
2077 boost::shared_ptr<ChannelList> c = channels.reader();
2079 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2080 if ((*chan)->source && (*chan)->source->flags() & JackPortIsPhysical) {
2081 have_physical = true;
2086 if (have_physical) {
2087 set_align_style (ExistingMaterial);
2089 set_align_style (CaptureTime);
2094 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2096 while (how_many--) {
2097 c->push_back (new ChannelInfo(_session.diskstream_buffer_size(), speed_buffer_size, wrap_buffer_size));
2100 _n_channels = c->size();
2106 AudioDiskstream::add_channel (uint32_t how_many)
2108 RCUWriter<ChannelList> writer (channels);
2109 boost::shared_ptr<ChannelList> c = writer.get_copy();
2111 return add_channel_to (c, how_many);
2115 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2117 while (--how_many && !c->empty()) {
2122 _n_channels = c->size();
2128 AudioDiskstream::remove_channel (uint32_t how_many)
2130 RCUWriter<ChannelList> writer (channels);
2131 boost::shared_ptr<ChannelList> c = writer.get_copy();
2133 return remove_channel_from (c, how_many);
2137 AudioDiskstream::playback_buffer_load () const
2139 boost::shared_ptr<ChannelList> c = channels.reader();
2141 return (float) ((double) c->front()->playback_buf->read_space()/
2142 (double) c->front()->playback_buf->bufsize());
2146 AudioDiskstream::capture_buffer_load () const
2148 boost::shared_ptr<ChannelList> c = channels.reader();
2150 return (float) ((double) c->front()->capture_buf->write_space()/
2151 (double) c->front()->capture_buf->bufsize());
2155 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2157 const XMLProperty* prop;
2158 XMLNodeList nlist = node.children();
2159 XMLNodeIterator niter;
2160 boost::shared_ptr<AudioFileSource> fs;
2161 boost::shared_ptr<AudioFileSource> first_fs;
2162 SourceList pending_sources;
2165 if ((prop = node.property (X_("at"))) == 0) {
2169 if (sscanf (prop->value().c_str(), "%" PRIu32, &position) != 1) {
2173 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2174 if ((*niter)->name() == X_("file")) {
2176 if ((prop = (*niter)->property (X_("path"))) == 0) {
2181 fs = boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createWritable (_session, prop->value(), false, _session.frame_rate()));
2184 catch (failed_constructor& err) {
2185 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2186 _name, prop->value())
2191 pending_sources.push_back (fs);
2193 if (first_fs == 0) {
2197 fs->set_captured_for (_name);
2201 if (pending_sources.size() == 0) {
2202 /* nothing can be done */
2206 if (pending_sources.size() != _n_channels) {
2207 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2212 boost::shared_ptr<AudioRegion> region;
2215 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, 0, first_fs->length(),
2216 region_name_from_path (first_fs->name(), true),
2217 0, AudioRegion::Flag (AudioRegion::DefaultFlags|AudioRegion::Automatic|AudioRegion::WholeFile)));
2218 region->special_set_position (0);
2221 catch (failed_constructor& err) {
2222 error << string_compose (_("%1: cannot create whole-file region from pending capture sources"),
2230 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, 0, first_fs->length(), region_name_from_path (first_fs->name(), true)));
2233 catch (failed_constructor& err) {
2234 error << string_compose (_("%1: cannot create region from pending capture sources"),
2241 _playlist->add_region (region, position);
2247 AudioDiskstream::set_destructive (bool yn)
2249 bool bounce_ignored;
2251 if (yn != destructive()) {
2254 /* requestor should already have checked this and
2255 bounced if necessary and desired
2257 if (!can_become_destructive (bounce_ignored)) {
2260 _flags = Flag (_flags | Destructive);
2261 use_destructive_playlist ();
2263 _flags = Flag (_flags & ~Destructive);
2264 reset_write_sources (true, true);
2272 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2275 requires_bounce = false;
2279 /* is there only one region ? */
2281 if (_playlist->n_regions() != 1) {
2282 requires_bounce = true;
2286 boost::shared_ptr<Region> first = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
2289 /* do the source(s) for the region cover the session start position ? */
2291 if (first->position() != _session.current_start_frame()) {
2292 if (first->start() > _session.current_start_frame()) {
2293 requires_bounce = true;
2298 /* is the source used by only 1 playlist ? */
2300 boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2304 if (afirst->source()->used() > 1) {
2305 requires_bounce = true;
2309 requires_bounce = false;
2313 AudioDiskstream::ChannelInfo::ChannelInfo (nframes_t bufsize, nframes_t speed_size, nframes_t wrap_size)
2317 current_capture_buffer = 0;
2318 current_playback_buffer = 0;
2319 curr_capture_cnt = 0;
2321 speed_buffer = new Sample[speed_size];
2322 playback_wrap_buffer = new Sample[wrap_size];
2323 capture_wrap_buffer = new Sample[wrap_size];
2325 playback_buf = new RingBufferNPT<Sample> (bufsize);
2326 capture_buf = new RingBufferNPT<Sample> (bufsize);
2327 capture_transition_buf = new RingBufferNPT<CaptureTransition> (128);
2329 /* touch the ringbuffer buffers, which will cause
2330 them to be mapped into locked physical RAM if
2331 we're running with mlockall(). this doesn't do
2335 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2336 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2337 memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2340 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2343 write_source.reset ();
2347 delete [] speed_buffer;
2351 if (playback_wrap_buffer) {
2352 delete [] playback_wrap_buffer;
2353 playback_wrap_buffer = 0;
2356 if (capture_wrap_buffer) {
2357 delete [] capture_wrap_buffer;
2358 capture_wrap_buffer = 0;
2362 delete playback_buf;
2371 if (capture_transition_buf) {
2372 delete capture_transition_buf;
2373 capture_transition_buf = 0;