2 Copyright (C) 2000-2006 Paul Davis
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
33 #include "pbd/error.h"
34 #include <glibmm/thread.h>
35 #include "pbd/xml++.h"
36 #include "pbd/memento_command.h"
37 #include "pbd/enumwriter.h"
38 #include "pbd/stacktrace.h"
40 #include "ardour/ardour.h"
41 #include "ardour/audioengine.h"
42 #include "ardour/analyser.h"
43 #include "ardour/audio_diskstream.h"
44 #include "ardour/utils.h"
45 #include "ardour/configuration.h"
46 #include "ardour/audiofilesource.h"
47 #include "ardour/send.h"
48 #include "ardour/region_factory.h"
49 #include "ardour/audioplaylist.h"
50 #include "ardour/playlist_factory.h"
51 #include "ardour/cycle_timer.h"
52 #include "ardour/audioregion.h"
53 #include "ardour/audio_port.h"
54 #include "ardour/source_factory.h"
55 #include "ardour/audio_buffer.h"
56 #include "ardour/session.h"
57 #include "ardour/io.h"
63 using namespace ARDOUR;
66 size_t AudioDiskstream::_working_buffers_size = 0;
67 Sample* AudioDiskstream::_mixdown_buffer = 0;
68 gain_t* AudioDiskstream::_gain_buffer = 0;
70 AudioDiskstream::AudioDiskstream (Session &sess, const string &name, Diskstream::Flag flag)
71 : Diskstream(sess, name, flag)
72 , deprecated_io_node(NULL)
73 , channels (new ChannelList)
75 /* prevent any write sources from being created */
85 AudioDiskstream::AudioDiskstream (Session& sess, const XMLNode& node)
86 : Diskstream(sess, node)
87 , deprecated_io_node(NULL)
88 , channels (new ChannelList)
93 if (set_state (node)) {
95 throw failed_constructor();
101 use_destructive_playlist ();
106 AudioDiskstream::init (Diskstream::Flag f)
110 /* there are no channels at this point, so these
111 two calls just get speed_buffer_size and wrap_buffer
112 size setup without duplicating their code.
115 set_block_size (_session.get_block_size());
116 allocate_temporary_buffers ();
119 assert(_n_channels == ChanCount(DataType::AUDIO, 1));
122 AudioDiskstream::~AudioDiskstream ()
127 RCUWriter<ChannelList> writer (channels);
128 boost::shared_ptr<ChannelList> c = writer.get_copy();
130 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
141 AudioDiskstream::allocate_working_buffers()
143 assert(disk_io_frames() > 0);
145 _working_buffers_size = disk_io_frames();
146 _mixdown_buffer = new Sample[_working_buffers_size];
147 _gain_buffer = new gain_t[_working_buffers_size];
151 AudioDiskstream::free_working_buffers()
153 delete [] _mixdown_buffer;
154 delete [] _gain_buffer;
155 _working_buffers_size = 0;
161 AudioDiskstream::non_realtime_input_change ()
163 cerr << "AD::NRIC ... " << name() << endl;
166 Glib::Mutex::Lock lm (state_lock);
168 if (input_change_pending == NoChange) {
173 RCUWriter<ChannelList> writer (channels);
174 boost::shared_ptr<ChannelList> c = writer.get_copy();
176 _n_channels.set(DataType::AUDIO, c->size());
178 if (_io->n_ports().n_audio() > _n_channels.n_audio()) {
179 add_channel_to (c, _io->n_ports().n_audio() - _n_channels.n_audio());
180 } else if (_io->n_ports().n_audio() < _n_channels.n_audio()) {
181 remove_channel_from (c, _n_channels.n_audio() - _io->n_ports().n_audio());
185 get_input_sources ();
186 set_capture_offset ();
188 if (first_input_change) {
189 set_align_style (_persistent_alignment_style);
190 first_input_change = false;
192 set_align_style_from_io ();
195 input_change_pending = NoChange;
197 /* implicit unlock */
200 /* reset capture files */
202 reset_write_sources (false);
204 /* now refill channel buffers */
206 if (speed() != 1.0f || speed() != -1.0f) {
207 seek ((nframes_t) (_session.transport_frame() * (double) speed()));
209 seek (_session.transport_frame());
214 AudioDiskstream::non_realtime_locate (nframes_t location)
216 /* now refill channel buffers */
218 if (speed() != 1.0f || speed() != -1.0f) {
219 seek ((nframes_t) (location * (double) speed()));
226 AudioDiskstream::get_input_sources ()
228 boost::shared_ptr<ChannelList> c = channels.reader();
231 ChannelList::iterator chan;
232 uint32_t ni = _io->n_ports().n_audio();
233 vector<string> connections;
235 for (n = 0, chan = c->begin(); chan != c->end() && n < ni; ++chan, ++n) {
237 connections.clear ();
239 if (_io->nth (n)->get_connections (connections) == 0) {
241 if ((*chan)->source) {
242 // _source->disable_metering ();
248 (*chan)->source = dynamic_cast<AudioPort*>(_session.engine().get_port_by_name (connections[0]) );
254 AudioDiskstream::find_and_use_playlist (const string& name)
256 boost::shared_ptr<AudioPlaylist> playlist;
258 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (_session.playlist_by_name (name))) == 0) {
259 playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, name));
263 error << string_compose(_("AudioDiskstream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
267 return use_playlist (playlist);
271 AudioDiskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
273 assert(boost::dynamic_pointer_cast<AudioPlaylist>(playlist));
275 Diskstream::use_playlist(playlist);
281 AudioDiskstream::use_new_playlist ()
284 boost::shared_ptr<AudioPlaylist> playlist;
286 if (!in_set_state && destructive()) {
291 newname = Playlist::bump_name (_playlist->name(), _session);
293 newname = Playlist::bump_name (_name, _session);
296 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, newname, hidden()))) != 0) {
298 playlist->set_orig_diskstream_id (id());
299 return use_playlist (playlist);
307 AudioDiskstream::use_copy_playlist ()
309 assert(audio_playlist());
315 if (_playlist == 0) {
316 error << string_compose(_("AudioDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
321 boost::shared_ptr<AudioPlaylist> playlist;
323 newname = Playlist::bump_name (_playlist->name(), _session);
325 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist>(PlaylistFactory::create (audio_playlist(), newname))) != 0) {
326 playlist->set_orig_diskstream_id (id());
327 return use_playlist (playlist);
334 AudioDiskstream::setup_destructive_playlist ()
337 boost::shared_ptr<ChannelList> c = channels.reader();
339 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
340 srcs.push_back ((*chan)->write_source);
343 /* a single full-sized region */
345 boost::shared_ptr<Region> region (RegionFactory::create (srcs, 0, max_frames - srcs.front()->natural_position(), _name));
346 _playlist->add_region (region, srcs.front()->natural_position());
350 AudioDiskstream::use_destructive_playlist ()
352 /* this is called from the XML-based constructor or ::set_destructive. when called,
353 we already have a playlist and a region, but we need to
354 set up our sources for write. we use the sources associated
355 with the (presumed single, full-extent) region.
358 boost::shared_ptr<Region> rp = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
361 reset_write_sources (false, true);
365 boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
368 throw failed_constructor();
371 /* be sure to stretch the region out to the maximum length */
373 region->set_length (max_frames - region->position(), this);
376 ChannelList::iterator chan;
377 boost::shared_ptr<ChannelList> c = channels.reader();
379 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
380 (*chan)->write_source = boost::dynamic_pointer_cast<AudioFileSource>(region->source (n));
381 assert((*chan)->write_source);
382 (*chan)->write_source->set_allow_remove_if_empty (false);
384 /* this might be false if we switched modes, so force it */
386 (*chan)->write_source->set_destructive (true);
389 /* the source list will never be reset for a destructive track */
393 AudioDiskstream::check_record_status (nframes_t transport_frame, nframes_t nframes, bool can_record)
395 int possibly_recording;
398 const int transport_rolling = 0x4;
399 const int track_rec_enabled = 0x2;
400 const int global_rec_enabled = 0x1;
402 /* merge together the 3 factors that affect record status, and compute
406 rolling = _session.transport_speed() != 0.0f;
407 possibly_recording = (rolling << 2) | (record_enabled() << 1) | can_record;
408 change = possibly_recording ^ last_possibly_recording;
410 if (possibly_recording == last_possibly_recording) {
416 /* if per-track or global rec-enable turned on while the other was already on, we've started recording */
418 if (((change & track_rec_enabled) && record_enabled() && (!(change & global_rec_enabled) && can_record)) ||
419 ((change & global_rec_enabled) && can_record && (!(change & track_rec_enabled) && record_enabled()))) {
421 /* starting to record: compute first+last frames */
423 first_recordable_frame = transport_frame + _capture_offset;
424 last_recordable_frame = max_frames;
425 capture_start_frame = transport_frame;
427 if (!(last_possibly_recording & transport_rolling) && (possibly_recording & transport_rolling)) {
429 /* was stopped, now rolling (and recording) */
431 if (_alignment_style == ExistingMaterial) {
432 first_recordable_frame += _session.worst_output_latency();
434 first_recordable_frame += _roll_delay;
439 /* was rolling, but record state changed */
441 if (_alignment_style == ExistingMaterial) {
443 if (!_session.config.get_punch_in()) {
445 /* manual punch in happens at the correct transport frame
446 because the user hit a button. but to get alignment correct
447 we have to back up the position of the new region to the
448 appropriate spot given the roll delay.
451 capture_start_frame -= _roll_delay;
453 /* XXX paul notes (august 2005): i don't know why
457 first_recordable_frame += _capture_offset;
461 /* autopunch toggles recording at the precise
462 transport frame, and then the DS waits
463 to start recording for a time that depends
464 on the output latency.
467 first_recordable_frame += _session.worst_output_latency();
472 if (_session.config.get_punch_in()) {
473 first_recordable_frame += _roll_delay;
475 capture_start_frame -= _roll_delay;
481 if (recordable() && destructive()) {
482 boost::shared_ptr<ChannelList> c = channels.reader();
483 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
485 RingBufferNPT<CaptureTransition>::rw_vector transvec;
486 (*chan)->capture_transition_buf->get_write_vector(&transvec);
488 if (transvec.len[0] > 0) {
489 transvec.buf[0]->type = CaptureStart;
490 transvec.buf[0]->capture_val = capture_start_frame;
491 (*chan)->capture_transition_buf->increment_write_ptr(1);
495 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
501 } else if (!record_enabled() || !can_record) {
505 last_recordable_frame = transport_frame + _capture_offset;
507 if (_alignment_style == ExistingMaterial) {
508 last_recordable_frame += _session.worst_output_latency();
510 last_recordable_frame += _roll_delay;
514 last_possibly_recording = possibly_recording;
518 AudioDiskstream::process (nframes_t transport_frame, nframes_t nframes, bool can_record, bool rec_monitors_input)
521 boost::shared_ptr<ChannelList> c = channels.reader();
522 ChannelList::iterator chan;
524 nframes_t rec_offset = 0;
525 nframes_t rec_nframes = 0;
526 bool nominally_recording;
527 bool re = record_enabled ();
528 bool collect_playback = false;
530 /* if we've already processed the frames corresponding to this call,
531 just return. this allows multiple routes that are taking input
532 from this diskstream to call our ::process() method, but have
533 this stuff only happen once. more commonly, it allows both
534 the AudioTrack that is using this AudioDiskstream *and* the Session
535 to call process() without problems.
542 commit_should_unlock = false;
544 if (!_io || !_io->active()) {
549 check_record_status (transport_frame, nframes, can_record);
551 nominally_recording = (can_record && re);
558 /* This lock is held until the end of AudioDiskstream::commit, so these two functions
559 must always be called as a pair. The only exception is if this function
560 returns a non-zero value, in which case, ::commit should not be called.
563 // If we can't take the state lock return.
564 if (!state_lock.trylock()) {
567 commit_should_unlock = true;
568 adjust_capture_position = 0;
570 for (chan = c->begin(); chan != c->end(); ++chan) {
571 (*chan)->current_capture_buffer = 0;
572 (*chan)->current_playback_buffer = 0;
575 if (nominally_recording || (_session.get_record_enabled() && _session.config.get_punch_in())) {
578 // Safeguard against situations where process() goes haywire when autopunching and last_recordable_frame < first_recordable_frame
579 if (last_recordable_frame < first_recordable_frame) {
580 last_recordable_frame = max_frames;
583 ot = coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
590 case OverlapInternal:
591 /* ---------- recrange
594 rec_nframes = nframes;
599 /* |--------| recrange
602 rec_nframes = transport_frame + nframes - first_recordable_frame;
604 rec_offset = first_recordable_frame - transport_frame;
609 /* |--------| recrange
612 rec_nframes = last_recordable_frame - transport_frame;
616 case OverlapExternal:
617 /* |--------| recrange
618 -------------- transrange
620 rec_nframes = last_recordable_frame - first_recordable_frame;
621 rec_offset = first_recordable_frame - transport_frame;
625 if (rec_nframes && !was_recording) {
626 capture_captured = 0;
627 was_recording = true;
632 if (can_record && !_last_capture_regions.empty()) {
633 _last_capture_regions.clear ();
636 if (nominally_recording || rec_nframes) {
638 uint32_t limit = _io->n_ports ().n_audio();
640 /* one or more ports could already have been removed from _io, but our
641 channel setup hasn't yet been updated. prevent us from trying to
642 use channels that correspond to missing ports. note that the
643 process callback (from which this is called) is always atomic
644 with respect to port removal/addition.
647 for (n = 0, chan = c->begin(); chan != c->end() && n < limit; ++chan, ++n) {
649 ChannelInfo* chaninfo (*chan);
651 chaninfo->capture_buf->get_write_vector (&chaninfo->capture_vector);
653 if (rec_nframes <= chaninfo->capture_vector.len[0]) {
655 chaninfo->current_capture_buffer = chaninfo->capture_vector.buf[0];
657 /* note: grab the entire port buffer, but only copy what we were supposed to
658 for recording, and use rec_offset
661 AudioPort* const ap = _io->audio (n);
663 assert(rec_nframes <= ap->get_audio_buffer(nframes).capacity());
664 memcpy (chaninfo->current_capture_buffer, ap->get_audio_buffer (rec_nframes).data(rec_offset), sizeof (Sample) * rec_nframes);
669 nframes_t total = chaninfo->capture_vector.len[0] + chaninfo->capture_vector.len[1];
671 if (rec_nframes > total) {
676 AudioPort* const ap = _io->audio (n);
679 Sample* buf = ap->get_audio_buffer(nframes).data();
680 nframes_t first = chaninfo->capture_vector.len[0];
682 memcpy (chaninfo->capture_wrap_buffer, buf, sizeof (Sample) * first);
683 memcpy (chaninfo->capture_vector.buf[0], buf, sizeof (Sample) * first);
684 memcpy (chaninfo->capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
685 memcpy (chaninfo->capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
687 chaninfo->current_capture_buffer = chaninfo->capture_wrap_buffer;
694 finish_capture (rec_monitors_input, c);
701 /* data will be written to disk */
703 if (rec_nframes == nframes && rec_offset == 0) {
705 for (chan = c->begin(); chan != c->end(); ++chan) {
706 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
709 playback_distance = nframes;
714 /* we can't use the capture buffer as the playback buffer, because
715 we recorded only a part of the current process' cycle data
719 collect_playback = true;
722 adjust_capture_position = rec_nframes;
724 } else if (nominally_recording) {
726 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
728 for (chan = c->begin(); chan != c->end(); ++chan) {
729 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
732 playback_distance = nframes;
736 collect_playback = true;
739 if (collect_playback) {
741 /* we're doing playback */
743 nframes_t necessary_samples;
745 /* no varispeed playback if we're recording, because the output .... TBD */
747 if (rec_nframes == 0 && _actual_speed != 1.0f) {
748 necessary_samples = (nframes_t) floor ((nframes * fabs (_actual_speed))) + 1;
750 necessary_samples = nframes;
753 for (chan = c->begin(); chan != c->end(); ++chan) {
754 (*chan)->playback_buf->get_read_vector (&(*chan)->playback_vector);
759 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
761 ChannelInfo* chaninfo (*chan);
763 if (necessary_samples <= chaninfo->playback_vector.len[0]) {
765 chaninfo->current_playback_buffer = chaninfo->playback_vector.buf[0];
768 nframes_t total = chaninfo->playback_vector.len[0] + chaninfo->playback_vector.len[1];
770 if (necessary_samples > total) {
771 cerr << "underrun for " << _name << endl;
777 memcpy ((char *) chaninfo->playback_wrap_buffer,
778 chaninfo->playback_vector.buf[0],
779 chaninfo->playback_vector.len[0] * sizeof (Sample));
780 memcpy (chaninfo->playback_wrap_buffer + chaninfo->playback_vector.len[0],
781 chaninfo->playback_vector.buf[1],
782 (necessary_samples - chaninfo->playback_vector.len[0])
785 chaninfo->current_playback_buffer = chaninfo->playback_wrap_buffer;
790 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
791 process_varispeed_playback(nframes, c);
793 playback_distance = nframes;
796 _speed = _target_speed;
807 /* we're exiting with failure, so ::commit will not
808 be called. unlock the state lock.
811 commit_should_unlock = false;
819 AudioDiskstream::process_varispeed_playback(nframes_t nframes, boost::shared_ptr<ChannelList> c)
821 ChannelList::iterator chan;
823 interpolation.set_target_speed (_target_speed);
824 interpolation.set_speed (_speed);
826 for (chan = c->begin(); chan != c->end(); ++chan) {
827 ChannelInfo* chaninfo (*chan);
829 playback_distance = interpolation.interpolate (
830 nframes, chaninfo->current_playback_buffer, chaninfo->speed_buffer);
835 AudioDiskstream::commit (nframes_t nframes)
837 bool need_butler = false;
839 if (!_io || !_io->active()) {
843 if (_actual_speed < 0.0) {
844 playback_sample -= playback_distance;
846 playback_sample += playback_distance;
849 boost::shared_ptr<ChannelList> c = channels.reader();
850 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
852 (*chan)->playback_buf->increment_read_ptr (playback_distance);
854 if (adjust_capture_position) {
855 (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
859 if (adjust_capture_position != 0) {
860 capture_captured += adjust_capture_position;
861 adjust_capture_position = 0;
865 if (_io && _io->active()) {
866 need_butler = c->front()->playback_buf->write_space() >= c->front()->playback_buf->bufsize() / 2;
871 if (_io && _io->active()) {
872 need_butler = c->front()->playback_buf->write_space() >= disk_io_chunk_frames
873 || c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
875 need_butler = c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
879 if (commit_should_unlock) {
889 AudioDiskstream::set_pending_overwrite (bool yn)
891 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
893 pending_overwrite = yn;
895 overwrite_frame = playback_sample;
896 overwrite_offset = channels.reader()->front()->playback_buf->get_read_ptr();
900 AudioDiskstream::overwrite_existing_buffers ()
902 boost::shared_ptr<ChannelList> c = channels.reader();
903 Sample* mixdown_buffer;
906 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
908 overwrite_queued = false;
910 /* assume all are the same size */
911 nframes_t size = c->front()->playback_buf->bufsize();
913 mixdown_buffer = new Sample[size];
914 gain_buffer = new float[size];
916 /* reduce size so that we can fill the buffer correctly. */
922 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
924 start = overwrite_frame;
925 nframes_t cnt = size;
927 /* to fill the buffer without resetting the playback sample, we need to
928 do it one or two chunks (normally two).
930 |----------------------------------------------------------------------|
934 |<- second chunk->||<----------------- first chunk ------------------>|
938 nframes_t to_read = size - overwrite_offset;
940 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, *chan, n, reversed)) {
941 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
942 _id, size, playback_sample) << endmsg;
950 if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer,
951 start, cnt, *chan, n, reversed)) {
952 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
953 _id, size, playback_sample) << endmsg;
962 pending_overwrite = false;
963 delete [] gain_buffer;
964 delete [] mixdown_buffer;
969 AudioDiskstream::seek (nframes_t frame, bool complete_refill)
973 ChannelList::iterator chan;
974 boost::shared_ptr<ChannelList> c = channels.reader();
976 Glib::Mutex::Lock lm (state_lock);
978 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
979 (*chan)->playback_buf->reset ();
980 (*chan)->capture_buf->reset ();
983 /* can't rec-enable in destructive mode if transport is before start */
985 if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
986 disengage_record_enable ();
989 playback_sample = frame;
992 if (complete_refill) {
993 while ((ret = do_refill_with_alloc ()) > 0) ;
995 ret = do_refill_with_alloc ();
1002 AudioDiskstream::can_internal_playback_seek (nframes_t distance)
1004 ChannelList::iterator chan;
1005 boost::shared_ptr<ChannelList> c = channels.reader();
1007 for (chan = c->begin(); chan != c->end(); ++chan) {
1008 if ((*chan)->playback_buf->read_space() < distance) {
1016 AudioDiskstream::internal_playback_seek (nframes_t distance)
1018 ChannelList::iterator chan;
1019 boost::shared_ptr<ChannelList> c = channels.reader();
1021 for (chan = c->begin(); chan != c->end(); ++chan) {
1022 (*chan)->playback_buf->increment_read_ptr (distance);
1025 first_recordable_frame += distance;
1026 playback_sample += distance;
1032 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer, nframes_t& start, nframes_t cnt,
1033 ChannelInfo* channel_info, int channel, bool reversed)
1035 nframes_t this_read = 0;
1036 bool reloop = false;
1037 nframes_t loop_end = 0;
1038 nframes_t loop_start = 0;
1039 nframes_t loop_length = 0;
1040 nframes_t offset = 0;
1043 /* XXX we don't currently play loops in reverse. not sure why */
1047 /* Make the use of a Location atomic for this read operation.
1049 Note: Locations don't get deleted, so all we care about
1050 when I say "atomic" is that we are always pointing to
1051 the same one and using a start/length values obtained
1055 if ((loc = loop_location) != 0) {
1056 loop_start = loc->start();
1057 loop_end = loc->end();
1058 loop_length = loop_end - loop_start;
1061 /* if we are looping, ensure that the first frame we read is at the correct
1062 position within the loop.
1065 if (loc && start >= loop_end) {
1066 //cerr << "start adjusted from " << start;
1067 start = loop_start + ((start - loop_start) % loop_length);
1068 //cerr << "to " << start << endl;
1071 //cerr << "start is " << start << " loopstart: " << loop_start << " loopend: " << loop_end << endl;
1080 /* take any loop into account. we can't read past the end of the loop. */
1082 if (loc && (loop_end - start < cnt)) {
1083 this_read = loop_end - start;
1084 //cerr << "reloop true: thisread: " << this_read << " cnt: " << cnt << endl;
1091 if (this_read == 0) {
1095 this_read = min(cnt,this_read);
1097 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
1098 error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), _id, this_read,
1103 _read_data_count = _playlist->read_data_count();
1107 swap_by_ptr (buf, buf + this_read - 1);
1111 /* if we read to the end of the loop, go back to the beginning */
1121 offset += this_read;
1128 AudioDiskstream::do_refill_with_alloc ()
1130 Sample* mix_buf = new Sample[disk_io_chunk_frames];
1131 float* gain_buf = new float[disk_io_chunk_frames];
1133 int ret = _do_refill(mix_buf, gain_buf);
1142 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer)
1146 RingBufferNPT<Sample>::rw_vector vector;
1147 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1148 nframes_t total_space;
1149 nframes_t zero_fill;
1151 ChannelList::iterator i;
1152 boost::shared_ptr<ChannelList> c = channels.reader();
1159 assert(mixdown_buffer);
1160 assert(gain_buffer);
1167 c->front()->playback_buf->get_write_vector (&vector);
1169 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1173 /* if there are 2+ chunks of disk i/o possible for
1174 this track, let the caller know so that it can arrange
1175 for us to be called again, ASAP.
1178 if (total_space >= (_slaved?3:2) * disk_io_chunk_frames) {
1182 /* if we're running close to normal speed and there isn't enough
1183 space to do disk_io_chunk_frames of I/O, then don't bother.
1185 at higher speeds, just do it because the sync between butler
1186 and audio thread may not be good enough.
1189 if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1193 /* when slaved, don't try to get too close to the read pointer. this
1194 leaves space for the buffer reversal to have something useful to
1198 if (_slaved && total_space < (c->front()->playback_buf->bufsize() / 2)) {
1202 /* never do more than disk_io_chunk_frames worth of disk input per call (limit doesn't apply for memset) */
1204 total_space = min (disk_io_chunk_frames, total_space);
1208 if (file_frame == 0) {
1210 /* at start: nothing to do but fill with silence */
1212 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1214 ChannelInfo* chan (*i);
1215 chan->playback_buf->get_write_vector (&vector);
1216 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1217 if (vector.len[1]) {
1218 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1220 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1225 if (file_frame < total_space) {
1227 /* too close to the start: read what we can,
1228 and then zero fill the rest
1231 zero_fill = total_space - file_frame;
1232 total_space = file_frame;
1242 if (file_frame == max_frames) {
1244 /* at end: nothing to do but fill with silence */
1246 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1248 ChannelInfo* chan (*i);
1249 chan->playback_buf->get_write_vector (&vector);
1250 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1251 if (vector.len[1]) {
1252 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1254 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1259 if (file_frame > max_frames - total_space) {
1261 /* to close to the end: read what we can, and zero fill the rest */
1263 zero_fill = total_space - (max_frames - file_frame);
1264 total_space = max_frames - file_frame;
1271 nframes_t file_frame_tmp = 0;
1273 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1275 ChannelInfo* chan (*i);
1278 nframes_t len1, len2;
1280 chan->playback_buf->get_write_vector (&vector);
1282 if (vector.len[0] > disk_io_chunk_frames) {
1284 /* we're not going to fill the first chunk, so certainly do not bother with the
1285 other part. it won't be connected with the part we do fill, as in:
1287 .... => writable space
1288 ++++ => readable space
1289 ^^^^ => 1 x disk_io_chunk_frames that would be filled
1291 |......|+++++++++++++|...............................|
1296 So, just pretend that the buf1 part isn't there.
1306 file_frame_tmp = file_frame;
1308 buf1 = vector.buf[0];
1309 len1 = vector.len[0];
1310 buf2 = vector.buf[1];
1311 len2 = vector.len[1];
1313 to_read = min (ts, len1);
1314 to_read = min (to_read, disk_io_chunk_frames);
1318 if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1323 chan->playback_buf->increment_write_ptr (to_read);
1327 to_read = min (ts, len2);
1331 /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1332 so read some or all of vector.len[1] as well.
1335 if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1340 chan->playback_buf->increment_write_ptr (to_read);
1349 file_frame = file_frame_tmp;
1356 /** Flush pending data to disk.
1358 * Important note: this function will write *AT MOST* disk_io_chunk_frames
1359 * of data to disk. it will never write more than that. If it writes that
1360 * much and there is more than that waiting to be written, it will return 1,
1361 * otherwise 0 on success or -1 on failure.
1363 * If there is less than disk_io_chunk_frames to be written, no data will be
1364 * written at all unless @a force_flush is true.
1367 AudioDiskstream::do_flush (RunContext context, bool force_flush)
1371 RingBufferNPT<Sample>::rw_vector vector;
1372 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1375 _write_data_count = 0;
1377 transvec.buf[0] = 0;
1378 transvec.buf[1] = 0;
1382 boost::shared_ptr<ChannelList> c = channels.reader();
1383 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1385 (*chan)->capture_buf->get_read_vector (&vector);
1387 total = vector.len[0] + vector.len[1];
1389 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1393 /* if there are 2+ chunks of disk i/o possible for
1394 this track, let the caller know so that it can arrange
1395 for us to be called again, ASAP.
1397 if we are forcing a flush, then if there is* any* extra
1398 work, let the caller know.
1400 if we are no longer recording and there is any extra work,
1401 let the caller know too.
1404 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1408 to_write = min (disk_io_chunk_frames, (nframes_t) vector.len[0]);
1410 // check the transition buffer when recording destructive
1411 // important that we get this after the capture buf
1413 if (destructive()) {
1414 (*chan)->capture_transition_buf->get_read_vector(&transvec);
1415 size_t transcount = transvec.len[0] + transvec.len[1];
1416 bool have_start = false;
1419 for (ti=0; ti < transcount; ++ti) {
1420 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1422 if (captrans.type == CaptureStart) {
1423 // by definition, the first data we got above represents the given capture pos
1425 (*chan)->write_source->mark_capture_start (captrans.capture_val);
1426 (*chan)->curr_capture_cnt = 0;
1430 else if (captrans.type == CaptureEnd) {
1432 // capture end, the capture_val represents total frames in capture
1434 if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1436 // shorten to make the write a perfect fit
1437 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
1439 if (nto_write < to_write) {
1440 ret = 1; // should we?
1442 to_write = nto_write;
1444 (*chan)->write_source->mark_capture_end ();
1446 // increment past this transition, but go no further
1451 // actually ends just beyond this chunk, so force more work
1459 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1463 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1464 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1468 (*chan)->capture_buf->increment_read_ptr (to_write);
1469 (*chan)->curr_capture_cnt += to_write;
1471 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1473 /* we wrote all of vector.len[0] but it wasn't an entire
1474 disk_io_chunk_frames of data, so arrange for some part
1475 of vector.len[1] to be flushed to disk as well.
1478 to_write = min ((nframes_t)(disk_io_chunk_frames - to_write), (nframes_t) vector.len[1]);
1480 if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1481 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1485 _write_data_count += (*chan)->write_source->write_data_count();
1487 (*chan)->capture_buf->increment_read_ptr (to_write);
1488 (*chan)->curr_capture_cnt += to_write;
1497 AudioDiskstream::transport_stopped (struct tm& when, time_t twhen, bool abort_capture)
1499 uint32_t buffer_position;
1500 bool more_work = true;
1502 boost::shared_ptr<AudioRegion> region;
1503 nframes_t total_capture;
1505 SourceList::iterator src;
1506 ChannelList::iterator chan;
1507 vector<CaptureInfo*>::iterator ci;
1508 boost::shared_ptr<ChannelList> c = channels.reader();
1510 bool mark_write_completed = false;
1512 finish_capture (true, c);
1514 /* butler is already stopped, but there may be work to do
1515 to flush remaining data to disk.
1518 while (more_work && !err) {
1519 switch (do_flush (TransportContext, true)) {
1526 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1531 /* XXX is there anything we can do if err != 0 ? */
1532 Glib::Mutex::Lock lm (capture_info_lock);
1534 if (capture_info.empty()) {
1538 if (abort_capture) {
1540 if (destructive()) {
1544 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1546 if ((*chan)->write_source) {
1548 (*chan)->write_source->mark_for_remove ();
1549 (*chan)->write_source->drop_references ();
1550 (*chan)->write_source.reset ();
1553 /* new source set up in "out" below */
1559 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1560 total_capture += (*ci)->frames;
1563 /* figure out the name for this take */
1565 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1567 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1571 s->update_header (capture_info.front()->start, when, twhen);
1572 s->set_captured_for (_name);
1573 s->mark_immutable ();
1574 if (Config->get_auto_analyse_audio()) {
1575 Analyser::queue_source_for_analysis (s, true);
1580 /* destructive tracks have a single, never changing region */
1582 if (destructive()) {
1584 /* send a signal that any UI can pick up to do the right thing. there is
1585 a small problem here in that a UI may need the peak data to be ready
1586 for the data that was recorded and this isn't interlocked with that
1587 process. this problem is deferred to the UI.
1590 _playlist->Modified();
1594 string whole_file_region_name;
1595 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1597 /* Register a new region with the Session that
1598 describes the entire source. Do this first
1599 so that any sub-regions will obviously be
1600 children of this one (later!)
1604 boost::shared_ptr<Region> rx (RegionFactory::create (srcs,
1605 c->front()->write_source->last_capture_start_frame(), total_capture,
1606 whole_file_region_name, 0,
1607 Region::Flag (Region::DefaultFlags|Region::Automatic|Region::WholeFile)));
1609 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1610 region->special_set_position (capture_info.front()->start);
1614 catch (failed_constructor& err) {
1615 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1619 _last_capture_regions.push_back (region);
1621 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1623 XMLNode &before = _playlist->get_state();
1624 _playlist->freeze ();
1626 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1630 _session.region_name (region_name, whole_file_region_name, false);
1632 // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->frames << " add region " << region_name << endl;
1635 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, buffer_position, (*ci)->frames, region_name));
1636 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1639 catch (failed_constructor& err) {
1640 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1641 continue; /* XXX is this OK? */
1644 region->GoingAway.connect (bind (mem_fun (*this, &Diskstream::remove_region_from_last_capture), boost::weak_ptr<Region>(region)));
1646 _last_capture_regions.push_back (region);
1648 i_am_the_modifier++;
1649 _playlist->add_region (region, (*ci)->start, 1, non_layered());
1650 i_am_the_modifier--;
1652 buffer_position += (*ci)->frames;
1656 XMLNode &after = _playlist->get_state();
1657 _session.add_command (new MementoCommand<Playlist>(*_playlist, &before, &after));
1660 mark_write_completed = true;
1663 reset_write_sources (mark_write_completed);
1667 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1671 capture_info.clear ();
1672 capture_start_frame = 0;
1676 AudioDiskstream::transport_looped (nframes_t transport_frame)
1678 if (was_recording) {
1679 // all we need to do is finish this capture, with modified capture length
1680 boost::shared_ptr<ChannelList> c = channels.reader();
1682 // adjust the capture length knowing that the data will be recorded to disk
1683 // only necessary after the first loop where we're recording
1684 if (capture_info.size() == 0) {
1685 capture_captured += _capture_offset;
1687 if (_alignment_style == ExistingMaterial) {
1688 capture_captured += _session.worst_output_latency();
1690 capture_captured += _roll_delay;
1694 finish_capture (true, c);
1696 // the next region will start recording via the normal mechanism
1697 // we'll set the start position to the current transport pos
1698 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1699 capture_start_frame = transport_frame;
1700 first_recordable_frame = transport_frame; // mild lie
1701 last_recordable_frame = max_frames;
1702 was_recording = true;
1704 if (recordable() && destructive()) {
1705 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1707 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1708 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1710 if (transvec.len[0] > 0) {
1711 transvec.buf[0]->type = CaptureStart;
1712 transvec.buf[0]->capture_val = capture_start_frame;
1713 (*chan)->capture_transition_buf->increment_write_ptr(1);
1717 fatal << X_("programming error: capture_transition_buf is full on rec loop! inconceivable!")
1727 AudioDiskstream::finish_capture (bool rec_monitors_input, boost::shared_ptr<ChannelList> c)
1729 was_recording = false;
1731 if (capture_captured == 0) {
1735 if (recordable() && destructive()) {
1736 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1738 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1739 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1741 if (transvec.len[0] > 0) {
1742 transvec.buf[0]->type = CaptureEnd;
1743 transvec.buf[0]->capture_val = capture_captured;
1744 (*chan)->capture_transition_buf->increment_write_ptr(1);
1748 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1754 CaptureInfo* ci = new CaptureInfo;
1756 ci->start = capture_start_frame;
1757 ci->frames = capture_captured;
1759 /* XXX theoretical race condition here. Need atomic exchange ?
1760 However, the circumstances when this is called right
1761 now (either on record-disable or transport_stopped)
1762 mean that no actual race exists. I think ...
1763 We now have a capture_info_lock, but it is only to be used
1764 to synchronize in the transport_stop and the capture info
1765 accessors, so that invalidation will not occur (both non-realtime).
1768 // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1770 capture_info.push_back (ci);
1771 capture_captured = 0;
1773 /* now we've finished a capture, reset first_recordable_frame for next time */
1774 first_recordable_frame = max_frames;
1778 AudioDiskstream::set_record_enabled (bool yn)
1780 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0) {
1784 /* can't rec-enable in destructive mode if transport is before start */
1786 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1790 if (yn && channels.reader()->front()->source == 0) {
1792 /* pick up connections not initiated *from* the IO object
1793 we're associated with.
1796 get_input_sources ();
1799 /* yes, i know that this not proof against race conditions, but its
1800 good enough. i think.
1803 if (record_enabled() != yn) {
1805 engage_record_enable ();
1807 disengage_record_enable ();
1813 AudioDiskstream::engage_record_enable ()
1815 bool rolling = _session.transport_speed() != 0.0f;
1816 boost::shared_ptr<ChannelList> c = channels.reader();
1818 g_atomic_int_set (&_record_enabled, 1);
1819 capturing_sources.clear ();
1821 if (Config->get_monitoring_model() == HardwareMonitoring) {
1823 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1824 if ((*chan)->source) {
1825 (*chan)->source->ensure_monitor_input (!(_session.config.get_auto_input() && rolling));
1827 capturing_sources.push_back ((*chan)->write_source);
1828 (*chan)->write_source->mark_streaming_write_started ();
1832 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1833 capturing_sources.push_back ((*chan)->write_source);
1834 (*chan)->write_source->mark_streaming_write_started ();
1838 RecordEnableChanged (); /* EMIT SIGNAL */
1842 AudioDiskstream::disengage_record_enable ()
1844 g_atomic_int_set (&_record_enabled, 0);
1845 boost::shared_ptr<ChannelList> c = channels.reader();
1846 if (Config->get_monitoring_model() == HardwareMonitoring) {
1847 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1848 if ((*chan)->source) {
1849 (*chan)->source->ensure_monitor_input (false);
1853 capturing_sources.clear ();
1854 RecordEnableChanged (); /* EMIT SIGNAL */
1858 AudioDiskstream::get_state ()
1860 XMLNode* node = new XMLNode ("AudioDiskstream");
1862 LocaleGuard lg (X_("POSIX"));
1863 boost::shared_ptr<ChannelList> c = channels.reader();
1865 node->add_property ("flags", enum_2_string (_flags));
1867 snprintf (buf, sizeof(buf), "%zd", c->size());
1868 node->add_property ("channels", buf);
1870 node->add_property ("playlist", _playlist->name());
1872 snprintf (buf, sizeof(buf), "%.12g", _visible_speed);
1873 node->add_property ("speed", buf);
1875 node->add_property("name", _name);
1876 id().print (buf, sizeof (buf));
1877 node->add_property("id", buf);
1879 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1881 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1882 XMLNode* cs_grandchild;
1884 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1885 cs_grandchild = new XMLNode (X_("file"));
1886 cs_grandchild->add_property (X_("path"), (*i)->path());
1887 cs_child->add_child_nocopy (*cs_grandchild);
1890 /* store the location where capture will start */
1894 if (_session.config.get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1895 snprintf (buf, sizeof (buf), "%" PRIu32, pi->start());
1897 snprintf (buf, sizeof (buf), "%" PRIu32, _session.transport_frame());
1900 cs_child->add_property (X_("at"), buf);
1901 node->add_child_nocopy (*cs_child);
1905 node->add_child_copy (*_extra_xml);
1912 AudioDiskstream::set_state (const XMLNode& node)
1914 const XMLProperty* prop;
1915 XMLNodeList nlist = node.children();
1916 XMLNodeIterator niter;
1917 uint32_t nchans = 1;
1918 XMLNode* capture_pending_node = 0;
1919 LocaleGuard lg (X_("POSIX"));
1921 in_set_state = true;
1923 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1924 if ((*niter)->name() == IO::state_node_name) {
1925 deprecated_io_node = new XMLNode (**niter);
1928 if ((*niter)->name() == X_("CapturingSources")) {
1929 capture_pending_node = *niter;
1933 /* prevent write sources from being created */
1935 in_set_state = true;
1937 if ((prop = node.property ("name")) != 0) {
1938 _name = prop->value();
1941 if (deprecated_io_node) {
1942 if ((prop = deprecated_io_node->property ("id")) != 0) {
1943 _id = prop->value ();
1946 if ((prop = node.property ("id")) != 0) {
1947 _id = prop->value ();
1951 if ((prop = node.property ("flags")) != 0) {
1952 _flags = Flag (string_2_enum (prop->value(), _flags));
1955 if ((prop = node.property ("channels")) != 0) {
1956 nchans = atoi (prop->value().c_str());
1959 // create necessary extra channels
1960 // we are always constructed with one and we always need one
1962 _n_channels.set(DataType::AUDIO, channels.reader()->size());
1964 if (nchans > _n_channels.n_audio()) {
1966 add_channel (nchans - _n_channels.n_audio());
1967 IO::PortCountChanged(_n_channels);
1969 } else if (nchans < _n_channels.n_audio()) {
1971 remove_channel (_n_channels.n_audio() - nchans);
1974 if ((prop = node.property ("playlist")) == 0) {
1979 bool had_playlist = (_playlist != 0);
1981 if (find_and_use_playlist (prop->value())) {
1985 if (!had_playlist) {
1986 _playlist->set_orig_diskstream_id (_id);
1989 if (!destructive() && capture_pending_node) {
1990 /* destructive streams have one and only one source per channel,
1991 and so they never end up in pending capture in any useful
1994 use_pending_capture_data (*capture_pending_node);
1999 if ((prop = node.property ("speed")) != 0) {
2000 double sp = atof (prop->value().c_str());
2002 if (realtime_set_speed (sp, false)) {
2003 non_realtime_set_speed ();
2007 in_set_state = false;
2009 /* make sure this is clear before we do anything else */
2011 capturing_sources.clear ();
2013 /* write sources are handled when we handle the input set
2014 up of the IO that owns this DS (::non_realtime_input_change())
2021 AudioDiskstream::use_new_write_source (uint32_t n)
2023 boost::shared_ptr<ChannelList> c = channels.reader();
2025 if (!recordable()) {
2029 if (n >= c->size()) {
2030 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
2034 ChannelInfo* chan = (*c)[n];
2036 if (chan->write_source) {
2037 chan->write_source->done_with_peakfile_writes ();
2038 chan->write_source->set_allow_remove_if_empty (true);
2039 chan->write_source.reset ();
2043 if ((chan->write_source = _session.create_audio_source_for_session (*this, n, destructive())) == 0) {
2044 throw failed_constructor();
2048 catch (failed_constructor &err) {
2049 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
2050 chan->write_source.reset ();
2054 /* do not remove destructive files even if they are empty */
2056 chan->write_source->set_allow_remove_if_empty (!destructive());
2062 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool force)
2064 ChannelList::iterator chan;
2065 boost::shared_ptr<ChannelList> c = channels.reader();
2068 cerr << _name << " RWS!!!\n";
2070 if (!recordable()) {
2074 capturing_sources.clear ();
2076 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
2077 if (!destructive()) {
2079 if ((*chan)->write_source && mark_write_complete) {
2080 (*chan)->write_source->mark_streaming_write_completed ();
2082 use_new_write_source (n);
2084 if (record_enabled()) {
2085 capturing_sources.push_back ((*chan)->write_source);
2089 if ((*chan)->write_source == 0) {
2090 use_new_write_source (n);
2095 if (destructive()) {
2097 /* we now have all our write sources set up, so create the
2098 playlist's single region.
2101 if (_playlist->empty()) {
2102 setup_destructive_playlist ();
2108 AudioDiskstream::rename_write_sources ()
2110 ChannelList::iterator chan;
2111 boost::shared_ptr<ChannelList> c = channels.reader();
2114 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
2115 if ((*chan)->write_source != 0) {
2116 (*chan)->write_source->set_source_name (_name, destructive());
2117 /* XXX what to do if one of them fails ? */
2125 AudioDiskstream::set_block_size (nframes_t nframes)
2127 if (_session.get_block_size() > speed_buffer_size) {
2128 speed_buffer_size = _session.get_block_size();
2129 boost::shared_ptr<ChannelList> c = channels.reader();
2131 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2132 if ((*chan)->speed_buffer)
2133 delete [] (*chan)->speed_buffer;
2134 (*chan)->speed_buffer = new Sample[speed_buffer_size];
2137 allocate_temporary_buffers ();
2141 AudioDiskstream::allocate_temporary_buffers ()
2143 /* make sure the wrap buffer is at least large enough to deal
2144 with the speeds up to 1.2, to allow for micro-variation
2145 when slaving to MTC, SMPTE etc.
2148 double sp = max (fabsf (_actual_speed), 1.2f);
2149 nframes_t required_wrap_size = (nframes_t) floor (_session.get_block_size() * sp) + 1;
2151 if (required_wrap_size > wrap_buffer_size) {
2153 boost::shared_ptr<ChannelList> c = channels.reader();
2155 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2156 if ((*chan)->playback_wrap_buffer)
2157 delete [] (*chan)->playback_wrap_buffer;
2158 (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
2159 if ((*chan)->capture_wrap_buffer)
2160 delete [] (*chan)->capture_wrap_buffer;
2161 (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
2164 wrap_buffer_size = required_wrap_size;
2169 AudioDiskstream::monitor_input (bool yn)
2171 boost::shared_ptr<ChannelList> c = channels.reader();
2173 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2175 if ((*chan)->source) {
2176 (*chan)->source->ensure_monitor_input (yn);
2182 AudioDiskstream::set_align_style_from_io ()
2184 bool have_physical = false;
2190 get_input_sources ();
2192 boost::shared_ptr<ChannelList> c = channels.reader();
2194 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2195 if ((*chan)->source && (*chan)->source->flags() & JackPortIsPhysical) {
2196 have_physical = true;
2201 if (have_physical) {
2202 set_align_style (ExistingMaterial);
2204 set_align_style (CaptureTime);
2209 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2211 while (how_many--) {
2212 c->push_back (new ChannelInfo(_session.audio_diskstream_buffer_size(), speed_buffer_size, wrap_buffer_size));
2215 _n_channels.set(DataType::AUDIO, c->size());
2221 AudioDiskstream::add_channel (uint32_t how_many)
2223 RCUWriter<ChannelList> writer (channels);
2224 boost::shared_ptr<ChannelList> c = writer.get_copy();
2226 return add_channel_to (c, how_many);
2230 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2232 while (how_many-- && !c->empty()) {
2233 //delete c->back(); // FIXME: crash (thread safe with RCU?)
2237 _n_channels.set(DataType::AUDIO, c->size());
2243 AudioDiskstream::remove_channel (uint32_t how_many)
2245 RCUWriter<ChannelList> writer (channels);
2246 boost::shared_ptr<ChannelList> c = writer.get_copy();
2248 return remove_channel_from (c, how_many);
2252 AudioDiskstream::playback_buffer_load () const
2254 boost::shared_ptr<ChannelList> c = channels.reader();
2256 return (float) ((double) c->front()->playback_buf->read_space()/
2257 (double) c->front()->playback_buf->bufsize());
2261 AudioDiskstream::capture_buffer_load () const
2263 boost::shared_ptr<ChannelList> c = channels.reader();
2265 return (float) ((double) c->front()->capture_buf->write_space()/
2266 (double) c->front()->capture_buf->bufsize());
2270 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2272 const XMLProperty* prop;
2273 XMLNodeList nlist = node.children();
2274 XMLNodeIterator niter;
2275 boost::shared_ptr<AudioFileSource> fs;
2276 boost::shared_ptr<AudioFileSource> first_fs;
2277 SourceList pending_sources;
2280 if ((prop = node.property (X_("at"))) == 0) {
2284 if (sscanf (prop->value().c_str(), "%" PRIu32, &position) != 1) {
2288 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2289 if ((*niter)->name() == X_("file")) {
2291 if ((prop = (*niter)->property (X_("path"))) == 0) {
2295 // This protects sessions from errant CapturingSources in stored sessions
2297 if (stat (prop->value().c_str(), &sbuf)) {
2302 fs = boost::dynamic_pointer_cast<AudioFileSource> (
2303 SourceFactory::createWritable (DataType::AUDIO, _session,
2304 prop->value(), true,
2305 false, _session.frame_rate()));
2308 catch (failed_constructor& err) {
2309 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2310 _name, prop->value())
2315 pending_sources.push_back (fs);
2317 if (first_fs == 0) {
2321 fs->set_captured_for (_name);
2325 if (pending_sources.size() == 0) {
2326 /* nothing can be done */
2330 if (pending_sources.size() != _n_channels.n_audio()) {
2331 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2336 boost::shared_ptr<AudioRegion> region;
2339 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (
2340 pending_sources, 0, first_fs->length(first_fs->timeline_position()),
2341 region_name_from_path (first_fs->name(), true), 0,
2342 Region::Flag (Region::DefaultFlags|Region::Automatic|Region::WholeFile)));
2343 region->special_set_position (0);
2346 catch (failed_constructor& err) {
2347 error << string_compose (
2348 _("%1: cannot create whole-file region from pending capture sources"),
2355 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (
2356 pending_sources, 0, first_fs->length(first_fs->timeline_position()),
2357 region_name_from_path (first_fs->name(), true)));
2360 catch (failed_constructor& err) {
2361 error << string_compose (_("%1: cannot create region from pending capture sources"),
2368 _playlist->add_region (region, position);
2374 AudioDiskstream::set_non_layered (bool yn)
2376 if (yn != non_layered()) {
2379 _flags = Flag (_flags | NonLayered);
2381 _flags = Flag (_flags & ~NonLayered);
2389 AudioDiskstream::set_destructive (bool yn)
2391 bool bounce_ignored;
2393 if (yn != destructive()) {
2396 /* requestor should already have checked this and
2397 bounced if necessary and desired
2399 if (!can_become_destructive (bounce_ignored)) {
2402 _flags = Flag (_flags | Destructive);
2403 use_destructive_playlist ();
2405 _flags = Flag (_flags & ~Destructive);
2406 reset_write_sources (true, true);
2414 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2417 requires_bounce = false;
2421 /* is there only one region ? */
2423 if (_playlist->n_regions() != 1) {
2424 requires_bounce = true;
2428 boost::shared_ptr<Region> first = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
2431 /* do the source(s) for the region cover the session start position ? */
2433 if (first->position() != _session.current_start_frame()) {
2434 if (first->start() > _session.current_start_frame()) {
2435 requires_bounce = true;
2440 /* is the source used by only 1 playlist ? */
2442 boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2446 if (afirst->source()->used() > 1) {
2447 requires_bounce = true;
2451 requires_bounce = false;
2455 AudioDiskstream::ChannelInfo::ChannelInfo (nframes_t bufsize, nframes_t speed_size, nframes_t wrap_size)
2459 current_capture_buffer = 0;
2460 current_playback_buffer = 0;
2461 curr_capture_cnt = 0;
2463 speed_buffer = new Sample[speed_size];
2464 playback_wrap_buffer = new Sample[wrap_size];
2465 capture_wrap_buffer = new Sample[wrap_size];
2467 playback_buf = new RingBufferNPT<Sample> (bufsize);
2468 capture_buf = new RingBufferNPT<Sample> (bufsize);
2469 capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2471 /* touch the ringbuffer buffers, which will cause
2472 them to be mapped into locked physical RAM if
2473 we're running with mlockall(). this doesn't do
2477 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2478 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2479 memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2482 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2485 write_source.reset ();
2488 delete [] speed_buffer;
2491 delete [] playback_wrap_buffer;
2492 playback_wrap_buffer = 0;
2494 delete [] capture_wrap_buffer;
2495 capture_wrap_buffer = 0;
2497 delete playback_buf;
2503 delete capture_transition_buf;
2504 capture_transition_buf = 0;