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 commit_should_unlock = false;
529 check_record_status (transport_frame, nframes, can_record);
531 nominally_recording = (can_record && re);
538 /* This lock is held until the end of AudioDiskstream::commit, so these two functions
539 must always be called as a pair. The only exception is if this function
540 returns a non-zero value, in which case, ::commit should not be called.
543 // If we can't take the state lock return.
544 if (!state_lock.trylock()) {
547 commit_should_unlock = true;
548 adjust_capture_position = 0;
550 for (chan = c->begin(); chan != c->end(); ++chan) {
551 (*chan)->current_capture_buffer = 0;
552 (*chan)->current_playback_buffer = 0;
555 if (nominally_recording || (_session.get_record_enabled() && Config->get_punch_in())) {
558 ot = coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
565 case OverlapInternal:
566 /* ---------- recrange
569 rec_nframes = nframes;
574 /* |--------| recrange
577 rec_nframes = transport_frame + nframes - first_recordable_frame;
579 rec_offset = first_recordable_frame - transport_frame;
584 /* |--------| recrange
587 rec_nframes = last_recordable_frame - transport_frame;
591 case OverlapExternal:
592 /* |--------| recrange
593 -------------- transrange
595 rec_nframes = last_recordable_frame - last_recordable_frame;
596 rec_offset = first_recordable_frame - transport_frame;
600 if (rec_nframes && !was_recording) {
601 capture_captured = 0;
602 was_recording = true;
607 if (can_record && !_last_capture_regions.empty()) {
608 _last_capture_regions.clear ();
611 if (nominally_recording || rec_nframes) {
613 uint32_t limit = _io->n_inputs ();
615 /* one or more ports could already have been removed from _io, but our
616 channel setup hasn't yet been updated. prevent us from trying to
617 use channels that correspond to missing ports. note that the
618 process callback (from which this is called) is always atomic
619 with respect to port removal/addition.
622 for (n = 0, chan = c->begin(); chan != c->end() && n < limit; ++chan, ++n) {
624 ChannelInfo* chaninfo (*chan);
626 chaninfo->capture_buf->get_write_vector (&chaninfo->capture_vector);
628 if (rec_nframes <= chaninfo->capture_vector.len[0]) {
630 chaninfo->current_capture_buffer = chaninfo->capture_vector.buf[0];
632 /* note: grab the entire port buffer, but only copy what we were supposed to for recording, and use
636 memcpy (chaninfo->current_capture_buffer, _io->input(n)->get_buffer (rec_nframes) + offset + rec_offset, sizeof (Sample) * rec_nframes);
640 nframes_t total = chaninfo->capture_vector.len[0] + chaninfo->capture_vector.len[1];
642 if (rec_nframes > total) {
647 Sample* buf = _io->input (n)->get_buffer (nframes) + offset;
648 nframes_t first = chaninfo->capture_vector.len[0];
650 memcpy (chaninfo->capture_wrap_buffer, buf, sizeof (Sample) * first);
651 memcpy (chaninfo->capture_vector.buf[0], buf, sizeof (Sample) * first);
652 memcpy (chaninfo->capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
653 memcpy (chaninfo->capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
655 chaninfo->current_capture_buffer = chaninfo->capture_wrap_buffer;
662 finish_capture (rec_monitors_input, c);
669 /* data will be written to disk */
671 if (rec_nframes == nframes && rec_offset == 0) {
673 for (chan = c->begin(); chan != c->end(); ++chan) {
674 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
677 playback_distance = nframes;
682 /* we can't use the capture buffer as the playback buffer, because
683 we recorded only a part of the current process' cycle data
687 collect_playback = true;
690 adjust_capture_position = rec_nframes;
692 } else if (nominally_recording) {
694 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
696 for (chan = c->begin(); chan != c->end(); ++chan) {
697 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
700 playback_distance = nframes;
704 collect_playback = true;
707 if (collect_playback) {
709 /* we're doing playback */
711 nframes_t necessary_samples;
713 /* no varispeed playback if we're recording, because the output .... TBD */
715 if (rec_nframes == 0 && _actual_speed != 1.0f) {
716 necessary_samples = (nframes_t) floor ((nframes * fabs (_actual_speed))) + 1;
718 necessary_samples = nframes;
721 for (chan = c->begin(); chan != c->end(); ++chan) {
722 (*chan)->playback_buf->get_read_vector (&(*chan)->playback_vector);
727 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
729 ChannelInfo* chaninfo (*chan);
731 if (necessary_samples <= chaninfo->playback_vector.len[0]) {
733 chaninfo->current_playback_buffer = chaninfo->playback_vector.buf[0];
736 nframes_t total = chaninfo->playback_vector.len[0] + chaninfo->playback_vector.len[1];
738 if (necessary_samples > total) {
744 memcpy ((char *) chaninfo->playback_wrap_buffer, chaninfo->playback_vector.buf[0],
745 chaninfo->playback_vector.len[0] * sizeof (Sample));
746 memcpy (chaninfo->playback_wrap_buffer + chaninfo->playback_vector.len[0], chaninfo->playback_vector.buf[1],
747 (necessary_samples - chaninfo->playback_vector.len[0]) * sizeof (Sample));
749 chaninfo->current_playback_buffer = chaninfo->playback_wrap_buffer;
754 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
756 uint64_t phase = last_phase;
759 // Linearly interpolate into the alt buffer
760 // using 40.24 fixp maths (swh)
762 for (chan = c->begin(); chan != c->end(); ++chan) {
765 ChannelInfo* chaninfo (*chan);
770 for (nframes_t outsample = 0; outsample < nframes; ++outsample) {
772 fr = (phase & 0xFFFFFF) / 16777216.0f;
773 chaninfo->speed_buffer[outsample] =
774 chaninfo->current_playback_buffer[i] * (1.0f - fr) +
775 chaninfo->current_playback_buffer[i+1] * fr;
779 chaninfo->current_playback_buffer = chaninfo->speed_buffer;
782 playback_distance = i + 1;
783 last_phase = (phase & 0xFFFFFF);
786 playback_distance = nframes;
798 /* we're exiting with failure, so ::commit will not
799 be called. unlock the state lock.
802 commit_should_unlock = false;
810 AudioDiskstream::commit (nframes_t nframes)
812 bool need_butler = false;
814 if (_actual_speed < 0.0) {
815 playback_sample -= playback_distance;
817 playback_sample += playback_distance;
820 boost::shared_ptr<ChannelList> c = channels.reader();
821 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
823 (*chan)->playback_buf->increment_read_ptr (playback_distance);
825 if (adjust_capture_position) {
826 (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
830 if (adjust_capture_position != 0) {
831 capture_captured += adjust_capture_position;
832 adjust_capture_position = 0;
836 need_butler = c->front()->playback_buf->write_space() >= c->front()->playback_buf->bufsize() / 2;
838 need_butler = c->front()->playback_buf->write_space() >= disk_io_chunk_frames
839 || c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
842 if (commit_should_unlock) {
852 AudioDiskstream::set_pending_overwrite (bool yn)
854 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
856 pending_overwrite = yn;
858 overwrite_frame = playback_sample;
859 overwrite_offset = channels.reader()->front()->playback_buf->get_read_ptr();
863 AudioDiskstream::overwrite_existing_buffers ()
865 boost::shared_ptr<ChannelList> c = channels.reader();
866 Sample* mixdown_buffer;
869 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
871 overwrite_queued = false;
873 /* assume all are the same size */
874 nframes_t size = c->front()->playback_buf->bufsize();
876 mixdown_buffer = new Sample[size];
877 gain_buffer = new float[size];
879 /* reduce size so that we can fill the buffer correctly. */
885 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
887 start = overwrite_frame;
888 nframes_t cnt = size;
890 /* to fill the buffer without resetting the playback sample, we need to
891 do it one or two chunks (normally two).
893 |----------------------------------------------------------------------|
897 |<- second chunk->||<----------------- first chunk ------------------>|
901 nframes_t to_read = size - overwrite_offset;
903 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, *chan, n, reversed)) {
904 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
905 _id, size, playback_sample) << endmsg;
913 if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer,
914 start, cnt, *chan, n, reversed)) {
915 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
916 _id, size, playback_sample) << endmsg;
925 pending_overwrite = false;
926 delete [] gain_buffer;
927 delete [] mixdown_buffer;
932 AudioDiskstream::seek (nframes_t frame, bool complete_refill)
936 ChannelList::iterator chan;
937 boost::shared_ptr<ChannelList> c = channels.reader();
939 Glib::Mutex::Lock lm (state_lock);
941 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
942 (*chan)->playback_buf->reset ();
943 (*chan)->capture_buf->reset ();
946 /* can't rec-enable in destructive mode if transport is before start */
948 if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
949 disengage_record_enable ();
952 playback_sample = frame;
955 if (complete_refill) {
956 while ((ret = do_refill_with_alloc ()) > 0) ;
958 ret = do_refill_with_alloc ();
965 AudioDiskstream::can_internal_playback_seek (nframes_t distance)
967 ChannelList::iterator chan;
968 boost::shared_ptr<ChannelList> c = channels.reader();
970 for (chan = c->begin(); chan != c->end(); ++chan) {
971 if ((*chan)->playback_buf->read_space() < distance) {
979 AudioDiskstream::internal_playback_seek (nframes_t distance)
981 ChannelList::iterator chan;
982 boost::shared_ptr<ChannelList> c = channels.reader();
984 for (chan = c->begin(); chan != c->end(); ++chan) {
985 (*chan)->playback_buf->increment_read_ptr (distance);
988 first_recordable_frame += distance;
989 playback_sample += distance;
995 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer, nframes_t& start, nframes_t cnt,
996 ChannelInfo* channel_info, int channel, bool reversed)
998 nframes_t this_read = 0;
1000 nframes_t loop_end = 0;
1001 nframes_t loop_start = 0;
1002 nframes_t loop_length = 0;
1003 nframes_t offset = 0;
1006 /* XXX we don't currently play loops in reverse. not sure why */
1010 /* Make the use of a Location atomic for this read operation.
1012 Note: Locations don't get deleted, so all we care about
1013 when I say "atomic" is that we are always pointing to
1014 the same one and using a start/length values obtained
1018 if ((loc = loop_location) != 0) {
1019 loop_start = loc->start();
1020 loop_end = loc->end();
1021 loop_length = loop_end - loop_start;
1024 /* if we are looping, ensure that the first frame we read is at the correct
1025 position within the loop.
1028 if (loc && start >= loop_end) {
1029 //cerr << "start adjusted from " << start;
1030 start = loop_start + ((start - loop_start) % loop_length);
1031 //cerr << "to " << start << endl;
1034 //cerr << "start is " << start << " loopstart: " << loop_start << " loopend: " << loop_end << endl;
1043 /* take any loop into account. we can't read past the end of the loop. */
1045 if (loc && (loop_end - start < cnt)) {
1046 this_read = loop_end - start;
1047 //cerr << "reloop true: thisread: " << this_read << " cnt: " << cnt << endl;
1054 if (this_read == 0) {
1058 this_read = min(cnt,this_read);
1060 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
1061 error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), _id, this_read,
1066 _read_data_count = _playlist->read_data_count();
1070 swap_by_ptr (buf, buf + this_read - 1);
1074 /* if we read to the end of the loop, go back to the beginning */
1084 offset += this_read;
1091 AudioDiskstream::do_refill_with_alloc ()
1093 Sample* mix_buf = new Sample[disk_io_chunk_frames];
1094 float* gain_buf = new float[disk_io_chunk_frames];
1096 int ret = _do_refill(mix_buf, gain_buf);
1105 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer)
1109 RingBufferNPT<Sample>::rw_vector vector;
1110 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1111 nframes_t total_space;
1112 nframes_t zero_fill;
1114 ChannelList::iterator i;
1115 boost::shared_ptr<ChannelList> c = channels.reader();
1122 assert(mixdown_buffer);
1123 assert(gain_buffer);
1130 c->front()->playback_buf->get_write_vector (&vector);
1132 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1136 /* if there are 2+ chunks of disk i/o possible for
1137 this track, let the caller know so that it can arrange
1138 for us to be called again, ASAP.
1141 if (total_space >= (_slaved?3:2) * disk_io_chunk_frames) {
1145 /* if we're running close to normal speed and there isn't enough
1146 space to do disk_io_chunk_frames of I/O, then don't bother.
1148 at higher speeds, just do it because the sync between butler
1149 and audio thread may not be good enough.
1152 if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1156 /* when slaved, don't try to get too close to the read pointer. this
1157 leaves space for the buffer reversal to have something useful to
1161 if (_slaved && total_space < (c->front()->playback_buf->bufsize() / 2)) {
1165 /* never do more than disk_io_chunk_frames worth of disk input per call (limit doesn't apply for memset) */
1167 total_space = min (disk_io_chunk_frames, total_space);
1171 if (file_frame == 0) {
1173 /* at start: nothing to do but fill with silence */
1175 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1177 ChannelInfo* chan (*i);
1178 chan->playback_buf->get_write_vector (&vector);
1179 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1180 if (vector.len[1]) {
1181 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1183 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1188 if (file_frame < total_space) {
1190 /* too close to the start: read what we can,
1191 and then zero fill the rest
1194 zero_fill = total_space - file_frame;
1195 total_space = file_frame;
1205 if (file_frame == max_frames) {
1207 /* at end: nothing to do but fill with silence */
1209 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1211 ChannelInfo* chan (*i);
1212 chan->playback_buf->get_write_vector (&vector);
1213 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1214 if (vector.len[1]) {
1215 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1217 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1222 if (file_frame > max_frames - total_space) {
1224 /* to close to the end: read what we can, and zero fill the rest */
1226 zero_fill = total_space - (max_frames - file_frame);
1227 total_space = max_frames - file_frame;
1234 nframes_t file_frame_tmp = 0;
1236 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1238 ChannelInfo* chan (*i);
1241 nframes_t len1, len2;
1243 chan->playback_buf->get_write_vector (&vector);
1245 if (vector.len[0] > disk_io_chunk_frames) {
1247 /* we're not going to fill the first chunk, so certainly do not bother with the
1248 other part. it won't be connected with the part we do fill, as in:
1250 .... => writable space
1251 ++++ => readable space
1252 ^^^^ => 1 x disk_io_chunk_frames that would be filled
1254 |......|+++++++++++++|...............................|
1259 So, just pretend that the buf1 part isn't there.
1269 file_frame_tmp = file_frame;
1271 buf1 = vector.buf[0];
1272 len1 = vector.len[0];
1273 buf2 = vector.buf[1];
1274 len2 = vector.len[1];
1276 to_read = min (ts, len1);
1277 to_read = min (to_read, disk_io_chunk_frames);
1281 if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1286 chan->playback_buf->increment_write_ptr (to_read);
1290 to_read = min (ts, len2);
1294 /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1295 so read some or all of vector.len[1] as well.
1298 if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1303 chan->playback_buf->increment_write_ptr (to_read);
1312 file_frame = file_frame_tmp;
1319 /** Flush pending data to disk.
1321 * Important note: this function will write *AT MOST* disk_io_chunk_frames
1322 * of data to disk. it will never write more than that. If it writes that
1323 * much and there is more than that waiting to be written, it will return 1,
1324 * otherwise 0 on success or -1 on failure.
1326 * If there is less than disk_io_chunk_frames to be written, no data will be
1327 * written at all unless @a force_flush is true.
1330 AudioDiskstream::do_flush (Session::RunContext context, bool force_flush)
1334 RingBufferNPT<Sample>::rw_vector vector;
1335 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1338 _write_data_count = 0;
1340 transvec.buf[0] = 0;
1341 transvec.buf[1] = 0;
1345 boost::shared_ptr<ChannelList> c = channels.reader();
1346 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1348 (*chan)->capture_buf->get_read_vector (&vector);
1350 total = vector.len[0] + vector.len[1];
1352 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1356 /* if there are 2+ chunks of disk i/o possible for
1357 this track, let the caller know so that it can arrange
1358 for us to be called again, ASAP.
1360 if we are forcing a flush, then if there is* any* extra
1361 work, let the caller know.
1363 if we are no longer recording and there is any extra work,
1364 let the caller know too.
1367 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1371 to_write = min (disk_io_chunk_frames, (nframes_t) vector.len[0]);
1373 // check the transition buffer when recording destructive
1374 // important that we get this after the capture buf
1376 if (destructive()) {
1377 (*chan)->capture_transition_buf->get_read_vector(&transvec);
1378 size_t transcount = transvec.len[0] + transvec.len[1];
1379 bool have_start = false;
1382 for (ti=0; ti < transcount; ++ti) {
1383 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1385 if (captrans.type == CaptureStart) {
1386 // by definition, the first data we got above represents the given capture pos
1388 (*chan)->write_source->mark_capture_start (captrans.capture_val);
1389 (*chan)->curr_capture_cnt = 0;
1393 else if (captrans.type == CaptureEnd) {
1395 // capture end, the capture_val represents total frames in capture
1397 if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1399 // shorten to make the write a perfect fit
1400 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
1402 if (nto_write < to_write) {
1403 ret = 1; // should we?
1405 to_write = nto_write;
1407 (*chan)->write_source->mark_capture_end ();
1409 // increment past this transition, but go no further
1414 // actually ends just beyond this chunk, so force more work
1422 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1426 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1427 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1431 (*chan)->capture_buf->increment_read_ptr (to_write);
1432 (*chan)->curr_capture_cnt += to_write;
1434 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1436 /* we wrote all of vector.len[0] but it wasn't an entire
1437 disk_io_chunk_frames of data, so arrange for some part
1438 of vector.len[1] to be flushed to disk as well.
1441 to_write = min ((nframes_t)(disk_io_chunk_frames - to_write), (nframes_t) vector.len[1]);
1443 if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1444 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1448 _write_data_count += (*chan)->write_source->write_data_count();
1450 (*chan)->capture_buf->increment_read_ptr (to_write);
1451 (*chan)->curr_capture_cnt += to_write;
1460 AudioDiskstream::transport_stopped (struct tm& when, time_t twhen, bool abort_capture)
1462 uint32_t buffer_position;
1463 bool more_work = true;
1465 boost::shared_ptr<AudioRegion> region;
1466 nframes_t total_capture;
1468 SourceList::iterator src;
1469 ChannelList::iterator chan;
1470 vector<CaptureInfo*>::iterator ci;
1471 boost::shared_ptr<ChannelList> c = channels.reader();
1473 bool mark_write_completed = false;
1475 finish_capture (true, c);
1477 /* butler is already stopped, but there may be work to do
1478 to flush remaining data to disk.
1481 while (more_work && !err) {
1482 switch (do_flush (Session::TransportContext, true)) {
1489 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1494 /* XXX is there anything we can do if err != 0 ? */
1495 Glib::Mutex::Lock lm (capture_info_lock);
1497 if (capture_info.empty()) {
1501 if (abort_capture) {
1503 if (destructive()) {
1507 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1509 if ((*chan)->write_source) {
1511 (*chan)->write_source->mark_for_remove ();
1512 (*chan)->write_source->drop_references ();
1513 (*chan)->write_source.reset ();
1516 /* new source set up in "out" below */
1522 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1523 total_capture += (*ci)->frames;
1526 /* figure out the name for this take */
1528 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1530 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1534 s->update_header (capture_info.front()->start, when, twhen);
1535 s->set_captured_for (_name);
1536 s->mark_immutable ();
1540 /* destructive tracks have a single, never changing region */
1542 if (destructive()) {
1544 /* send a signal that any UI can pick up to do the right thing. there is
1545 a small problem here in that a UI may need the peak data to be ready
1546 for the data that was recorded and this isn't interlocked with that
1547 process. this problem is deferred to the UI.
1550 _playlist->Modified();
1554 string whole_file_region_name;
1555 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1557 /* Register a new region with the Session that
1558 describes the entire source. Do this first
1559 so that any sub-regions will obviously be
1560 children of this one (later!)
1564 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, c->front()->write_source->last_capture_start_frame(), total_capture,
1565 whole_file_region_name,
1566 0, AudioRegion::Flag (AudioRegion::DefaultFlags|AudioRegion::Automatic|AudioRegion::WholeFile)));
1568 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1569 region->special_set_position (capture_info.front()->start);
1573 catch (failed_constructor& err) {
1574 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1578 _last_capture_regions.push_back (region);
1580 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1582 XMLNode &before = _playlist->get_state();
1583 _playlist->freeze ();
1585 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1589 _session.region_name (region_name, whole_file_region_name, false);
1591 // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->frames << " add region " << region_name << endl;
1594 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, buffer_position, (*ci)->frames, region_name));
1595 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1598 catch (failed_constructor& err) {
1599 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1600 continue; /* XXX is this OK? */
1603 region->GoingAway.connect (bind (mem_fun (*this, &Diskstream::remove_region_from_last_capture), boost::weak_ptr<Region>(region)));
1605 _last_capture_regions.push_back (region);
1607 i_am_the_modifier++;
1608 _playlist->add_region (region, (*ci)->start);
1609 i_am_the_modifier--;
1611 buffer_position += (*ci)->frames;
1615 XMLNode &after = _playlist->get_state();
1616 _session.add_command (new MementoCommand<Playlist>(*_playlist, &before, &after));
1619 mark_write_completed = true;
1622 reset_write_sources (mark_write_completed);
1626 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1630 capture_info.clear ();
1631 capture_start_frame = 0;
1635 AudioDiskstream::finish_capture (bool rec_monitors_input, boost::shared_ptr<ChannelList> c)
1637 was_recording = false;
1639 if (capture_captured == 0) {
1643 if (recordable() && destructive()) {
1644 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1646 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1647 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1650 if (transvec.len[0] > 0) {
1651 transvec.buf[0]->type = CaptureEnd;
1652 transvec.buf[0]->capture_val = capture_captured;
1653 (*chan)->capture_transition_buf->increment_write_ptr(1);
1657 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1663 CaptureInfo* ci = new CaptureInfo;
1665 ci->start = capture_start_frame;
1666 ci->frames = capture_captured;
1668 /* XXX theoretical race condition here. Need atomic exchange ?
1669 However, the circumstances when this is called right
1670 now (either on record-disable or transport_stopped)
1671 mean that no actual race exists. I think ...
1672 We now have a capture_info_lock, but it is only to be used
1673 to synchronize in the transport_stop and the capture info
1674 accessors, so that invalidation will not occur (both non-realtime).
1677 // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1679 capture_info.push_back (ci);
1680 capture_captured = 0;
1684 AudioDiskstream::set_record_enabled (bool yn)
1686 if (!recordable() || !_session.record_enabling_legal() || _io->n_inputs() == 0) {
1690 /* can't rec-enable in destructive mode if transport is before start */
1692 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1696 if (yn && channels.reader()->front()->source == 0) {
1698 /* pick up connections not initiated *from* the IO object
1699 we're associated with.
1702 get_input_sources ();
1705 /* yes, i know that this not proof against race conditions, but its
1706 good enough. i think.
1709 if (record_enabled() != yn) {
1711 engage_record_enable ();
1713 disengage_record_enable ();
1719 AudioDiskstream::engage_record_enable ()
1721 bool rolling = _session.transport_speed() != 0.0f;
1722 boost::shared_ptr<ChannelList> c = channels.reader();
1724 g_atomic_int_set (&_record_enabled, 1);
1725 capturing_sources.clear ();
1727 if (Config->get_monitoring_model() == HardwareMonitoring) {
1729 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1730 if ((*chan)->source) {
1731 (*chan)->source->ensure_monitor_input (!(Config->get_auto_input() && rolling));
1733 capturing_sources.push_back ((*chan)->write_source);
1737 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1738 capturing_sources.push_back ((*chan)->write_source);
1742 RecordEnableChanged (); /* EMIT SIGNAL */
1746 AudioDiskstream::disengage_record_enable ()
1748 g_atomic_int_set (&_record_enabled, 0);
1749 boost::shared_ptr<ChannelList> c = channels.reader();
1750 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1751 if (Config->get_monitoring_model() == HardwareMonitoring) {
1752 if ((*chan)->source) {
1753 (*chan)->source->ensure_monitor_input (false);
1757 capturing_sources.clear ();
1758 RecordEnableChanged (); /* EMIT SIGNAL */
1762 AudioDiskstream::get_state ()
1764 XMLNode* node = new XMLNode ("AudioDiskstream");
1766 LocaleGuard lg (X_("POSIX"));
1767 boost::shared_ptr<ChannelList> c = channels.reader();
1769 node->add_property ("flags", enum_2_string (_flags));
1771 snprintf (buf, sizeof(buf), "%zd", c->size());
1772 node->add_property ("channels", buf);
1774 node->add_property ("playlist", _playlist->name());
1776 snprintf (buf, sizeof(buf), "%.12g", _visible_speed);
1777 node->add_property ("speed", buf);
1779 node->add_property("name", _name);
1780 id().print (buf, sizeof (buf));
1781 node->add_property("id", buf);
1783 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1785 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1786 XMLNode* cs_grandchild;
1788 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1789 cs_grandchild = new XMLNode (X_("file"));
1790 cs_grandchild->add_property (X_("path"), (*i)->path());
1791 cs_child->add_child_nocopy (*cs_grandchild);
1794 /* store the location where capture will start */
1798 if (Config->get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1799 snprintf (buf, sizeof (buf), "%" PRIu32, pi->start());
1801 snprintf (buf, sizeof (buf), "%" PRIu32, _session.transport_frame());
1804 cs_child->add_property (X_("at"), buf);
1805 node->add_child_nocopy (*cs_child);
1809 node->add_child_copy (*_extra_xml);
1816 AudioDiskstream::set_state (const XMLNode& node)
1818 const XMLProperty* prop;
1819 XMLNodeList nlist = node.children();
1820 XMLNodeIterator niter;
1821 uint32_t nchans = 1;
1822 XMLNode* capture_pending_node = 0;
1823 LocaleGuard lg (X_("POSIX"));
1825 in_set_state = true;
1827 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1828 if ((*niter)->name() == IO::state_node_name) {
1829 deprecated_io_node = new XMLNode (**niter);
1832 if ((*niter)->name() == X_("CapturingSources")) {
1833 capture_pending_node = *niter;
1837 /* prevent write sources from being created */
1839 in_set_state = true;
1841 if ((prop = node.property ("name")) != 0) {
1842 _name = prop->value();
1845 if (deprecated_io_node) {
1846 if ((prop = deprecated_io_node->property ("id")) != 0) {
1847 _id = prop->value ();
1850 if ((prop = node.property ("id")) != 0) {
1851 _id = prop->value ();
1855 if ((prop = node.property ("flags")) != 0) {
1856 _flags = Flag (string_2_enum (prop->value(), _flags));
1859 if ((prop = node.property ("channels")) != 0) {
1860 nchans = atoi (prop->value().c_str());
1863 // create necessary extra channels
1864 // we are always constructed with one and we always need one
1866 _n_channels = channels.reader()->size();
1868 if (nchans > _n_channels) {
1870 add_channel (nchans - _n_channels);
1872 } else if (nchans < _n_channels) {
1874 remove_channel (_n_channels - nchans);
1877 if ((prop = node.property ("playlist")) == 0) {
1882 bool had_playlist = (_playlist != 0);
1884 if (find_and_use_playlist (prop->value())) {
1888 if (!had_playlist) {
1889 _playlist->set_orig_diskstream_id (_id);
1892 if (!destructive() && capture_pending_node) {
1893 /* destructive streams have one and only one source per channel,
1894 and so they never end up in pending capture in any useful
1897 use_pending_capture_data (*capture_pending_node);
1902 if ((prop = node.property ("speed")) != 0) {
1903 double sp = atof (prop->value().c_str());
1905 if (realtime_set_speed (sp, false)) {
1906 non_realtime_set_speed ();
1910 in_set_state = false;
1912 /* make sure this is clear before we do anything else */
1914 capturing_sources.clear ();
1916 /* write sources are handled when we handle the input set
1917 up of the IO that owns this DS (::non_realtime_input_change())
1920 in_set_state = false;
1926 AudioDiskstream::use_new_write_source (uint32_t n)
1928 boost::shared_ptr<ChannelList> c = channels.reader();
1930 if (!recordable()) {
1934 if (n >= c->size()) {
1935 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
1939 ChannelInfo* chan = (*c)[n];
1941 if (chan->write_source) {
1942 chan->write_source->done_with_peakfile_writes ();
1943 chan->write_source->set_allow_remove_if_empty (true);
1944 chan->write_source.reset ();
1948 if ((chan->write_source = _session.create_audio_source_for_session (*this, n, destructive())) == 0) {
1949 throw failed_constructor();
1953 catch (failed_constructor &err) {
1954 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
1955 chan->write_source.reset ();
1959 /* do not remove destructive files even if they are empty */
1961 chan->write_source->set_allow_remove_if_empty (!destructive());
1967 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool force)
1969 ChannelList::iterator chan;
1970 boost::shared_ptr<ChannelList> c = channels.reader();
1973 if (!recordable()) {
1977 capturing_sources.clear ();
1979 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1980 if (!destructive()) {
1982 if ((*chan)->write_source && mark_write_complete) {
1983 (*chan)->write_source->mark_streaming_write_completed ();
1985 use_new_write_source (n);
1987 if (record_enabled()) {
1988 capturing_sources.push_back ((*chan)->write_source);
1992 if ((*chan)->write_source == 0) {
1993 use_new_write_source (n);
1998 if (destructive()) {
2000 /* we now have all our write sources set up, so create the
2001 playlist's single region.
2004 if (_playlist->empty()) {
2005 setup_destructive_playlist ();
2011 AudioDiskstream::rename_write_sources ()
2013 ChannelList::iterator chan;
2014 boost::shared_ptr<ChannelList> c = channels.reader();
2017 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
2018 if ((*chan)->write_source != 0) {
2019 (*chan)->write_source->set_name (_name, destructive());
2020 /* XXX what to do if one of them fails ? */
2028 AudioDiskstream::set_block_size (nframes_t nframes)
2030 if (_session.get_block_size() > speed_buffer_size) {
2031 speed_buffer_size = _session.get_block_size();
2032 boost::shared_ptr<ChannelList> c = channels.reader();
2034 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2035 if ((*chan)->speed_buffer) delete [] (*chan)->speed_buffer;
2036 (*chan)->speed_buffer = new Sample[speed_buffer_size];
2039 allocate_temporary_buffers ();
2043 AudioDiskstream::allocate_temporary_buffers ()
2045 /* make sure the wrap buffer is at least large enough to deal
2046 with the speeds up to 1.2, to allow for micro-variation
2047 when slaving to MTC, SMPTE etc.
2050 double sp = max (fabsf (_actual_speed), 1.2f);
2051 nframes_t required_wrap_size = (nframes_t) floor (_session.get_block_size() * sp) + 1;
2053 if (required_wrap_size > wrap_buffer_size) {
2055 boost::shared_ptr<ChannelList> c = channels.reader();
2057 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2058 if ((*chan)->playback_wrap_buffer) delete [] (*chan)->playback_wrap_buffer;
2059 (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
2060 if ((*chan)->capture_wrap_buffer) delete [] (*chan)->capture_wrap_buffer;
2061 (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
2064 wrap_buffer_size = required_wrap_size;
2069 AudioDiskstream::monitor_input (bool yn)
2071 boost::shared_ptr<ChannelList> c = channels.reader();
2073 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2075 if ((*chan)->source) {
2076 (*chan)->source->ensure_monitor_input (yn);
2082 AudioDiskstream::set_align_style_from_io ()
2084 bool have_physical = false;
2090 get_input_sources ();
2092 boost::shared_ptr<ChannelList> c = channels.reader();
2094 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2095 if ((*chan)->source && (*chan)->source->flags() & JackPortIsPhysical) {
2096 have_physical = true;
2101 if (have_physical) {
2102 set_align_style (ExistingMaterial);
2104 set_align_style (CaptureTime);
2109 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2111 while (how_many--) {
2112 c->push_back (new ChannelInfo(_session.diskstream_buffer_size(), speed_buffer_size, wrap_buffer_size));
2115 _n_channels = c->size();
2121 AudioDiskstream::add_channel (uint32_t how_many)
2123 RCUWriter<ChannelList> writer (channels);
2124 boost::shared_ptr<ChannelList> c = writer.get_copy();
2126 return add_channel_to (c, how_many);
2130 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2132 while (--how_many && !c->empty()) {
2137 _n_channels = c->size();
2143 AudioDiskstream::remove_channel (uint32_t how_many)
2145 RCUWriter<ChannelList> writer (channels);
2146 boost::shared_ptr<ChannelList> c = writer.get_copy();
2148 return remove_channel_from (c, how_many);
2152 AudioDiskstream::playback_buffer_load () const
2154 boost::shared_ptr<ChannelList> c = channels.reader();
2156 return (float) ((double) c->front()->playback_buf->read_space()/
2157 (double) c->front()->playback_buf->bufsize());
2161 AudioDiskstream::capture_buffer_load () const
2163 boost::shared_ptr<ChannelList> c = channels.reader();
2165 return (float) ((double) c->front()->capture_buf->write_space()/
2166 (double) c->front()->capture_buf->bufsize());
2170 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2172 const XMLProperty* prop;
2173 XMLNodeList nlist = node.children();
2174 XMLNodeIterator niter;
2175 boost::shared_ptr<AudioFileSource> fs;
2176 boost::shared_ptr<AudioFileSource> first_fs;
2177 SourceList pending_sources;
2180 if ((prop = node.property (X_("at"))) == 0) {
2184 if (sscanf (prop->value().c_str(), "%" PRIu32, &position) != 1) {
2188 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2189 if ((*niter)->name() == X_("file")) {
2191 if ((prop = (*niter)->property (X_("path"))) == 0) {
2196 fs = boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createWritable (_session, prop->value(), false, _session.frame_rate()));
2199 catch (failed_constructor& err) {
2200 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2201 _name, prop->value())
2206 pending_sources.push_back (fs);
2208 if (first_fs == 0) {
2212 fs->set_captured_for (_name);
2216 if (pending_sources.size() == 0) {
2217 /* nothing can be done */
2221 if (pending_sources.size() != _n_channels) {
2222 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2227 boost::shared_ptr<AudioRegion> region;
2230 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, 0, first_fs->length(),
2231 region_name_from_path (first_fs->name(), true),
2232 0, AudioRegion::Flag (AudioRegion::DefaultFlags|AudioRegion::Automatic|AudioRegion::WholeFile)));
2233 region->special_set_position (0);
2236 catch (failed_constructor& err) {
2237 error << string_compose (_("%1: cannot create whole-file region from pending capture sources"),
2245 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, 0, first_fs->length(), region_name_from_path (first_fs->name(), true)));
2248 catch (failed_constructor& err) {
2249 error << string_compose (_("%1: cannot create region from pending capture sources"),
2256 _playlist->add_region (region, position);
2262 AudioDiskstream::set_destructive (bool yn)
2264 bool bounce_ignored;
2266 if (yn != destructive()) {
2269 /* requestor should already have checked this and
2270 bounced if necessary and desired
2272 if (!can_become_destructive (bounce_ignored)) {
2275 _flags = Flag (_flags | Destructive);
2276 use_destructive_playlist ();
2278 _flags = Flag (_flags & ~Destructive);
2279 reset_write_sources (true, true);
2287 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2290 requires_bounce = false;
2294 /* is there only one region ? */
2296 if (_playlist->n_regions() != 1) {
2297 requires_bounce = true;
2301 boost::shared_ptr<Region> first = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
2304 /* do the source(s) for the region cover the session start position ? */
2306 if (first->position() != _session.current_start_frame()) {
2307 if (first->start() > _session.current_start_frame()) {
2308 requires_bounce = true;
2313 /* is the source used by only 1 playlist ? */
2315 boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2319 if (afirst->source()->used() > 1) {
2320 requires_bounce = true;
2324 requires_bounce = false;
2328 AudioDiskstream::ChannelInfo::ChannelInfo (nframes_t bufsize, nframes_t speed_size, nframes_t wrap_size)
2332 current_capture_buffer = 0;
2333 current_playback_buffer = 0;
2334 curr_capture_cnt = 0;
2336 speed_buffer = new Sample[speed_size];
2337 playback_wrap_buffer = new Sample[wrap_size];
2338 capture_wrap_buffer = new Sample[wrap_size];
2340 playback_buf = new RingBufferNPT<Sample> (bufsize);
2341 capture_buf = new RingBufferNPT<Sample> (bufsize);
2342 capture_transition_buf = new RingBufferNPT<CaptureTransition> (128);
2344 /* touch the ringbuffer buffers, which will cause
2345 them to be mapped into locked physical RAM if
2346 we're running with mlockall(). this doesn't do
2350 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2351 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2352 memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2355 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2358 write_source.reset ();
2362 delete [] speed_buffer;
2366 if (playback_wrap_buffer) {
2367 delete [] playback_wrap_buffer;
2368 playback_wrap_buffer = 0;
2371 if (capture_wrap_buffer) {
2372 delete [] capture_wrap_buffer;
2373 capture_wrap_buffer = 0;
2377 delete playback_buf;
2386 if (capture_transition_buf) {
2387 delete capture_transition_buf;
2388 capture_transition_buf = 0;