2 Copyright (C) 2009-2016 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.
21 #include "pbd/memento_command.h"
23 #include "ardour/audioengine.h"
24 #include "ardour/audioplaylist.h"
25 #include "ardour/audio_buffer.h"
26 #include "ardour/butler.h"
27 #include "ardour/debug.h"
28 #include "ardour/disk_reader.h"
29 #include "ardour/midi_ring_buffer.h"
30 #include "ardour/midi_playlist.h"
31 #include "ardour/pannable.h"
32 #include "ardour/playlist.h"
33 #include "ardour/playlist_factory.h"
34 #include "ardour/session.h"
35 #include "ardour/session_playlists.h"
37 using namespace ARDOUR;
41 ARDOUR::framecnt_t DiskReader::_chunk_frames = default_chunk_frames ();
42 PBD::Signal0<void> DiskReader::Underrun;
43 Sample* DiskReader::_mixdown_buffer = 0;
44 gain_t* DiskReader::_gain_buffer = 0;
45 framecnt_t DiskReader::midi_readahead = 4096;
47 DiskReader::DiskReader (Session& s, string const & str, DiskIOProcessor::Flag f)
48 : DiskIOProcessor (s, str, f)
51 , overwrite_offset (0)
52 , _pending_overwrite (false)
53 , overwrite_queued (false)
54 , _monitoring_choice (MonitorDisk)
55 , _gui_feed_buffer (AudioEngine::instance()->raw_buffer_size (DataType::MIDI))
59 DiskReader::~DiskReader ()
61 DEBUG_TRACE (DEBUG::Destruction, string_compose ("DiskReader %1 deleted\n", _name));
63 for (uint32_t n = 0; n < DataType::num_types; ++n) {
65 _playlists[n]->release ();
70 RCUWriter<ChannelList> writer (channels);
71 boost::shared_ptr<ChannelList> c = writer.get_copy();
73 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
86 DiskReader::allocate_working_buffers()
88 /* with varifill buffer refilling, we compute the read size in bytes (to optimize
89 for disk i/o bandwidth) and then convert back into samples. These buffers
90 need to reflect the maximum size we could use, which is 4MB reads, or 2M samples
93 _mixdown_buffer = new Sample[2*1048576];
94 _gain_buffer = new gain_t[2*1048576];
98 DiskReader::free_working_buffers()
100 delete [] _mixdown_buffer;
101 delete [] _gain_buffer;
107 DiskReader::default_chunk_frames()
113 DiskReader::set_name (string const & str)
116 for (uint32_t n = 0; n < DataType::num_types; ++n) {
118 _playlists[n]->set_name (str);
121 SessionObject::set_name(str);
128 DiskReader::set_roll_delay (ARDOUR::framecnt_t nframes)
130 _roll_delay = nframes;
134 DiskReader::state (bool full)
136 XMLNode& node (DiskIOProcessor::state (full));
141 DiskReader::set_state (const XMLNode& node, int version)
143 if (DiskIOProcessor::set_state (node, version)) {
151 DiskReader::realtime_handle_transport_stopped ()
156 DiskReader::realtime_locate ()
161 DiskReader::buffer_load () const
163 /* Note: for MIDI it's not trivial to differentiate the following two cases:
165 1. The playback buffer is empty because the system has run out of time to fill it.
166 2. The playback buffer is empty because there is no more data on the playlist.
168 If we use a simple buffer load computation, we will report that the MIDI diskstream
169 cannot keep up when #2 happens, when in fact it can. Since MIDI data rates
170 are so low compared to audio, just use the audio value here.
173 boost::shared_ptr<ChannelList> c = channels.reader();
176 /* no channels, so no buffers, so completely full and ready to playback, sir! */
180 PBD::RingBufferNPT<Sample> * b = c->front()->buf;
181 return (float) ((double) b->read_space() / (double) b->bufsize());
185 DiskReader::adjust_buffering ()
187 boost::shared_ptr<ChannelList> c = channels.reader();
189 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
190 (*chan)->resize (_session.butler()->audio_diskstream_playback_buffer_size());
195 DiskReader::playlist_changed (const PropertyChange&)
197 playlist_modified ();
201 DiskReader::playlist_modified ()
203 if (!i_am_the_modifier && !overwrite_queued) {
204 // !!!! _session.request_overwrite_buffer (this);
205 overwrite_queued = true;
210 DiskReader::use_playlist (DataType dt, boost::shared_ptr<Playlist> playlist)
212 bool prior_playlist = false;
214 if (_playlists[dt]) {
215 prior_playlist = true;
218 if (DiskIOProcessor::use_playlist (dt, playlist)) {
222 /* don't do this if we've already asked for it *or* if we are setting up
223 the diskstream for the very first time - the input changed handling will
224 take care of the buffer refill.
227 if (!overwrite_queued && prior_playlist) {
228 // !!! _session.request_overwrite_buffer (this);
229 overwrite_queued = true;
236 DiskReader::run (BufferSet& bufs, framepos_t start_frame, framepos_t end_frame,
237 double speed, pframes_t nframes, bool result_required)
240 boost::shared_ptr<ChannelList> c = channels.reader();
241 ChannelList::iterator chan;
242 framecnt_t playback_distance = 0;
243 const bool need_disk_signal = result_required || _monitoring_choice == MonitorDisk || _monitoring_choice == MonitorCue;
245 if (fabsf (_actual_speed) != 1.0f) {
246 midi_interpolation.set_speed (_target_speed);
247 interpolation.set_speed (_target_speed);
248 playback_distance = midi_interpolation.distance (nframes);
250 playback_distance = nframes;
253 if (!need_disk_signal) {
255 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
256 (*chan)->buf->increment_read_ptr (playback_distance);
262 /* we're doing playback */
264 size_t n_buffers = bufs.count().n_audio();
265 size_t n_chans = c->size();
268 if (n_chans > n_buffers) {
269 scaling = ((float) n_buffers)/n_chans;
274 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
276 AudioBuffer& buf (bufs.get_audio (n%n_buffers));
277 Sample* outgoing = buf.data ();
279 ChannelInfo* chaninfo (*chan);
281 chaninfo->buf->get_read_vector (&(*chan)->rw_vector);
283 if (playback_distance <= (framecnt_t) chaninfo->rw_vector.len[0]) {
285 if (fabsf (_actual_speed) != 1.0f) {
286 (void) interpolation.interpolate (
288 chaninfo->rw_vector.buf[0],
291 memcpy (outgoing, chaninfo->rw_vector.buf[0], sizeof (Sample) * playback_distance);
296 const framecnt_t total = chaninfo->rw_vector.len[0] + chaninfo->rw_vector.len[1];
298 if (playback_distance <= total) {
300 /* We have enough samples, but not in one lump.
303 if (fabsf (_actual_speed) != 1.0f) {
304 interpolation.interpolate (n, chaninfo->rw_vector.len[0],
305 chaninfo->rw_vector.buf[0],
307 outgoing += chaninfo->rw_vector.len[0];
308 interpolation.interpolate (n, playback_distance - chaninfo->rw_vector.len[0],
309 chaninfo->rw_vector.buf[1],
313 chaninfo->rw_vector.buf[0],
314 chaninfo->rw_vector.len[0] * sizeof (Sample));
315 outgoing += chaninfo->rw_vector.len[0];
317 chaninfo->rw_vector.buf[1],
318 (playback_distance - chaninfo->rw_vector.len[0]) * sizeof (Sample));
323 cerr << _name << " Need " << playback_distance << " total = " << total << endl;
324 cerr << "underrun for " << _name << endl;
325 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 underrun in %2, total space = %3\n",
326 DEBUG_THREAD_SELF, name(), total));
334 if (scaling != 1.0f) {
335 apply_gain_to_buffer (outgoing, nframes, scaling);
338 chaninfo->buf->increment_read_ptr (playback_distance);
339 _speed = _target_speed;
342 /* MIDI data handling */
344 if (!_session.declick_out_pending()) {
346 /* copy the diskstream data to all output buffers */
348 MidiBuffer& mbuf (bufs.get_midi (0));
349 get_playback (mbuf, playback_distance);
352 if (_target_speed > 0 && _actual_speed != 1.0f) {
353 MidiBuffer& mbuf (bufs.get_midi (0));
354 for (MidiBuffer::iterator i = mbuf.begin(); i != mbuf.end(); ++i) {
355 MidiBuffer::TimeType *tme = i.timeptr();
356 *tme = (*tme) * nframes / playback_distance;
361 _need_butler = false;
363 if (_actual_speed < 0.0) {
364 playback_sample -= playback_distance;
366 playback_sample += playback_distance;
371 if (c->front()->buf->write_space() >= c->front()->buf->bufsize() / 2) {
375 if ((framecnt_t) c->front()->buf->write_space() >= _chunk_frames) {
381 /* MIDI butler needed part */
383 uint32_t frames_read = g_atomic_int_get(const_cast<gint*>(&_frames_read_from_ringbuffer));
384 uint32_t frames_written = g_atomic_int_get(const_cast<gint*>(&_frames_written_to_ringbuffer));
387 cerr << name() << " MDS written: " << frames_written << " - read: " << frames_read <<
388 " = " << frames_written - frames_read
389 << " + " << playback_distance << " < " << midi_readahead << " = " << need_butler << ")" << endl;
392 /* frames_read will generally be less than frames_written, but
393 * immediately after an overwrite, we can end up having read some data
394 * before we've written any. we don't need to trip an assert() on this,
395 * but we do need to check so that the decision on whether or not we
396 * need the butler is done correctly.
401 * Doing heavy GUI operations[1] can stall also the butler.
402 * The RT-thread meanwhile will happily continue and
403 * ‘frames_read’ (from buffer to output) will become larger
404 * than ‘frames_written’ (from disk to buffer).
406 * The disk-stream is now behind..
408 * In those cases the butler needs to be summed to refill the buffer (done now)
409 * AND we need to skip (frames_read - frames_written). ie remove old events
410 * before playback_sample from the rinbuffer.
412 * [1] one way to do so is described at #6170.
413 * For me just popping up the context-menu on a MIDI-track header
414 * of a track with a large (think beethoven :) midi-region also did the
415 * trick. The playhead stalls for 2 or 3 sec, until the context-menu shows.
417 * In both cases the root cause is that redrawing MIDI regions on the GUI is still very slow
420 if (frames_read <= frames_written) {
421 if ((frames_written - frames_read) + playback_distance < midi_readahead) {
428 /* make sure bufs shows whatever data we had available */
431 cnt.set (DataType::MIDI, 1);
432 cnt.set (DataType::AUDIO, bufs.count().n_audio());
433 bufs.set_count (cnt);
437 DiskReader::calculate_playback_distance (pframes_t nframes)
439 frameoffset_t playback_distance = nframes;
441 if (_actual_speed != 1.0f && _actual_speed != -1.0f) {
442 interpolation.set_speed (_target_speed);
443 boost::shared_ptr<ChannelList> c = channels.reader();
445 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++channel) {
446 playback_distance = interpolation.interpolate (channel, nframes, NULL, NULL);
449 playback_distance = nframes;
452 if (_actual_speed < 0.0) {
453 return -playback_distance;
455 return playback_distance;
460 DiskReader::set_pending_overwrite (bool yn)
462 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
464 _pending_overwrite = yn;
466 overwrite_frame = playback_sample;
468 boost::shared_ptr<ChannelList> c = channels.reader ();
470 overwrite_offset = c->front()->buf->get_read_ptr();
475 DiskReader::overwrite_existing_buffers ()
479 boost::shared_ptr<ChannelList> c = channels.reader();
481 overwrite_queued = false;
487 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
489 /* assume all are the same size */
490 framecnt_t size = c->front()->buf->bufsize();
492 std::auto_ptr<Sample> mixdown_buffer (new Sample[size]);
493 std::auto_ptr<float> gain_buffer (new float[size]);
495 /* reduce size so that we can fill the buffer correctly (ringbuffers
496 can only handle size-1, otherwise they appear to be empty)
503 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
505 start = overwrite_frame;
506 framecnt_t cnt = size;
508 /* to fill the buffer without resetting the playback sample, we need to
509 do it one or two chunks (normally two).
511 |----------------------------------------------------------------------|
515 |<- second chunk->||<----------------- first chunk ------------------>|
519 framecnt_t to_read = size - overwrite_offset;
521 if (audio_read ((*chan)->buf->buffer() + overwrite_offset, mixdown_buffer.get(), gain_buffer.get(), start, to_read, n, reversed)) {
522 error << string_compose(_("DiskReader %1: when refilling, cannot read %2 from playlist at frame %3"),
523 id(), size, playback_sample) << endmsg;
531 if (audio_read ((*chan)->buf->buffer(), mixdown_buffer.get(), gain_buffer.get(), start, cnt, n, reversed)) {
532 error << string_compose(_("DiskReader %1: when refilling, cannot read %2 from playlist at frame %3"),
533 id(), size, playback_sample) << endmsg;
545 if (_midi_buf && _playlists[DataType::MIDI]) {
547 /* Clear the playback buffer contents. This is safe as long as the butler
548 thread is suspended, which it should be.
551 _midi_buf->reset_tracker ();
553 g_atomic_int_set (&_frames_read_from_ringbuffer, 0);
554 g_atomic_int_set (&_frames_written_to_ringbuffer, 0);
556 /* Resolve all currently active notes in the playlist. This is more
557 aggressive than it needs to be: ideally we would only resolve what is
558 absolutely necessary, but this seems difficult and/or impossible without
559 having the old data or knowing what change caused the overwrite.
561 midi_playlist()->resolve_note_trackers (*_midi_buf, overwrite_frame);
563 midi_read (overwrite_frame, _chunk_frames, false);
565 file_frame = overwrite_frame; // it was adjusted by ::midi_read()
568 _pending_overwrite = false;
574 DiskReader::seek (framepos_t frame, bool complete_refill)
578 ChannelList::iterator chan;
579 boost::shared_ptr<ChannelList> c = channels.reader();
581 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
582 (*chan)->buf->reset ();
585 if (g_atomic_int_get (&_frames_read_from_ringbuffer) == 0) {
586 /* we haven't read anything since the last seek,
587 so flush all note trackers to prevent
594 g_atomic_int_set(&_frames_read_from_ringbuffer, 0);
595 g_atomic_int_set(&_frames_written_to_ringbuffer, 0);
597 playback_sample = frame;
600 if (complete_refill) {
601 /* call _do_refill() to refill the entire buffer, using
602 the largest reads possible.
604 while ((ret = do_refill_with_alloc (false)) > 0) ;
606 /* call _do_refill() to refill just one chunk, and then
609 ret = do_refill_with_alloc (true);
617 DiskReader::can_internal_playback_seek (framecnt_t distance)
621 ChannelList::iterator chan;
622 boost::shared_ptr<ChannelList> c = channels.reader();
624 for (chan = c->begin(); chan != c->end(); ++chan) {
625 if ((*chan)->buf->read_space() < (size_t) distance) {
632 uint32_t frames_read = g_atomic_int_get(&_frames_read_from_ringbuffer);
633 uint32_t frames_written = g_atomic_int_get(&_frames_written_to_ringbuffer);
635 return ((frames_written - frames_read) < distance);
639 DiskReader::internal_playback_seek (framecnt_t distance)
641 ChannelList::iterator chan;
642 boost::shared_ptr<ChannelList> c = channels.reader();
644 for (chan = c->begin(); chan != c->end(); ++chan) {
645 (*chan)->buf->increment_read_ptr (::llabs(distance));
648 playback_sample += distance;
654 void swap_by_ptr (Sample *first, Sample *last)
656 while (first < last) {
663 /** Read some data for 1 channel from our playlist into a buffer.
664 * @param buf Buffer to write to.
665 * @param start Session frame to start reading from; updated to where we end up
667 * @param cnt Count of samples to read.
668 * @param reversed true if we are running backwards, otherwise false.
671 DiskReader::audio_read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer,
672 framepos_t& start, framecnt_t cnt,
673 int channel, bool reversed)
675 framecnt_t this_read = 0;
677 framepos_t loop_end = 0;
678 framepos_t loop_start = 0;
679 framecnt_t offset = 0;
682 /* XXX we don't currently play loops in reverse. not sure why */
686 framecnt_t loop_length = 0;
688 /* Make the use of a Location atomic for this read operation.
690 Note: Locations don't get deleted, so all we care about
691 when I say "atomic" is that we are always pointing to
692 the same one and using a start/length values obtained
696 if ((loc = loop_location) != 0) {
697 loop_start = loc->start();
698 loop_end = loc->end();
699 loop_length = loop_end - loop_start;
702 /* if we are looping, ensure that the first frame we read is at the correct
703 position within the loop.
706 if (loc && start >= loop_end) {
707 start = loop_start + ((start - loop_start) % loop_length);
716 /* We need this while loop in case we hit a loop boundary, in which case our read from
717 the playlist must be split into more than one section.
722 /* take any loop into account. we can't read past the end of the loop. */
724 if (loc && (loop_end - start < cnt)) {
725 this_read = loop_end - start;
732 if (this_read == 0) {
736 this_read = min(cnt,this_read);
738 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
739 error << string_compose(_("DiskReader %1: cannot read %2 from playlist at frame %3"), id(), this_read,
746 swap_by_ptr (buf, buf + this_read - 1);
750 /* if we read to the end of the loop, go back to the beginning */
767 DiskReader::_do_refill_with_alloc (bool partial_fill)
769 /* We limit disk reads to at most 4MB chunks, which with floating point
770 samples would be 1M samples. But we might use 16 or 14 bit samples,
771 in which case 4MB is more samples than that. Therefore size this for
772 the smallest sample value .. 4MB = 2M samples (16 bit).
776 std::auto_ptr<Sample> mix_buf (new Sample[2*1048576]);
777 std::auto_ptr<float> gain_buf (new float[2*1048576]);
779 int ret = refill_audio (mix_buf.get(), gain_buf.get(), (partial_fill ? _chunk_frames : 0));
786 return refill_midi ();
790 DiskReader::refill (Sample* mixdown_buffer, float* gain_buffer, framecnt_t fill_level)
792 int ret = refill_audio (mixdown_buffer, gain_buffer, fill_level);
798 return refill_midi ();
802 /** Get some more data from disk and put it in our channels' bufs,
803 * if there is suitable space in them.
805 * If fill_level is non-zero, then we will refill the buffer so that there is
806 * still at least fill_level samples of space left to be filled. This is used
807 * after locates so that we do not need to wait to fill the entire buffer.
812 DiskReader::refill_audio (Sample* mixdown_buffer, float* gain_buffer, framecnt_t fill_level)
814 if (_session.state_of_the_state() & Session::Loading) {
820 RingBufferNPT<Sample>::rw_vector vector;
821 bool const reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
822 framecnt_t total_space;
823 framecnt_t zero_fill;
825 ChannelList::iterator i;
826 boost::shared_ptr<ChannelList> c = channels.reader();
829 /* do not read from disk while session is marked as Loading, to avoid
830 useless redundant I/O.
837 assert(mixdown_buffer);
845 c->front()->buf->get_write_vector (&vector);
847 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
848 /* nowhere to write to */
853 if (fill_level < total_space) {
854 total_space -= fill_level;
856 /* we can't do anything with it */
861 /* if we're running close to normal speed and there isn't enough
862 space to do disk_read_chunk_frames of I/O, then don't bother.
864 at higher speeds, just do it because the sync between butler
865 and audio thread may not be good enough.
867 Note: it is a design assumption that disk_read_chunk_frames is smaller
868 than the playback buffer size, so this check should never trip when
869 the playback buffer is empty.
872 if ((total_space < _chunk_frames) && fabs (_actual_speed) < 2.0f) {
876 /* when slaved, don't try to get too close to the read pointer. this
877 leaves space for the buffer reversal to have something useful to
881 if (_slaved && total_space < (framecnt_t) (c->front()->buf->bufsize() / 2)) {
887 if (file_frame == 0) {
889 /* at start: nothing to do but fill with silence */
891 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
893 ChannelInfo* chan (*i);
894 chan->buf->get_write_vector (&vector);
895 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
897 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
899 chan->buf->increment_write_ptr (vector.len[0] + vector.len[1]);
904 if (file_frame < total_space) {
906 /* too close to the start: read what we can,
907 and then zero fill the rest
910 zero_fill = total_space - file_frame;
911 total_space = file_frame;
920 if (file_frame == max_framepos) {
922 /* at end: nothing to do but fill with silence */
924 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
926 ChannelInfo* chan (*i);
927 chan->buf->get_write_vector (&vector);
928 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
930 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
932 chan->buf->increment_write_ptr (vector.len[0] + vector.len[1]);
937 if (file_frame > max_framepos - total_space) {
939 /* to close to the end: read what we can, and zero fill the rest */
941 zero_fill = total_space - (max_framepos - file_frame);
942 total_space = max_framepos - file_frame;
949 framepos_t file_frame_tmp = 0;
951 /* total_space is in samples. We want to optimize read sizes in various sizes using bytes */
953 const size_t bits_per_sample = format_data_width (_session.config.get_native_file_data_format());
954 size_t total_bytes = total_space * bits_per_sample / 8;
956 /* chunk size range is 256kB to 4MB. Bigger is faster in terms of MB/sec, but bigger chunk size always takes longer
958 size_t byte_size_for_read = max ((size_t) (256 * 1024), min ((size_t) (4 * 1048576), total_bytes));
960 /* find nearest (lower) multiple of 16384 */
962 byte_size_for_read = (byte_size_for_read / 16384) * 16384;
964 /* now back to samples */
966 framecnt_t samples_to_read = byte_size_for_read / (bits_per_sample / 8);
968 //cerr << name() << " will read " << byte_size_for_read << " out of total bytes " << total_bytes << " in buffer of "
969 // << c->front()->buf->bufsize() * bits_per_sample / 8 << " bps = " << bits_per_sample << endl;
970 // cerr << name () << " read samples = " << samples_to_read << " out of total space " << total_space << " in buffer of " << c->front()->buf->bufsize() << " samples\n";
972 // uint64_t before = g_get_monotonic_time ();
975 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
977 ChannelInfo* chan (*i);
980 framecnt_t len1, len2;
982 chan->buf->get_write_vector (&vector);
984 if ((framecnt_t) vector.len[0] > samples_to_read) {
986 /* we're not going to fill the first chunk, so certainly do not bother with the
987 other part. it won't be connected with the part we do fill, as in:
989 .... => writable space
990 ++++ => readable space
991 ^^^^ => 1 x disk_read_chunk_frames that would be filled
993 |......|+++++++++++++|...............................|
998 So, just pretend that the buf1 part isn't there.
1008 file_frame_tmp = file_frame;
1010 buf1 = vector.buf[0];
1011 len1 = vector.len[0];
1012 buf2 = vector.buf[1];
1013 len2 = vector.len[1];
1015 to_read = min (ts, len1);
1016 to_read = min (to_read, (framecnt_t) samples_to_read);
1018 assert (to_read >= 0);
1022 if (audio_read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1027 chan->buf->increment_write_ptr (to_read);
1031 to_read = min (ts, len2);
1035 /* we read all of vector.len[0], but it wasn't the
1036 entire samples_to_read of data, so read some or
1037 all of vector.len[1] as well.
1040 if (audio_read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1045 chan->buf->increment_write_ptr (to_read);
1049 /* XXX: do something */
1054 // elapsed = g_get_monotonic_time () - before;
1055 // cerr << "\tbandwidth = " << (byte_size_for_read / 1048576.0) / (elapsed/1000000.0) << "MB/sec\n";
1057 file_frame = file_frame_tmp;
1058 assert (file_frame >= 0);
1060 ret = ((total_space - samples_to_read) > _chunk_frames);
1062 c->front()->buf->get_write_vector (&vector);
1069 DiskReader::playlist_ranges_moved (list< Evoral::RangeMove<framepos_t> > const & movements_frames, bool from_undo)
1071 /* If we're coming from an undo, it will have handled
1072 automation undo (it must, since automation-follows-regions
1073 can lose automation data). Hence we can do nothing here.
1080 if (!_route || Config->get_automation_follows_regions () == false) {
1084 list< Evoral::RangeMove<double> > movements;
1086 for (list< Evoral::RangeMove<framepos_t> >::const_iterator i = movements_frames.begin();
1087 i != movements_frames.end();
1090 movements.push_back(Evoral::RangeMove<double>(i->from, i->length, i->to));
1093 /* move panner automation */
1094 boost::shared_ptr<Pannable> pannable = _route->pannable();
1095 Evoral::ControlSet::Controls& c (pannable->controls());
1097 for (Evoral::ControlSet::Controls::iterator ci = c.begin(); ci != c.end(); ++ci) {
1098 boost::shared_ptr<AutomationControl> ac = boost::dynamic_pointer_cast<AutomationControl>(ci->second);
1102 boost::shared_ptr<AutomationList> alist = ac->alist();
1103 if (!alist->size()) {
1106 XMLNode & before = alist->get_state ();
1107 bool const things_moved = alist->move_ranges (movements);
1109 _session.add_command (new MementoCommand<AutomationList> (
1110 *alist.get(), &before, &alist->get_state ()));
1113 /* move processor automation */
1114 _route->foreach_processor (boost::bind (&DiskReader::move_processor_automation, this, _1, movements_frames));
1118 DiskReader::move_processor_automation (boost::weak_ptr<Processor> p, list< Evoral::RangeMove<framepos_t> > const & movements_frames)
1120 boost::shared_ptr<Processor> processor (p.lock ());
1125 list< Evoral::RangeMove<double> > movements;
1126 for (list< Evoral::RangeMove<framepos_t> >::const_iterator i = movements_frames.begin(); i != movements_frames.end(); ++i) {
1127 movements.push_back(Evoral::RangeMove<double>(i->from, i->length, i->to));
1130 set<Evoral::Parameter> const a = processor->what_can_be_automated ();
1132 for (set<Evoral::Parameter>::const_iterator i = a.begin (); i != a.end (); ++i) {
1133 boost::shared_ptr<AutomationList> al = processor->automation_control(*i)->alist();
1137 XMLNode & before = al->get_state ();
1138 bool const things_moved = al->move_ranges (movements);
1140 _session.add_command (
1141 new MementoCommand<AutomationList> (
1142 *al.get(), &before, &al->get_state ()
1149 boost::shared_ptr<MidiBuffer>
1150 DiskReader::get_gui_feed_buffer () const
1152 boost::shared_ptr<MidiBuffer> b (new MidiBuffer (AudioEngine::instance()->raw_buffer_size (DataType::MIDI)));
1154 Glib::Threads::Mutex::Lock lm (_gui_feed_buffer_mutex);
1155 b->copy (_gui_feed_buffer);
1160 DiskReader::reset_tracker ()
1162 _midi_buf->reset_tracker ();
1164 boost::shared_ptr<MidiPlaylist> mp (midi_playlist());
1167 mp->reset_note_trackers ();
1172 DiskReader::resolve_tracker (Evoral::EventSink<framepos_t>& buffer, framepos_t time)
1174 _midi_buf->resolve_tracker(buffer, time);
1176 boost::shared_ptr<MidiPlaylist> mp (midi_playlist());
1179 mp->reset_note_trackers ();
1184 DiskReader::flush_playback (framepos_t start, framepos_t end)
1186 _midi_buf->flush (start, end);
1187 g_atomic_int_add (&_frames_read_from_ringbuffer, end - start);
1190 /** Writes playback events from playback_sample for nframes to dst, translating time stamps
1191 * so that an event at playback_sample has time = 0
1194 DiskReader::get_playback (MidiBuffer& dst, framecnt_t nframes)
1198 Location* loc = loop_location;
1200 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose (
1201 "%1 MDS pre-read read %8 offset = %9 @ %4..%5 from %2 write to %3, LOOPED ? %6 .. %7\n", _name,
1202 _midi_buf->get_read_ptr(), _midi_buf->get_write_ptr(), playback_sample, playback_sample + nframes,
1203 (loc ? loc->start() : -1), (loc ? loc->end() : -1), nframes, Port::port_offset()));
1205 //cerr << "======== PRE ========\n";
1206 //_midi_buf->dump (cerr);
1207 //cerr << "----------------\n";
1209 size_t events_read = 0;
1212 framepos_t effective_start;
1214 Evoral::Range<framepos_t> loop_range (loc->start(), loc->end() - 1);
1215 effective_start = loop_range.squish (playback_sample);
1217 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("looped, effective start adjusted to %1\n", effective_start));
1219 if (effective_start == loc->start()) {
1220 /* We need to turn off notes that may extend
1221 beyond the loop end.
1224 _midi_buf->resolve_tracker (dst, 0);
1227 /* for split-cycles we need to offset the events */
1229 if (loc->end() >= effective_start && loc->end() < effective_start + nframes) {
1231 /* end of loop is within the range we are reading, so
1232 split the read in two, and lie about the location
1236 framecnt_t first, second;
1238 first = loc->end() - effective_start;
1239 second = nframes - first;
1241 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read for eff %1 end %2: %3 and %4, cycle offset %5\n",
1242 effective_start, loc->end(), first, second));
1245 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read #1, from %1 for %2\n",
1246 effective_start, first));
1247 events_read = _midi_buf->read (dst, effective_start, first);
1251 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read #2, from %1 for %2\n",
1252 loc->start(), second));
1253 events_read += _midi_buf->read (dst, loc->start(), second);
1257 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read #3, adjusted start as %1 for %2\n",
1258 effective_start, nframes));
1259 events_read = _midi_buf->read (dst, effective_start, effective_start + nframes);
1262 const size_t n_skipped = _midi_buf->skip_to (playback_sample);
1263 if (n_skipped > 0) {
1264 warning << string_compose(_("MidiDiskstream %1: skipped %2 events, possible underflow"), id(), n_skipped) << endmsg;
1266 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("playback buffer read, from %1 to %2 (%3)", playback_sample, playback_sample + nframes, nframes));
1267 events_read = _midi_buf->read (dst, playback_sample, playback_sample + nframes);
1270 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose (
1271 "%1 MDS events read %2 range %3 .. %4 rspace %5 wspace %6 r@%7 w@%8\n",
1272 _name, events_read, playback_sample, playback_sample + nframes,
1273 _midi_buf->read_space(), _midi_buf->write_space(),
1274 _midi_buf->get_read_ptr(), _midi_buf->get_write_ptr()));
1276 g_atomic_int_add (&_frames_read_from_ringbuffer, nframes);
1278 //cerr << "======== POST ========\n";
1279 //_midi_buf->dump (cerr);
1280 //cerr << "----------------\n";
1283 /** @a start is set to the new frame position (TIME) read up to */
1285 DiskReader::midi_read (framepos_t& start, framecnt_t dur, bool reversed)
1287 framecnt_t this_read = 0;
1288 framepos_t loop_end = 0;
1289 framepos_t loop_start = 0;
1290 framecnt_t loop_length = 0;
1291 Location* loc = loop_location;
1292 framepos_t effective_start = start;
1293 Evoral::Range<framepos_t>* loop_range (0);
1295 // MidiTrack* mt = dynamic_cast<MidiTrack*>(_track);
1296 // MidiChannelFilter* filter = mt ? &mt->playback_filter() : 0;
1297 MidiChannelFilter* filter = 0;
1299 frameoffset_t loop_offset = 0;
1301 if (!reversed && loc) {
1302 get_location_times (loc, &loop_start, &loop_end, &loop_length);
1307 /* take any loop into account. we can't read past the end of the loop. */
1309 if (loc && !reversed) {
1312 loop_range = new Evoral::Range<framepos_t> (loop_start, loop_end-1); // inclusive semantics require -1
1315 /* if we are (seamlessly) looping, ensure that the first frame we read is at the correct
1316 position within the loop.
1319 effective_start = loop_range->squish (effective_start);
1321 if ((loop_end - effective_start) <= dur) {
1322 /* too close to end of loop to read "dur", so
1325 this_read = loop_end - effective_start;
1334 if (this_read == 0) {
1338 this_read = min (dur,this_read);
1340 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("MDS ::read at %1 for %2 loffset %3\n", effective_start, this_read, loop_offset));
1342 if (midi_playlist()->read (*_midi_buf, effective_start, this_read, loop_range, 0, filter) != this_read) {
1343 error << string_compose(
1344 _("MidiDiskstream %1: cannot read %2 from playlist at frame %3"),
1345 id(), this_read, start) << endmsg;
1349 g_atomic_int_add (&_frames_written_to_ringbuffer, this_read);
1353 // Swap note ons with note offs here. etc?
1354 // Fully reversing MIDI requires look-ahead (well, behind) to find previous
1355 // CC values etc. hard.
1359 /* adjust passed-by-reference argument (note: this is
1360 monotonic and does not reflect looping.
1364 /* similarly adjust effective_start, but this may be
1365 readjusted for seamless looping as we continue around
1368 effective_start += this_read;
1372 //offset += this_read;
1379 DiskReader::refill_midi ()
1382 size_t write_space = _midi_buf->write_space();
1383 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1385 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("MDS refill, write space = %1 file frame = %2\n",
1386 write_space, file_frame));
1388 /* no space to write */
1389 if (write_space == 0) {
1397 /* at end: nothing to do */
1398 if (file_frame == max_framepos) {
1402 if (_playlists[DataType::MIDI]) {
1404 const uint32_t frames_read = g_atomic_int_get (&_frames_read_from_ringbuffer);
1405 const uint32_t frames_written = g_atomic_int_get (&_frames_written_to_ringbuffer);
1407 if ((frames_read < frames_written) && (frames_written - frames_read) >= midi_readahead) {
1411 framecnt_t to_read = midi_readahead - ((framecnt_t)frames_written - (framecnt_t)frames_read);
1413 to_read = min (to_read, (framecnt_t) (max_framepos - file_frame));
1414 to_read = min (to_read, (framecnt_t) write_space);
1416 if (midi_read (file_frame, to_read, reversed)) {