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.
20 #include "pbd/enumwriter.h"
22 #include "pbd/memento_command.h"
24 #include "ardour/audioengine.h"
25 #include "ardour/audioplaylist.h"
26 #include "ardour/audio_buffer.h"
27 #include "ardour/butler.h"
28 #include "ardour/debug.h"
29 #include "ardour/disk_reader.h"
30 #include "ardour/midi_ring_buffer.h"
31 #include "ardour/midi_playlist.h"
32 #include "ardour/pannable.h"
33 #include "ardour/playlist.h"
34 #include "ardour/playlist_factory.h"
35 #include "ardour/session.h"
36 #include "ardour/session_playlists.h"
38 using namespace ARDOUR;
42 ARDOUR::framecnt_t DiskReader::_chunk_frames = default_chunk_frames ();
43 PBD::Signal0<void> DiskReader::Underrun;
44 Sample* DiskReader::_mixdown_buffer = 0;
45 gain_t* DiskReader::_gain_buffer = 0;
46 framecnt_t DiskReader::midi_readahead = 4096;
48 DiskReader::DiskReader (Session& s, string const & str, DiskIOProcessor::Flag f)
49 : DiskIOProcessor (s, str, f)
52 , overwrite_offset (0)
53 , _pending_overwrite (false)
54 , overwrite_queued (false)
55 , _gui_feed_buffer (AudioEngine::instance()->raw_buffer_size (DataType::MIDI))
59 DiskReader::~DiskReader ()
61 DEBUG_TRACE (DEBUG::Destruction, string_compose ("DiskReader %1 @ %2 deleted\n", _name, this));
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)
115 string my_name = X_("playback:");
118 if (_name != my_name) {
119 SessionObject::set_name (my_name);
126 DiskReader::set_roll_delay (ARDOUR::framecnt_t nframes)
128 _roll_delay = nframes;
132 DiskReader::state (bool full)
134 XMLNode& node (DiskIOProcessor::state (full));
135 node.set_property(X_("type"), X_("diskreader"));
140 DiskReader::set_state (const XMLNode& node, int version)
142 if (DiskIOProcessor::set_state (node, version)) {
150 DiskReader::realtime_handle_transport_stopped ()
152 realtime_speed_change ();
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 (_route);
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 || _session.loading())) {
228 _session.request_overwrite_buffer (_route);
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 frameoffset_t playback_distance;
243 MonitorState ms = _route->monitoring_state ();
246 if (!_pending_active) {
251 if (_pending_active) {
258 _need_butler = false;
260 if (speed == 0.0 && (ms == MonitoringDisk)) {
261 /* stopped. Don't accidentally pass any data from disk
262 * into our outputs (e.g. via interpolation)
264 bufs.silence (nframes, 0);
268 if (speed != 1.0f && speed != -1.0f) {
269 interpolation.set_speed (speed);
270 midi_interpolation.set_speed (speed);
271 playback_distance = midi_interpolation.distance (nframes);
273 playback_distance = -playback_distance;
276 playback_distance = nframes;
279 BufferSet& scratch_bufs (_session.get_scratch_buffers (bufs.count()));
280 const bool still_locating = _session.global_locate_pending();
282 if (!result_required || ((ms & MonitoringDisk) == 0) || still_locating) {
284 /* no need for actual disk data, just advance read pointer and return */
286 if (!still_locating) {
287 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
288 (*chan)->buf->increment_read_ptr (playback_distance);
292 /* if monitoring disk but locating, put silence in the buffers */
294 if (still_locating && (ms == MonitoringDisk)) {
295 bufs.silence (playback_distance, 0);
300 /* we need audio data from disk */
302 size_t n_buffers = bufs.count().n_audio();
303 size_t n_chans = c->size();
306 if (n_chans > n_buffers) {
307 scaling = ((float) n_buffers)/n_chans;
312 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
314 ChannelInfo* chaninfo (*chan);
315 AudioBuffer& output (bufs.get_audio (n%n_buffers));
316 Sample* disk_signal = 0; /* assignment not really needed but it keeps the compiler quiet and helps track bugs */
318 if (ms & MonitoringInput) {
319 /* put disk stream in scratch buffer, blend at end */
320 disk_signal = scratch_bufs.get_audio(n).data ();
322 /* no input stream needed, just overwrite buffers */
323 disk_signal = output.data ();
326 chaninfo->buf->get_read_vector (&(*chan)->rw_vector);
328 if (playback_distance <= (framecnt_t) chaninfo->rw_vector.len[0]) {
330 if (fabsf (speed) != 1.0f) {
331 (void) interpolation.interpolate (
333 chaninfo->rw_vector.buf[0],
335 } else if (speed != 0.0) {
336 memcpy (disk_signal, chaninfo->rw_vector.buf[0], sizeof (Sample) * playback_distance);
341 const framecnt_t total = chaninfo->rw_vector.len[0] + chaninfo->rw_vector.len[1];
343 if (playback_distance <= total) {
345 /* We have enough samples, but not in one lump.
348 if (fabsf (speed) != 1.0f) {
349 interpolation.interpolate (n, chaninfo->rw_vector.len[0],
350 chaninfo->rw_vector.buf[0],
352 disk_signal += chaninfo->rw_vector.len[0];
353 interpolation.interpolate (n, playback_distance - chaninfo->rw_vector.len[0],
354 chaninfo->rw_vector.buf[1],
356 } else if (speed != 0.0) {
358 chaninfo->rw_vector.buf[0],
359 chaninfo->rw_vector.len[0] * sizeof (Sample));
360 memcpy (disk_signal + chaninfo->rw_vector.len[0],
361 chaninfo->rw_vector.buf[1],
362 (playback_distance - chaninfo->rw_vector.len[0]) * sizeof (Sample));
367 cerr << _name << " Need " << playback_distance << " total = " << total << endl;
368 cerr << "underrun for " << _name << endl;
369 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 underrun in %2, total space = %3\n",
370 DEBUG_THREAD_SELF, name(), total));
377 if (scaling != 1.0f && speed != 0.0) {
378 apply_gain_to_buffer (disk_signal, nframes, scaling);
381 chaninfo->buf->increment_read_ptr (playback_distance);
383 if ((speed != 0.0) && (ms & MonitoringInput)) {
384 /* mix the disk signal into the input signal (already in bufs) */
385 mix_buffers_no_gain (output.data(), disk_signal, speed == 0.0 ? nframes : playback_distance);
390 /* MIDI data handling */
392 if (!_session.declick_out_pending()) {
393 if (ms & MonitoringDisk && !still_locating) {
394 get_midi_playback (bufs.get_midi (0), playback_distance, ms, scratch_bufs, speed, playback_distance);
398 if (!still_locating) {
401 playback_sample -= playback_distance;
403 playback_sample += playback_distance;
406 if (_playlists[DataType::AUDIO]) {
409 if (c->front()->buf->write_space() >= c->front()->buf->bufsize() / 2) {
410 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1: slaved, write space = %2 of %3\n", name(), c->front()->buf->write_space(),
411 c->front()->buf->bufsize()));
415 if ((framecnt_t) c->front()->buf->write_space() >= _chunk_frames) {
416 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1: write space = %2 of %3\n", name(), c->front()->buf->write_space(),
424 if (_playlists[DataType::MIDI]) {
425 /* MIDI butler needed part */
427 uint32_t frames_read = g_atomic_int_get(const_cast<gint*>(&_frames_read_from_ringbuffer));
428 uint32_t frames_written = g_atomic_int_get(const_cast<gint*>(&_frames_written_to_ringbuffer));
431 cerr << name() << " MDS written: " << frames_written << " - read: " << frames_read <<
432 " = " << frames_written - frames_read
433 << " + " << playback_distance << " < " << midi_readahead << " = " << need_butler << ")" << endl;
436 /* frames_read will generally be less than frames_written, but
437 * immediately after an overwrite, we can end up having read some data
438 * before we've written any. we don't need to trip an assert() on this,
439 * but we do need to check so that the decision on whether or not we
440 * need the butler is done correctly.
445 * Doing heavy GUI operations[1] can stall also the butler.
446 * The RT-thread meanwhile will happily continue and
447 * ‘frames_read’ (from buffer to output) will become larger
448 * than ‘frames_written’ (from disk to buffer).
450 * The disk-stream is now behind..
452 * In those cases the butler needs to be summed to refill the buffer (done now)
453 * AND we need to skip (frames_read - frames_written). ie remove old events
454 * before playback_sample from the rinbuffer.
456 * [1] one way to do so is described at #6170.
457 * For me just popping up the context-menu on a MIDI-track header
458 * of a track with a large (think beethoven :) midi-region also did the
459 * trick. The playhead stalls for 2 or 3 sec, until the context-menu shows.
461 * In both cases the root cause is that redrawing MIDI regions on the GUI is still very slow
464 if (frames_read <= frames_written) {
465 if ((frames_written - frames_read) + playback_distance < midi_readahead) {
475 // DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 reader run, needs butler = %2\n", name(), _need_butler));
479 DiskReader::set_pending_overwrite (bool yn)
481 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
483 _pending_overwrite = yn;
485 overwrite_frame = playback_sample;
487 boost::shared_ptr<ChannelList> c = channels.reader ();
489 overwrite_offset = c->front()->buf->get_read_ptr();
494 DiskReader::overwrite_existing_buffers ()
498 boost::shared_ptr<ChannelList> c = channels.reader();
500 overwrite_queued = false;
502 DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1 overwriting existing buffers at %2\n", overwrite_frame));
508 const bool reversed = _session.transport_speed() < 0.0f;
510 /* assume all are the same size */
511 framecnt_t size = c->front()->buf->bufsize();
513 std::auto_ptr<Sample> mixdown_buffer (new Sample[size]);
514 std::auto_ptr<float> gain_buffer (new float[size]);
516 /* reduce size so that we can fill the buffer correctly (ringbuffers
517 can only handle size-1, otherwise they appear to be empty)
524 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
526 start = overwrite_frame;
527 framecnt_t cnt = size;
529 /* to fill the buffer without resetting the playback sample, we need to
530 do it one or two chunks (normally two).
532 |----------------------------------------------------------------------|
536 |<- second chunk->||<----------------- first chunk ------------------>|
540 framecnt_t to_read = size - overwrite_offset;
542 if (audio_read ((*chan)->buf->buffer() + overwrite_offset, mixdown_buffer.get(), gain_buffer.get(), start, to_read, n, reversed)) {
543 error << string_compose(_("DiskReader %1: when refilling, cannot read %2 from playlist at frame %3"),
544 id(), size, playback_sample) << endmsg;
552 if (audio_read ((*chan)->buf->buffer(), mixdown_buffer.get(), gain_buffer.get(), start, cnt, n, reversed)) {
553 error << string_compose(_("DiskReader %1: when refilling, cannot read %2 from playlist at frame %3"),
554 id(), size, playback_sample) << endmsg;
566 if (_midi_buf && _playlists[DataType::MIDI]) {
568 /* Clear the playback buffer contents. This is safe as long as the butler
569 thread is suspended, which it should be.
572 _midi_buf->reset_tracker ();
574 g_atomic_int_set (&_frames_read_from_ringbuffer, 0);
575 g_atomic_int_set (&_frames_written_to_ringbuffer, 0);
577 /* Resolve all currently active notes in the playlist. This is more
578 aggressive than it needs to be: ideally we would only resolve what is
579 absolutely necessary, but this seems difficult and/or impossible without
580 having the old data or knowing what change caused the overwrite.
582 midi_playlist()->resolve_note_trackers (*_midi_buf, overwrite_frame);
584 midi_read (overwrite_frame, _chunk_frames, false);
586 file_frame = overwrite_frame; // it was adjusted by ::midi_read()
589 _pending_overwrite = false;
595 DiskReader::seek (framepos_t frame, bool complete_refill)
599 ChannelList::iterator chan;
600 boost::shared_ptr<ChannelList> c = channels.reader();
602 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
603 (*chan)->buf->reset ();
606 if (g_atomic_int_get (&_frames_read_from_ringbuffer) == 0) {
607 /* we haven't read anything since the last seek,
608 so flush all note trackers to prevent
615 g_atomic_int_set(&_frames_read_from_ringbuffer, 0);
616 g_atomic_int_set(&_frames_written_to_ringbuffer, 0);
618 playback_sample = frame;
621 if (complete_refill) {
622 /* call _do_refill() to refill the entire buffer, using
623 the largest reads possible.
625 while ((ret = do_refill_with_alloc (false)) > 0) ;
627 /* call _do_refill() to refill just one chunk, and then
630 ret = do_refill_with_alloc (true);
638 DiskReader::can_internal_playback_seek (framecnt_t distance)
642 ChannelList::iterator chan;
643 boost::shared_ptr<ChannelList> c = channels.reader();
645 for (chan = c->begin(); chan != c->end(); ++chan) {
646 if ((*chan)->buf->read_space() < (size_t) distance) {
653 uint32_t frames_read = g_atomic_int_get(&_frames_read_from_ringbuffer);
654 uint32_t frames_written = g_atomic_int_get(&_frames_written_to_ringbuffer);
656 return ((frames_written - frames_read) < distance);
660 DiskReader::internal_playback_seek (framecnt_t distance)
662 ChannelList::iterator chan;
663 boost::shared_ptr<ChannelList> c = channels.reader();
665 for (chan = c->begin(); chan != c->end(); ++chan) {
666 (*chan)->buf->increment_read_ptr (::llabs(distance));
669 playback_sample += distance;
675 void swap_by_ptr (Sample *first, Sample *last)
677 while (first < last) {
684 /** Read some data for 1 channel from our playlist into a buffer.
685 * @param buf Buffer to write to.
686 * @param start Session frame to start reading from; updated to where we end up
688 * @param cnt Count of samples to read.
689 * @param reversed true if we are running backwards, otherwise false.
692 DiskReader::audio_read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer,
693 framepos_t& start, framecnt_t cnt,
694 int channel, bool reversed)
696 framecnt_t this_read = 0;
698 framepos_t loop_end = 0;
699 framepos_t loop_start = 0;
700 framecnt_t offset = 0;
703 if (!_playlists[DataType::AUDIO]) {
704 memset (buf, 0, sizeof (Sample) * cnt);
708 /* XXX we don't currently play loops in reverse. not sure why */
712 framecnt_t loop_length = 0;
714 /* Make the use of a Location atomic for this read operation.
716 Note: Locations don't get deleted, so all we care about
717 when I say "atomic" is that we are always pointing to
718 the same one and using a start/length values obtained
722 if ((loc = loop_location) != 0) {
723 loop_start = loc->start();
724 loop_end = loc->end();
725 loop_length = loop_end - loop_start;
728 /* if we are looping, ensure that the first frame we read is at the correct
729 position within the loop.
732 if (loc && start >= loop_end) {
733 start = loop_start + ((start - loop_start) % loop_length);
742 /* We need this while loop in case we hit a loop boundary, in which case our read from
743 the playlist must be split into more than one section.
748 /* take any loop into account. we can't read past the end of the loop. */
750 if (loc && (loop_end - start < cnt)) {
751 this_read = loop_end - start;
758 if (this_read == 0) {
762 this_read = min(cnt,this_read);
764 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
765 error << string_compose(_("DiskReader %1: cannot read %2 from playlist at frame %3"), id(), this_read,
772 swap_by_ptr (buf, buf + this_read - 1);
776 /* if we read to the end of the loop, go back to the beginning */
793 DiskReader::_do_refill_with_alloc (bool partial_fill)
795 /* We limit disk reads to at most 4MB chunks, which with floating point
796 samples would be 1M samples. But we might use 16 or 14 bit samples,
797 in which case 4MB is more samples than that. Therefore size this for
798 the smallest sample value .. 4MB = 2M samples (16 bit).
802 std::auto_ptr<Sample> mix_buf (new Sample[2*1048576]);
803 std::auto_ptr<float> gain_buf (new float[2*1048576]);
805 int ret = refill_audio (mix_buf.get(), gain_buf.get(), (partial_fill ? _chunk_frames : 0));
812 return refill_midi ();
816 DiskReader::refill (Sample* mixdown_buffer, float* gain_buffer, framecnt_t fill_level)
818 int ret = refill_audio (mixdown_buffer, gain_buffer, fill_level);
824 return refill_midi ();
828 /** Get some more data from disk and put it in our channels' bufs,
829 * if there is suitable space in them.
831 * If fill_level is non-zero, then we will refill the buffer so that there is
832 * still at least fill_level samples of space left to be filled. This is used
833 * after locates so that we do not need to wait to fill the entire buffer.
838 DiskReader::refill_audio (Sample* mixdown_buffer, float* gain_buffer, framecnt_t fill_level)
840 /* do not read from disk while session is marked as Loading, to avoid
841 useless redundant I/O.
844 if (_session.loading()) {
850 RingBufferNPT<Sample>::rw_vector vector;
851 bool const reversed = _session.transport_speed() < 0.0f;
852 framecnt_t total_space;
853 framecnt_t zero_fill;
855 ChannelList::iterator i;
856 boost::shared_ptr<ChannelList> c = channels.reader();
863 assert(mixdown_buffer);
871 c->front()->buf->get_write_vector (&vector);
873 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
874 DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1: no space to refill\n", name()));
875 /* nowhere to write to */
880 if (fill_level < total_space) {
881 total_space -= fill_level;
883 /* we can't do anything with it */
888 /* if we're running close to normal speed and there isn't enough
889 space to do disk_read_chunk_frames of I/O, then don't bother.
891 at higher speeds, just do it because the sync between butler
892 and audio thread may not be good enough.
894 Note: it is a design assumption that disk_read_chunk_frames is smaller
895 than the playback buffer size, so this check should never trip when
896 the playback buffer is empty.
899 DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1: space to refill %2 vs. chunk %3 (speed = %4)\n", name(), total_space, _chunk_frames, _session.transport_speed()));
900 if ((total_space < _chunk_frames) && fabs (_session.transport_speed()) < 2.0f) {
904 /* when slaved, don't try to get too close to the read pointer. this
905 leaves space for the buffer reversal to have something useful to
909 if (_slaved && total_space < (framecnt_t) (c->front()->buf->bufsize() / 2)) {
910 DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1: not enough to refill while slaved\n", this));
916 if (file_frame == 0) {
918 /* at start: nothing to do but fill with silence */
920 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
922 ChannelInfo* chan (*i);
923 chan->buf->get_write_vector (&vector);
924 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
926 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
928 chan->buf->increment_write_ptr (vector.len[0] + vector.len[1]);
933 if (file_frame < total_space) {
935 /* too close to the start: read what we can,
936 and then zero fill the rest
939 zero_fill = total_space - file_frame;
940 total_space = file_frame;
949 if (file_frame == max_framepos) {
951 /* at end: nothing to do but fill with silence */
953 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
955 ChannelInfo* chan (*i);
956 chan->buf->get_write_vector (&vector);
957 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
959 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
961 chan->buf->increment_write_ptr (vector.len[0] + vector.len[1]);
966 if (file_frame > max_framepos - total_space) {
968 /* to close to the end: read what we can, and zero fill the rest */
970 zero_fill = total_space - (max_framepos - file_frame);
971 total_space = max_framepos - file_frame;
978 framepos_t file_frame_tmp = 0;
980 /* total_space is in samples. We want to optimize read sizes in various sizes using bytes */
982 const size_t bits_per_sample = format_data_width (_session.config.get_native_file_data_format());
983 size_t total_bytes = total_space * bits_per_sample / 8;
985 /* chunk size range is 256kB to 4MB. Bigger is faster in terms of MB/sec, but bigger chunk size always takes longer
987 size_t byte_size_for_read = max ((size_t) (256 * 1024), min ((size_t) (4 * 1048576), total_bytes));
989 /* find nearest (lower) multiple of 16384 */
991 byte_size_for_read = (byte_size_for_read / 16384) * 16384;
993 /* now back to samples */
995 framecnt_t samples_to_read = byte_size_for_read / (bits_per_sample / 8);
997 DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1: will refill %2 channels with %3 samples\n", name(), c->size(), total_space));
999 // uint64_t before = g_get_monotonic_time ();
1000 // uint64_t elapsed;
1002 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1004 ChannelInfo* chan (*i);
1007 framecnt_t len1, len2;
1009 chan->buf->get_write_vector (&vector);
1011 if ((framecnt_t) vector.len[0] > samples_to_read) {
1013 /* we're not going to fill the first chunk, so certainly do not bother with the
1014 other part. it won't be connected with the part we do fill, as in:
1016 .... => writable space
1017 ++++ => readable space
1018 ^^^^ => 1 x disk_read_chunk_frames that would be filled
1020 |......|+++++++++++++|...............................|
1025 So, just pretend that the buf1 part isn't there.
1035 file_frame_tmp = file_frame;
1037 buf1 = vector.buf[0];
1038 len1 = vector.len[0];
1039 buf2 = vector.buf[1];
1040 len2 = vector.len[1];
1042 to_read = min (ts, len1);
1043 to_read = min (to_read, (framecnt_t) samples_to_read);
1045 assert (to_read >= 0);
1049 if (audio_read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1054 chan->buf->increment_write_ptr (to_read);
1058 to_read = min (ts, len2);
1062 /* we read all of vector.len[0], but it wasn't the
1063 entire samples_to_read of data, so read some or
1064 all of vector.len[1] as well.
1067 if (audio_read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1072 chan->buf->increment_write_ptr (to_read);
1076 /* XXX: do something */
1081 // elapsed = g_get_monotonic_time () - before;
1082 // cerr << '\t' << name() << ": bandwidth = " << (byte_size_for_read / 1048576.0) / (elapsed/1000000.0) << "MB/sec\n";
1084 file_frame = file_frame_tmp;
1085 assert (file_frame >= 0);
1087 ret = ((total_space - samples_to_read) > _chunk_frames);
1089 c->front()->buf->get_write_vector (&vector);
1096 DiskReader::playlist_ranges_moved (list< Evoral::RangeMove<framepos_t> > const & movements_frames, bool from_undo)
1098 /* If we're coming from an undo, it will have handled
1099 automation undo (it must, since automation-follows-regions
1100 can lose automation data). Hence we can do nothing here.
1107 if (!_route || Config->get_automation_follows_regions () == false) {
1111 list< Evoral::RangeMove<double> > movements;
1113 for (list< Evoral::RangeMove<framepos_t> >::const_iterator i = movements_frames.begin();
1114 i != movements_frames.end();
1117 movements.push_back(Evoral::RangeMove<double>(i->from, i->length, i->to));
1120 /* move panner automation */
1121 boost::shared_ptr<Pannable> pannable = _route->pannable();
1122 Evoral::ControlSet::Controls& c (pannable->controls());
1124 for (Evoral::ControlSet::Controls::iterator ci = c.begin(); ci != c.end(); ++ci) {
1125 boost::shared_ptr<AutomationControl> ac = boost::dynamic_pointer_cast<AutomationControl>(ci->second);
1129 boost::shared_ptr<AutomationList> alist = ac->alist();
1130 if (!alist->size()) {
1133 XMLNode & before = alist->get_state ();
1134 bool const things_moved = alist->move_ranges (movements);
1136 _session.add_command (new MementoCommand<AutomationList> (
1137 *alist.get(), &before, &alist->get_state ()));
1140 /* move processor automation */
1141 _route->foreach_processor (boost::bind (&DiskReader::move_processor_automation, this, _1, movements_frames));
1145 DiskReader::move_processor_automation (boost::weak_ptr<Processor> p, list< Evoral::RangeMove<framepos_t> > const & movements_frames)
1147 boost::shared_ptr<Processor> processor (p.lock ());
1152 list< Evoral::RangeMove<double> > movements;
1153 for (list< Evoral::RangeMove<framepos_t> >::const_iterator i = movements_frames.begin(); i != movements_frames.end(); ++i) {
1154 movements.push_back(Evoral::RangeMove<double>(i->from, i->length, i->to));
1157 set<Evoral::Parameter> const a = processor->what_can_be_automated ();
1159 for (set<Evoral::Parameter>::const_iterator i = a.begin (); i != a.end (); ++i) {
1160 boost::shared_ptr<AutomationList> al = processor->automation_control(*i)->alist();
1164 XMLNode & before = al->get_state ();
1165 bool const things_moved = al->move_ranges (movements);
1167 _session.add_command (
1168 new MementoCommand<AutomationList> (
1169 *al.get(), &before, &al->get_state ()
1176 boost::shared_ptr<MidiBuffer>
1177 DiskReader::get_gui_feed_buffer () const
1179 boost::shared_ptr<MidiBuffer> b (new MidiBuffer (AudioEngine::instance()->raw_buffer_size (DataType::MIDI)));
1181 Glib::Threads::Mutex::Lock lm (_gui_feed_buffer_mutex);
1182 b->copy (_gui_feed_buffer);
1187 DiskReader::reset_tracker ()
1189 _midi_buf->reset_tracker ();
1191 boost::shared_ptr<MidiPlaylist> mp (midi_playlist());
1194 mp->reset_note_trackers ();
1199 DiskReader::resolve_tracker (Evoral::EventSink<framepos_t>& buffer, framepos_t time)
1201 _midi_buf->resolve_tracker(buffer, time);
1203 boost::shared_ptr<MidiPlaylist> mp (midi_playlist());
1206 mp->reset_note_trackers ();
1210 /** Writes playback events from playback_sample for nframes to dst, translating time stamps
1211 * so that an event at playback_sample has time = 0
1214 DiskReader::get_midi_playback (MidiBuffer& dst, framecnt_t nframes, MonitorState ms, BufferSet& scratch_bufs, double speed, framecnt_t playback_distance)
1218 if ((ms & MonitoringInput) == 0) {
1222 target = &scratch_bufs.get_midi (0);
1225 if (ms & MonitoringDisk) {
1226 /* no disk data needed */
1228 Location* loc = loop_location;
1230 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose (
1231 "%1 MDS pre-read read %8 offset = %9 @ %4..%5 from %2 write to %3, LOOPED ? %6 .. %7\n", _name,
1232 _midi_buf->get_read_ptr(), _midi_buf->get_write_ptr(), playback_sample, playback_sample + nframes,
1233 (loc ? loc->start() : -1), (loc ? loc->end() : -1), nframes, Port::port_offset()));
1235 //cerr << "======== PRE ========\n";
1236 //_midi_buf->dump (cerr);
1237 //cerr << "----------------\n";
1239 size_t events_read = 0;
1242 framepos_t effective_start;
1244 Evoral::Range<framepos_t> loop_range (loc->start(), loc->end() - 1);
1245 effective_start = loop_range.squish (playback_sample);
1247 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("looped, effective start adjusted to %1\n", effective_start));
1249 if (effective_start == loc->start()) {
1250 /* We need to turn off notes that may extend
1251 beyond the loop end.
1254 _midi_buf->resolve_tracker (*target, 0);
1257 /* for split-cycles we need to offset the events */
1259 if (loc->end() >= effective_start && loc->end() < effective_start + nframes) {
1261 /* end of loop is within the range we are reading, so
1262 split the read in two, and lie about the location
1266 framecnt_t first, second;
1268 first = loc->end() - effective_start;
1269 second = nframes - first;
1271 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read for eff %1 end %2: %3 and %4, cycle offset %5\n",
1272 effective_start, loc->end(), first, second));
1275 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read #1, from %1 for %2\n",
1276 effective_start, first));
1277 events_read = _midi_buf->read (*target, effective_start, first);
1281 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read #2, from %1 for %2\n",
1282 loc->start(), second));
1283 events_read += _midi_buf->read (*target, loc->start(), second);
1287 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read #3, adjusted start as %1 for %2\n",
1288 effective_start, nframes));
1289 events_read = _midi_buf->read (*target, effective_start, effective_start + nframes);
1292 const size_t n_skipped = _midi_buf->skip_to (playback_sample);
1293 if (n_skipped > 0) {
1294 warning << string_compose(_("MidiDiskstream %1: skipped %2 events, possible underflow"), id(), n_skipped) << endmsg;
1296 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("playback buffer read, from %1 to %2 (%3)", playback_sample, playback_sample + nframes, nframes));
1297 events_read = _midi_buf->read (*target, playback_sample, playback_sample + nframes);
1300 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose (
1301 "%1 MDS events read %2 range %3 .. %4 rspace %5 wspace %6 r@%7 w@%8\n",
1302 _name, events_read, playback_sample, playback_sample + nframes,
1303 _midi_buf->read_space(), _midi_buf->write_space(),
1304 _midi_buf->get_read_ptr(), _midi_buf->get_write_ptr()));
1307 g_atomic_int_add (&_frames_read_from_ringbuffer, nframes);
1311 if (speed != 0.0 && fabsf (speed) != 1.0f) {
1312 for (MidiBuffer::iterator i = target->begin(); i != target->end(); ++i) {
1313 MidiBuffer::TimeType *tme = i.timeptr();
1314 *tme = (*tme) * nframes / playback_distance;
1318 if (ms & MonitoringInput) {
1319 dst.merge_from (*target, nframes);
1322 //cerr << "======== POST ========\n";
1323 //_midi_buf->dump (cerr);
1324 //cerr << "----------------\n";
1327 /** @a start is set to the new frame position (TIME) read up to */
1329 DiskReader::midi_read (framepos_t& start, framecnt_t dur, bool reversed)
1331 framecnt_t this_read = 0;
1332 framepos_t loop_end = 0;
1333 framepos_t loop_start = 0;
1334 framecnt_t loop_length = 0;
1335 Location* loc = loop_location;
1336 framepos_t effective_start = start;
1337 Evoral::Range<framepos_t>* loop_range (0);
1339 // MidiTrack* mt = dynamic_cast<MidiTrack*>(_track);
1340 // MidiChannelFilter* filter = mt ? &mt->playback_filter() : 0;
1341 MidiChannelFilter* filter = 0;
1343 frameoffset_t loop_offset = 0;
1345 if (!reversed && loc) {
1346 get_location_times (loc, &loop_start, &loop_end, &loop_length);
1351 /* take any loop into account. we can't read past the end of the loop. */
1353 if (loc && !reversed) {
1356 loop_range = new Evoral::Range<framepos_t> (loop_start, loop_end-1); // inclusive semantics require -1
1359 /* if we are (seamlessly) looping, ensure that the first frame we read is at the correct
1360 position within the loop.
1363 effective_start = loop_range->squish (effective_start);
1365 if ((loop_end - effective_start) <= dur) {
1366 /* too close to end of loop to read "dur", so
1369 this_read = loop_end - effective_start;
1378 if (this_read == 0) {
1382 this_read = min (dur,this_read);
1384 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("MDS ::read at %1 for %2 loffset %3\n", effective_start, this_read, loop_offset));
1386 if (midi_playlist()->read (*_midi_buf, effective_start, this_read, loop_range, 0, filter) != this_read) {
1387 error << string_compose(
1388 _("MidiDiskstream %1: cannot read %2 from playlist at frame %3"),
1389 id(), this_read, start) << endmsg;
1393 g_atomic_int_add (&_frames_written_to_ringbuffer, this_read);
1397 // Swap note ons with note offs here. etc?
1398 // Fully reversing MIDI requires look-ahead (well, behind) to find previous
1399 // CC values etc. hard.
1403 /* adjust passed-by-reference argument (note: this is
1404 monotonic and does not reflect looping.
1408 /* similarly adjust effective_start, but this may be
1409 readjusted for seamless looping as we continue around
1412 effective_start += this_read;
1416 //offset += this_read;
1423 DiskReader::refill_midi ()
1425 if (!_playlists[DataType::MIDI]) {
1429 size_t write_space = _midi_buf->write_space();
1430 const bool reversed = _session.transport_speed() < 0.0f;
1432 DEBUG_TRACE (DEBUG::DiskIO, string_compose ("MIDI refill, write space = %1 file frame = %2\n", write_space, file_frame));
1434 /* no space to write */
1435 if (write_space == 0) {
1443 /* at end: nothing to do */
1445 if (file_frame == max_framepos) {
1450 const uint32_t frames_read = g_atomic_int_get (&_frames_read_from_ringbuffer);
1451 const uint32_t frames_written = g_atomic_int_get (&_frames_written_to_ringbuffer);
1453 if ((frames_read < frames_written) && (frames_written - frames_read) >= midi_readahead) {
1457 framecnt_t to_read = midi_readahead - ((framecnt_t)frames_written - (framecnt_t)frames_read);
1459 to_read = min (to_read, (framecnt_t) (max_framepos - file_frame));
1460 to_read = min (to_read, (framecnt_t) write_space);
1462 if (midi_read (file_frame, to_read, reversed)) {