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/audio_port.h>
54 #include <ardour/source_factory.h>
60 using namespace ARDOUR;
63 size_t AudioDiskstream::_working_buffers_size = 0;
64 Sample* AudioDiskstream::_mixdown_buffer = 0;
65 gain_t* AudioDiskstream::_gain_buffer = 0;
67 AudioDiskstream::AudioDiskstream (Session &sess, const string &name, Diskstream::Flag flag)
68 : Diskstream(sess, name, flag)
69 , deprecated_io_node(NULL)
70 , channels (new ChannelList)
72 /* prevent any write sources from being created */
82 AudioDiskstream::AudioDiskstream (Session& sess, const XMLNode& node)
83 : Diskstream(sess, node)
84 , deprecated_io_node(NULL)
85 , channels (new ChannelList)
90 if (set_state (node)) {
92 throw failed_constructor();
98 use_destructive_playlist ();
103 AudioDiskstream::init (Diskstream::Flag f)
107 /* there are no channels at this point, so these
108 two calls just get speed_buffer_size and wrap_buffer
109 size setup without duplicating their code.
112 set_block_size (_session.get_block_size());
113 allocate_temporary_buffers ();
116 assert(_n_channels == ChanCount(DataType::AUDIO, 1));
119 AudioDiskstream::~AudioDiskstream ()
124 RCUWriter<ChannelList> writer (channels);
125 boost::shared_ptr<ChannelList> c = writer.get_copy();
127 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
138 AudioDiskstream::allocate_working_buffers()
140 assert(disk_io_frames() > 0);
142 _working_buffers_size = disk_io_frames();
143 _mixdown_buffer = new Sample[_working_buffers_size];
144 _gain_buffer = new gain_t[_working_buffers_size];
148 AudioDiskstream::free_working_buffers()
150 delete [] _mixdown_buffer;
151 delete [] _gain_buffer;
152 _working_buffers_size = 0;
158 AudioDiskstream::non_realtime_input_change ()
161 Glib::Mutex::Lock lm (state_lock);
163 if (input_change_pending == NoChange) {
168 RCUWriter<ChannelList> writer (channels);
169 boost::shared_ptr<ChannelList> c = writer.get_copy();
171 _n_channels.set(DataType::AUDIO, c->size());
173 if (_io->n_inputs().get(DataType::AUDIO) > _n_channels.get(DataType::AUDIO)) {
174 add_channel_to (c, _io->n_inputs().get(DataType::AUDIO) - _n_channels.get(DataType::AUDIO));
175 } else if (_io->n_inputs().get(DataType::AUDIO) < _n_channels.get(DataType::AUDIO)) {
176 remove_channel_from (c, _n_channels.get(DataType::AUDIO) - _io->n_inputs().get(DataType::AUDIO));
180 get_input_sources ();
181 set_capture_offset ();
183 if (first_input_change) {
184 set_align_style (_persistent_alignment_style);
185 first_input_change = false;
187 set_align_style_from_io ();
190 input_change_pending = NoChange;
192 /* implicit unlock */
195 /* reset capture files */
197 reset_write_sources (false);
199 /* now refill channel buffers */
201 if (speed() != 1.0f || speed() != -1.0f) {
202 seek ((nframes_t) (_session.transport_frame() * (double) speed()));
204 seek (_session.transport_frame());
209 AudioDiskstream::get_input_sources ()
211 boost::shared_ptr<ChannelList> c = channels.reader();
214 ChannelList::iterator chan;
215 uint32_t ni = _io->n_inputs().get(DataType::AUDIO);
217 for (n = 0, chan = c->begin(); chan != c->end() && n < ni; ++chan, ++n) {
219 const char **connections = _io->input(n)->get_connections ();
221 if (connections == 0 || connections[0] == 0) {
223 if ((*chan)->source) {
224 // _source->disable_metering ();
230 (*chan)->source = dynamic_cast<AudioPort*>(
231 _session.engine().get_port_by_name (connections[0]) );
241 AudioDiskstream::find_and_use_playlist (const string& name)
243 boost::shared_ptr<AudioPlaylist> playlist;
245 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (_session.playlist_by_name (name))) == 0) {
246 playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (_session, name));
250 error << string_compose(_("AudioDiskstream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
254 return use_playlist (playlist);
258 AudioDiskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
260 assert(boost::dynamic_pointer_cast<AudioPlaylist>(playlist));
262 Diskstream::use_playlist(playlist);
268 AudioDiskstream::use_new_playlist ()
271 boost::shared_ptr<AudioPlaylist> playlist;
273 if (!in_set_state && destructive()) {
278 newname = Playlist::bump_name (_playlist->name(), _session);
280 newname = Playlist::bump_name (_name, _session);
283 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (_session, newname, hidden()))) != 0) {
285 playlist->set_orig_diskstream_id (id());
286 return use_playlist (playlist);
294 AudioDiskstream::use_copy_playlist ()
296 assert(audio_playlist());
302 if (_playlist == 0) {
303 error << string_compose(_("AudioDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
308 boost::shared_ptr<AudioPlaylist> playlist;
310 newname = Playlist::bump_name (_playlist->name(), _session);
312 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist>(PlaylistFactory::create (audio_playlist(), newname))) != 0) {
313 playlist->set_orig_diskstream_id (id());
314 return use_playlist (playlist);
321 AudioDiskstream::setup_destructive_playlist ()
324 boost::shared_ptr<ChannelList> c = channels.reader();
326 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
327 srcs.push_back ((*chan)->write_source);
330 /* a single full-sized region */
332 boost::shared_ptr<Region> region (RegionFactory::create (srcs, 0, max_frames - srcs.front()->natural_position(), _name));
333 _playlist->add_region (region, srcs.front()->natural_position());
337 AudioDiskstream::use_destructive_playlist ()
339 /* this is called from the XML-based constructor or ::set_destructive. when called,
340 we already have a playlist and a region, but we need to
341 set up our sources for write. we use the sources associated
342 with the (presumed single, full-extent) region.
345 boost::shared_ptr<Region> rp = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
348 reset_write_sources (false, true);
352 boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
355 throw failed_constructor();
358 /* be sure to stretch the region out to the maximum length */
360 region->set_length (max_frames - region->position(), this);
363 ChannelList::iterator chan;
364 boost::shared_ptr<ChannelList> c = channels.reader();
366 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
367 (*chan)->write_source = boost::dynamic_pointer_cast<AudioFileSource>(region->source (n));
368 assert((*chan)->write_source);
369 (*chan)->write_source->set_allow_remove_if_empty (false);
371 /* this might be false if we switched modes, so force it */
373 (*chan)->write_source->set_destructive (true);
376 /* the source list will never be reset for a destructive track */
380 AudioDiskstream::check_record_status (nframes_t transport_frame, nframes_t nframes, bool can_record)
382 int possibly_recording;
385 const int transport_rolling = 0x4;
386 const int track_rec_enabled = 0x2;
387 const int global_rec_enabled = 0x1;
389 /* merge together the 3 factors that affect record status, and compute
393 rolling = _session.transport_speed() != 0.0f;
394 possibly_recording = (rolling << 2) | (record_enabled() << 1) | can_record;
395 change = possibly_recording ^ last_possibly_recording;
397 if (possibly_recording == last_possibly_recording) {
403 /* if per-track or global rec-enable turned on while the other was already on, we've started recording */
405 if ((change & track_rec_enabled) && record_enabled() && (!(change & global_rec_enabled) && can_record) ||
406 ((change & global_rec_enabled) && can_record && (!(change & track_rec_enabled) && record_enabled()))) {
408 /* starting to record: compute first+last frames */
410 first_recordable_frame = transport_frame + _capture_offset;
411 last_recordable_frame = max_frames;
412 capture_start_frame = transport_frame;
414 if (!(last_possibly_recording & transport_rolling) && (possibly_recording & transport_rolling)) {
416 /* was stopped, now rolling (and recording) */
418 if (_alignment_style == ExistingMaterial) {
419 first_recordable_frame += _session.worst_output_latency();
421 first_recordable_frame += _roll_delay;
426 /* was rolling, but record state changed */
428 if (_alignment_style == ExistingMaterial) {
430 if (!Config->get_punch_in()) {
432 /* manual punch in happens at the correct transport frame
433 because the user hit a button. but to get alignment correct
434 we have to back up the position of the new region to the
435 appropriate spot given the roll delay.
438 capture_start_frame -= _roll_delay;
440 /* XXX paul notes (august 2005): i don't know why
444 first_recordable_frame += _capture_offset;
448 /* autopunch toggles recording at the precise
449 transport frame, and then the DS waits
450 to start recording for a time that depends
451 on the output latency.
454 first_recordable_frame += _session.worst_output_latency();
459 if (Config->get_punch_in()) {
460 first_recordable_frame += _roll_delay;
462 capture_start_frame -= _roll_delay;
468 if (_flags & Recordable) {
469 boost::shared_ptr<ChannelList> c = channels.reader();
470 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
472 RingBufferNPT<CaptureTransition>::rw_vector transvec;
473 (*chan)->capture_transition_buf->get_write_vector(&transvec);
475 if (transvec.len[0] > 0) {
476 transvec.buf[0]->type = CaptureStart;
477 transvec.buf[0]->capture_val = capture_start_frame;
478 (*chan)->capture_transition_buf->increment_write_ptr(1);
482 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
488 } else if (!record_enabled() || !can_record) {
492 last_recordable_frame = transport_frame + _capture_offset;
494 if (_alignment_style == ExistingMaterial) {
495 last_recordable_frame += _session.worst_output_latency();
497 last_recordable_frame += _roll_delay;
501 last_possibly_recording = possibly_recording;
505 AudioDiskstream::process (nframes_t transport_frame, nframes_t nframes, nframes_t offset, bool can_record, bool rec_monitors_input)
508 boost::shared_ptr<ChannelList> c = channels.reader();
509 ChannelList::iterator chan;
511 nframes_t rec_offset = 0;
512 nframes_t rec_nframes = 0;
513 bool nominally_recording;
514 bool re = record_enabled ();
515 bool collect_playback = false;
517 /* if we've already processed the frames corresponding to this call,
518 just return. this allows multiple routes that are taking input
519 from this diskstream to call our ::process() method, but have
520 this stuff only happen once. more commonly, it allows both
521 the AudioTrack that is using this AudioDiskstream *and* the Session
522 to call process() without problems.
529 commit_should_unlock = false;
531 check_record_status (transport_frame, nframes, can_record);
533 nominally_recording = (can_record && re);
540 /* This lock is held until the end of AudioDiskstream::commit, so these two functions
541 must always be called as a pair. The only exception is if this function
542 returns a non-zero value, in which case, ::commit should not be called.
545 // If we can't take the state lock return.
546 if (!state_lock.trylock()) {
549 commit_should_unlock = true;
550 adjust_capture_position = 0;
552 for (chan = c->begin(); chan != c->end(); ++chan) {
553 (*chan)->current_capture_buffer = 0;
554 (*chan)->current_playback_buffer = 0;
557 if (nominally_recording || (_session.get_record_enabled() && Config->get_punch_in())) {
560 ot = coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
567 case OverlapInternal:
568 /* ---------- recrange
571 rec_nframes = nframes;
576 /* |--------| recrange
579 rec_nframes = transport_frame + nframes - first_recordable_frame;
581 rec_offset = first_recordable_frame - transport_frame;
586 /* |--------| recrange
589 rec_nframes = last_recordable_frame - transport_frame;
593 case OverlapExternal:
594 /* |--------| recrange
595 -------------- transrange
597 rec_nframes = last_recordable_frame - last_recordable_frame;
598 rec_offset = first_recordable_frame - transport_frame;
602 if (rec_nframes && !was_recording) {
603 capture_captured = 0;
604 was_recording = true;
609 if (can_record && !_last_capture_regions.empty()) {
610 _last_capture_regions.clear ();
613 if (nominally_recording || rec_nframes) {
615 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
617 ChannelInfo* chaninfo (*chan);
619 chaninfo->capture_buf->get_write_vector (&chaninfo->capture_vector);
621 if (rec_nframes <= chaninfo->capture_vector.len[0]) {
623 chaninfo->current_capture_buffer = chaninfo->capture_vector.buf[0];
625 /* note: grab the entire port buffer, but only copy what we were supposed to for recording, and use
629 AudioPort* const ap = _io->audio_input(n);
631 assert(rec_nframes <= ap->get_audio_buffer().capacity());
632 memcpy (chaninfo->current_capture_buffer, ap->get_audio_buffer().data(rec_nframes, offset + rec_offset), sizeof (Sample) * rec_nframes);
636 nframes_t total = chaninfo->capture_vector.len[0] + chaninfo->capture_vector.len[1];
638 if (rec_nframes > total) {
643 AudioPort* const ap = _io->audio_input(n);
646 Sample* buf = ap->get_audio_buffer().data(nframes, offset);
647 nframes_t first = chaninfo->capture_vector.len[0];
649 memcpy (chaninfo->capture_wrap_buffer, buf, sizeof (Sample) * first);
650 memcpy (chaninfo->capture_vector.buf[0], buf, sizeof (Sample) * first);
651 memcpy (chaninfo->capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
652 memcpy (chaninfo->capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
654 chaninfo->current_capture_buffer = chaninfo->capture_wrap_buffer;
661 finish_capture (rec_monitors_input, c);
668 /* data will be written to disk */
670 if (rec_nframes == nframes && rec_offset == 0) {
672 for (chan = c->begin(); chan != c->end(); ++chan) {
673 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
676 playback_distance = nframes;
681 /* we can't use the capture buffer as the playback buffer, because
682 we recorded only a part of the current process' cycle data
686 collect_playback = true;
689 adjust_capture_position = rec_nframes;
691 } else if (nominally_recording) {
693 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
695 for (chan = c->begin(); chan != c->end(); ++chan) {
696 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
699 playback_distance = nframes;
703 collect_playback = true;
706 if (collect_playback) {
708 /* we're doing playback */
710 nframes_t necessary_samples;
712 /* no varispeed playback if we're recording, because the output .... TBD */
714 if (rec_nframes == 0 && _actual_speed != 1.0f) {
715 necessary_samples = (nframes_t) floor ((nframes * fabs (_actual_speed))) + 1;
717 necessary_samples = nframes;
720 for (chan = c->begin(); chan != c->end(); ++chan) {
721 (*chan)->playback_buf->get_read_vector (&(*chan)->playback_vector);
726 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
728 ChannelInfo* chaninfo (*chan);
730 if (necessary_samples <= chaninfo->playback_vector.len[0]) {
732 chaninfo->current_playback_buffer = chaninfo->playback_vector.buf[0];
735 nframes_t total = chaninfo->playback_vector.len[0] + chaninfo->playback_vector.len[1];
737 if (necessary_samples > total) {
743 memcpy ((char *) chaninfo->playback_wrap_buffer, chaninfo->playback_vector.buf[0],
744 chaninfo->playback_vector.len[0] * sizeof (Sample));
745 memcpy (chaninfo->playback_wrap_buffer + chaninfo->playback_vector.len[0], chaninfo->playback_vector.buf[1],
746 (necessary_samples - chaninfo->playback_vector.len[0]) * sizeof (Sample));
748 chaninfo->current_playback_buffer = chaninfo->playback_wrap_buffer;
753 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
755 uint64_t phase = last_phase;
758 // Linearly interpolate into the alt buffer
759 // using 40.24 fixp maths (swh)
761 for (chan = c->begin(); chan != c->end(); ++chan) {
764 ChannelInfo* chaninfo (*chan);
769 for (nframes_t outsample = 0; outsample < nframes; ++outsample) {
771 fr = (phase & 0xFFFFFF) / 16777216.0f;
772 chaninfo->speed_buffer[outsample] =
773 chaninfo->current_playback_buffer[i] * (1.0f - fr) +
774 chaninfo->current_playback_buffer[i+1] * fr;
778 chaninfo->current_playback_buffer = chaninfo->speed_buffer;
781 playback_distance = i + 1;
782 last_phase = (phase & 0xFFFFFF);
785 playback_distance = nframes;
797 /* we're exiting with failure, so ::commit will not
798 be called. unlock the state lock.
801 commit_should_unlock = false;
809 AudioDiskstream::commit (nframes_t nframes)
811 bool need_butler = false;
813 if (_actual_speed < 0.0) {
814 playback_sample -= playback_distance;
816 playback_sample += playback_distance;
819 boost::shared_ptr<ChannelList> c = channels.reader();
820 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
822 (*chan)->playback_buf->increment_read_ptr (playback_distance);
824 if (adjust_capture_position) {
825 (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
829 if (adjust_capture_position != 0) {
830 capture_captured += adjust_capture_position;
831 adjust_capture_position = 0;
835 need_butler = c->front()->playback_buf->write_space() >= c->front()->playback_buf->bufsize() / 2;
837 need_butler = c->front()->playback_buf->write_space() >= disk_io_chunk_frames
838 || c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
841 if (commit_should_unlock) {
851 AudioDiskstream::set_pending_overwrite (bool yn)
853 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
855 pending_overwrite = yn;
857 overwrite_frame = playback_sample;
858 overwrite_offset = channels.reader()->front()->playback_buf->get_read_ptr();
862 AudioDiskstream::overwrite_existing_buffers ()
864 boost::shared_ptr<ChannelList> c = channels.reader();
865 Sample* mixdown_buffer;
868 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
870 overwrite_queued = false;
872 /* assume all are the same size */
873 nframes_t size = c->front()->playback_buf->bufsize();
875 mixdown_buffer = new Sample[size];
876 gain_buffer = new float[size];
878 /* reduce size so that we can fill the buffer correctly. */
884 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
886 start = overwrite_frame;
887 nframes_t cnt = size;
889 /* to fill the buffer without resetting the playback sample, we need to
890 do it one or two chunks (normally two).
892 |----------------------------------------------------------------------|
896 |<- second chunk->||<----------------- first chunk ------------------>|
900 nframes_t to_read = size - overwrite_offset;
902 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, *chan, n, reversed)) {
903 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
904 _id, size, playback_sample) << endmsg;
912 if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer,
913 start, cnt, *chan, n, reversed)) {
914 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
915 _id, size, playback_sample) << endmsg;
924 pending_overwrite = false;
925 delete [] gain_buffer;
926 delete [] mixdown_buffer;
931 AudioDiskstream::seek (nframes_t frame, bool complete_refill)
935 ChannelList::iterator chan;
936 boost::shared_ptr<ChannelList> c = channels.reader();
938 Glib::Mutex::Lock lm (state_lock);
940 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
941 (*chan)->playback_buf->reset ();
942 (*chan)->capture_buf->reset ();
945 /* can't rec-enable in destructive mode if transport is before start */
947 if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
948 disengage_record_enable ();
951 playback_sample = frame;
954 if (complete_refill) {
955 while ((ret = do_refill_with_alloc ()) > 0) ;
957 ret = do_refill_with_alloc ();
964 AudioDiskstream::can_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 if ((*chan)->playback_buf->read_space() < distance) {
978 AudioDiskstream::internal_playback_seek (nframes_t distance)
980 ChannelList::iterator chan;
981 boost::shared_ptr<ChannelList> c = channels.reader();
983 for (chan = c->begin(); chan != c->end(); ++chan) {
984 (*chan)->playback_buf->increment_read_ptr (distance);
987 first_recordable_frame += distance;
988 playback_sample += distance;
994 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer, nframes_t& start, nframes_t cnt,
995 ChannelInfo* channel_info, int channel, bool reversed)
997 nframes_t this_read = 0;
999 nframes_t loop_end = 0;
1000 nframes_t loop_start = 0;
1001 nframes_t loop_length = 0;
1002 nframes_t offset = 0;
1005 /* XXX we don't currently play loops in reverse. not sure why */
1009 /* Make the use of a Location atomic for this read operation.
1011 Note: Locations don't get deleted, so all we care about
1012 when I say "atomic" is that we are always pointing to
1013 the same one and using a start/length values obtained
1017 if ((loc = loop_location) != 0) {
1018 loop_start = loc->start();
1019 loop_end = loc->end();
1020 loop_length = loop_end - loop_start;
1023 /* if we are looping, ensure that the first frame we read is at the correct
1024 position within the loop.
1027 if (loc && start >= loop_end) {
1028 //cerr << "start adjusted from " << start;
1029 start = loop_start + ((start - loop_start) % loop_length);
1030 //cerr << "to " << start << endl;
1033 //cerr << "start is " << start << " loopstart: " << loop_start << " loopend: " << loop_end << endl;
1042 /* take any loop into account. we can't read past the end of the loop. */
1044 if (loc && (loop_end - start < cnt)) {
1045 this_read = loop_end - start;
1046 //cerr << "reloop true: thisread: " << this_read << " cnt: " << cnt << endl;
1053 if (this_read == 0) {
1057 this_read = min(cnt,this_read);
1059 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
1060 error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), _id, this_read,
1065 _read_data_count = _playlist->read_data_count();
1069 swap_by_ptr (buf, buf + this_read - 1);
1073 /* if we read to the end of the loop, go back to the beginning */
1083 offset += this_read;
1090 AudioDiskstream::do_refill_with_alloc ()
1092 Sample* mix_buf = new Sample[disk_io_chunk_frames];
1093 float* gain_buf = new float[disk_io_chunk_frames];
1095 int ret = _do_refill(mix_buf, gain_buf);
1104 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer)
1108 RingBufferNPT<Sample>::rw_vector vector;
1109 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1110 nframes_t total_space;
1111 nframes_t zero_fill;
1113 ChannelList::iterator i;
1114 boost::shared_ptr<ChannelList> c = channels.reader();
1121 assert(mixdown_buffer);
1122 assert(gain_buffer);
1129 c->front()->playback_buf->get_write_vector (&vector);
1131 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1135 /* if there are 2+ chunks of disk i/o possible for
1136 this track, let the caller know so that it can arrange
1137 for us to be called again, ASAP.
1140 if (total_space >= (_slaved?3:2) * disk_io_chunk_frames) {
1144 /* if we're running close to normal speed and there isn't enough
1145 space to do disk_io_chunk_frames of I/O, then don't bother.
1147 at higher speeds, just do it because the sync between butler
1148 and audio thread may not be good enough.
1151 if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1155 /* when slaved, don't try to get too close to the read pointer. this
1156 leaves space for the buffer reversal to have something useful to
1160 if (_slaved && total_space < (c->front()->playback_buf->bufsize() / 2)) {
1164 /* never do more than disk_io_chunk_frames worth of disk input per call (limit doesn't apply for memset) */
1166 total_space = min (disk_io_chunk_frames, total_space);
1170 if (file_frame == 0) {
1172 /* at start: nothing to do but fill with silence */
1174 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1176 ChannelInfo* chan (*i);
1177 chan->playback_buf->get_write_vector (&vector);
1178 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1179 if (vector.len[1]) {
1180 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1182 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1187 if (file_frame < total_space) {
1189 /* too close to the start: read what we can,
1190 and then zero fill the rest
1193 zero_fill = total_space - file_frame;
1194 total_space = file_frame;
1204 if (file_frame == max_frames) {
1206 /* at end: nothing to do but fill with silence */
1208 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1210 ChannelInfo* chan (*i);
1211 chan->playback_buf->get_write_vector (&vector);
1212 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1213 if (vector.len[1]) {
1214 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1216 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1221 if (file_frame > max_frames - total_space) {
1223 /* to close to the end: read what we can, and zero fill the rest */
1225 zero_fill = total_space - (max_frames - file_frame);
1226 total_space = max_frames - file_frame;
1233 nframes_t file_frame_tmp = 0;
1235 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1237 ChannelInfo* chan (*i);
1240 nframes_t len1, len2;
1242 chan->playback_buf->get_write_vector (&vector);
1244 if (vector.len[0] > disk_io_chunk_frames) {
1246 /* we're not going to fill the first chunk, so certainly do not bother with the
1247 other part. it won't be connected with the part we do fill, as in:
1249 .... => writable space
1250 ++++ => readable space
1251 ^^^^ => 1 x disk_io_chunk_frames that would be filled
1253 |......|+++++++++++++|...............................|
1258 So, just pretend that the buf1 part isn't there.
1268 file_frame_tmp = file_frame;
1270 buf1 = vector.buf[0];
1271 len1 = vector.len[0];
1272 buf2 = vector.buf[1];
1273 len2 = vector.len[1];
1275 to_read = min (ts, len1);
1276 to_read = min (to_read, disk_io_chunk_frames);
1280 if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1285 chan->playback_buf->increment_write_ptr (to_read);
1289 to_read = min (ts, len2);
1293 /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1294 so read some or all of vector.len[1] as well.
1297 if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1302 chan->playback_buf->increment_write_ptr (to_read);
1311 file_frame = file_frame_tmp;
1318 /** Flush pending data to disk.
1320 * Important note: this function will write *AT MOST* disk_io_chunk_frames
1321 * of data to disk. it will never write more than that. If it writes that
1322 * much and there is more than that waiting to be written, it will return 1,
1323 * otherwise 0 on success or -1 on failure.
1325 * If there is less than disk_io_chunk_frames to be written, no data will be
1326 * written at all unless @a force_flush is true.
1329 AudioDiskstream::do_flush (Session::RunContext context, bool force_flush)
1333 RingBufferNPT<Sample>::rw_vector vector;
1334 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1337 _write_data_count = 0;
1339 transvec.buf[0] = 0;
1340 transvec.buf[1] = 0;
1344 boost::shared_ptr<ChannelList> c = channels.reader();
1345 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1347 (*chan)->capture_buf->get_read_vector (&vector);
1349 total = vector.len[0] + vector.len[1];
1351 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1355 /* if there are 2+ chunks of disk i/o possible for
1356 this track, let the caller know so that it can arrange
1357 for us to be called again, ASAP.
1359 if we are forcing a flush, then if there is* any* extra
1360 work, let the caller know.
1362 if we are no longer recording and there is any extra work,
1363 let the caller know too.
1366 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1370 to_write = min (disk_io_chunk_frames, (nframes_t) vector.len[0]);
1372 // check the transition buffer when recording destructive
1373 // important that we get this after the capture buf
1375 if (destructive()) {
1376 (*chan)->capture_transition_buf->get_read_vector(&transvec);
1377 size_t transcount = transvec.len[0] + transvec.len[1];
1378 bool have_start = false;
1381 for (ti=0; ti < transcount; ++ti) {
1382 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1384 if (captrans.type == CaptureStart) {
1385 // by definition, the first data we got above represents the given capture pos
1387 (*chan)->write_source->mark_capture_start (captrans.capture_val);
1388 (*chan)->curr_capture_cnt = 0;
1392 else if (captrans.type == CaptureEnd) {
1394 // capture end, the capture_val represents total frames in capture
1396 if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1398 // shorten to make the write a perfect fit
1399 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
1401 if (nto_write < to_write) {
1402 ret = 1; // should we?
1404 to_write = nto_write;
1406 (*chan)->write_source->mark_capture_end ();
1408 // increment past this transition, but go no further
1413 // actually ends just beyond this chunk, so force more work
1421 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1425 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1426 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1430 (*chan)->capture_buf->increment_read_ptr (to_write);
1431 (*chan)->curr_capture_cnt += to_write;
1433 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1435 /* we wrote all of vector.len[0] but it wasn't an entire
1436 disk_io_chunk_frames of data, so arrange for some part
1437 of vector.len[1] to be flushed to disk as well.
1440 to_write = min ((nframes_t)(disk_io_chunk_frames - to_write), (nframes_t) vector.len[1]);
1442 if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1443 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1447 _write_data_count += (*chan)->write_source->write_data_count();
1449 (*chan)->capture_buf->increment_read_ptr (to_write);
1450 (*chan)->curr_capture_cnt += to_write;
1459 AudioDiskstream::transport_stopped (struct tm& when, time_t twhen, bool abort_capture)
1461 uint32_t buffer_position;
1462 bool more_work = true;
1464 boost::shared_ptr<AudioRegion> region;
1465 nframes_t total_capture;
1467 SourceList::iterator src;
1468 ChannelList::iterator chan;
1469 vector<CaptureInfo*>::iterator ci;
1470 boost::shared_ptr<ChannelList> c = channels.reader();
1472 bool mark_write_completed = false;
1474 finish_capture (true, c);
1476 /* butler is already stopped, but there may be work to do
1477 to flush remaining data to disk.
1480 while (more_work && !err) {
1481 switch (do_flush (Session::TransportContext, true)) {
1488 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1493 /* XXX is there anything we can do if err != 0 ? */
1494 Glib::Mutex::Lock lm (capture_info_lock);
1496 if (capture_info.empty()) {
1500 if (abort_capture) {
1502 if (destructive()) {
1506 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1508 if ((*chan)->write_source) {
1510 (*chan)->write_source->mark_for_remove ();
1511 (*chan)->write_source->drop_references ();
1512 (*chan)->write_source.reset ();
1515 /* new source set up in "out" below */
1521 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1522 total_capture += (*ci)->frames;
1525 /* figure out the name for this take */
1527 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1529 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1533 s->update_header (capture_info.front()->start, when, twhen);
1534 s->set_captured_for (_name);
1535 s->mark_immutable ();
1539 /* destructive tracks have a single, never changing region */
1541 if (destructive()) {
1543 /* send a signal that any UI can pick up to do the right thing. there is
1544 a small problem here in that a UI may need the peak data to be ready
1545 for the data that was recorded and this isn't interlocked with that
1546 process. this problem is deferred to the UI.
1549 _playlist->Modified();
1553 string whole_file_region_name;
1554 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1556 /* Register a new region with the Session that
1557 describes the entire source. Do this first
1558 so that any sub-regions will obviously be
1559 children of this one (later!)
1563 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, c->front()->write_source->last_capture_start_frame(), total_capture,
1564 whole_file_region_name,
1565 0, AudioRegion::Flag (AudioRegion::DefaultFlags|AudioRegion::Automatic|AudioRegion::WholeFile)));
1567 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1568 region->special_set_position (capture_info.front()->start);
1572 catch (failed_constructor& err) {
1573 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1577 _last_capture_regions.push_back (region);
1579 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1581 XMLNode &before = _playlist->get_state();
1582 _playlist->freeze ();
1584 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1588 _session.region_name (region_name, whole_file_region_name, false);
1590 // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->frames << " add region " << region_name << endl;
1593 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, buffer_position, (*ci)->frames, region_name));
1594 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1597 catch (failed_constructor& err) {
1598 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1599 continue; /* XXX is this OK? */
1602 region->GoingAway.connect (bind (mem_fun (*this, &Diskstream::remove_region_from_last_capture), boost::weak_ptr<Region>(region)));
1604 _last_capture_regions.push_back (region);
1606 i_am_the_modifier++;
1607 _playlist->add_region (region, (*ci)->start);
1608 i_am_the_modifier--;
1610 buffer_position += (*ci)->frames;
1614 XMLNode &after = _playlist->get_state();
1615 _session.add_command (new MementoCommand<Playlist>(*_playlist, &before, &after));
1618 mark_write_completed = true;
1621 reset_write_sources (mark_write_completed);
1625 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1629 capture_info.clear ();
1630 capture_start_frame = 0;
1634 AudioDiskstream::finish_capture (bool rec_monitors_input, boost::shared_ptr<ChannelList> c)
1636 was_recording = false;
1638 if (capture_captured == 0) {
1642 if (recordable() && destructive()) {
1643 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1645 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1646 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1649 if (transvec.len[0] > 0) {
1650 transvec.buf[0]->type = CaptureEnd;
1651 transvec.buf[0]->capture_val = capture_captured;
1652 (*chan)->capture_transition_buf->increment_write_ptr(1);
1656 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1662 CaptureInfo* ci = new CaptureInfo;
1664 ci->start = capture_start_frame;
1665 ci->frames = capture_captured;
1667 /* XXX theoretical race condition here. Need atomic exchange ?
1668 However, the circumstances when this is called right
1669 now (either on record-disable or transport_stopped)
1670 mean that no actual race exists. I think ...
1671 We now have a capture_info_lock, but it is only to be used
1672 to synchronize in the transport_stop and the capture info
1673 accessors, so that invalidation will not occur (both non-realtime).
1676 // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1678 capture_info.push_back (ci);
1679 capture_captured = 0;
1683 AudioDiskstream::set_record_enabled (bool yn)
1685 if (!recordable() || !_session.record_enabling_legal() || _io->n_inputs().get(DataType::AUDIO) == 0) {
1689 /* can't rec-enable in destructive mode if transport is before start */
1691 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1695 if (yn && channels.reader()->front()->source == 0) {
1697 /* pick up connections not initiated *from* the IO object
1698 we're associated with.
1701 get_input_sources ();
1704 /* yes, i know that this not proof against race conditions, but its
1705 good enough. i think.
1708 if (record_enabled() != yn) {
1710 engage_record_enable ();
1712 disengage_record_enable ();
1718 AudioDiskstream::engage_record_enable ()
1720 bool rolling = _session.transport_speed() != 0.0f;
1721 boost::shared_ptr<ChannelList> c = channels.reader();
1723 g_atomic_int_set (&_record_enabled, 1);
1724 capturing_sources.clear ();
1726 if (Config->get_monitoring_model() == HardwareMonitoring) {
1728 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1729 if ((*chan)->source) {
1730 (*chan)->source->ensure_monitor_input (!(Config->get_auto_input() && rolling));
1732 capturing_sources.push_back ((*chan)->write_source);
1736 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1737 capturing_sources.push_back ((*chan)->write_source);
1741 RecordEnableChanged (); /* EMIT SIGNAL */
1745 AudioDiskstream::disengage_record_enable ()
1747 g_atomic_int_set (&_record_enabled, 0);
1748 boost::shared_ptr<ChannelList> c = channels.reader();
1749 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1750 if (Config->get_monitoring_model() == HardwareMonitoring) {
1751 if ((*chan)->source) {
1752 (*chan)->source->ensure_monitor_input (false);
1756 capturing_sources.clear ();
1757 RecordEnableChanged (); /* EMIT SIGNAL */
1761 AudioDiskstream::get_state ()
1763 XMLNode* node = new XMLNode ("AudioDiskstream");
1765 LocaleGuard lg (X_("POSIX"));
1766 boost::shared_ptr<ChannelList> c = channels.reader();
1768 node->add_property ("flags", enum_2_string (_flags));
1770 snprintf (buf, sizeof(buf), "%zd", c->size());
1771 node->add_property ("channels", buf);
1773 node->add_property ("playlist", _playlist->name());
1775 snprintf (buf, sizeof(buf), "%.12g", _visible_speed);
1776 node->add_property ("speed", buf);
1778 node->add_property("name", _name);
1779 id().print (buf, sizeof (buf));
1780 node->add_property("id", buf);
1782 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1784 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1785 XMLNode* cs_grandchild;
1787 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1788 cs_grandchild = new XMLNode (X_("file"));
1789 cs_grandchild->add_property (X_("path"), (*i)->path());
1790 cs_child->add_child_nocopy (*cs_grandchild);
1793 /* store the location where capture will start */
1797 if (Config->get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1798 snprintf (buf, sizeof (buf), "%" PRIu32, pi->start());
1800 snprintf (buf, sizeof (buf), "%" PRIu32, _session.transport_frame());
1803 cs_child->add_property (X_("at"), buf);
1804 node->add_child_nocopy (*cs_child);
1808 node->add_child_copy (*_extra_xml);
1815 AudioDiskstream::set_state (const XMLNode& node)
1817 const XMLProperty* prop;
1818 XMLNodeList nlist = node.children();
1819 XMLNodeIterator niter;
1820 uint32_t nchans = 1;
1821 XMLNode* capture_pending_node = 0;
1822 LocaleGuard lg (X_("POSIX"));
1824 in_set_state = true;
1826 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1827 if ((*niter)->name() == IO::state_node_name) {
1828 deprecated_io_node = new XMLNode (**niter);
1831 if ((*niter)->name() == X_("CapturingSources")) {
1832 capture_pending_node = *niter;
1836 /* prevent write sources from being created */
1838 in_set_state = true;
1840 if ((prop = node.property ("name")) != 0) {
1841 _name = prop->value();
1844 if (deprecated_io_node) {
1845 if ((prop = deprecated_io_node->property ("id")) != 0) {
1846 _id = prop->value ();
1849 if ((prop = node.property ("id")) != 0) {
1850 _id = prop->value ();
1854 if ((prop = node.property ("flags")) != 0) {
1855 _flags = Flag (string_2_enum (prop->value(), _flags));
1858 if ((prop = node.property ("channels")) != 0) {
1859 nchans = atoi (prop->value().c_str());
1862 // create necessary extra channels
1863 // we are always constructed with one and we always need one
1865 _n_channels.set(DataType::AUDIO, channels.reader()->size());
1867 if (nchans > _n_channels.get(DataType::AUDIO)) {
1869 add_channel (nchans - _n_channels.get(DataType::AUDIO));
1871 } else if (nchans < _n_channels.get(DataType::AUDIO)) {
1873 remove_channel (_n_channels.get(DataType::AUDIO) - nchans);
1876 if ((prop = node.property ("playlist")) == 0) {
1881 bool had_playlist = (_playlist != 0);
1883 if (find_and_use_playlist (prop->value())) {
1887 if (!had_playlist) {
1888 _playlist->set_orig_diskstream_id (_id);
1891 if (!destructive() && capture_pending_node) {
1892 /* destructive streams have one and only one source per channel,
1893 and so they never end up in pending capture in any useful
1896 use_pending_capture_data (*capture_pending_node);
1901 if ((prop = node.property ("speed")) != 0) {
1902 double sp = atof (prop->value().c_str());
1904 if (realtime_set_speed (sp, false)) {
1905 non_realtime_set_speed ();
1909 in_set_state = false;
1911 /* make sure this is clear before we do anything else */
1913 capturing_sources.clear ();
1915 /* write sources are handled when we handle the input set
1916 up of the IO that owns this DS (::non_realtime_input_change())
1919 in_set_state = false;
1925 AudioDiskstream::use_new_write_source (uint32_t n)
1927 boost::shared_ptr<ChannelList> c = channels.reader();
1929 if (!recordable()) {
1933 if (n >= c->size()) {
1934 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
1938 ChannelInfo* chan = (*c)[n];
1940 if (chan->write_source) {
1941 chan->write_source->done_with_peakfile_writes ();
1942 chan->write_source->set_allow_remove_if_empty (true);
1943 chan->write_source.reset ();
1947 if ((chan->write_source = _session.create_audio_source_for_session (*this, n, destructive())) == 0) {
1948 throw failed_constructor();
1952 catch (failed_constructor &err) {
1953 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
1954 chan->write_source.reset ();
1958 /* do not remove destructive files even if they are empty */
1960 chan->write_source->set_allow_remove_if_empty (!destructive());
1966 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool force)
1968 ChannelList::iterator chan;
1969 boost::shared_ptr<ChannelList> c = channels.reader();
1972 if (!recordable()) {
1976 capturing_sources.clear ();
1978 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1979 if (!destructive()) {
1981 if ((*chan)->write_source && mark_write_complete) {
1982 (*chan)->write_source->mark_streaming_write_completed ();
1984 use_new_write_source (n);
1986 if (record_enabled()) {
1987 capturing_sources.push_back ((*chan)->write_source);
1991 if ((*chan)->write_source == 0) {
1992 use_new_write_source (n);
1997 if (destructive()) {
1999 /* we now have all our write sources set up, so create the
2000 playlist's single region.
2003 if (_playlist->empty()) {
2004 setup_destructive_playlist ();
2010 AudioDiskstream::rename_write_sources ()
2012 ChannelList::iterator chan;
2013 boost::shared_ptr<ChannelList> c = channels.reader();
2016 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
2017 if ((*chan)->write_source != 0) {
2018 (*chan)->write_source->set_name (_name, destructive());
2019 /* XXX what to do if one of them fails ? */
2027 AudioDiskstream::set_block_size (nframes_t nframes)
2029 if (_session.get_block_size() > speed_buffer_size) {
2030 speed_buffer_size = _session.get_block_size();
2031 boost::shared_ptr<ChannelList> c = channels.reader();
2033 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2034 if ((*chan)->speed_buffer) delete [] (*chan)->speed_buffer;
2035 (*chan)->speed_buffer = new Sample[speed_buffer_size];
2038 allocate_temporary_buffers ();
2042 AudioDiskstream::allocate_temporary_buffers ()
2044 /* make sure the wrap buffer is at least large enough to deal
2045 with the speeds up to 1.2, to allow for micro-variation
2046 when slaving to MTC, SMPTE etc.
2049 double sp = max (fabsf (_actual_speed), 1.2f);
2050 nframes_t required_wrap_size = (nframes_t) floor (_session.get_block_size() * sp) + 1;
2052 if (required_wrap_size > wrap_buffer_size) {
2054 boost::shared_ptr<ChannelList> c = channels.reader();
2056 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2057 if ((*chan)->playback_wrap_buffer) delete [] (*chan)->playback_wrap_buffer;
2058 (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
2059 if ((*chan)->capture_wrap_buffer) delete [] (*chan)->capture_wrap_buffer;
2060 (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
2063 wrap_buffer_size = required_wrap_size;
2068 AudioDiskstream::monitor_input (bool yn)
2070 boost::shared_ptr<ChannelList> c = channels.reader();
2072 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2074 if ((*chan)->source) {
2075 (*chan)->source->ensure_monitor_input (yn);
2081 AudioDiskstream::set_align_style_from_io ()
2083 bool have_physical = false;
2089 get_input_sources ();
2091 boost::shared_ptr<ChannelList> c = channels.reader();
2093 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2094 if ((*chan)->source && (*chan)->source->flags() & JackPortIsPhysical) {
2095 have_physical = true;
2100 if (have_physical) {
2101 set_align_style (ExistingMaterial);
2103 set_align_style (CaptureTime);
2108 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2110 while (how_many--) {
2111 c->push_back (new ChannelInfo(_session.diskstream_buffer_size(), speed_buffer_size, wrap_buffer_size));
2114 _n_channels.set(DataType::AUDIO, c->size());
2120 AudioDiskstream::add_channel (uint32_t how_many)
2122 RCUWriter<ChannelList> writer (channels);
2123 boost::shared_ptr<ChannelList> c = writer.get_copy();
2125 return add_channel_to (c, how_many);
2129 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2131 while (--how_many && !c->empty()) {
2136 _n_channels.set(DataType::AUDIO, c->size());
2142 AudioDiskstream::remove_channel (uint32_t how_many)
2144 RCUWriter<ChannelList> writer (channels);
2145 boost::shared_ptr<ChannelList> c = writer.get_copy();
2147 return remove_channel_from (c, how_many);
2151 AudioDiskstream::playback_buffer_load () const
2153 boost::shared_ptr<ChannelList> c = channels.reader();
2155 return (float) ((double) c->front()->playback_buf->read_space()/
2156 (double) c->front()->playback_buf->bufsize());
2160 AudioDiskstream::capture_buffer_load () const
2162 boost::shared_ptr<ChannelList> c = channels.reader();
2164 return (float) ((double) c->front()->capture_buf->write_space()/
2165 (double) c->front()->capture_buf->bufsize());
2169 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2171 const XMLProperty* prop;
2172 XMLNodeList nlist = node.children();
2173 XMLNodeIterator niter;
2174 boost::shared_ptr<AudioFileSource> fs;
2175 boost::shared_ptr<AudioFileSource> first_fs;
2176 SourceList pending_sources;
2179 if ((prop = node.property (X_("at"))) == 0) {
2183 if (sscanf (prop->value().c_str(), "%" PRIu32, &position) != 1) {
2187 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2188 if ((*niter)->name() == X_("file")) {
2190 if ((prop = (*niter)->property (X_("path"))) == 0) {
2195 fs = boost::dynamic_pointer_cast<AudioFileSource> (
2196 SourceFactory::createWritable (DataType::AUDIO, _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.get(DataType::AUDIO)) {
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;