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));
62 Glib::Threads::Mutex::Lock lm (state_lock);
64 for (uint32_t n = 0; n < DataType::num_types; ++n) {
66 _playlists[n]->release ();
71 RCUWriter<ChannelList> writer (channels);
72 boost::shared_ptr<ChannelList> c = writer.get_copy();
74 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
87 DiskReader::allocate_working_buffers()
89 /* with varifill buffer refilling, we compute the read size in bytes (to optimize
90 for disk i/o bandwidth) and then convert back into samples. These buffers
91 need to reflect the maximum size we could use, which is 4MB reads, or 2M samples
94 _mixdown_buffer = new Sample[2*1048576];
95 _gain_buffer = new gain_t[2*1048576];
99 DiskReader::free_working_buffers()
101 delete [] _mixdown_buffer;
102 delete [] _gain_buffer;
108 DiskReader::default_chunk_frames()
114 DiskReader::set_name (string const & str)
117 for (uint32_t n = 0; n < DataType::num_types; ++n) {
119 _playlists[n]->set_name (str);
122 SessionObject::set_name(str);
129 DiskReader::set_roll_delay (ARDOUR::framecnt_t nframes)
131 _roll_delay = nframes;
135 DiskReader::state (bool full)
137 XMLNode& node (DiskIOProcessor::state (full));
142 DiskReader::set_state (const XMLNode& node, int version)
144 if (DiskIOProcessor::set_state (node, version)) {
152 DiskReader::realtime_handle_transport_stopped ()
157 DiskReader::realtime_locate ()
162 DiskReader::buffer_load () const
164 /* Note: for MIDI it's not trivial to differentiate the following two cases:
166 1. The playback buffer is empty because the system has run out of time to fill it.
167 2. The playback buffer is empty because there is no more data on the playlist.
169 If we use a simple buffer load computation, we will report that the MIDI diskstream
170 cannot keep up when #2 happens, when in fact it can. Since MIDI data rates
171 are so low compared to audio, just use the audio value here.
174 boost::shared_ptr<ChannelList> c = channels.reader();
177 /* no channels, so no buffers, so completely full and ready to playback, sir! */
181 PBD::RingBufferNPT<Sample> * b = c->front()->buf;
182 return (float) ((double) b->read_space() / (double) b->bufsize());
186 DiskReader::adjust_buffering ()
188 boost::shared_ptr<ChannelList> c = channels.reader();
190 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
191 (*chan)->resize (_session.butler()->audio_diskstream_playback_buffer_size());
196 DiskReader::playlist_changed (const PropertyChange&)
198 playlist_modified ();
202 DiskReader::playlist_modified ()
204 if (!i_am_the_modifier && !overwrite_queued) {
205 // !!!! _session.request_overwrite_buffer (this);
206 overwrite_queued = true;
211 DiskReader::use_playlist (DataType dt, boost::shared_ptr<Playlist> playlist)
213 bool prior_playlist = false;
215 if (_playlists[dt]) {
216 prior_playlist = true;
219 if (DiskIOProcessor::use_playlist (dt, playlist)) {
223 /* don't do this if we've already asked for it *or* if we are setting up
224 the diskstream for the very first time - the input changed handling will
225 take care of the buffer refill.
228 if (!overwrite_queued && prior_playlist) {
229 // !!! _session.request_overwrite_buffer (this);
230 overwrite_queued = true;
237 DiskReader::run (BufferSet& bufs, framepos_t start_frame, framepos_t end_frame,
238 double speed, pframes_t nframes, bool result_required)
241 boost::shared_ptr<ChannelList> c = channels.reader();
242 ChannelList::iterator chan;
243 framecnt_t playback_distance = 0;
245 Glib::Threads::Mutex::Lock sm (state_lock, Glib::Threads::TRY_LOCK);
251 const bool need_disk_signal = result_required || _monitoring_choice == MonitorDisk || _monitoring_choice == MonitorCue;
253 if (fabsf (_actual_speed) != 1.0f) {
254 midi_interpolation.set_speed (_target_speed);
255 interpolation.set_speed (_target_speed);
256 playback_distance = midi_interpolation.distance (nframes);
258 playback_distance = nframes;
261 if (!need_disk_signal) {
263 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
264 (*chan)->buf->increment_read_ptr (playback_distance);
270 /* we're doing playback */
272 size_t n_buffers = bufs.count().n_audio();
273 size_t n_chans = c->size();
276 if (n_chans > n_buffers) {
277 scaling = ((float) n_buffers)/n_chans;
282 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
284 AudioBuffer& buf (bufs.get_audio (n%n_buffers));
285 Sample* outgoing = buf.data ();
287 ChannelInfo* chaninfo (*chan);
289 chaninfo->buf->get_read_vector (&(*chan)->rw_vector);
291 if (playback_distance <= (framecnt_t) chaninfo->rw_vector.len[0]) {
293 if (fabsf (_actual_speed) != 1.0f) {
294 (void) interpolation.interpolate (
296 chaninfo->rw_vector.buf[0],
299 memcpy (outgoing, chaninfo->rw_vector.buf[0], sizeof (Sample) * playback_distance);
304 const framecnt_t total = chaninfo->rw_vector.len[0] + chaninfo->rw_vector.len[1];
306 if (playback_distance <= total) {
308 /* We have enough samples, but not in one lump.
311 if (fabsf (_actual_speed) != 1.0f) {
312 interpolation.interpolate (n, chaninfo->rw_vector.len[0],
313 chaninfo->rw_vector.buf[0],
315 outgoing += chaninfo->rw_vector.len[0];
316 interpolation.interpolate (n, playback_distance - chaninfo->rw_vector.len[0],
317 chaninfo->rw_vector.buf[1],
321 chaninfo->rw_vector.buf[0],
322 chaninfo->rw_vector.len[0] * sizeof (Sample));
323 outgoing += chaninfo->rw_vector.len[0];
325 chaninfo->rw_vector.buf[1],
326 (playback_distance - chaninfo->rw_vector.len[0]) * sizeof (Sample));
331 cerr << _name << " Need " << playback_distance << " total = " << total << endl;
332 cerr << "underrun for " << _name << endl;
333 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 underrun in %2, total space = %3\n",
334 DEBUG_THREAD_SELF, name(), total));
342 if (scaling != 1.0f) {
343 apply_gain_to_buffer (outgoing, nframes, scaling);
346 chaninfo->buf->increment_read_ptr (playback_distance);
347 _speed = _target_speed;
350 /* MIDI data handling */
352 if (!_session.declick_out_pending()) {
354 /* copy the diskstream data to all output buffers */
356 MidiBuffer& mbuf (bufs.get_midi (0));
357 get_playback (mbuf, playback_distance);
360 if (_target_speed > 0 && _actual_speed != 1.0f) {
361 MidiBuffer& mbuf (bufs.get_midi (0));
362 for (MidiBuffer::iterator i = mbuf.begin(); i != mbuf.end(); ++i) {
363 MidiBuffer::TimeType *tme = i.timeptr();
364 *tme = (*tme) * nframes / playback_distance;
369 _need_butler = false;
371 if (_actual_speed < 0.0) {
372 playback_sample -= playback_distance;
374 playback_sample += playback_distance;
379 if (c->front()->buf->write_space() >= c->front()->buf->bufsize() / 2) {
383 if ((framecnt_t) c->front()->buf->write_space() >= _chunk_frames) {
389 /* MIDI butler needed part */
391 uint32_t frames_read = g_atomic_int_get(const_cast<gint*>(&_frames_read_from_ringbuffer));
392 uint32_t frames_written = g_atomic_int_get(const_cast<gint*>(&_frames_written_to_ringbuffer));
395 cerr << name() << " MDS written: " << frames_written << " - read: " << frames_read <<
396 " = " << frames_written - frames_read
397 << " + " << playback_distance << " < " << midi_readahead << " = " << need_butler << ")" << endl;
400 /* frames_read will generally be less than frames_written, but
401 * immediately after an overwrite, we can end up having read some data
402 * before we've written any. we don't need to trip an assert() on this,
403 * but we do need to check so that the decision on whether or not we
404 * need the butler is done correctly.
409 * Doing heavy GUI operations[1] can stall also the butler.
410 * The RT-thread meanwhile will happily continue and
411 * ‘frames_read’ (from buffer to output) will become larger
412 * than ‘frames_written’ (from disk to buffer).
414 * The disk-stream is now behind..
416 * In those cases the butler needs to be summed to refill the buffer (done now)
417 * AND we need to skip (frames_read - frames_written). ie remove old events
418 * before playback_sample from the rinbuffer.
420 * [1] one way to do so is described at #6170.
421 * For me just popping up the context-menu on a MIDI-track header
422 * of a track with a large (think beethoven :) midi-region also did the
423 * trick. The playhead stalls for 2 or 3 sec, until the context-menu shows.
425 * In both cases the root cause is that redrawing MIDI regions on the GUI is still very slow
428 if (frames_read <= frames_written) {
429 if ((frames_written - frames_read) + playback_distance < midi_readahead) {
436 /* make sure bufs shows whatever data we had available */
439 cnt.set (DataType::MIDI, 1);
440 cnt.set (DataType::AUDIO, bufs.count().n_audio());
441 bufs.set_count (cnt);
445 DiskReader::calculate_playback_distance (pframes_t nframes)
447 frameoffset_t playback_distance = nframes;
449 if (_actual_speed != 1.0f && _actual_speed != -1.0f) {
450 interpolation.set_speed (_target_speed);
451 boost::shared_ptr<ChannelList> c = channels.reader();
453 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++channel) {
454 playback_distance = interpolation.interpolate (channel, nframes, NULL, NULL);
457 playback_distance = nframes;
460 if (_actual_speed < 0.0) {
461 return -playback_distance;
463 return playback_distance;
468 DiskReader::set_pending_overwrite (bool yn)
470 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
472 _pending_overwrite = yn;
474 overwrite_frame = playback_sample;
476 boost::shared_ptr<ChannelList> c = channels.reader ();
478 overwrite_offset = c->front()->buf->get_read_ptr();
483 DiskReader::overwrite_existing_buffers ()
487 boost::shared_ptr<ChannelList> c = channels.reader();
489 overwrite_queued = false;
495 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
497 /* assume all are the same size */
498 framecnt_t size = c->front()->buf->bufsize();
500 std::auto_ptr<Sample> mixdown_buffer (new Sample[size]);
501 std::auto_ptr<float> gain_buffer (new float[size]);
503 /* reduce size so that we can fill the buffer correctly (ringbuffers
504 can only handle size-1, otherwise they appear to be empty)
511 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
513 start = overwrite_frame;
514 framecnt_t cnt = size;
516 /* to fill the buffer without resetting the playback sample, we need to
517 do it one or two chunks (normally two).
519 |----------------------------------------------------------------------|
523 |<- second chunk->||<----------------- first chunk ------------------>|
527 framecnt_t to_read = size - overwrite_offset;
529 if (audio_read ((*chan)->buf->buffer() + overwrite_offset, mixdown_buffer.get(), gain_buffer.get(), start, to_read, n, reversed)) {
530 error << string_compose(_("DiskReader %1: when refilling, cannot read %2 from playlist at frame %3"),
531 id(), size, playback_sample) << endmsg;
539 if (audio_read ((*chan)->buf->buffer(), mixdown_buffer.get(), gain_buffer.get(), start, cnt, n, reversed)) {
540 error << string_compose(_("DiskReader %1: when refilling, cannot read %2 from playlist at frame %3"),
541 id(), size, playback_sample) << endmsg;
553 if (_midi_buf && _playlists[DataType::MIDI]) {
555 /* Clear the playback buffer contents. This is safe as long as the butler
556 thread is suspended, which it should be.
559 _midi_buf->reset_tracker ();
561 g_atomic_int_set (&_frames_read_from_ringbuffer, 0);
562 g_atomic_int_set (&_frames_written_to_ringbuffer, 0);
564 /* Resolve all currently active notes in the playlist. This is more
565 aggressive than it needs to be: ideally we would only resolve what is
566 absolutely necessary, but this seems difficult and/or impossible without
567 having the old data or knowing what change caused the overwrite.
569 midi_playlist()->resolve_note_trackers (*_midi_buf, overwrite_frame);
571 midi_read (overwrite_frame, _chunk_frames, false);
573 file_frame = overwrite_frame; // it was adjusted by ::midi_read()
576 _pending_overwrite = false;
582 DiskReader::seek (framepos_t frame, bool complete_refill)
586 ChannelList::iterator chan;
587 boost::shared_ptr<ChannelList> c = channels.reader();
589 Glib::Threads::Mutex::Lock lm (state_lock);
591 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
592 (*chan)->buf->reset ();
595 if (g_atomic_int_get (&_frames_read_from_ringbuffer) == 0) {
596 /* we haven't read anything since the last seek,
597 so flush all note trackers to prevent
604 g_atomic_int_set(&_frames_read_from_ringbuffer, 0);
605 g_atomic_int_set(&_frames_written_to_ringbuffer, 0);
607 playback_sample = frame;
610 if (complete_refill) {
611 /* call _do_refill() to refill the entire buffer, using
612 the largest reads possible.
614 while ((ret = do_refill_with_alloc (false)) > 0) ;
616 /* call _do_refill() to refill just one chunk, and then
619 ret = do_refill_with_alloc (true);
627 DiskReader::can_internal_playback_seek (framecnt_t distance)
631 ChannelList::iterator chan;
632 boost::shared_ptr<ChannelList> c = channels.reader();
634 for (chan = c->begin(); chan != c->end(); ++chan) {
635 if ((*chan)->buf->read_space() < (size_t) distance) {
642 uint32_t frames_read = g_atomic_int_get(&_frames_read_from_ringbuffer);
643 uint32_t frames_written = g_atomic_int_get(&_frames_written_to_ringbuffer);
645 return ((frames_written - frames_read) < distance);
649 DiskReader::internal_playback_seek (framecnt_t distance)
651 ChannelList::iterator chan;
652 boost::shared_ptr<ChannelList> c = channels.reader();
654 for (chan = c->begin(); chan != c->end(); ++chan) {
655 (*chan)->buf->increment_read_ptr (::llabs(distance));
658 playback_sample += distance;
664 void swap_by_ptr (Sample *first, Sample *last)
666 while (first < last) {
673 /** Read some data for 1 channel from our playlist into a buffer.
674 * @param buf Buffer to write to.
675 * @param start Session frame to start reading from; updated to where we end up
677 * @param cnt Count of samples to read.
678 * @param reversed true if we are running backwards, otherwise false.
681 DiskReader::audio_read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer,
682 framepos_t& start, framecnt_t cnt,
683 int channel, bool reversed)
685 framecnt_t this_read = 0;
687 framepos_t loop_end = 0;
688 framepos_t loop_start = 0;
689 framecnt_t offset = 0;
692 /* XXX we don't currently play loops in reverse. not sure why */
696 framecnt_t loop_length = 0;
698 /* Make the use of a Location atomic for this read operation.
700 Note: Locations don't get deleted, so all we care about
701 when I say "atomic" is that we are always pointing to
702 the same one and using a start/length values obtained
706 if ((loc = loop_location) != 0) {
707 loop_start = loc->start();
708 loop_end = loc->end();
709 loop_length = loop_end - loop_start;
712 /* if we are looping, ensure that the first frame we read is at the correct
713 position within the loop.
716 if (loc && start >= loop_end) {
717 start = loop_start + ((start - loop_start) % loop_length);
726 /* We need this while loop in case we hit a loop boundary, in which case our read from
727 the playlist must be split into more than one section.
732 /* take any loop into account. we can't read past the end of the loop. */
734 if (loc && (loop_end - start < cnt)) {
735 this_read = loop_end - start;
742 if (this_read == 0) {
746 this_read = min(cnt,this_read);
748 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
749 error << string_compose(_("DiskReader %1: cannot read %2 from playlist at frame %3"), id(), this_read,
756 swap_by_ptr (buf, buf + this_read - 1);
760 /* if we read to the end of the loop, go back to the beginning */
777 DiskReader::_do_refill_with_alloc (bool partial_fill)
779 /* We limit disk reads to at most 4MB chunks, which with floating point
780 samples would be 1M samples. But we might use 16 or 14 bit samples,
781 in which case 4MB is more samples than that. Therefore size this for
782 the smallest sample value .. 4MB = 2M samples (16 bit).
786 std::auto_ptr<Sample> mix_buf (new Sample[2*1048576]);
787 std::auto_ptr<float> gain_buf (new float[2*1048576]);
789 int ret = refill_audio (mix_buf.get(), gain_buf.get(), (partial_fill ? _chunk_frames : 0));
796 return refill_midi ();
800 DiskReader::refill (Sample* mixdown_buffer, float* gain_buffer, framecnt_t fill_level)
802 int ret = refill_audio (mixdown_buffer, gain_buffer, fill_level);
808 return refill_midi ();
812 /** Get some more data from disk and put it in our channels' bufs,
813 * if there is suitable space in them.
815 * If fill_level is non-zero, then we will refill the buffer so that there is
816 * still at least fill_level samples of space left to be filled. This is used
817 * after locates so that we do not need to wait to fill the entire buffer.
822 DiskReader::refill_audio (Sample* mixdown_buffer, float* gain_buffer, framecnt_t fill_level)
824 if (_session.state_of_the_state() & Session::Loading) {
830 RingBufferNPT<Sample>::rw_vector vector;
831 bool const reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
832 framecnt_t total_space;
833 framecnt_t zero_fill;
835 ChannelList::iterator i;
836 boost::shared_ptr<ChannelList> c = channels.reader();
839 /* do not read from disk while session is marked as Loading, to avoid
840 useless redundant I/O.
847 assert(mixdown_buffer);
855 c->front()->buf->get_write_vector (&vector);
857 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
858 /* nowhere to write to */
863 if (fill_level < total_space) {
864 total_space -= fill_level;
866 /* we can't do anything with it */
871 /* if we're running close to normal speed and there isn't enough
872 space to do disk_read_chunk_frames of I/O, then don't bother.
874 at higher speeds, just do it because the sync between butler
875 and audio thread may not be good enough.
877 Note: it is a design assumption that disk_read_chunk_frames is smaller
878 than the playback buffer size, so this check should never trip when
879 the playback buffer is empty.
882 if ((total_space < _chunk_frames) && fabs (_actual_speed) < 2.0f) {
886 /* when slaved, don't try to get too close to the read pointer. this
887 leaves space for the buffer reversal to have something useful to
891 if (_slaved && total_space < (framecnt_t) (c->front()->buf->bufsize() / 2)) {
897 if (file_frame == 0) {
899 /* at start: nothing to do but fill with silence */
901 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
903 ChannelInfo* chan (*i);
904 chan->buf->get_write_vector (&vector);
905 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
907 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
909 chan->buf->increment_write_ptr (vector.len[0] + vector.len[1]);
914 if (file_frame < total_space) {
916 /* too close to the start: read what we can,
917 and then zero fill the rest
920 zero_fill = total_space - file_frame;
921 total_space = file_frame;
930 if (file_frame == max_framepos) {
932 /* at end: nothing to do but fill with silence */
934 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
936 ChannelInfo* chan (*i);
937 chan->buf->get_write_vector (&vector);
938 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
940 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
942 chan->buf->increment_write_ptr (vector.len[0] + vector.len[1]);
947 if (file_frame > max_framepos - total_space) {
949 /* to close to the end: read what we can, and zero fill the rest */
951 zero_fill = total_space - (max_framepos - file_frame);
952 total_space = max_framepos - file_frame;
959 framepos_t file_frame_tmp = 0;
961 /* total_space is in samples. We want to optimize read sizes in various sizes using bytes */
963 const size_t bits_per_sample = format_data_width (_session.config.get_native_file_data_format());
964 size_t total_bytes = total_space * bits_per_sample / 8;
966 /* chunk size range is 256kB to 4MB. Bigger is faster in terms of MB/sec, but bigger chunk size always takes longer
968 size_t byte_size_for_read = max ((size_t) (256 * 1024), min ((size_t) (4 * 1048576), total_bytes));
970 /* find nearest (lower) multiple of 16384 */
972 byte_size_for_read = (byte_size_for_read / 16384) * 16384;
974 /* now back to samples */
976 framecnt_t samples_to_read = byte_size_for_read / (bits_per_sample / 8);
978 //cerr << name() << " will read " << byte_size_for_read << " out of total bytes " << total_bytes << " in buffer of "
979 // << c->front()->buf->bufsize() * bits_per_sample / 8 << " bps = " << bits_per_sample << endl;
980 // cerr << name () << " read samples = " << samples_to_read << " out of total space " << total_space << " in buffer of " << c->front()->buf->bufsize() << " samples\n";
982 // uint64_t before = g_get_monotonic_time ();
985 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
987 ChannelInfo* chan (*i);
990 framecnt_t len1, len2;
992 chan->buf->get_write_vector (&vector);
994 if ((framecnt_t) vector.len[0] > samples_to_read) {
996 /* we're not going to fill the first chunk, so certainly do not bother with the
997 other part. it won't be connected with the part we do fill, as in:
999 .... => writable space
1000 ++++ => readable space
1001 ^^^^ => 1 x disk_read_chunk_frames that would be filled
1003 |......|+++++++++++++|...............................|
1008 So, just pretend that the buf1 part isn't there.
1018 file_frame_tmp = file_frame;
1020 buf1 = vector.buf[0];
1021 len1 = vector.len[0];
1022 buf2 = vector.buf[1];
1023 len2 = vector.len[1];
1025 to_read = min (ts, len1);
1026 to_read = min (to_read, (framecnt_t) samples_to_read);
1028 assert (to_read >= 0);
1032 if (audio_read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1037 chan->buf->increment_write_ptr (to_read);
1041 to_read = min (ts, len2);
1045 /* we read all of vector.len[0], but it wasn't the
1046 entire samples_to_read of data, so read some or
1047 all of vector.len[1] as well.
1050 if (audio_read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1055 chan->buf->increment_write_ptr (to_read);
1059 /* XXX: do something */
1064 // elapsed = g_get_monotonic_time () - before;
1065 // cerr << "\tbandwidth = " << (byte_size_for_read / 1048576.0) / (elapsed/1000000.0) << "MB/sec\n";
1067 file_frame = file_frame_tmp;
1068 assert (file_frame >= 0);
1070 ret = ((total_space - samples_to_read) > _chunk_frames);
1072 c->front()->buf->get_write_vector (&vector);
1079 DiskReader::playlist_ranges_moved (list< Evoral::RangeMove<framepos_t> > const & movements_frames, bool from_undo)
1081 /* If we're coming from an undo, it will have handled
1082 automation undo (it must, since automation-follows-regions
1083 can lose automation data). Hence we can do nothing here.
1090 if (!_route || Config->get_automation_follows_regions () == false) {
1094 list< Evoral::RangeMove<double> > movements;
1096 for (list< Evoral::RangeMove<framepos_t> >::const_iterator i = movements_frames.begin();
1097 i != movements_frames.end();
1100 movements.push_back(Evoral::RangeMove<double>(i->from, i->length, i->to));
1103 /* move panner automation */
1104 boost::shared_ptr<Pannable> pannable = _route->pannable();
1105 Evoral::ControlSet::Controls& c (pannable->controls());
1107 for (Evoral::ControlSet::Controls::iterator ci = c.begin(); ci != c.end(); ++ci) {
1108 boost::shared_ptr<AutomationControl> ac = boost::dynamic_pointer_cast<AutomationControl>(ci->second);
1112 boost::shared_ptr<AutomationList> alist = ac->alist();
1113 if (!alist->size()) {
1116 XMLNode & before = alist->get_state ();
1117 bool const things_moved = alist->move_ranges (movements);
1119 _session.add_command (new MementoCommand<AutomationList> (
1120 *alist.get(), &before, &alist->get_state ()));
1123 /* move processor automation */
1124 _route->foreach_processor (boost::bind (&DiskReader::move_processor_automation, this, _1, movements_frames));
1128 DiskReader::move_processor_automation (boost::weak_ptr<Processor> p, list< Evoral::RangeMove<framepos_t> > const & movements_frames)
1130 boost::shared_ptr<Processor> processor (p.lock ());
1135 list< Evoral::RangeMove<double> > movements;
1136 for (list< Evoral::RangeMove<framepos_t> >::const_iterator i = movements_frames.begin(); i != movements_frames.end(); ++i) {
1137 movements.push_back(Evoral::RangeMove<double>(i->from, i->length, i->to));
1140 set<Evoral::Parameter> const a = processor->what_can_be_automated ();
1142 for (set<Evoral::Parameter>::const_iterator i = a.begin (); i != a.end (); ++i) {
1143 boost::shared_ptr<AutomationList> al = processor->automation_control(*i)->alist();
1147 XMLNode & before = al->get_state ();
1148 bool const things_moved = al->move_ranges (movements);
1150 _session.add_command (
1151 new MementoCommand<AutomationList> (
1152 *al.get(), &before, &al->get_state ()
1159 boost::shared_ptr<MidiBuffer>
1160 DiskReader::get_gui_feed_buffer () const
1162 boost::shared_ptr<MidiBuffer> b (new MidiBuffer (AudioEngine::instance()->raw_buffer_size (DataType::MIDI)));
1164 Glib::Threads::Mutex::Lock lm (_gui_feed_buffer_mutex);
1165 b->copy (_gui_feed_buffer);
1170 DiskReader::reset_tracker ()
1172 _midi_buf->reset_tracker ();
1174 boost::shared_ptr<MidiPlaylist> mp (midi_playlist());
1177 mp->reset_note_trackers ();
1182 DiskReader::resolve_tracker (Evoral::EventSink<framepos_t>& buffer, framepos_t time)
1184 _midi_buf->resolve_tracker(buffer, time);
1186 boost::shared_ptr<MidiPlaylist> mp (midi_playlist());
1189 mp->reset_note_trackers ();
1194 DiskReader::flush_playback (framepos_t start, framepos_t end)
1196 _midi_buf->flush (start, end);
1197 g_atomic_int_add (&_frames_read_from_ringbuffer, end - start);
1200 /** Writes playback events from playback_sample for nframes to dst, translating time stamps
1201 * so that an event at playback_sample has time = 0
1204 DiskReader::get_playback (MidiBuffer& dst, framecnt_t nframes)
1208 Location* loc = loop_location;
1210 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose (
1211 "%1 MDS pre-read read %8 offset = %9 @ %4..%5 from %2 write to %3, LOOPED ? %6 .. %7\n", _name,
1212 _midi_buf->get_read_ptr(), _midi_buf->get_write_ptr(), playback_sample, playback_sample + nframes,
1213 (loc ? loc->start() : -1), (loc ? loc->end() : -1), nframes, Port::port_offset()));
1215 //cerr << "======== PRE ========\n";
1216 //_midi_buf->dump (cerr);
1217 //cerr << "----------------\n";
1219 size_t events_read = 0;
1222 framepos_t effective_start;
1224 Evoral::Range<framepos_t> loop_range (loc->start(), loc->end() - 1);
1225 effective_start = loop_range.squish (playback_sample);
1227 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("looped, effective start adjusted to %1\n", effective_start));
1229 if (effective_start == loc->start()) {
1230 /* We need to turn off notes that may extend
1231 beyond the loop end.
1234 _midi_buf->resolve_tracker (dst, 0);
1237 /* for split-cycles we need to offset the events */
1239 if (loc->end() >= effective_start && loc->end() < effective_start + nframes) {
1241 /* end of loop is within the range we are reading, so
1242 split the read in two, and lie about the location
1246 framecnt_t first, second;
1248 first = loc->end() - effective_start;
1249 second = nframes - first;
1251 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read for eff %1 end %2: %3 and %4, cycle offset %5\n",
1252 effective_start, loc->end(), first, second));
1255 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read #1, from %1 for %2\n",
1256 effective_start, first));
1257 events_read = _midi_buf->read (dst, effective_start, first);
1261 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read #2, from %1 for %2\n",
1262 loc->start(), second));
1263 events_read += _midi_buf->read (dst, loc->start(), second);
1267 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read #3, adjusted start as %1 for %2\n",
1268 effective_start, nframes));
1269 events_read = _midi_buf->read (dst, effective_start, effective_start + nframes);
1272 const size_t n_skipped = _midi_buf->skip_to (playback_sample);
1273 if (n_skipped > 0) {
1274 warning << string_compose(_("MidiDiskstream %1: skipped %2 events, possible underflow"), id(), n_skipped) << endmsg;
1276 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("playback buffer read, from %1 to %2 (%3)", playback_sample, playback_sample + nframes, nframes));
1277 events_read = _midi_buf->read (dst, playback_sample, playback_sample + nframes);
1280 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose (
1281 "%1 MDS events read %2 range %3 .. %4 rspace %5 wspace %6 r@%7 w@%8\n",
1282 _name, events_read, playback_sample, playback_sample + nframes,
1283 _midi_buf->read_space(), _midi_buf->write_space(),
1284 _midi_buf->get_read_ptr(), _midi_buf->get_write_ptr()));
1286 g_atomic_int_add (&_frames_read_from_ringbuffer, nframes);
1288 //cerr << "======== POST ========\n";
1289 //_midi_buf->dump (cerr);
1290 //cerr << "----------------\n";
1293 /** @a start is set to the new frame position (TIME) read up to */
1295 DiskReader::midi_read (framepos_t& start, framecnt_t dur, bool reversed)
1297 framecnt_t this_read = 0;
1298 framepos_t loop_end = 0;
1299 framepos_t loop_start = 0;
1300 framecnt_t loop_length = 0;
1301 Location* loc = loop_location;
1302 framepos_t effective_start = start;
1303 Evoral::Range<framepos_t>* loop_range (0);
1305 // MidiTrack* mt = dynamic_cast<MidiTrack*>(_track);
1306 // MidiChannelFilter* filter = mt ? &mt->playback_filter() : 0;
1307 MidiChannelFilter* filter = 0;
1309 frameoffset_t loop_offset = 0;
1311 if (!reversed && loc) {
1312 get_location_times (loc, &loop_start, &loop_end, &loop_length);
1317 /* take any loop into account. we can't read past the end of the loop. */
1319 if (loc && !reversed) {
1322 loop_range = new Evoral::Range<framepos_t> (loop_start, loop_end-1); // inclusive semantics require -1
1325 /* if we are (seamlessly) looping, ensure that the first frame we read is at the correct
1326 position within the loop.
1329 effective_start = loop_range->squish (effective_start);
1331 if ((loop_end - effective_start) <= dur) {
1332 /* too close to end of loop to read "dur", so
1335 this_read = loop_end - effective_start;
1344 if (this_read == 0) {
1348 this_read = min (dur,this_read);
1350 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("MDS ::read at %1 for %2 loffset %3\n", effective_start, this_read, loop_offset));
1352 if (midi_playlist()->read (*_midi_buf, effective_start, this_read, loop_range, 0, filter) != this_read) {
1353 error << string_compose(
1354 _("MidiDiskstream %1: cannot read %2 from playlist at frame %3"),
1355 id(), this_read, start) << endmsg;
1359 g_atomic_int_add (&_frames_written_to_ringbuffer, this_read);
1363 // Swap note ons with note offs here. etc?
1364 // Fully reversing MIDI requires look-ahead (well, behind) to find previous
1365 // CC values etc. hard.
1369 /* adjust passed-by-reference argument (note: this is
1370 monotonic and does not reflect looping.
1374 /* similarly adjust effective_start, but this may be
1375 readjusted for seamless looping as we continue around
1378 effective_start += this_read;
1382 //offset += this_read;
1389 DiskReader::refill_midi ()
1392 size_t write_space = _midi_buf->write_space();
1393 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1395 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("MDS refill, write space = %1 file frame = %2\n",
1396 write_space, file_frame));
1398 /* no space to write */
1399 if (write_space == 0) {
1407 /* at end: nothing to do */
1408 if (file_frame == max_framepos) {
1412 uint32_t frames_read = g_atomic_int_get (&_frames_read_from_ringbuffer);
1413 uint32_t frames_written = g_atomic_int_get (&_frames_written_to_ringbuffer);
1415 if ((frames_read < frames_written) && (frames_written - frames_read) >= midi_readahead) {
1419 framecnt_t to_read = midi_readahead - ((framecnt_t)frames_written - (framecnt_t)frames_read);
1421 to_read = min (to_read, (framecnt_t) (max_framepos - file_frame));
1422 to_read = min (to_read, (framecnt_t) write_space);
1424 if (midi_read (file_frame, to_read, reversed)) {