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/analyser.h"
41 #include "ardour/ardour.h"
42 #include "ardour/audio_buffer.h"
43 #include "ardour/audio_diskstream.h"
44 #include "ardour/audio_port.h"
45 #include "ardour/audioengine.h"
46 #include "ardour/audiofilesource.h"
47 #include "ardour/audioplaylist.h"
48 #include "ardour/audioregion.h"
49 #include "ardour/butler.h"
50 #include "ardour/configuration.h"
51 #include "ardour/cycle_timer.h"
52 #include "ardour/io.h"
53 #include "ardour/playlist_factory.h"
54 #include "ardour/region_factory.h"
55 #include "ardour/send.h"
56 #include "ardour/session.h"
57 #include "ardour/source_factory.h"
58 #include "ardour/utils.h"
64 using namespace ARDOUR;
67 size_t AudioDiskstream::_working_buffers_size = 0;
68 Sample* AudioDiskstream::_mixdown_buffer = 0;
69 gain_t* AudioDiskstream::_gain_buffer = 0;
71 AudioDiskstream::AudioDiskstream (Session &sess, const string &name, Diskstream::Flag flag)
72 : Diskstream(sess, name, flag)
73 , deprecated_io_node(NULL)
74 , channels (new ChannelList)
76 /* prevent any write sources from being created */
86 AudioDiskstream::AudioDiskstream (Session& sess, const XMLNode& node)
87 : Diskstream(sess, node)
88 , deprecated_io_node(NULL)
89 , channels (new ChannelList)
94 if (set_state (node, Stateful::loading_state_version)) {
96 throw failed_constructor();
102 use_destructive_playlist ();
107 AudioDiskstream::init (Diskstream::Flag f)
111 /* there are no channels at this point, so these
112 two calls just get speed_buffer_size and wrap_buffer
113 size setup without duplicating their code.
116 set_block_size (_session.get_block_size());
117 allocate_temporary_buffers ();
120 assert(_n_channels == ChanCount(DataType::AUDIO, 1));
123 AudioDiskstream::~AudioDiskstream ()
128 RCUWriter<ChannelList> writer (channels);
129 boost::shared_ptr<ChannelList> c = writer.get_copy();
131 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
142 AudioDiskstream::allocate_working_buffers()
144 assert(disk_io_frames() > 0);
146 _working_buffers_size = disk_io_frames();
147 _mixdown_buffer = new Sample[_working_buffers_size];
148 _gain_buffer = new gain_t[_working_buffers_size];
152 AudioDiskstream::free_working_buffers()
154 delete [] _mixdown_buffer;
155 delete [] _gain_buffer;
156 _working_buffers_size = 0;
162 AudioDiskstream::non_realtime_input_change ()
165 Glib::Mutex::Lock lm (state_lock);
167 if (input_change_pending == NoChange) {
172 RCUWriter<ChannelList> writer (channels);
173 boost::shared_ptr<ChannelList> c = writer.get_copy();
175 _n_channels.set(DataType::AUDIO, c->size());
177 if (_io->n_ports().n_audio() > _n_channels.n_audio()) {
178 add_channel_to (c, _io->n_ports().n_audio() - _n_channels.n_audio());
179 } else if (_io->n_ports().n_audio() < _n_channels.n_audio()) {
180 remove_channel_from (c, _n_channels.n_audio() - _io->n_ports().n_audio());
184 get_input_sources ();
185 set_capture_offset ();
187 if (first_input_change) {
188 set_align_style (_persistent_alignment_style);
189 first_input_change = false;
191 set_align_style_from_io ();
194 input_change_pending = NoChange;
196 /* implicit unlock */
199 /* reset capture files */
201 reset_write_sources (false);
203 /* now refill channel buffers */
205 if (speed() != 1.0f || speed() != -1.0f) {
206 seek ((nframes_t) (_session.transport_frame() * (double) speed()));
208 seek (_session.transport_frame());
213 AudioDiskstream::non_realtime_locate (nframes_t location)
215 /* now refill channel buffers */
217 if (speed() != 1.0f || speed() != -1.0f) {
218 seek ((nframes_t) (location * (double) speed()));
225 AudioDiskstream::get_input_sources ()
227 boost::shared_ptr<ChannelList> c = channels.reader();
230 ChannelList::iterator chan;
231 uint32_t ni = _io->n_ports().n_audio();
232 vector<string> connections;
234 for (n = 0, chan = c->begin(); chan != c->end() && n < ni; ++chan, ++n) {
236 connections.clear ();
238 if (_io->nth (n)->get_connections (connections) == 0) {
240 if ((*chan)->source) {
241 // _source->disable_metering ();
247 (*chan)->source = dynamic_cast<AudioPort*>(_session.engine().get_port_by_name (connections[0]) );
253 AudioDiskstream::find_and_use_playlist (const string& name)
255 boost::shared_ptr<AudioPlaylist> playlist;
257 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (_session.playlist_by_name (name))) == 0) {
258 playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, name));
262 error << string_compose(_("AudioDiskstream: Playlist \"%1\" isn't an audio playlist"), name) << endmsg;
266 return use_playlist (playlist);
270 AudioDiskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
272 assert(boost::dynamic_pointer_cast<AudioPlaylist>(playlist));
274 Diskstream::use_playlist(playlist);
280 AudioDiskstream::use_new_playlist ()
283 boost::shared_ptr<AudioPlaylist> playlist;
285 if (!in_set_state && destructive()) {
290 newname = Playlist::bump_name (_playlist->name(), _session);
292 newname = Playlist::bump_name (_name, _session);
295 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (DataType::AUDIO, _session, newname, hidden()))) != 0) {
297 playlist->set_orig_diskstream_id (id());
298 return use_playlist (playlist);
306 AudioDiskstream::use_copy_playlist ()
308 assert(audio_playlist());
314 if (_playlist == 0) {
315 error << string_compose(_("AudioDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
320 boost::shared_ptr<AudioPlaylist> playlist;
322 newname = Playlist::bump_name (_playlist->name(), _session);
324 if ((playlist = boost::dynamic_pointer_cast<AudioPlaylist>(PlaylistFactory::create (audio_playlist(), newname))) != 0) {
325 playlist->set_orig_diskstream_id (id());
326 return use_playlist (playlist);
333 AudioDiskstream::setup_destructive_playlist ()
336 boost::shared_ptr<ChannelList> c = channels.reader();
338 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
339 srcs.push_back ((*chan)->write_source);
342 /* a single full-sized region */
344 boost::shared_ptr<Region> region (RegionFactory::create (srcs, 0, max_frames - srcs.front()->natural_position(), _name));
345 _playlist->add_region (region, srcs.front()->natural_position());
349 AudioDiskstream::use_destructive_playlist ()
351 /* this is called from the XML-based constructor or ::set_destructive. when called,
352 we already have a playlist and a region, but we need to
353 set up our sources for write. we use the sources associated
354 with the (presumed single, full-extent) region.
357 boost::shared_ptr<Region> rp = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
360 reset_write_sources (false, true);
364 boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
367 throw failed_constructor();
370 /* be sure to stretch the region out to the maximum length */
372 region->set_length (max_frames - region->position(), this);
375 ChannelList::iterator chan;
376 boost::shared_ptr<ChannelList> c = channels.reader();
378 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
379 (*chan)->write_source = boost::dynamic_pointer_cast<AudioFileSource>(region->source (n));
380 assert((*chan)->write_source);
381 (*chan)->write_source->set_allow_remove_if_empty (false);
383 /* this might be false if we switched modes, so force it */
385 (*chan)->write_source->set_destructive (true);
388 /* the source list will never be reset for a destructive track */
392 AudioDiskstream::prepare_record_status(nframes_t capture_start_frame)
394 if (recordable() && destructive()) {
395 boost::shared_ptr<ChannelList> c = channels.reader();
396 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
398 RingBufferNPT<CaptureTransition>::rw_vector transvec;
399 (*chan)->capture_transition_buf->get_write_vector(&transvec);
401 if (transvec.len[0] > 0) {
402 transvec.buf[0]->type = CaptureStart;
403 transvec.buf[0]->capture_val = capture_start_frame;
404 (*chan)->capture_transition_buf->increment_write_ptr(1);
408 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
416 AudioDiskstream::process (nframes_t transport_frame, nframes_t nframes, bool can_record, bool rec_monitors_input)
419 boost::shared_ptr<ChannelList> c = channels.reader();
420 ChannelList::iterator chan;
422 nframes_t rec_offset = 0;
423 nframes_t rec_nframes = 0;
424 bool nominally_recording;
425 bool re = record_enabled ();
426 bool collect_playback = false;
428 /* if we've already processed the frames corresponding to this call,
429 just return. this allows multiple routes that are taking input
430 from this diskstream to call our ::process() method, but have
431 this stuff only happen once. more commonly, it allows both
432 the AudioTrack that is using this AudioDiskstream *and* the Session
433 to call process() without problems.
440 commit_should_unlock = false;
442 if (!_io || !_io->active()) {
447 check_record_status (transport_frame, nframes, can_record);
449 nominally_recording = (can_record && re);
456 /* This lock is held until the end of AudioDiskstream::commit, so these two functions
457 must always be called as a pair. The only exception is if this function
458 returns a non-zero value, in which case, ::commit should not be called.
461 // If we can't take the state lock return.
462 if (!state_lock.trylock()) {
465 commit_should_unlock = true;
466 adjust_capture_position = 0;
468 for (chan = c->begin(); chan != c->end(); ++chan) {
469 (*chan)->current_capture_buffer = 0;
470 (*chan)->current_playback_buffer = 0;
473 if (nominally_recording || (_session.get_record_enabled() && _session.config.get_punch_in())) {
474 // Safeguard against situations where process() goes haywire when autopunching and last_recordable_frame < first_recordable_frame
475 if (last_recordable_frame < first_recordable_frame) {
476 last_recordable_frame = max_frames;
479 OverlapType ot = coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
481 calculate_record_range(ot, transport_frame, nframes, rec_nframes, rec_offset);
483 if (rec_nframes && !was_recording) {
484 capture_captured = 0;
485 was_recording = true;
490 if (can_record && !_last_capture_regions.empty()) {
491 _last_capture_regions.clear ();
494 if (nominally_recording || rec_nframes) {
496 uint32_t limit = _io->n_ports ().n_audio();
498 /* one or more ports could already have been removed from _io, but our
499 channel setup hasn't yet been updated. prevent us from trying to
500 use channels that correspond to missing ports. note that the
501 process callback (from which this is called) is always atomic
502 with respect to port removal/addition.
505 for (n = 0, chan = c->begin(); chan != c->end() && n < limit; ++chan, ++n) {
507 ChannelInfo* chaninfo (*chan);
509 chaninfo->capture_buf->get_write_vector (&chaninfo->capture_vector);
511 if (rec_nframes <= chaninfo->capture_vector.len[0]) {
513 chaninfo->current_capture_buffer = chaninfo->capture_vector.buf[0];
515 /* note: grab the entire port buffer, but only copy what we were supposed to
516 for recording, and use rec_offset
519 AudioPort* const ap = _io->audio (n);
521 assert(rec_nframes <= ap->get_audio_buffer(nframes).capacity());
522 memcpy (chaninfo->current_capture_buffer, ap->get_audio_buffer (rec_nframes).data(rec_offset), sizeof (Sample) * rec_nframes);
527 nframes_t total = chaninfo->capture_vector.len[0] + chaninfo->capture_vector.len[1];
529 if (rec_nframes > total) {
534 AudioPort* const ap = _io->audio (n);
537 Sample* buf = ap->get_audio_buffer(nframes).data();
538 nframes_t first = chaninfo->capture_vector.len[0];
540 memcpy (chaninfo->capture_wrap_buffer, buf, sizeof (Sample) * first);
541 memcpy (chaninfo->capture_vector.buf[0], buf, sizeof (Sample) * first);
542 memcpy (chaninfo->capture_wrap_buffer+first, buf + first, sizeof (Sample) * (rec_nframes - first));
543 memcpy (chaninfo->capture_vector.buf[1], buf + first, sizeof (Sample) * (rec_nframes - first));
545 chaninfo->current_capture_buffer = chaninfo->capture_wrap_buffer;
552 finish_capture (rec_monitors_input, c);
559 /* data will be written to disk */
561 if (rec_nframes == nframes && rec_offset == 0) {
563 for (chan = c->begin(); chan != c->end(); ++chan) {
564 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
567 playback_distance = nframes;
572 /* we can't use the capture buffer as the playback buffer, because
573 we recorded only a part of the current process' cycle data
577 collect_playback = true;
580 adjust_capture_position = rec_nframes;
582 } else if (nominally_recording) {
584 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
586 for (chan = c->begin(); chan != c->end(); ++chan) {
587 (*chan)->current_playback_buffer = (*chan)->current_capture_buffer;
590 playback_distance = nframes;
594 collect_playback = true;
597 if (collect_playback) {
599 /* we're doing playback */
601 nframes_t necessary_samples;
603 /* no varispeed playback if we're recording, because the output .... TBD */
605 if (rec_nframes == 0 && _actual_speed != 1.0f) {
606 necessary_samples = (nframes_t) floor ((nframes * fabs (_actual_speed))) + 1;
608 necessary_samples = nframes;
611 for (chan = c->begin(); chan != c->end(); ++chan) {
612 (*chan)->playback_buf->get_read_vector (&(*chan)->playback_vector);
617 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
619 ChannelInfo* chaninfo (*chan);
621 if (necessary_samples <= chaninfo->playback_vector.len[0]) {
623 chaninfo->current_playback_buffer = chaninfo->playback_vector.buf[0];
626 nframes_t total = chaninfo->playback_vector.len[0] + chaninfo->playback_vector.len[1];
628 if (necessary_samples > total) {
629 cerr << _name << " Need " << necessary_samples << " total = " << total << endl;
630 cerr << "underrun for " << _name << endl;
636 memcpy ((char *) chaninfo->playback_wrap_buffer,
637 chaninfo->playback_vector.buf[0],
638 chaninfo->playback_vector.len[0] * sizeof (Sample));
639 memcpy (chaninfo->playback_wrap_buffer + chaninfo->playback_vector.len[0],
640 chaninfo->playback_vector.buf[1],
641 (necessary_samples - chaninfo->playback_vector.len[0])
644 chaninfo->current_playback_buffer = chaninfo->playback_wrap_buffer;
649 if (rec_nframes == 0 && _actual_speed != 1.0f && _actual_speed != -1.0f) {
650 process_varispeed_playback(nframes, c);
652 playback_distance = nframes;
655 _speed = _target_speed;
666 /* we're exiting with failure, so ::commit will not
667 be called. unlock the state lock.
670 commit_should_unlock = false;
678 AudioDiskstream::process_varispeed_playback(nframes_t nframes, boost::shared_ptr<ChannelList> c)
680 ChannelList::iterator chan;
682 interpolation.set_speed (_target_speed);
685 for (chan = c->begin(); chan != c->end(); ++chan, ++channel) {
686 ChannelInfo* chaninfo (*chan);
688 playback_distance = interpolation.interpolate (
689 channel, nframes, chaninfo->current_playback_buffer, chaninfo->speed_buffer);
691 chaninfo->current_playback_buffer = chaninfo->speed_buffer;
696 AudioDiskstream::commit (nframes_t /*nframes*/)
698 bool need_butler = false;
700 if (!_io || !_io->active()) {
704 if (_actual_speed < 0.0) {
705 playback_sample -= playback_distance;
707 playback_sample += playback_distance;
710 boost::shared_ptr<ChannelList> c = channels.reader();
711 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
713 (*chan)->playback_buf->increment_read_ptr (playback_distance);
715 if (adjust_capture_position) {
716 (*chan)->capture_buf->increment_write_ptr (adjust_capture_position);
720 if (adjust_capture_position != 0) {
721 capture_captured += adjust_capture_position;
722 adjust_capture_position = 0;
726 if (_io && _io->active()) {
727 need_butler = c->front()->playback_buf->write_space() >= c->front()->playback_buf->bufsize() / 2;
732 if (_io && _io->active()) {
733 need_butler = c->front()->playback_buf->write_space() >= disk_io_chunk_frames
734 || c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
736 need_butler = c->front()->capture_buf->read_space() >= disk_io_chunk_frames;
740 if (commit_should_unlock) {
750 AudioDiskstream::set_pending_overwrite (bool yn)
752 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
754 pending_overwrite = yn;
756 overwrite_frame = playback_sample;
757 overwrite_offset = channels.reader()->front()->playback_buf->get_read_ptr();
761 AudioDiskstream::overwrite_existing_buffers ()
763 boost::shared_ptr<ChannelList> c = channels.reader();
764 Sample* mixdown_buffer;
767 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
769 overwrite_queued = false;
771 /* assume all are the same size */
772 nframes_t size = c->front()->playback_buf->bufsize();
774 mixdown_buffer = new Sample[size];
775 gain_buffer = new float[size];
777 /* reduce size so that we can fill the buffer correctly. */
783 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
785 start = overwrite_frame;
786 nframes_t cnt = size;
788 /* to fill the buffer without resetting the playback sample, we need to
789 do it one or two chunks (normally two).
791 |----------------------------------------------------------------------|
795 |<- second chunk->||<----------------- first chunk ------------------>|
799 nframes_t to_read = size - overwrite_offset;
801 if (read ((*chan)->playback_buf->buffer() + overwrite_offset, mixdown_buffer, gain_buffer, start, to_read, *chan, n, reversed)) {
802 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
803 _id, size, playback_sample) << endmsg;
811 if (read ((*chan)->playback_buf->buffer(), mixdown_buffer, gain_buffer,
812 start, cnt, *chan, n, reversed)) {
813 error << string_compose(_("AudioDiskstream %1: when refilling, cannot read %2 from playlist at frame %3"),
814 _id, size, playback_sample) << endmsg;
823 pending_overwrite = false;
824 delete [] gain_buffer;
825 delete [] mixdown_buffer;
830 AudioDiskstream::seek (nframes_t frame, bool complete_refill)
834 ChannelList::iterator chan;
835 boost::shared_ptr<ChannelList> c = channels.reader();
837 Glib::Mutex::Lock lm (state_lock);
839 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
840 (*chan)->playback_buf->reset ();
841 (*chan)->capture_buf->reset ();
844 /* can't rec-enable in destructive mode if transport is before start */
846 if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
847 disengage_record_enable ();
850 playback_sample = frame;
853 if (complete_refill) {
854 while ((ret = do_refill_with_alloc ()) > 0) ;
856 ret = do_refill_with_alloc ();
863 AudioDiskstream::can_internal_playback_seek (nframes_t distance)
865 ChannelList::iterator chan;
866 boost::shared_ptr<ChannelList> c = channels.reader();
868 for (chan = c->begin(); chan != c->end(); ++chan) {
869 if ((*chan)->playback_buf->read_space() < distance) {
877 AudioDiskstream::internal_playback_seek (nframes_t distance)
879 ChannelList::iterator chan;
880 boost::shared_ptr<ChannelList> c = channels.reader();
882 for (chan = c->begin(); chan != c->end(); ++chan) {
883 (*chan)->playback_buf->increment_read_ptr (distance);
886 first_recordable_frame += distance;
887 playback_sample += distance;
893 AudioDiskstream::read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer, nframes_t& start, nframes_t cnt,
894 ChannelInfo* /*channel_info*/, int channel, bool reversed)
896 nframes_t this_read = 0;
898 nframes_t loop_end = 0;
899 nframes_t loop_start = 0;
900 nframes_t loop_length = 0;
901 nframes_t offset = 0;
904 /* XXX we don't currently play loops in reverse. not sure why */
908 /* Make the use of a Location atomic for this read operation.
910 Note: Locations don't get deleted, so all we care about
911 when I say "atomic" is that we are always pointing to
912 the same one and using a start/length values obtained
916 if ((loc = loop_location) != 0) {
917 loop_start = loc->start();
918 loop_end = loc->end();
919 loop_length = loop_end - loop_start;
922 /* if we are looping, ensure that the first frame we read is at the correct
923 position within the loop.
926 if (loc && start >= loop_end) {
927 //cerr << "start adjusted from " << start;
928 start = loop_start + ((start - loop_start) % loop_length);
929 //cerr << "to " << start << endl;
932 //cerr << "start is " << start << " loopstart: " << loop_start << " loopend: " << loop_end << endl;
941 /* take any loop into account. we can't read past the end of the loop. */
943 if (loc && (loop_end - start < cnt)) {
944 this_read = loop_end - start;
945 //cerr << "reloop true: thisread: " << this_read << " cnt: " << cnt << endl;
952 if (this_read == 0) {
956 this_read = min(cnt,this_read);
958 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
959 error << string_compose(_("AudioDiskstream %1: cannot read %2 from playlist at frame %3"), _id, this_read,
964 _read_data_count = _playlist->read_data_count();
968 swap_by_ptr (buf, buf + this_read - 1);
972 /* if we read to the end of the loop, go back to the beginning */
989 AudioDiskstream::do_refill_with_alloc ()
991 Sample* mix_buf = new Sample[disk_io_chunk_frames];
992 float* gain_buf = new float[disk_io_chunk_frames];
994 int ret = _do_refill(mix_buf, gain_buf);
1003 AudioDiskstream::_do_refill (Sample* mixdown_buffer, float* gain_buffer)
1007 RingBufferNPT<Sample>::rw_vector vector;
1008 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1009 nframes_t total_space;
1010 nframes_t zero_fill;
1012 ChannelList::iterator i;
1013 boost::shared_ptr<ChannelList> c = channels.reader();
1020 assert(mixdown_buffer);
1021 assert(gain_buffer);
1028 c->front()->playback_buf->get_write_vector (&vector);
1030 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1034 /* if there are 2+ chunks of disk i/o possible for
1035 this track, let the caller know so that it can arrange
1036 for us to be called again, ASAP.
1039 if (total_space >= (_slaved?3:2) * disk_io_chunk_frames) {
1043 /* if we're running close to normal speed and there isn't enough
1044 space to do disk_io_chunk_frames of I/O, then don't bother.
1046 at higher speeds, just do it because the sync between butler
1047 and audio thread may not be good enough.
1050 if ((total_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
1054 /* when slaved, don't try to get too close to the read pointer. this
1055 leaves space for the buffer reversal to have something useful to
1059 if (_slaved && total_space < (c->front()->playback_buf->bufsize() / 2)) {
1063 /* never do more than disk_io_chunk_frames worth of disk input per call (limit doesn't apply for memset) */
1065 total_space = min (disk_io_chunk_frames, total_space);
1069 if (file_frame == 0) {
1071 /* at start: nothing to do but fill with silence */
1073 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1075 ChannelInfo* chan (*i);
1076 chan->playback_buf->get_write_vector (&vector);
1077 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1078 if (vector.len[1]) {
1079 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1081 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1086 if (file_frame < total_space) {
1088 /* too close to the start: read what we can,
1089 and then zero fill the rest
1092 zero_fill = total_space - file_frame;
1093 total_space = file_frame;
1103 if (file_frame == max_frames) {
1105 /* at end: nothing to do but fill with silence */
1107 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1109 ChannelInfo* chan (*i);
1110 chan->playback_buf->get_write_vector (&vector);
1111 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1112 if (vector.len[1]) {
1113 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1115 chan->playback_buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1120 if (file_frame > max_frames - total_space) {
1122 /* to close to the end: read what we can, and zero fill the rest */
1124 zero_fill = total_space - (max_frames - file_frame);
1125 total_space = max_frames - file_frame;
1132 nframes_t file_frame_tmp = 0;
1134 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1136 ChannelInfo* chan (*i);
1139 nframes_t len1, len2;
1141 chan->playback_buf->get_write_vector (&vector);
1143 if (vector.len[0] > disk_io_chunk_frames) {
1145 /* we're not going to fill the first chunk, so certainly do not bother with the
1146 other part. it won't be connected with the part we do fill, as in:
1148 .... => writable space
1149 ++++ => readable space
1150 ^^^^ => 1 x disk_io_chunk_frames that would be filled
1152 |......|+++++++++++++|...............................|
1157 So, just pretend that the buf1 part isn't there.
1167 file_frame_tmp = file_frame;
1169 buf1 = vector.buf[0];
1170 len1 = vector.len[0];
1171 buf2 = vector.buf[1];
1172 len2 = vector.len[1];
1174 to_read = min (ts, len1);
1175 to_read = min (to_read, disk_io_chunk_frames);
1179 if (read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1184 chan->playback_buf->increment_write_ptr (to_read);
1188 to_read = min (ts, len2);
1192 /* we read all of vector.len[0], but it wasn't an entire disk_io_chunk_frames of data,
1193 so read some or all of vector.len[1] as well.
1196 if (read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan, chan_n, reversed)) {
1201 chan->playback_buf->increment_write_ptr (to_read);
1210 file_frame = file_frame_tmp;
1217 /** Flush pending data to disk.
1219 * Important note: this function will write *AT MOST* disk_io_chunk_frames
1220 * of data to disk. it will never write more than that. If it writes that
1221 * much and there is more than that waiting to be written, it will return 1,
1222 * otherwise 0 on success or -1 on failure.
1224 * If there is less than disk_io_chunk_frames to be written, no data will be
1225 * written at all unless @a force_flush is true.
1228 AudioDiskstream::do_flush (RunContext /*context*/, bool force_flush)
1232 RingBufferNPT<Sample>::rw_vector vector;
1233 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1236 _write_data_count = 0;
1238 transvec.buf[0] = 0;
1239 transvec.buf[1] = 0;
1243 boost::shared_ptr<ChannelList> c = channels.reader();
1244 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1246 (*chan)->capture_buf->get_read_vector (&vector);
1248 total = vector.len[0] + vector.len[1];
1250 if (total == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
1254 /* if there are 2+ chunks of disk i/o possible for
1255 this track, let the caller know so that it can arrange
1256 for us to be called again, ASAP.
1258 if we are forcing a flush, then if there is* any* extra
1259 work, let the caller know.
1261 if we are no longer recording and there is any extra work,
1262 let the caller know too.
1265 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1269 to_write = min (disk_io_chunk_frames, (nframes_t) vector.len[0]);
1271 // check the transition buffer when recording destructive
1272 // important that we get this after the capture buf
1274 if (destructive()) {
1275 (*chan)->capture_transition_buf->get_read_vector(&transvec);
1276 size_t transcount = transvec.len[0] + transvec.len[1];
1277 bool have_start = false;
1280 for (ti=0; ti < transcount; ++ti) {
1281 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
1283 if (captrans.type == CaptureStart) {
1284 // by definition, the first data we got above represents the given capture pos
1286 (*chan)->write_source->mark_capture_start (captrans.capture_val);
1287 (*chan)->curr_capture_cnt = 0;
1291 else if (captrans.type == CaptureEnd) {
1293 // capture end, the capture_val represents total frames in capture
1295 if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
1297 // shorten to make the write a perfect fit
1298 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
1300 if (nto_write < to_write) {
1301 ret = 1; // should we?
1303 to_write = nto_write;
1305 (*chan)->write_source->mark_capture_end ();
1307 // increment past this transition, but go no further
1312 // actually ends just beyond this chunk, so force more work
1320 (*chan)->capture_transition_buf->increment_read_ptr(ti);
1324 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1325 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1329 (*chan)->capture_buf->increment_read_ptr (to_write);
1330 (*chan)->curr_capture_cnt += to_write;
1332 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < disk_io_chunk_frames) && !destructive()) {
1334 /* we wrote all of vector.len[0] but it wasn't an entire
1335 disk_io_chunk_frames of data, so arrange for some part
1336 of vector.len[1] to be flushed to disk as well.
1339 to_write = min ((nframes_t)(disk_io_chunk_frames - to_write), (nframes_t) vector.len[1]);
1341 if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1342 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), _id) << endmsg;
1346 _write_data_count += (*chan)->write_source->write_data_count();
1348 (*chan)->capture_buf->increment_read_ptr (to_write);
1349 (*chan)->curr_capture_cnt += to_write;
1358 AudioDiskstream::transport_stopped (struct tm& when, time_t twhen, bool abort_capture)
1360 uint32_t buffer_position;
1361 bool more_work = true;
1363 boost::shared_ptr<AudioRegion> region;
1364 nframes_t total_capture;
1366 SourceList::iterator src;
1367 ChannelList::iterator chan;
1368 vector<CaptureInfo*>::iterator ci;
1369 boost::shared_ptr<ChannelList> c = channels.reader();
1371 bool mark_write_completed = false;
1373 finish_capture (true, c);
1375 /* butler is already stopped, but there may be work to do
1376 to flush remaining data to disk.
1379 while (more_work && !err) {
1380 switch (do_flush (TransportContext, true)) {
1387 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1392 /* XXX is there anything we can do if err != 0 ? */
1393 Glib::Mutex::Lock lm (capture_info_lock);
1395 if (capture_info.empty()) {
1399 if (abort_capture) {
1401 if (destructive()) {
1405 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1407 if ((*chan)->write_source) {
1409 (*chan)->write_source->mark_for_remove ();
1410 (*chan)->write_source->drop_references ();
1411 (*chan)->write_source.reset ();
1414 /* new source set up in "out" below */
1420 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1421 total_capture += (*ci)->frames;
1424 /* figure out the name for this take */
1426 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1428 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1432 s->update_header (capture_info.front()->start, when, twhen);
1433 s->set_captured_for (_name);
1434 s->mark_immutable ();
1435 if (Config->get_auto_analyse_audio()) {
1436 Analyser::queue_source_for_analysis (s, true);
1441 /* destructive tracks have a single, never changing region */
1443 if (destructive()) {
1445 /* send a signal that any UI can pick up to do the right thing. there is
1446 a small problem here in that a UI may need the peak data to be ready
1447 for the data that was recorded and this isn't interlocked with that
1448 process. this problem is deferred to the UI.
1451 _playlist->Modified();
1455 string whole_file_region_name;
1456 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1458 /* Register a new region with the Session that
1459 describes the entire source. Do this first
1460 so that any sub-regions will obviously be
1461 children of this one (later!)
1465 boost::shared_ptr<Region> rx (RegionFactory::create (srcs,
1466 c->front()->write_source->last_capture_start_frame(), total_capture,
1467 whole_file_region_name, 0,
1468 Region::Flag (Region::DefaultFlags|Region::Automatic|Region::WholeFile)));
1470 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1471 region->special_set_position (capture_info.front()->start);
1475 catch (failed_constructor& err) {
1476 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1480 _last_capture_regions.push_back (region);
1482 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1484 XMLNode &before = _playlist->get_state();
1485 _playlist->freeze ();
1487 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1491 _session.region_name (region_name, whole_file_region_name, false);
1493 // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->frames << " add region " << region_name << endl;
1496 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, buffer_position, (*ci)->frames, region_name));
1497 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1500 catch (failed_constructor& err) {
1501 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1502 continue; /* XXX is this OK? */
1505 region->GoingAway.connect (bind (mem_fun (*this, &Diskstream::remove_region_from_last_capture), boost::weak_ptr<Region>(region)));
1507 _last_capture_regions.push_back (region);
1509 i_am_the_modifier++;
1510 _playlist->add_region (region, (*ci)->start, 1, non_layered());
1511 i_am_the_modifier--;
1513 buffer_position += (*ci)->frames;
1517 XMLNode &after = _playlist->get_state();
1518 _session.add_command (new MementoCommand<Playlist>(*_playlist, &before, &after));
1521 mark_write_completed = true;
1524 reset_write_sources (mark_write_completed);
1528 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1532 capture_info.clear ();
1533 capture_start_frame = 0;
1537 AudioDiskstream::transport_looped (nframes_t transport_frame)
1539 if (was_recording) {
1540 // all we need to do is finish this capture, with modified capture length
1541 boost::shared_ptr<ChannelList> c = channels.reader();
1543 // adjust the capture length knowing that the data will be recorded to disk
1544 // only necessary after the first loop where we're recording
1545 if (capture_info.size() == 0) {
1546 capture_captured += _capture_offset;
1548 if (_alignment_style == ExistingMaterial) {
1549 capture_captured += _session.worst_output_latency();
1551 capture_captured += _roll_delay;
1555 finish_capture (true, c);
1557 // the next region will start recording via the normal mechanism
1558 // we'll set the start position to the current transport pos
1559 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1560 capture_start_frame = transport_frame;
1561 first_recordable_frame = transport_frame; // mild lie
1562 last_recordable_frame = max_frames;
1563 was_recording = true;
1565 if (recordable() && destructive()) {
1566 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1568 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1569 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1571 if (transvec.len[0] > 0) {
1572 transvec.buf[0]->type = CaptureStart;
1573 transvec.buf[0]->capture_val = capture_start_frame;
1574 (*chan)->capture_transition_buf->increment_write_ptr(1);
1578 fatal << X_("programming error: capture_transition_buf is full on rec loop! inconceivable!")
1588 AudioDiskstream::finish_capture (bool /*rec_monitors_input*/, boost::shared_ptr<ChannelList> c)
1590 was_recording = false;
1592 if (capture_captured == 0) {
1596 if (recordable() && destructive()) {
1597 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1599 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1600 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1602 if (transvec.len[0] > 0) {
1603 transvec.buf[0]->type = CaptureEnd;
1604 transvec.buf[0]->capture_val = capture_captured;
1605 (*chan)->capture_transition_buf->increment_write_ptr(1);
1609 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
1615 CaptureInfo* ci = new CaptureInfo;
1617 ci->start = capture_start_frame;
1618 ci->frames = capture_captured;
1620 /* XXX theoretical race condition here. Need atomic exchange ?
1621 However, the circumstances when this is called right
1622 now (either on record-disable or transport_stopped)
1623 mean that no actual race exists. I think ...
1624 We now have a capture_info_lock, but it is only to be used
1625 to synchronize in the transport_stop and the capture info
1626 accessors, so that invalidation will not occur (both non-realtime).
1629 // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1631 capture_info.push_back (ci);
1632 capture_captured = 0;
1634 /* now we've finished a capture, reset first_recordable_frame for next time */
1635 first_recordable_frame = max_frames;
1639 AudioDiskstream::set_record_enabled (bool yn)
1641 if (!recordable() || !_session.record_enabling_legal() || _io->n_ports().n_audio() == 0) {
1645 /* can't rec-enable in destructive mode if transport is before start */
1647 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
1651 if (yn && channels.reader()->front()->source == 0) {
1653 /* pick up connections not initiated *from* the IO object
1654 we're associated with.
1657 get_input_sources ();
1660 /* yes, i know that this not proof against race conditions, but its
1661 good enough. i think.
1664 if (record_enabled() != yn) {
1666 engage_record_enable ();
1668 disengage_record_enable ();
1674 AudioDiskstream::engage_record_enable ()
1676 bool rolling = _session.transport_speed() != 0.0f;
1677 boost::shared_ptr<ChannelList> c = channels.reader();
1679 g_atomic_int_set (&_record_enabled, 1);
1680 capturing_sources.clear ();
1682 if (Config->get_monitoring_model() == HardwareMonitoring) {
1684 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1685 if ((*chan)->source) {
1686 (*chan)->source->ensure_monitor_input (!(_session.config.get_auto_input() && rolling));
1688 capturing_sources.push_back ((*chan)->write_source);
1689 (*chan)->write_source->mark_streaming_write_started ();
1693 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1694 capturing_sources.push_back ((*chan)->write_source);
1695 (*chan)->write_source->mark_streaming_write_started ();
1699 RecordEnableChanged (); /* EMIT SIGNAL */
1703 AudioDiskstream::disengage_record_enable ()
1705 g_atomic_int_set (&_record_enabled, 0);
1706 boost::shared_ptr<ChannelList> c = channels.reader();
1707 if (Config->get_monitoring_model() == HardwareMonitoring) {
1708 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1709 if ((*chan)->source) {
1710 (*chan)->source->ensure_monitor_input (false);
1714 capturing_sources.clear ();
1715 RecordEnableChanged (); /* EMIT SIGNAL */
1719 AudioDiskstream::get_state ()
1721 XMLNode* node = new XMLNode ("AudioDiskstream");
1723 LocaleGuard lg (X_("POSIX"));
1724 boost::shared_ptr<ChannelList> c = channels.reader();
1726 node->add_property ("flags", enum_2_string (_flags));
1728 snprintf (buf, sizeof(buf), "%zd", c->size());
1729 node->add_property ("channels", buf);
1731 node->add_property ("playlist", _playlist->name());
1733 snprintf (buf, sizeof(buf), "%.12g", _visible_speed);
1734 node->add_property ("speed", buf);
1736 node->add_property("name", _name);
1737 id().print (buf, sizeof (buf));
1738 node->add_property("id", buf);
1740 if (!capturing_sources.empty() && _session.get_record_enabled()) {
1742 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1743 XMLNode* cs_grandchild;
1745 for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = capturing_sources.begin(); i != capturing_sources.end(); ++i) {
1746 cs_grandchild = new XMLNode (X_("file"));
1747 cs_grandchild->add_property (X_("path"), (*i)->path());
1748 cs_child->add_child_nocopy (*cs_grandchild);
1751 /* store the location where capture will start */
1755 if (_session.config.get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1756 snprintf (buf, sizeof (buf), "%" PRId64, pi->start());
1758 snprintf (buf, sizeof (buf), "%" PRId64, _session.transport_frame());
1761 cs_child->add_property (X_("at"), buf);
1762 node->add_child_nocopy (*cs_child);
1766 node->add_child_copy (*_extra_xml);
1773 AudioDiskstream::set_state (const XMLNode& node, int /*version*/)
1775 const XMLProperty* prop;
1776 XMLNodeList nlist = node.children();
1777 XMLNodeIterator niter;
1778 uint32_t nchans = 1;
1779 XMLNode* capture_pending_node = 0;
1780 LocaleGuard lg (X_("POSIX"));
1782 in_set_state = true;
1784 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1785 if ((*niter)->name() == IO::state_node_name) {
1786 deprecated_io_node = new XMLNode (**niter);
1789 if ((*niter)->name() == X_("CapturingSources")) {
1790 capture_pending_node = *niter;
1794 /* prevent write sources from being created */
1796 in_set_state = true;
1798 if ((prop = node.property ("name")) != 0) {
1799 _name = prop->value();
1802 if (deprecated_io_node) {
1803 if ((prop = deprecated_io_node->property ("id")) != 0) {
1804 _id = prop->value ();
1807 if ((prop = node.property ("id")) != 0) {
1808 _id = prop->value ();
1812 if ((prop = node.property ("flags")) != 0) {
1813 _flags = Flag (string_2_enum (prop->value(), _flags));
1816 if ((prop = node.property ("channels")) != 0) {
1817 nchans = atoi (prop->value().c_str());
1820 // create necessary extra channels
1821 // we are always constructed with one and we always need one
1823 _n_channels.set(DataType::AUDIO, channels.reader()->size());
1825 if (nchans > _n_channels.n_audio()) {
1827 add_channel (nchans - _n_channels.n_audio());
1828 IO::PortCountChanged(_n_channels);
1830 } else if (nchans < _n_channels.n_audio()) {
1832 remove_channel (_n_channels.n_audio() - nchans);
1835 if ((prop = node.property ("playlist")) == 0) {
1840 bool had_playlist = (_playlist != 0);
1842 if (find_and_use_playlist (prop->value())) {
1846 if (!had_playlist) {
1847 _playlist->set_orig_diskstream_id (_id);
1850 if (!destructive() && capture_pending_node) {
1851 /* destructive streams have one and only one source per channel,
1852 and so they never end up in pending capture in any useful
1855 use_pending_capture_data (*capture_pending_node);
1860 if ((prop = node.property ("speed")) != 0) {
1861 double sp = atof (prop->value().c_str());
1863 if (realtime_set_speed (sp, false)) {
1864 non_realtime_set_speed ();
1868 in_set_state = false;
1870 /* make sure this is clear before we do anything else */
1872 capturing_sources.clear ();
1874 /* write sources are handled when we handle the input set
1875 up of the IO that owns this DS (::non_realtime_input_change())
1882 AudioDiskstream::use_new_write_source (uint32_t n)
1884 boost::shared_ptr<ChannelList> c = channels.reader();
1886 if (!recordable()) {
1890 if (n >= c->size()) {
1891 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
1895 ChannelInfo* chan = (*c)[n];
1897 if (chan->write_source) {
1898 chan->write_source->done_with_peakfile_writes ();
1899 chan->write_source->set_allow_remove_if_empty (true);
1900 chan->write_source.reset ();
1904 if ((chan->write_source = _session.create_audio_source_for_session (*this, n, destructive())) == 0) {
1905 throw failed_constructor();
1909 catch (failed_constructor &err) {
1910 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
1911 chan->write_source.reset ();
1915 /* do not remove destructive files even if they are empty */
1917 chan->write_source->set_allow_remove_if_empty (!destructive());
1923 AudioDiskstream::reset_write_sources (bool mark_write_complete, bool /*force*/)
1925 ChannelList::iterator chan;
1926 boost::shared_ptr<ChannelList> c = channels.reader();
1929 if (!_session.writable() || !recordable()) {
1933 capturing_sources.clear ();
1935 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1936 if (!destructive()) {
1938 if ((*chan)->write_source && mark_write_complete) {
1939 (*chan)->write_source->mark_streaming_write_completed ();
1941 use_new_write_source (n);
1943 if (record_enabled()) {
1944 capturing_sources.push_back ((*chan)->write_source);
1948 if ((*chan)->write_source == 0) {
1949 use_new_write_source (n);
1954 if (destructive()) {
1956 /* we now have all our write sources set up, so create the
1957 playlist's single region.
1960 if (_playlist->empty()) {
1961 setup_destructive_playlist ();
1967 AudioDiskstream::rename_write_sources ()
1969 ChannelList::iterator chan;
1970 boost::shared_ptr<ChannelList> c = channels.reader();
1973 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1974 if ((*chan)->write_source != 0) {
1975 (*chan)->write_source->set_source_name (_name, destructive());
1976 /* XXX what to do if one of them fails ? */
1984 AudioDiskstream::set_block_size (nframes_t /*nframes*/)
1986 if (_session.get_block_size() > speed_buffer_size) {
1987 speed_buffer_size = _session.get_block_size();
1988 boost::shared_ptr<ChannelList> c = channels.reader();
1990 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1991 if ((*chan)->speed_buffer)
1992 delete [] (*chan)->speed_buffer;
1993 (*chan)->speed_buffer = new Sample[speed_buffer_size];
1996 allocate_temporary_buffers ();
2000 AudioDiskstream::allocate_temporary_buffers ()
2002 /* make sure the wrap buffer is at least large enough to deal
2003 with the speeds up to 1.2, to allow for micro-variation
2004 when slaving to MTC, Timecode etc.
2007 double sp = max (fabsf (_actual_speed), 1.2f);
2008 nframes_t required_wrap_size = (nframes_t) floor (_session.get_block_size() * sp) + 1;
2010 if (required_wrap_size > wrap_buffer_size) {
2012 boost::shared_ptr<ChannelList> c = channels.reader();
2014 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2015 if ((*chan)->playback_wrap_buffer)
2016 delete [] (*chan)->playback_wrap_buffer;
2017 (*chan)->playback_wrap_buffer = new Sample[required_wrap_size];
2018 if ((*chan)->capture_wrap_buffer)
2019 delete [] (*chan)->capture_wrap_buffer;
2020 (*chan)->capture_wrap_buffer = new Sample[required_wrap_size];
2023 wrap_buffer_size = required_wrap_size;
2028 AudioDiskstream::monitor_input (bool yn)
2030 boost::shared_ptr<ChannelList> c = channels.reader();
2032 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2034 if ((*chan)->source) {
2035 (*chan)->source->ensure_monitor_input (yn);
2041 AudioDiskstream::set_align_style_from_io ()
2043 bool have_physical = false;
2049 get_input_sources ();
2051 boost::shared_ptr<ChannelList> c = channels.reader();
2053 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
2054 if ((*chan)->source && (*chan)->source->flags() & JackPortIsPhysical) {
2055 have_physical = true;
2060 if (have_physical) {
2061 set_align_style (ExistingMaterial);
2063 set_align_style (CaptureTime);
2068 AudioDiskstream::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2070 while (how_many--) {
2071 c->push_back (new ChannelInfo(_session.butler()->audio_diskstream_buffer_size(), speed_buffer_size, wrap_buffer_size));
2072 interpolation.add_channel_to (_session.butler()->audio_diskstream_buffer_size(), speed_buffer_size);
2075 _n_channels.set(DataType::AUDIO, c->size());
2081 AudioDiskstream::add_channel (uint32_t how_many)
2083 RCUWriter<ChannelList> writer (channels);
2084 boost::shared_ptr<ChannelList> c = writer.get_copy();
2086 return add_channel_to (c, how_many);
2090 AudioDiskstream::remove_channel_from (boost::shared_ptr<ChannelList> c, uint32_t how_many)
2092 while (how_many-- && !c->empty()) {
2093 // FIXME: crash (thread safe with RCU?)
2094 // memory leak, when disabled.... :(
2097 interpolation.remove_channel_from ();
2100 _n_channels.set(DataType::AUDIO, c->size());
2106 AudioDiskstream::remove_channel (uint32_t how_many)
2108 RCUWriter<ChannelList> writer (channels);
2109 boost::shared_ptr<ChannelList> c = writer.get_copy();
2111 return remove_channel_from (c, how_many);
2115 AudioDiskstream::playback_buffer_load () const
2117 boost::shared_ptr<ChannelList> c = channels.reader();
2119 return (float) ((double) c->front()->playback_buf->read_space()/
2120 (double) c->front()->playback_buf->bufsize());
2124 AudioDiskstream::capture_buffer_load () const
2126 boost::shared_ptr<ChannelList> c = channels.reader();
2128 return (float) ((double) c->front()->capture_buf->write_space()/
2129 (double) c->front()->capture_buf->bufsize());
2133 AudioDiskstream::use_pending_capture_data (XMLNode& node)
2135 const XMLProperty* prop;
2136 XMLNodeList nlist = node.children();
2137 XMLNodeIterator niter;
2138 boost::shared_ptr<AudioFileSource> fs;
2139 boost::shared_ptr<AudioFileSource> first_fs;
2140 SourceList pending_sources;
2143 if ((prop = node.property (X_("at"))) == 0) {
2147 if (sscanf (prop->value().c_str(), "%" PRIu32, &position) != 1) {
2151 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2152 if ((*niter)->name() == X_("file")) {
2154 if ((prop = (*niter)->property (X_("path"))) == 0) {
2158 // This protects sessions from errant CapturingSources in stored sessions
2160 if (stat (prop->value().c_str(), &sbuf)) {
2165 fs = boost::dynamic_pointer_cast<AudioFileSource> (
2166 SourceFactory::createWritable (DataType::AUDIO, _session,
2167 prop->value(), true,
2168 false, _session.frame_rate()));
2171 catch (failed_constructor& err) {
2172 error << string_compose (_("%1: cannot restore pending capture source file %2"),
2173 _name, prop->value())
2178 pending_sources.push_back (fs);
2180 if (first_fs == 0) {
2184 fs->set_captured_for (_name);
2188 if (pending_sources.size() == 0) {
2189 /* nothing can be done */
2193 if (pending_sources.size() != _n_channels.n_audio()) {
2194 error << string_compose (_("%1: incorrect number of pending sources listed - ignoring them all"), _name)
2199 boost::shared_ptr<AudioRegion> region;
2202 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (
2203 pending_sources, 0, first_fs->length(first_fs->timeline_position()),
2204 region_name_from_path (first_fs->name(), true), 0,
2205 Region::Flag (Region::DefaultFlags|Region::Automatic|Region::WholeFile)));
2206 region->special_set_position (0);
2209 catch (failed_constructor& err) {
2210 error << string_compose (
2211 _("%1: cannot create whole-file region from pending capture sources"),
2218 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (
2219 pending_sources, 0, first_fs->length(first_fs->timeline_position()),
2220 region_name_from_path (first_fs->name(), true)));
2223 catch (failed_constructor& err) {
2224 error << string_compose (_("%1: cannot create region from pending capture sources"),
2231 _playlist->add_region (region, position);
2237 AudioDiskstream::set_non_layered (bool yn)
2239 if (yn != non_layered()) {
2242 _flags = Flag (_flags | NonLayered);
2244 _flags = Flag (_flags & ~NonLayered);
2252 AudioDiskstream::set_destructive (bool yn)
2254 bool bounce_ignored;
2256 if (yn != destructive()) {
2259 /* requestor should already have checked this and
2260 bounced if necessary and desired
2262 if (!can_become_destructive (bounce_ignored)) {
2265 _flags = Flag (_flags | Destructive);
2266 use_destructive_playlist ();
2268 _flags = Flag (_flags & ~Destructive);
2269 reset_write_sources (true, true);
2277 AudioDiskstream::can_become_destructive (bool& requires_bounce) const
2280 requires_bounce = false;
2284 /* is there only one region ? */
2286 if (_playlist->n_regions() != 1) {
2287 requires_bounce = true;
2291 boost::shared_ptr<Region> first = _playlist->find_next_region (_session.current_start_frame(), Start, 1);
2294 /* do the source(s) for the region cover the session start position ? */
2296 if (first->position() != _session.current_start_frame()) {
2297 if (first->start() > _session.current_start_frame()) {
2298 requires_bounce = true;
2303 /* is the source used by only 1 playlist ? */
2305 boost::shared_ptr<AudioRegion> afirst = boost::dynamic_pointer_cast<AudioRegion> (first);
2309 if (_session.source_use_count (afirst->source()) > 1) {
2310 requires_bounce = true;
2314 requires_bounce = false;
2318 AudioDiskstream::ChannelInfo::ChannelInfo (nframes_t bufsize, nframes_t speed_size, nframes_t wrap_size)
2322 current_capture_buffer = 0;
2323 current_playback_buffer = 0;
2324 curr_capture_cnt = 0;
2326 speed_buffer = new Sample[speed_size];
2327 playback_wrap_buffer = new Sample[wrap_size];
2328 capture_wrap_buffer = new Sample[wrap_size];
2330 playback_buf = new RingBufferNPT<Sample> (bufsize);
2331 capture_buf = new RingBufferNPT<Sample> (bufsize);
2332 capture_transition_buf = new RingBufferNPT<CaptureTransition> (256);
2334 /* touch the ringbuffer buffers, which will cause
2335 them to be mapped into locked physical RAM if
2336 we're running with mlockall(). this doesn't do
2340 memset (playback_buf->buffer(), 0, sizeof (Sample) * playback_buf->bufsize());
2341 memset (capture_buf->buffer(), 0, sizeof (Sample) * capture_buf->bufsize());
2342 memset (capture_transition_buf->buffer(), 0, sizeof (CaptureTransition) * capture_transition_buf->bufsize());
2345 AudioDiskstream::ChannelInfo::~ChannelInfo ()
2348 write_source.reset ();
2351 delete [] speed_buffer;
2354 delete [] playback_wrap_buffer;
2355 playback_wrap_buffer = 0;
2357 delete [] capture_wrap_buffer;
2358 capture_wrap_buffer = 0;
2360 delete playback_buf;
2366 delete capture_transition_buf;
2367 capture_transition_buf = 0;