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.
31 #include "pbd/error.h"
32 #include "pbd/xml++.h"
33 #include "pbd/memento_command.h"
34 #include "pbd/enumwriter.h"
35 #include "pbd/stateful_diff_command.h"
37 #include "ardour/analyser.h"
38 #include "ardour/audio_buffer.h"
39 #include "ardour/audio_diskstream.h"
40 #include "ardour/audio_port.h"
41 #include "ardour/audioengine.h"
42 #include "ardour/audiofilesource.h"
43 #include "ardour/audioplaylist.h"
44 #include "ardour/audioregion.h"
45 #include "ardour/butler.h"
46 #include "ardour/debug.h"
47 #include "ardour/io.h"
48 #include "ardour/playlist_factory.h"
49 #include "ardour/region_factory.h"
50 #include "ardour/session.h"
51 #include "ardour/session_playlists.h"
52 #include "ardour/source_factory.h"
53 #include "ardour/track.h"
54 #include "ardour/types.h"
55 #include "ardour/utils.h"
61 using namespace ARDOUR;
64 size_t AudioDiskstream::_working_buffers_size = 0;
65 Sample* AudioDiskstream::_mixdown_buffer = 0;
66 gain_t* AudioDiskstream::_gain_buffer = 0;
68 AudioDiskstream::AudioDiskstream (Session &sess, const string &name, Diskstream::Flag flag)
69 : Diskstream(sess, name, flag)
70 , channels (new ChannelList)
72 /* prevent any write sources from being created */
79 AudioDiskstream::AudioDiskstream (Session& sess, const XMLNode& node)
80 : Diskstream(sess, node)
81 , channels (new ChannelList)
86 if (set_state (node, Stateful::loading_state_version)) {
88 throw failed_constructor();
94 use_destructive_playlist ();
99 AudioDiskstream::init ()
101 /* there are no channels at this point, so these
102 two calls just get speed_buffer_size and wrap_buffer
103 size setup without duplicating their code.
106 set_block_size (_session.get_block_size());
107 allocate_temporary_buffers ();
110 AudioDiskstream::~AudioDiskstream ()
112 DEBUG_TRACE (DEBUG::Destruction, string_compose ("Audio Diskstream %1 destructor\n", _name));
115 RCUWriter<ChannelList> writer (channels);
116 boost::shared_ptr<ChannelList> c = writer.get_copy();
118 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
129 AudioDiskstream::allocate_working_buffers()
131 assert(disk_io_frames() > 0);
133 _working_buffers_size = disk_io_frames();
134 _mixdown_buffer = new Sample[_working_buffers_size];
135 _gain_buffer = new gain_t[_working_buffers_size];
139 AudioDiskstream::free_working_buffers()
141 delete [] _mixdown_buffer;
142 delete [] _gain_buffer;
143 _working_buffers_size = 0;
149 AudioDiskstream::non_realtime_input_change ()
152 Glib::Threads::Mutex::Lock lm (state_lock);
154 if (input_change_pending.type == IOChange::NoChange) {
158 if (input_change_pending.type == IOChange::ConfigurationChanged) {
159 RCUWriter<ChannelList> writer (channels);
160 boost::shared_ptr<ChannelList> c = writer.get_copy();
162 _n_channels.set(DataType::AUDIO, c->size());
164 if (_io->n_ports().n_audio() > _n_channels.n_audio()) {
165 add_channel_to (c, _io->n_ports().n_audio() - _n_channels.n_audio());
166 } else if (_io->n_ports().n_audio() < _n_channels.n_audio()) {
167 remove_channel_from (c, _n_channels.n_audio() - _io->n_ports().n_audio());
171 if (input_change_pending.type & IOChange::ConnectionsChanged) {
172 get_input_sources ();
173 set_capture_offset ();
174 set_align_style_from_io ();
177 input_change_pending = IOChange::NoChange;
179 /* implicit unlock */
182 /* reset capture files */
184 reset_write_sources (false);
186 /* now refill channel buffers */
188 if (speed() != 1.0f || speed() != -1.0f) {
189 seek ((framepos_t) (_session.transport_frame() * (double) speed()));
191 seek (_session.transport_frame());
196 AudioDiskstream::non_realtime_locate (framepos_t location)
198 /* now refill channel buffers */
200 if (speed() != 1.0f || speed() != -1.0f) {
201 seek ((framepos_t) (location * (double) speed()));
208 AudioDiskstream::get_input_sources ()
210 boost::shared_ptr<ChannelList> c = channels.reader();
213 ChannelList::iterator chan;
214 uint32_t ni = _io->n_ports().n_audio();
215 vector<string> connections;
217 for (n = 0, chan = c->begin(); chan != c->end() && n < ni; ++chan, ++n) {
219 connections.clear ();
221 if (_io->nth (n)->get_connections (connections) == 0) {
222 if (!(*chan)->source.name.empty()) {
223 // _source->disable_metering ();
225 (*chan)->source.name = string();
227 (*chan)->source.name = connections[0];
233 AudioDiskstream::find_and_use_playlist (const string& name)
235 boost::shared_ptr<AudioPlaylist> playlist;
237 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (_session.playlists->by_name (name))) == 0) {
238 playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, name));
242 error << string_compose(_("AudioDiskstream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
246 return use_playlist (playlist);
250 AudioDiskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
252 assert(boost::dynamic_pointer_cast<AudioPlaylist>(playlist));
254 Diskstream::use_playlist(playlist);
260 AudioDiskstream::use_new_playlist ()
263 boost::shared_ptr<AudioPlaylist> playlist;
265 if (!in_set_state && destructive()) {
270 newname = Playlist::bump_name (_playlist->name(), _session);
272 newname = Playlist::bump_name (_name, _session);
275 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, newname, hidden()))) != 0) {
277 return use_playlist (playlist);
285 AudioDiskstream::use_copy_playlist ()
287 assert(audio_playlist());
293 if (_playlist == 0) {
294 error << string_compose(_("AudioDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
299 boost::shared_ptr<AudioPlaylist> playlist;
301 newname = Playlist::bump_name (_playlist->name(), _session);
303 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist>(PlaylistFactory::create (audio_playlist(), newname))) != 0) {
304 return use_playlist (playlist);
311 AudioDiskstream::setup_destructive_playlist ()
314 boost::shared_ptr<ChannelList> c = channels.reader();
316 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
317 srcs.push_back ((*chan)->write_source);
320 /* a single full-sized region */
322 assert (!srcs.empty ());
325 plist.add (Properties::name, _name.val());
326 plist.add (Properties::start, 0);
327 plist.add (Properties::length, max_framepos - (max_framepos - srcs.front()->natural_position()));
329 boost::shared_ptr<Region> region (RegionFactory::create (srcs, plist));
330 _playlist->add_region (region, srcs.front()->natural_position());
334 AudioDiskstream::use_destructive_playlist ()
336 /* this is called from the XML-based constructor or ::set_destructive. when called,
337 we already have a playlist and a region, but we need to
338 set up our sources for write. we use the sources associated
339 with the (presumed single, full-extent) region.
342 boost::shared_ptr<Region> rp = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
345 reset_write_sources (false, true);
349 boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
352 throw failed_constructor();
355 /* be sure to stretch the region out to the maximum length */
357 region->set_length (max_framepos - region->position());
360 ChannelList::iterator chan;
361 boost::shared_ptr<ChannelList> c = channels.reader();
363 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
364 (*chan)->write_source = boost::dynamic_pointer_cast<AudioFileSource>(region->source (n));
365 assert((*chan)->write_source);
366 (*chan)->write_source->set_allow_remove_if_empty (false);
368 /* this might be false if we switched modes, so force it */
370 (*chan)->write_source->set_destructive (true);
373 /* the source list will never be reset for a destructive track */
377 AudioDiskstream::prepare_record_status(framepos_t capture_start_frame)
379 if (recordable() && destructive()) {
380 boost::shared_ptr<ChannelList> c = channels.reader();
381 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
383 RingBufferNPT<CaptureTransition>::rw_vector transitions;
384 (*chan)->capture_transition_buf->get_write_vector (&transitions);
386 if (transitions.len[0] > 0) {
387 transitions.buf[0]->type = CaptureStart;
388 transitions.buf[0]->capture_val = capture_start_frame;
389 (*chan)->capture_transition_buf->increment_write_ptr(1);
392 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
400 /** Do some record stuff [not described in this comment!]
403 * - Setup playback_distance with the nframes, or nframes adjusted
404 * for current varispeed, if appropriate.
405 * - Setup current_playback_buffer in each ChannelInfo to point to data
406 * that someone can read playback_distance worth of data from.
409 AudioDiskstream::process (BufferSet& bufs, framepos_t transport_frame, pframes_t nframes, framecnt_t& playback_distance, bool need_disk_signal)
412 boost::shared_ptr<ChannelList> c = channels.reader();
413 ChannelList::iterator chan;
414 framecnt_t rec_offset = 0;
415 framecnt_t rec_nframes = 0;
416 bool collect_playback = false;
417 bool can_record = _session.actively_recording ();
419 playback_distance = 0;
421 if (!_io || !_io->active()) {
425 check_record_status (transport_frame, can_record);
431 Glib::Threads::Mutex::Lock sm (state_lock, Glib::Threads::TRY_LOCK);
437 adjust_capture_position = 0;
439 for (chan = c->begin(); chan != c->end(); ++chan) {
440 (*chan)->current_capture_buffer = 0;
441 (*chan)->current_playback_buffer = 0;
444 // Safeguard against situations where process() goes haywire when autopunching
445 // and last_recordable_frame < first_recordable_frame
447 if (last_recordable_frame < first_recordable_frame) {
448 last_recordable_frame = max_framepos;
451 if (record_enabled()) {
453 Evoral::OverlapType ot = Evoral::coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
454 calculate_record_range (ot, transport_frame, nframes, rec_nframes, rec_offset);
456 if (rec_nframes && !was_recording) {
457 capture_captured = 0;
458 was_recording = true;
462 if (can_record && !_last_capture_sources.empty()) {
463 _last_capture_sources.clear ();
468 uint32_t limit = _io->n_ports ().n_audio();
470 /* one or more ports could already have been removed from _io, but our
471 channel setup hasn't yet been updated. prevent us from trying to
472 use channels that correspond to missing ports. note that the
473 process callback (from which this is called) is always atomic
474 with respect to port removal/addition.
477 for (n = 0, chan = c->begin(); chan != c->end() && n < limit; ++chan, ++n) {
479 ChannelInfo* chaninfo (*chan);
481 chaninfo->capture_buf->get_write_vector (&chaninfo->capture_vector);
483 if (rec_nframes <= (framecnt_t) chaninfo->capture_vector.len[0]) {
485 chaninfo->current_capture_buffer = chaninfo->capture_vector.buf[0];
487 /* note: grab the entire port buffer, but only copy what we were supposed to
488 for recording, and use rec_offset
491 boost::shared_ptr<AudioPort> const ap = _io->audio (n);
493 assert(rec_nframes <= (framecnt_t) ap->get_audio_buffer(nframes).capacity());
495 Sample *buf = bufs.get_audio (n).data(rec_offset);
496 memcpy (chaninfo->current_capture_buffer, buf, sizeof (Sample) * rec_nframes);
500 framecnt_t total = chaninfo->capture_vector.len[0] + chaninfo->capture_vector.len[1];
502 if (rec_nframes > total) {
507 boost::shared_ptr<AudioPort> const ap = _io->audio (n);
510 Sample *buf = bufs.get_audio (n).data(rec_offset);
511 framecnt_t first = chaninfo->capture_vector.len[0];
513 memcpy (chaninfo->capture_wrap_buffer, buf, sizeof (Sample) * first);
514 memcpy (chaninfo->capture_vector.buf[0], buf, sizeof (Sample) * first);
515 memcpy (chaninfo->capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
516 memcpy (chaninfo->capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
518 chaninfo->current_capture_buffer = chaninfo->capture_wrap_buffer;
532 /* data will be written to disk */
534 if (rec_nframes == nframes && rec_offset == 0) {
536 for (chan = c->begin(); chan != c->end(); ++chan) {
537 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
540 playback_distance = nframes;
545 /* we can't use the capture buffer as the playback buffer, because
546 we recorded only a part of the current process' cycle data
550 collect_playback = true;
553 adjust_capture_position = rec_nframes;
555 } else if (can_record && record_enabled()) {
557 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
559 for (chan = c->begin(); chan != c->end(); ++chan) {
560 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
563 playback_distance = nframes;
567 collect_playback = true;
570 if ((_track->monitoring_state () & MonitoringDisk) || collect_playback) {
572 /* we're doing playback */
574 framecnt_t necessary_samples;
576 /* no varispeed playback if we're recording, because the output .... TBD */
578 if (rec_nframes == 0 && _actual_speed != 1.0f) {
579 necessary_samples = (framecnt_t) ceil ((nframes * fabs (_actual_speed))) + 2;
581 necessary_samples = nframes;
584 for (chan = c->begin(); chan != c->end(); ++chan) {
585 (*chan)->playback_buf->get_read_vector (&(*chan)->playback_vector);
590 /* Setup current_playback_buffer in each ChannelInfo to point to data that someone
591 can read necessary_samples (== nframes at a transport speed of 1) worth of data
595 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
597 ChannelInfo* chaninfo (*chan);
599 if (necessary_samples <= (framecnt_t) chaninfo->playback_vector.len[0]) {
600 /* There are enough samples in the first part of the ringbuffer */
601 chaninfo->current_playback_buffer = chaninfo->playback_vector.buf[0];
604 framecnt_t total = chaninfo->playback_vector.len[0] + chaninfo->playback_vector.len[1];
606 if (necessary_samples > total) {
607 cerr << _name << " Need " << necessary_samples << " total = " << total << endl;
608 cerr << "underrun for " << _name << endl;
614 /* We have enough samples, but not in one lump. Coalesce the two parts
615 into one in playback_wrap_buffer in our ChannelInfo, and specify that
616 as our current_playback_buffer.
619 assert(wrap_buffer_size >= necessary_samples);
621 /* Copy buf[0] from playback_buf */
622 memcpy ((char *) chaninfo->playback_wrap_buffer,
623 chaninfo->playback_vector.buf[0],
624 chaninfo->playback_vector.len[0] * sizeof (Sample));
626 /* Copy buf[1] from playback_buf */
627 memcpy (chaninfo->playback_wrap_buffer + chaninfo->playback_vector.len[0],
628 chaninfo->playback_vector.buf[1],
629 (necessary_samples - chaninfo->playback_vector.len[0])
632 chaninfo->current_playback_buffer = chaninfo->playback_wrap_buffer;
637 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
639 interpolation.set_speed (_target_speed);
642 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++channel) {
643 ChannelInfo* chaninfo (*chan);
645 playback_distance = interpolation.interpolate (
646 channel, nframes, chaninfo->current_playback_buffer, chaninfo->speed_buffer);
648 chaninfo->current_playback_buffer = chaninfo->speed_buffer;
652 playback_distance = nframes;
655 _speed = _target_speed;
658 if (need_disk_signal) {
660 /* copy data over to buffer set */
662 size_t n_buffers = bufs.count().n_audio();
663 size_t n_chans = c->size();
664 gain_t scaling = 1.0f;
666 if (n_chans > n_buffers) {
667 scaling = ((float) n_buffers)/n_chans;
670 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
672 AudioBuffer& buf (bufs.get_audio (n%n_buffers));
673 ChannelInfo* chaninfo (*chan);
676 if (scaling != 1.0f) {
677 buf.read_from_with_gain (chaninfo->current_playback_buffer, nframes, scaling);
679 buf.read_from (chaninfo->current_playback_buffer, nframes);
682 if (scaling != 1.0f) {
683 buf.accumulate_with_gain_from (chaninfo->current_playback_buffer, nframes, scaling);
685 buf.accumulate_from (chaninfo->current_playback_buffer, nframes);
690 /* leave the MIDI count alone */
691 ChanCount cnt (DataType::AUDIO, n_chans);
692 cnt.set (DataType::MIDI, bufs.count().n_midi());
693 bufs.set_count (cnt);
695 /* extra buffers will already be silent, so leave them alone */
702 AudioDiskstream::calculate_playback_distance (pframes_t nframes)
704 frameoffset_t playback_distance = nframes;
706 if (record_enabled()) {
707 playback_distance = nframes;
708 } else if (_actual_speed != 1.0f && _actual_speed != -1.0f) {
709 interpolation.set_speed (_target_speed);
710 boost::shared_ptr<ChannelList> c = channels.reader();
712 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++channel) {
713 playback_distance = interpolation.interpolate (channel, nframes, NULL, NULL);
716 playback_distance = nframes;
719 if (_actual_speed < 0.0) {
720 return -playback_distance;
722 return playback_distance;
726 /** Update various things including playback_sample, read pointer on each channel's playback_buf
727 * and write pointer on each channel's capture_buf. Also wout whether the butler is needed.
728 * @return true if the butler is required.
731 AudioDiskstream::commit (framecnt_t playback_distance)
733 bool need_butler = false;
735 if (!_io || !_io->active()) {
739 if (_actual_speed < 0.0) {
740 playback_sample -= playback_distance;
742 playback_sample += playback_distance;
745 boost::shared_ptr<ChannelList> c = channels.reader();
746 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
748 (*chan)->playback_buf->increment_read_ptr (playback_distance);
750 if (adjust_capture_position) {
751 (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
755 if (adjust_capture_position != 0) {
756 capture_captured += adjust_capture_position;
757 adjust_capture_position = 0;
765 if (_io && _io->active()) {
766 need_butler = c->front()->playback_buf->write_space() >= c->front()->playback_buf->bufsize() / 2;
771 if (_io && _io->active()) {
772 need_butler = ((framecnt_t) c->front()->playback_buf->write_space() >= disk_io_chunk_frames)
773 || ((framecnt_t) c->front()->capture_buf->read_space() >= disk_io_chunk_frames);
775 need_butler = ((framecnt_t) c->front()->capture_buf->read_space() >= disk_io_chunk_frames);
783 AudioDiskstream::set_pending_overwrite (bool yn)
785 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
787 _pending_overwrite = yn;
789 overwrite_frame = playback_sample;
791 boost::shared_ptr<ChannelList> c = channels.reader ();
793 overwrite_offset = c->front()->playback_buf->get_read_ptr();
798 AudioDiskstream::overwrite_existing_buffers ()
800 boost::shared_ptr<ChannelList> c = channels.reader();
802 _pending_overwrite = false;
806 Sample* mixdown_buffer;
809 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
811 overwrite_queued = false;
813 /* assume all are the same size */
814 framecnt_t size = c->front()->playback_buf->bufsize();
816 mixdown_buffer = new Sample[size];
817 gain_buffer = new float[size];
819 /* reduce size so that we can fill the buffer correctly (ringbuffers
820 can only handle size-1, otherwise they appear to be empty)
827 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
829 start = overwrite_frame;
830 framecnt_t cnt = size;
832 /* to fill the buffer without resetting the playback sample, we need to
833 do it one or two chunks (normally two).
835 |----------------------------------------------------------------------|
839 |<- second chunk->||<----------------- first chunk ------------------>|
843 framecnt_t to_read = size - overwrite_offset;
845 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, n, reversed)) {
846 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
847 id(), size, playback_sample) << endmsg;
855 if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer, start, cnt, n, reversed)) {
856 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
857 id(), size, playback_sample) << endmsg;
866 _pending_overwrite = false;
867 delete [] gain_buffer;
868 delete [] mixdown_buffer;
873 AudioDiskstream::seek (framepos_t frame, bool complete_refill)
877 ChannelList::iterator chan;
878 boost::shared_ptr<ChannelList> c = channels.reader();
880 Glib::Threads::Mutex::Lock lm (state_lock);
882 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
883 (*chan)->playback_buf->reset ();
884 (*chan)->capture_buf->reset ();
887 /* can't rec-enable in destructive mode if transport is before start */
889 if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
890 disengage_record_enable ();
893 playback_sample = frame;
896 if (complete_refill) {
897 while ((ret = do_refill_with_alloc ()) > 0) ;
899 ret = do_refill_with_alloc ();
906 AudioDiskstream::can_internal_playback_seek (framecnt_t distance)
908 ChannelList::iterator chan;
909 boost::shared_ptr<ChannelList> c = channels.reader();
911 for (chan = c->begin(); chan != c->end(); ++chan) {
912 if ((*chan)->playback_buf->read_space() < (size_t) distance) {
920 AudioDiskstream::internal_playback_seek (framecnt_t distance)
922 ChannelList::iterator chan;
923 boost::shared_ptr<ChannelList> c = channels.reader();
925 for (chan = c->begin(); chan != c->end(); ++chan) {
926 (*chan)->playback_buf->increment_read_ptr (llabs(distance));
929 if (first_recordable_frame < max_framepos) {
930 first_recordable_frame += distance;
932 playback_sample += distance;
937 /** Read some data for 1 channel from our playlist into a buffer.
938 * @param buf Buffer to write to.
939 * @param start Session frame to start reading from; updated to where we end up
941 * @param cnt Count of samples to read.
942 * @param reversed true if we are running backwards, otherwise false.
945 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer,
946 framepos_t& start, framecnt_t cnt,
947 int channel, bool reversed)
949 framecnt_t this_read = 0;
951 framepos_t loop_end = 0;
952 framepos_t loop_start = 0;
953 framecnt_t offset = 0;
956 /* XXX we don't currently play loops in reverse. not sure why */
960 framecnt_t loop_length = 0;
962 /* Make the use of a Location atomic for this read operation.
964 Note: Locations don't get deleted, so all we care about
965 when I say "atomic" is that we are always pointing to
966 the same one and using a start/length values obtained
970 if ((loc = loop_location) != 0) {
971 loop_start = loc->start();
972 loop_end = loc->end();
973 loop_length = loop_end - loop_start;
976 /* if we are looping, ensure that the first frame we read is at the correct
977 position within the loop.
980 if (loc && start >= loop_end) {
981 start = loop_start + ((start - loop_start) % loop_length);
989 /* We need this while loop in case we hit a loop boundary, in which case our read from
990 the playlist must be split into more than one section.
995 /* take any loop into account. we can't read past the end of the loop. */
997 if (loc && (loop_end - start < cnt)) {
998 this_read = loop_end - start;
1005 if (this_read == 0) {
1009 this_read = min(cnt,this_read);
1011 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
1012 error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), id(), this_read,
1019 swap_by_ptr (buf, buf + this_read - 1);
1023 /* if we read to the end of the loop, go back to the beginning */
1033 offset += this_read;
1040 AudioDiskstream::do_refill_with_alloc ()
1042 Sample* mix_buf = new Sample[disk_io_chunk_frames];
1043 float* gain_buf = new float[disk_io_chunk_frames];
1045 int ret = _do_refill(mix_buf, gain_buf);
1053 /** Get some more data from disk and put it in our channels' playback_bufs,
1054 * if there is suitable space in them.
1057 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer)
1061 RingBufferNPT<Sample>::rw_vector vector;
1062 bool const reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1063 framecnt_t total_space;
1064 framecnt_t zero_fill;
1066 ChannelList::iterator i;
1067 boost::shared_ptr<ChannelList> c = channels.reader();
1074 assert(mixdown_buffer);
1075 assert(gain_buffer);
1082 c->front()->playback_buf->get_write_vector (&vector);
1084 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1085 /* nowhere to write to */
1089 /* if there are 2+ chunks of disk i/o possible for
1090 this track, let the caller know so that it can arrange
1091 for us to be called again, ASAP.
1094 if (total_space >= (_slaved ? 3 : 2) * disk_io_chunk_frames) {
1098 /* if we're running close to normal speed and there isn't enough
1099 space to do disk_io_chunk_frames of I/O, then don't bother.
1101 at higher speeds, just do it because the sync between butler
1102 and audio thread may not be good enough.
1104 Note: it is a design assumption that disk_io_chunk_frames is smaller
1105 than the playback buffer size, so this check should never trip when
1106 the playback buffer is empty.
1109 if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1113 /* when slaved, don't try to get too close to the read pointer. this
1114 leaves space for the buffer reversal to have something useful to
1118 if (_slaved && total_space < (framecnt_t) (c->front()->playback_buf->bufsize() / 2)) {
1122 /* never do more than disk_io_chunk_frames worth of disk input per call (limit doesn't apply for memset) */
1124 total_space = min (disk_io_chunk_frames, total_space);
1128 if (file_frame == 0) {
1130 /* at start: nothing to do but fill with silence */
1132 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1134 ChannelInfo* chan (*i);
1135 chan->playback_buf->get_write_vector (&vector);
1136 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1137 if (vector.len[1]) {
1138 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1140 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1145 if (file_frame < total_space) {
1147 /* too close to the start: read what we can,
1148 and then zero fill the rest
1151 zero_fill = total_space - file_frame;
1152 total_space = file_frame;
1161 if (file_frame == max_framepos) {
1163 /* at end: nothing to do but fill with silence */
1165 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1167 ChannelInfo* chan (*i);
1168 chan->playback_buf->get_write_vector (&vector);
1169 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1170 if (vector.len[1]) {
1171 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1173 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1178 if (file_frame > max_framepos - total_space) {
1180 /* to close to the end: read what we can, and zero fill the rest */
1182 zero_fill = total_space - (max_framepos - file_frame);
1183 total_space = max_framepos - file_frame;
1190 framepos_t file_frame_tmp = 0;
1192 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1194 ChannelInfo* chan (*i);
1197 framecnt_t len1, len2;
1199 chan->playback_buf->get_write_vector (&vector);
1201 if ((framecnt_t) vector.len[0] > disk_io_chunk_frames) {
1203 /* we're not going to fill the first chunk, so certainly do not bother with the
1204 other part. it won't be connected with the part we do fill, as in:
1206 .... => writable space
1207 ++++ => readable space
1208 ^^^^ => 1 x disk_io_chunk_frames that would be filled
1210 |......|+++++++++++++|...............................|
1215 So, just pretend that the buf1 part isn't there.
1225 file_frame_tmp = file_frame;
1227 buf1 = vector.buf[0];
1228 len1 = vector.len[0];
1229 buf2 = vector.buf[1];
1230 len2 = vector.len[1];
1232 to_read = min (ts, len1);
1233 to_read = min (to_read, disk_io_chunk_frames);
1235 assert (to_read >= 0);
1239 if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1244 chan->playback_buf->increment_write_ptr (to_read);
1248 to_read = min (ts, len2);
1252 /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1253 so read some or all of vector.len[1] as well.
1256 if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1261 chan->playback_buf->increment_write_ptr (to_read);
1265 /* XXX: do something */
1270 file_frame = file_frame_tmp;
1271 assert (file_frame >= 0);
1278 /** Flush pending data to disk.
1280 * Important note: this function will write *AT MOST* disk_io_chunk_frames
1281 * of data to disk. it will never write more than that. If it writes that
1282 * much and there is more than that waiting to be written, it will return 1,
1283 * otherwise 0 on success or -1 on failure.
1285 * If there is less than disk_io_chunk_frames to be written, no data will be
1286 * written at all unless @a force_flush is true.
1289 AudioDiskstream::do_flush (RunContext /*context*/, bool force_flush)
1293 RingBufferNPT<Sample>::rw_vector vector;
1294 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1297 transvec.buf[0] = 0;
1298 transvec.buf[1] = 0;
1302 boost::shared_ptr<ChannelList> c = channels.reader();
1303 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1305 (*chan)->capture_buf->get_read_vector (&vector);
1307 total = vector.len[0] + vector.len[1];
1309 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1313 /* if there are 2+ chunks of disk i/o possible for
1314 this track, let the caller know so that it can arrange
1315 for us to be called again, ASAP.
1317 if we are forcing a flush, then if there is* any* extra
1318 work, let the caller know.
1320 if we are no longer recording and there is any extra work,
1321 let the caller know too.
1324 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1328 to_write = min (disk_io_chunk_frames, (framecnt_t) vector.len[0]);
1330 // check the transition buffer when recording destructive
1331 // important that we get this after the capture buf
1333 if (destructive()) {
1334 (*chan)->capture_transition_buf->get_read_vector(&transvec);
1335 size_t transcount = transvec.len[0] + transvec.len[1];
1338 for (ti=0; ti < transcount; ++ti) {
1339 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1341 if (captrans.type == CaptureStart) {
1342 // by definition, the first data we got above represents the given capture pos
1344 (*chan)->write_source->mark_capture_start (captrans.capture_val);
1345 (*chan)->curr_capture_cnt = 0;
1347 } else if (captrans.type == CaptureEnd) {
1349 // capture end, the capture_val represents total frames in capture
1351 if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1353 // shorten to make the write a perfect fit
1354 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
1356 if (nto_write < to_write) {
1357 ret = 1; // should we?
1359 to_write = nto_write;
1361 (*chan)->write_source->mark_capture_end ();
1363 // increment past this transition, but go no further
1368 // actually ends just beyond this chunk, so force more work
1376 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1380 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1381 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), id()) << endmsg;
1385 (*chan)->capture_buf->increment_read_ptr (to_write);
1386 (*chan)->curr_capture_cnt += to_write;
1388 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1390 /* we wrote all of vector.len[0] but it wasn't an entire
1391 disk_io_chunk_frames of data, so arrange for some part
1392 of vector.len[1] to be flushed to disk as well.
1395 to_write = min ((framecnt_t)(disk_io_chunk_frames - to_write), (framecnt_t) vector.len[1]);
1397 if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1398 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), id()) << endmsg;
1402 (*chan)->capture_buf->increment_read_ptr (to_write);
1403 (*chan)->curr_capture_cnt += to_write;
1412 AudioDiskstream::transport_stopped_wallclock (struct tm& when, time_t twhen, bool abort_capture)
1414 uint32_t buffer_position;
1415 bool more_work = true;
1417 boost::shared_ptr<AudioRegion> region;
1418 framecnt_t total_capture;
1420 SourceList::iterator src;
1421 ChannelList::iterator chan;
1422 vector<CaptureInfo*>::iterator ci;
1423 boost::shared_ptr<ChannelList> c = channels.reader();
1425 bool mark_write_completed = false;
1429 /* butler is already stopped, but there may be work to do
1430 to flush remaining data to disk.
1433 while (more_work && !err) {
1434 switch (do_flush (TransportContext, true)) {
1441 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1446 /* XXX is there anything we can do if err != 0 ? */
1447 Glib::Threads::Mutex::Lock lm (capture_info_lock);
1449 if (capture_info.empty()) {
1453 if (abort_capture) {
1455 if (destructive()) {
1459 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1461 if ((*chan)->write_source) {
1463 (*chan)->write_source->mark_for_remove ();
1464 (*chan)->write_source->drop_references ();
1465 (*chan)->write_source.reset ();
1468 /* new source set up in "out" below */
1474 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1475 total_capture += (*ci)->frames;
1478 /* figure out the name for this take */
1480 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1482 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1486 s->update_header (capture_info.front()->start, when, twhen);
1487 s->set_captured_for (_name.val());
1488 s->mark_immutable ();
1490 if (Config->get_auto_analyse_audio()) {
1491 Analyser::queue_source_for_analysis (s, true);
1496 /* destructive tracks have a single, never changing region */
1498 if (destructive()) {
1500 /* send a signal that any UI can pick up to do the right thing. there is
1501 a small problem here in that a UI may need the peak data to be ready
1502 for the data that was recorded and this isn't interlocked with that
1503 process. this problem is deferred to the UI.
1506 _playlist->LayeringChanged(); // XXX this may not get the UI to do the right thing
1510 string whole_file_region_name;
1511 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1513 /* Register a new region with the Session that
1514 describes the entire source. Do this first
1515 so that any sub-regions will obviously be
1516 children of this one (later!)
1522 plist.add (Properties::start, c->front()->write_source->last_capture_start_frame());
1523 plist.add (Properties::length, total_capture);
1524 plist.add (Properties::name, whole_file_region_name);
1525 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1526 rx->set_automatic (true);
1527 rx->set_whole_file (true);
1529 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1530 region->special_set_position (capture_info.front()->start);
1534 catch (failed_constructor& err) {
1535 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1539 _last_capture_sources.insert (_last_capture_sources.end(), srcs.begin(), srcs.end());
1541 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1543 _playlist->clear_changes ();
1544 _playlist->set_capture_insertion_in_progress (true);
1545 _playlist->freeze ();
1547 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1551 RegionFactory::region_name (region_name, whole_file_region_name, false);
1553 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1 capture start @ %2 length %3 add new region %4\n",
1554 _name, (*ci)->start, (*ci)->frames, region_name));
1560 plist.add (Properties::start, buffer_position);
1561 plist.add (Properties::length, (*ci)->frames);
1562 plist.add (Properties::name, region_name);
1564 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1565 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1568 catch (failed_constructor& err) {
1569 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1570 continue; /* XXX is this OK? */
1573 i_am_the_modifier++;
1575 _playlist->add_region (region, (*ci)->start, 1, non_layered());
1576 _playlist->set_layer (region, DBL_MAX);
1577 i_am_the_modifier--;
1579 buffer_position += (*ci)->frames;
1583 _playlist->set_capture_insertion_in_progress (false);
1584 _session.add_command (new StatefulDiffCommand (_playlist));
1587 mark_write_completed = true;
1590 reset_write_sources (mark_write_completed);
1594 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1598 capture_info.clear ();
1599 capture_start_frame = 0;
1603 AudioDiskstream::transport_looped (framepos_t transport_frame)
1605 if (was_recording) {
1606 // all we need to do is finish this capture, with modified capture length
1607 boost::shared_ptr<ChannelList> c = channels.reader();
1609 // adjust the capture length knowing that the data will be recorded to disk
1610 // only necessary after the first loop where we're recording
1611 if (capture_info.size() == 0) {
1612 capture_captured += _capture_offset;
1614 if (_alignment_style == ExistingMaterial) {
1615 capture_captured += _session.worst_output_latency();
1617 capture_captured += _roll_delay;
1623 // the next region will start recording via the normal mechanism
1624 // we'll set the start position to the current transport pos
1625 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1626 capture_start_frame = transport_frame;
1627 first_recordable_frame = transport_frame; // mild lie
1628 last_recordable_frame = max_framepos;
1629 was_recording = true;
1631 if (recordable() && destructive()) {
1632 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1634 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1635 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1637 if (transvec.len[0] > 0) {
1638 transvec.buf[0]->type = CaptureStart;
1639 transvec.buf[0]->capture_val = capture_start_frame;
1640 (*chan)->capture_transition_buf->increment_write_ptr(1);
1644 fatal << X_("programming error: capture_transition_buf is full on rec loop! inconceivable!")
1654 AudioDiskstream::finish_capture (boost::shared_ptr<ChannelList> c)
1656 was_recording = false;
1657 first_recordable_frame = max_framepos;
1658 last_recordable_frame = max_framepos;
1660 if (capture_captured == 0) {
1664 if (recordable() && destructive()) {
1665 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1667 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1668 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1670 if (transvec.len[0] > 0) {
1671 transvec.buf[0]->type = CaptureEnd;
1672 transvec.buf[0]->capture_val = capture_captured;
1673 (*chan)->capture_transition_buf->increment_write_ptr(1);
1677 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1683 CaptureInfo* ci = new CaptureInfo;
1685 ci->start = capture_start_frame;
1686 ci->frames = capture_captured;
1688 /* XXX theoretical race condition here. Need atomic exchange ?
1689 However, the circumstances when this is called right
1690 now (either on record-disable or transport_stopped)
1691 mean that no actual race exists. I think ...
1692 We now have a capture_info_lock, but it is only to be used
1693 to synchronize in the transport_stop and the capture info
1694 accessors, so that invalidation will not occur (both non-realtime).
1697 // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1699 capture_info.push_back (ci);
1700 capture_captured = 0;
1702 /* now we've finished a capture, reset first_recordable_frame for next time */
1703 first_recordable_frame = max_framepos;
1707 AudioDiskstream::set_record_enabled (bool yn)
1709 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0) {
1713 /* can't rec-enable in destructive mode if transport is before start */
1715 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1719 /* yes, i know that this not proof against race conditions, but its
1720 good enough. i think.
1723 if (record_enabled() != yn) {
1725 engage_record_enable ();
1727 disengage_record_enable ();
1730 RecordEnableChanged (); /* EMIT SIGNAL */
1735 AudioDiskstream::prep_record_enable ()
1737 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0) {
1741 /* can't rec-enable in destructive mode if transport is before start */
1743 if (destructive() && _session.transport_frame() < _session.current_start_frame()) {
1747 bool rolling = _session.transport_speed() != 0.0f;
1748 boost::shared_ptr<ChannelList> c = channels.reader();
1750 capturing_sources.clear ();
1752 if (Config->get_monitoring_model() == HardwareMonitoring) {
1754 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1755 (*chan)->source.request_input_monitoring (!(_session.config.get_auto_input() && rolling));
1756 capturing_sources.push_back ((*chan)->write_source);
1757 (*chan)->write_source->mark_streaming_write_started ();
1761 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1762 capturing_sources.push_back ((*chan)->write_source);
1763 (*chan)->write_source->mark_streaming_write_started ();
1771 AudioDiskstream::prep_record_disable ()
1773 boost::shared_ptr<ChannelList> c = channels.reader();
1774 if (Config->get_monitoring_model() == HardwareMonitoring) {
1775 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1776 (*chan)->source.request_input_monitoring (false);
1779 capturing_sources.clear ();
1785 AudioDiskstream::get_state ()
1787 XMLNode& node (Diskstream::get_state());
1789 LocaleGuard lg (X_("POSIX"));
1791 boost::shared_ptr<ChannelList> c = channels.reader();
1792 snprintf (buf, sizeof(buf), "%zd", c->size());
1793 node.add_property ("channels", buf);
1795 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1797 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1798 XMLNode* cs_grandchild;
1800 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1801 cs_grandchild = new XMLNode (X_("file"));
1802 cs_grandchild->add_property (X_("path"), (*i)->path());
1803 cs_child->add_child_nocopy (*cs_grandchild);
1806 /* store the location where capture will start */
1810 if (_session.config.get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1811 snprintf (buf, sizeof (buf), "%" PRId64, pi->start());
1813 snprintf (buf, sizeof (buf), "%" PRId64, _session.transport_frame());
1816 cs_child->add_property (X_("at"), buf);
1817 node.add_child_nocopy (*cs_child);
1824 AudioDiskstream::set_state (const XMLNode& node, int version)
1826 const XMLProperty* prop;
1827 XMLNodeList nlist = node.children();
1828 XMLNodeIterator niter;
1829 uint32_t nchans = 1;
1830 XMLNode* capture_pending_node = 0;
1831 LocaleGuard lg (X_("POSIX"));
1833 /* prevent write sources from being created */
1835 in_set_state = true;
1837 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1838 if ((*niter)->name() == IO::state_node_name) {
1839 deprecated_io_node = new XMLNode (**niter);
1842 if ((*niter)->name() == X_("CapturingSources")) {
1843 capture_pending_node = *niter;
1847 if (Diskstream::set_state (node, version)) {
1851 if ((prop = node.property ("channels")) != 0) {
1852 nchans = atoi (prop->value().c_str());
1855 // create necessary extra channels
1856 // we are always constructed with one and we always need one
1858 _n_channels.set(DataType::AUDIO, channels.reader()->size());
1860 if (nchans > _n_channels.n_audio()) {
1862 add_channel (nchans - _n_channels.n_audio());
1863 IO::PortCountChanged(_n_channels);
1865 } else if (nchans < _n_channels.n_audio()) {
1867 remove_channel (_n_channels.n_audio() - nchans);
1872 if (!destructive() && capture_pending_node) {
1873 /* destructive streams have one and only one source per channel,
1874 and so they never end up in pending capture in any useful
1877 use_pending_capture_data (*capture_pending_node);
1880 in_set_state = false;
1882 /* make sure this is clear before we do anything else */
1884 capturing_sources.clear ();
1886 /* write sources are handled when we handle the input set
1887 up of the IO that owns this DS (::non_realtime_input_change())
1894 AudioDiskstream::use_new_write_source (uint32_t n)
1896 boost::shared_ptr<ChannelList> c = channels.reader();
1898 if (!recordable()) {
1902 if (n >= c->size()) {
1903 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
1907 ChannelInfo* chan = (*c)[n];
1910 if ((chan->write_source = _session.create_audio_source_for_session (
1911 n_channels().n_audio(), name(), n, destructive())) == 0) {
1912 throw failed_constructor();
1916 catch (failed_constructor &err) {
1917 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
1918 chan->write_source.reset ();
1922 /* do not remove destructive files even if they are empty */
1924 chan->write_source->set_allow_remove_if_empty (!destructive());
1929 list<boost::shared_ptr<Source> >
1930 AudioDiskstream::steal_write_sources()
1932 /* not possible to steal audio write sources */
1933 list<boost::shared_ptr<Source> > ret;
1938 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool /*force*/)
1940 ChannelList::iterator chan;
1941 boost::shared_ptr<ChannelList> c = channels.reader();
1944 if (!_session.writable() || !recordable()) {
1948 capturing_sources.clear ();
1950 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1952 if (!destructive()) {
1954 if ((*chan)->write_source) {
1956 if (mark_write_complete) {
1957 (*chan)->write_source->mark_streaming_write_completed ();
1958 (*chan)->write_source->done_with_peakfile_writes ();
1961 if ((*chan)->write_source->removable()) {
1962 (*chan)->write_source->mark_for_remove ();
1963 (*chan)->write_source->drop_references ();
1966 (*chan)->write_source.reset ();
1969 use_new_write_source (n);
1971 if (record_enabled()) {
1972 capturing_sources.push_back ((*chan)->write_source);
1977 if ((*chan)->write_source == 0) {
1978 use_new_write_source (n);
1983 if (destructive() && !c->empty ()) {
1985 /* we now have all our write sources set up, so create the
1986 playlist's single region.
1989 if (_playlist->empty()) {
1990 setup_destructive_playlist ();
1996 AudioDiskstream::set_block_size (pframes_t /*nframes*/)
1998 if (_session.get_block_size() > speed_buffer_size) {
1999 speed_buffer_size = _session.get_block_size();
2000 boost::shared_ptr<ChannelList> c = channels.reader();
2002 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2003 if ((*chan)->speed_buffer)
2004 delete [] (*chan)->speed_buffer;
2005 (*chan)->speed_buffer = new Sample[speed_buffer_size];
2008 allocate_temporary_buffers ();
2012 AudioDiskstream::allocate_temporary_buffers ()
2014 /* make sure the wrap buffer is at least large enough to deal
2015 with the speeds up to 1.2, to allow for micro-variation
2016 when slaving to MTC, Timecode etc.
2019 double const sp = max (fabsf (_actual_speed), 1.2f);
2020 framecnt_t required_wrap_size = (framecnt_t) ceil (_session.get_block_size() * sp) + 2;
2022 if (required_wrap_size > wrap_buffer_size) {
2024 boost::shared_ptr<ChannelList> c = channels.reader();
2026 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2027 if ((*chan)->playback_wrap_buffer) {
2028 delete [] (*chan)->playback_wrap_buffer;
2030 (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
2031 if ((*chan)->capture_wrap_buffer) {
2032 delete [] (*chan)->capture_wrap_buffer;
2034 (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
2037 wrap_buffer_size = required_wrap_size;
2042 AudioDiskstream::request_input_monitoring (bool yn)
2044 boost::shared_ptr<ChannelList> c = channels.reader();
2046 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2047 (*chan)->source.request_input_monitoring (yn);
2052 AudioDiskstream::set_align_style_from_io ()
2054 bool have_physical = false;
2056 if (_alignment_choice != Automatic) {
2064 get_input_sources ();
2066 boost::shared_ptr<ChannelList> c = channels.reader();
2068 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2069 if ((*chan)->source.is_physical ()) {
2070 have_physical = true;
2075 if (have_physical) {
2076 set_align_style (ExistingMaterial);
2078 set_align_style (CaptureTime);
2083 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2085 while (how_many--) {
2086 c->push_back (new ChannelInfo(
2087 _session.butler()->audio_diskstream_playback_buffer_size(),
2088 _session.butler()->audio_diskstream_capture_buffer_size(),
2089 speed_buffer_size, wrap_buffer_size));
2090 interpolation.add_channel_to (
2091 _session.butler()->audio_diskstream_playback_buffer_size(),
2095 _n_channels.set(DataType::AUDIO, c->size());
2101 AudioDiskstream::add_channel (uint32_t how_many)
2103 RCUWriter<ChannelList> writer (channels);
2104 boost::shared_ptr<ChannelList> c = writer.get_copy();
2106 return add_channel_to (c, how_many);
2110 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2112 while (how_many-- && !c->empty()) {
2115 interpolation.remove_channel_from ();
2118 _n_channels.set(DataType::AUDIO, c->size());
2124 AudioDiskstream::remove_channel (uint32_t how_many)
2126 RCUWriter<ChannelList> writer (channels);
2127 boost::shared_ptr<ChannelList> c = writer.get_copy();
2129 return remove_channel_from (c, how_many);
2133 AudioDiskstream::playback_buffer_load () const
2135 boost::shared_ptr<ChannelList> c = channels.reader();
2141 return (float) ((double) c->front()->playback_buf->read_space()/
2142 (double) c->front()->playback_buf->bufsize());
2146 AudioDiskstream::capture_buffer_load () const
2148 boost::shared_ptr<ChannelList> c = channels.reader();
2154 return (float) ((double) c->front()->capture_buf->write_space()/
2155 (double) c->front()->capture_buf->bufsize());
2159 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2161 const XMLProperty* prop;
2162 XMLNodeList nlist = node.children();
2163 XMLNodeIterator niter;
2164 boost::shared_ptr<AudioFileSource> fs;
2165 boost::shared_ptr<AudioFileSource> first_fs;
2166 SourceList pending_sources;
2167 framepos_t position;
2169 if ((prop = node.property (X_("at"))) == 0) {
2173 if (sscanf (prop->value().c_str(), "%" PRIu64, &position) != 1) {
2177 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2178 if ((*niter)->name() == X_("file")) {
2180 if ((prop = (*niter)->property (X_("path"))) == 0) {
2184 // This protects sessions from errant CapturingSources in stored sessions
2186 if (stat (prop->value().c_str(), &sbuf)) {
2191 fs = boost::dynamic_pointer_cast<AudioFileSource> (
2192 SourceFactory::createWritable (
2193 DataType::AUDIO, _session,
2194 prop->value(), false, _session.frame_rate()));
2197 catch (failed_constructor& err) {
2198 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2199 _name, prop->value())
2204 pending_sources.push_back (fs);
2206 if (first_fs == 0) {
2210 fs->set_captured_for (_name.val());
2214 if (pending_sources.size() == 0) {
2215 /* nothing can be done */
2219 if (pending_sources.size() != _n_channels.n_audio()) {
2220 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2225 boost::shared_ptr<AudioRegion> region;
2231 plist.add (Properties::start, 0);
2232 plist.add (Properties::length, first_fs->length (first_fs->timeline_position()));
2233 plist.add (Properties::name, region_name_from_path (first_fs->name(), true));
2235 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (pending_sources, plist));
2237 region->set_automatic (true);
2238 region->set_whole_file (true);
2239 region->special_set_position (0);
2242 catch (failed_constructor& err) {
2243 error << string_compose (
2244 _("%1: cannot create whole-file region from pending capture sources"),
2250 _playlist->add_region (region, position);
2256 AudioDiskstream::set_non_layered (bool yn)
2258 if (yn != non_layered()) {
2261 _flags = Flag (_flags | NonLayered);
2263 _flags = Flag (_flags & ~NonLayered);
2271 AudioDiskstream::set_destructive (bool yn)
2273 if (yn != destructive()) {
2276 bool bounce_ignored;
2277 /* requestor should already have checked this and
2278 bounced if necessary and desired
2280 if (!can_become_destructive (bounce_ignored)) {
2283 _flags = Flag (_flags | Destructive);
2284 use_destructive_playlist ();
2286 _flags = Flag (_flags & ~Destructive);
2287 reset_write_sources (true, true);
2295 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2298 requires_bounce = false;
2302 /* is there only one region ? */
2304 if (_playlist->n_regions() != 1) {
2305 requires_bounce = true;
2309 boost::shared_ptr<Region> first = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
2311 requires_bounce = false;
2315 /* do the source(s) for the region cover the session start position ? */
2317 if (first->position() != _session.current_start_frame()) {
2318 if (first->start() > _session.current_start_frame()) {
2319 requires_bounce = true;
2324 /* is the source used by only 1 playlist ? */
2326 boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2330 if (_session.playlists->source_use_count (afirst->source()) > 1) {
2331 requires_bounce = true;
2335 requires_bounce = false;
2340 AudioDiskstream::adjust_playback_buffering ()
2342 boost::shared_ptr<ChannelList> c = channels.reader();
2344 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2345 (*chan)->resize_playback (_session.butler()->audio_diskstream_playback_buffer_size());
2350 AudioDiskstream::adjust_capture_buffering ()
2352 boost::shared_ptr<ChannelList> c = channels.reader();
2354 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2355 (*chan)->resize_capture (_session.butler()->audio_diskstream_capture_buffer_size());
2360 AudioDiskstream::ChannelSource::is_physical () const
2366 return AudioEngine::instance()->port_is_physical (name);
2370 AudioDiskstream::ChannelSource::request_input_monitoring (bool yn) const
2376 return AudioEngine::instance()->request_input_monitoring (name, yn);
2379 AudioDiskstream::ChannelInfo::ChannelInfo (framecnt_t playback_bufsize, framecnt_t capture_bufsize, framecnt_t speed_size, framecnt_t wrap_size)
2381 current_capture_buffer = 0;
2382 current_playback_buffer = 0;
2383 curr_capture_cnt = 0;
2385 speed_buffer = new Sample[speed_size];
2386 playback_wrap_buffer = new Sample[wrap_size];
2387 capture_wrap_buffer = new Sample[wrap_size];
2389 playback_buf = new RingBufferNPT<Sample> (playback_bufsize);
2390 capture_buf = new RingBufferNPT<Sample> (capture_bufsize);
2391 capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2393 /* touch the ringbuffer buffers, which will cause
2394 them to be mapped into locked physical RAM if
2395 we're running with mlockall(). this doesn't do
2399 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2400 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2401 memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2405 AudioDiskstream::ChannelInfo::resize_playback (framecnt_t playback_bufsize)
2407 delete playback_buf;
2408 playback_buf = new RingBufferNPT<Sample> (playback_bufsize);
2409 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2413 AudioDiskstream::ChannelInfo::resize_capture (framecnt_t capture_bufsize)
2417 capture_buf = new RingBufferNPT<Sample> (capture_bufsize);
2418 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2421 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2423 write_source.reset ();
2425 delete [] speed_buffer;
2428 delete [] playback_wrap_buffer;
2429 playback_wrap_buffer = 0;
2431 delete [] capture_wrap_buffer;
2432 capture_wrap_buffer = 0;
2434 delete playback_buf;
2440 delete capture_transition_buf;
2441 capture_transition_buf = 0;
2446 AudioDiskstream::set_name (string const & name)
2448 Diskstream::set_name (name);
2450 /* get a new write source so that its name reflects the new diskstream name */
2452 boost::shared_ptr<ChannelList> c = channels.reader();
2453 ChannelList::iterator i;
2456 for (n = 0, i = c->begin(); i != c->end(); ++i, ++n) {
2457 use_new_write_source (n);