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/midi_track.h"
33 #include "ardour/pannable.h"
34 #include "ardour/playlist.h"
35 #include "ardour/playlist_factory.h"
36 #include "ardour/session.h"
37 #include "ardour/session_playlists.h"
39 using namespace ARDOUR;
43 ARDOUR::framecnt_t DiskReader::_chunk_frames = default_chunk_frames ();
44 PBD::Signal0<void> DiskReader::Underrun;
45 Sample* DiskReader::_mixdown_buffer = 0;
46 gain_t* DiskReader::_gain_buffer = 0;
47 framecnt_t DiskReader::midi_readahead = 4096;
48 bool DiskReader::no_disk_output = false;
50 DiskReader::DiskReader (Session& s, string const & str, DiskIOProcessor::Flag f)
51 : DiskIOProcessor (s, str, f)
54 , overwrite_offset (0)
55 , _pending_overwrite (false)
56 , overwrite_queued (false)
57 , _gui_feed_buffer (AudioEngine::instance()->raw_buffer_size (DataType::MIDI))
59 file_frame[DataType::AUDIO] = 0;
60 file_frame[DataType::MIDI] = 0;
63 DiskReader::~DiskReader ()
65 DEBUG_TRACE (DEBUG::Destruction, string_compose ("DiskReader %1 @ %2 deleted\n", _name, this));
67 for (uint32_t n = 0; n < DataType::num_types; ++n) {
69 _playlists[n]->release ();
74 RCUWriter<ChannelList> writer (channels);
75 boost::shared_ptr<ChannelList> c = writer.get_copy();
77 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
90 DiskReader::allocate_working_buffers()
92 /* with varifill buffer refilling, we compute the read size in bytes (to optimize
93 for disk i/o bandwidth) and then convert back into samples. These buffers
94 need to reflect the maximum size we could use, which is 4MB reads, or 2M samples
97 _mixdown_buffer = new Sample[2*1048576];
98 _gain_buffer = new gain_t[2*1048576];
102 DiskReader::free_working_buffers()
104 delete [] _mixdown_buffer;
105 delete [] _gain_buffer;
111 DiskReader::default_chunk_frames()
117 DiskReader::set_name (string const & str)
119 string my_name = X_("playback:");
122 if (_name != my_name) {
123 SessionObject::set_name (my_name);
130 DiskReader::set_roll_delay (ARDOUR::framecnt_t nframes)
132 _roll_delay = nframes;
136 DiskReader::state (bool full)
138 XMLNode& node (DiskIOProcessor::state (full));
139 node.set_property(X_("type"), X_("diskreader"));
144 DiskReader::set_state (const XMLNode& node, int version)
146 if (DiskIOProcessor::set_state (node, version)) {
154 DiskReader::realtime_handle_transport_stopped ()
156 realtime_speed_change ();
160 DiskReader::realtime_locate ()
165 DiskReader::buffer_load () const
167 /* Note: for MIDI it's not trivial to differentiate the following two cases:
169 1. The playback buffer is empty because the system has run out of time to fill it.
170 2. The playback buffer is empty because there is no more data on the playlist.
172 If we use a simple buffer load computation, we will report that the MIDI diskstream
173 cannot keep up when #2 happens, when in fact it can. Since MIDI data rates
174 are so low compared to audio, just use the audio value here.
177 boost::shared_ptr<ChannelList> c = channels.reader();
180 /* no channels, so no buffers, so completely full and ready to playback, sir! */
184 PBD::RingBufferNPT<Sample> * b = c->front()->buf;
185 return (float) ((double) b->read_space() / (double) b->bufsize());
189 DiskReader::adjust_buffering ()
191 boost::shared_ptr<ChannelList> c = channels.reader();
193 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
194 (*chan)->resize (_session.butler()->audio_diskstream_playback_buffer_size());
199 DiskReader::playlist_changed (const PropertyChange&)
201 playlist_modified ();
205 DiskReader::playlist_modified ()
207 if (!i_am_the_modifier && !overwrite_queued) {
208 _session.request_overwrite_buffer (_route);
209 overwrite_queued = true;
214 DiskReader::use_playlist (DataType dt, boost::shared_ptr<Playlist> playlist)
216 bool prior_playlist = false;
218 if (_playlists[dt]) {
219 prior_playlist = true;
222 if (DiskIOProcessor::use_playlist (dt, playlist)) {
226 /* don't do this if we've already asked for it *or* if we are setting up
227 the diskstream for the very first time - the input changed handling will
228 take care of the buffer refill.
231 if (!overwrite_queued && (prior_playlist || _session.loading())) {
232 _session.request_overwrite_buffer (_route);
233 overwrite_queued = true;
240 DiskReader::run (BufferSet& bufs, framepos_t start_frame, framepos_t end_frame,
241 double speed, pframes_t nframes, bool result_required)
244 boost::shared_ptr<ChannelList> c = channels.reader();
245 ChannelList::iterator chan;
246 frameoffset_t playback_distance;
247 MonitorState ms = _route->monitoring_state ();
250 if (!_pending_active) {
255 if (_pending_active) {
262 if (speed == 0.0 && (ms == MonitoringDisk)) {
263 /* stopped. Don't accidentally pass any data from disk
264 * into our outputs (e.g. via interpolation)
266 bufs.silence (nframes, 0);
270 if (speed != 1.0f && speed != -1.0f) {
271 interpolation.set_speed (speed);
272 midi_interpolation.set_speed (speed);
273 playback_distance = midi_interpolation.distance (nframes);
275 playback_distance = -playback_distance;
278 playback_distance = nframes;
281 BufferSet& scratch_bufs (_session.get_scratch_buffers (bufs.count()));
282 const bool still_locating = _session.global_locate_pending();
284 if (!result_required || ((ms & MonitoringDisk) == 0) || still_locating) {
286 /* no need for actual disk data, just advance read pointer and return */
288 if (!still_locating) {
289 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
290 (*chan)->buf->increment_read_ptr (playback_distance);
294 /* if monitoring disk but locating put silence in the buffers */
296 if (still_locating && (ms == MonitoringDisk)) {
297 bufs.silence (playback_distance, 0);
302 /* we need audio data from disk */
304 size_t n_buffers = bufs.count().n_audio();
305 size_t n_chans = c->size();
308 if (n_chans > n_buffers) {
309 scaling = ((float) n_buffers)/n_chans;
314 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
316 ChannelInfo* chaninfo (*chan);
317 AudioBuffer& output (bufs.get_audio (n%n_buffers));
318 Sample* disk_signal = 0; /* assignment not really needed but it keeps the compiler quiet and helps track bugs */
320 if (ms & MonitoringInput) {
321 /* put disk stream in scratch buffer, blend at end */
322 disk_signal = scratch_bufs.get_audio(n).data ();
324 /* no input stream needed, just overwrite buffers */
325 disk_signal = output.data ();
328 chaninfo->buf->get_read_vector (&(*chan)->rw_vector);
330 if (playback_distance <= (framecnt_t) chaninfo->rw_vector.len[0]) {
332 if (fabsf (speed) != 1.0f) {
333 (void) interpolation.interpolate (
335 chaninfo->rw_vector.buf[0],
337 } else if (speed != 0.0) {
338 memcpy (disk_signal, chaninfo->rw_vector.buf[0], sizeof (Sample) * playback_distance);
343 const framecnt_t total = chaninfo->rw_vector.len[0] + chaninfo->rw_vector.len[1];
345 if (playback_distance <= total) {
347 /* We have enough samples, but not in one lump.
350 if (fabsf (speed) != 1.0f) {
351 interpolation.interpolate (n, chaninfo->rw_vector.len[0],
352 chaninfo->rw_vector.buf[0],
354 disk_signal += chaninfo->rw_vector.len[0];
355 interpolation.interpolate (n, playback_distance - chaninfo->rw_vector.len[0],
356 chaninfo->rw_vector.buf[1],
358 } else if (speed != 0.0) {
360 chaninfo->rw_vector.buf[0],
361 chaninfo->rw_vector.len[0] * sizeof (Sample));
362 memcpy (disk_signal + chaninfo->rw_vector.len[0],
363 chaninfo->rw_vector.buf[1],
364 (playback_distance - chaninfo->rw_vector.len[0]) * sizeof (Sample));
369 cerr << _name << " Need " << playback_distance << " total = " << total << endl;
370 cerr << "underrun for " << _name << endl;
371 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 underrun in %2, total space = %3\n",
372 DEBUG_THREAD_SELF, name(), total));
379 if (scaling != 1.0f && speed != 0.0) {
380 apply_gain_to_buffer (disk_signal, nframes, scaling);
383 chaninfo->buf->increment_read_ptr (playback_distance);
385 if (!no_disk_output && (speed != 0.0) && (ms & MonitoringInput)) {
386 /* mix the disk signal into the input signal (already in bufs) */
387 mix_buffers_no_gain (output.data(), disk_signal, speed == 0.0 ? nframes : playback_distance);
392 /* MIDI data handling */
394 if (!_session.declick_out_pending()) {
395 if (ms & MonitoringDisk && !still_locating) {
396 get_midi_playback (bufs.get_midi (0), playback_distance, ms, scratch_bufs, speed, playback_distance);
400 if (!still_locating) {
402 bool butler_required = false;
405 playback_sample -= playback_distance;
407 playback_sample += playback_distance;
410 if (_playlists[DataType::AUDIO]) {
413 if (c->front()->buf->write_space() >= c->front()->buf->bufsize() / 2) {
414 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1: slaved, write space = %2 of %3\n", name(), c->front()->buf->write_space(),
415 c->front()->buf->bufsize()));
416 butler_required = true;
419 if ((framecnt_t) c->front()->buf->write_space() >= _chunk_frames) {
420 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1: write space = %2 of %3\n", name(), c->front()->buf->write_space(),
422 butler_required = true;
428 if (_playlists[DataType::MIDI]) {
429 /* MIDI butler needed part */
431 uint32_t frames_read = g_atomic_int_get(const_cast<gint*>(&_frames_read_from_ringbuffer));
432 uint32_t frames_written = g_atomic_int_get(const_cast<gint*>(&_frames_written_to_ringbuffer));
435 cerr << name() << " MDS written: " << frames_written << " - read: " << frames_read <<
436 " = " << frames_written - frames_read
437 << " + " << playback_distance << " < " << midi_readahead << " = " << need_butler << ")" << endl;
440 /* frames_read will generally be less than frames_written, but
441 * immediately after an overwrite, we can end up having read some data
442 * before we've written any. we don't need to trip an assert() on this,
443 * but we do need to check so that the decision on whether or not we
444 * need the butler is done correctly.
449 * Doing heavy GUI operations[1] can stall also the butler.
450 * The RT-thread meanwhile will happily continue and
451 * ‘frames_read’ (from buffer to output) will become larger
452 * than ‘frames_written’ (from disk to buffer).
454 * The disk-stream is now behind..
456 * In those cases the butler needs to be summed to refill the buffer (done now)
457 * AND we need to skip (frames_read - frames_written). ie remove old events
458 * before playback_sample from the rinbuffer.
460 * [1] one way to do so is described at #6170.
461 * For me just popping up the context-menu on a MIDI-track header
462 * of a track with a large (think beethoven :) midi-region also did the
463 * trick. The playhead stalls for 2 or 3 sec, until the context-menu shows.
465 * In both cases the root cause is that redrawing MIDI regions on the GUI is still very slow
468 if (frames_read <= frames_written) {
469 if ((frames_written - frames_read) + playback_distance < midi_readahead) {
470 butler_required = true;
473 butler_required = true;
478 _need_butler = butler_required;
481 // DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 reader run, needs butler = %2\n", name(), _need_butler));
485 DiskReader::set_pending_overwrite (bool yn)
487 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
489 _pending_overwrite = yn;
491 overwrite_frame = playback_sample;
493 boost::shared_ptr<ChannelList> c = channels.reader ();
495 overwrite_offset = c->front()->buf->get_read_ptr();
500 DiskReader::overwrite_existing_buffers ()
504 boost::shared_ptr<ChannelList> c = channels.reader();
506 overwrite_queued = false;
508 DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1 overwriting existing buffers at %2\n", overwrite_frame));
514 const bool reversed = _session.transport_speed() < 0.0f;
516 /* assume all are the same size */
517 framecnt_t size = c->front()->buf->bufsize();
519 std::auto_ptr<Sample> mixdown_buffer (new Sample[size]);
520 std::auto_ptr<float> gain_buffer (new float[size]);
522 /* reduce size so that we can fill the buffer correctly (ringbuffers
523 can only handle size-1, otherwise they appear to be empty)
530 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
532 start = overwrite_frame;
533 framecnt_t cnt = size;
535 /* to fill the buffer without resetting the playback sample, we need to
536 do it one or two chunks (normally two).
538 |----------------------------------------------------------------------|
542 |<- second chunk->||<----------------- first chunk ------------------>|
546 framecnt_t to_read = size - overwrite_offset;
548 if (audio_read ((*chan)->buf->buffer() + overwrite_offset, mixdown_buffer.get(), gain_buffer.get(), start, to_read, n, reversed)) {
549 error << string_compose(_("DiskReader %1: when refilling, cannot read %2 from playlist at frame %3"),
550 id(), size, playback_sample) << endmsg;
558 if (audio_read ((*chan)->buf->buffer(), mixdown_buffer.get(), gain_buffer.get(), start, cnt, n, reversed)) {
559 error << string_compose(_("DiskReader %1: when refilling, cannot read %2 from playlist at frame %3"),
560 id(), size, playback_sample) << endmsg;
572 if (_midi_buf && _playlists[DataType::MIDI]) {
574 /* Clear the playback buffer contents. This is safe as long as the butler
575 thread is suspended, which it should be.
578 _midi_buf->reset_tracker ();
580 g_atomic_int_set (&_frames_read_from_ringbuffer, 0);
581 g_atomic_int_set (&_frames_written_to_ringbuffer, 0);
583 /* Resolve all currently active notes in the playlist. This is more
584 aggressive than it needs to be: ideally we would only resolve what is
585 absolutely necessary, but this seems difficult and/or impossible without
586 having the old data or knowing what change caused the overwrite.
588 midi_playlist()->resolve_note_trackers (*_midi_buf, overwrite_frame);
590 midi_read (overwrite_frame, _chunk_frames, false);
591 file_frame[DataType::MIDI] = overwrite_frame; // overwrite_frame was adjusted by ::midi_read() to the new position
594 _pending_overwrite = false;
600 DiskReader::seek (framepos_t frame, bool complete_refill)
604 ChannelList::iterator chan;
605 boost::shared_ptr<ChannelList> c = channels.reader();
607 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
608 (*chan)->buf->reset ();
611 if (g_atomic_int_get (&_frames_read_from_ringbuffer) == 0) {
612 /* we haven't read anything since the last seek,
613 so flush all note trackers to prevent
620 g_atomic_int_set(&_frames_read_from_ringbuffer, 0);
621 g_atomic_int_set(&_frames_written_to_ringbuffer, 0);
623 playback_sample = frame;
624 file_frame[DataType::AUDIO] = frame;
625 file_frame[DataType::MIDI] = frame;
627 if (complete_refill) {
628 /* call _do_refill() to refill the entire buffer, using
629 the largest reads possible.
631 while ((ret = do_refill_with_alloc (false)) > 0) ;
633 /* call _do_refill() to refill just one chunk, and then
636 ret = do_refill_with_alloc (true);
644 DiskReader::can_internal_playback_seek (framecnt_t distance)
648 ChannelList::iterator chan;
649 boost::shared_ptr<ChannelList> c = channels.reader();
651 for (chan = c->begin(); chan != c->end(); ++chan) {
652 if ((*chan)->buf->read_space() < (size_t) distance) {
659 uint32_t frames_read = g_atomic_int_get(&_frames_read_from_ringbuffer);
660 uint32_t frames_written = g_atomic_int_get(&_frames_written_to_ringbuffer);
662 return ((frames_written - frames_read) < distance);
666 DiskReader::internal_playback_seek (framecnt_t distance)
668 ChannelList::iterator chan;
669 boost::shared_ptr<ChannelList> c = channels.reader();
671 for (chan = c->begin(); chan != c->end(); ++chan) {
672 (*chan)->buf->increment_read_ptr (::llabs(distance));
675 playback_sample += distance;
681 void swap_by_ptr (Sample *first, Sample *last)
683 while (first < last) {
690 /** Read some data for 1 channel from our playlist into a buffer.
691 * @param buf Buffer to write to.
692 * @param start Session frame to start reading from; updated to where we end up
694 * @param cnt Count of samples to read.
695 * @param reversed true if we are running backwards, otherwise false.
698 DiskReader::audio_read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer,
699 framepos_t& start, framecnt_t cnt,
700 int channel, bool reversed)
702 framecnt_t this_read = 0;
704 framepos_t loop_end = 0;
705 framepos_t loop_start = 0;
706 framecnt_t offset = 0;
709 if (!_playlists[DataType::AUDIO]) {
710 memset (buf, 0, sizeof (Sample) * cnt);
714 /* XXX we don't currently play loops in reverse. not sure why */
718 framecnt_t loop_length = 0;
720 /* Make the use of a Location atomic for this read operation.
722 Note: Locations don't get deleted, so all we care about
723 when I say "atomic" is that we are always pointing to
724 the same one and using a start/length values obtained
728 if ((loc = loop_location) != 0) {
729 loop_start = loc->start();
730 loop_end = loc->end();
731 loop_length = loop_end - loop_start;
734 /* if we are looping, ensure that the first frame we read is at the correct
735 position within the loop.
738 if (loc && start >= loop_end) {
739 start = loop_start + ((start - loop_start) % loop_length);
748 /* We need this while loop in case we hit a loop boundary, in which case our read from
749 the playlist must be split into more than one section.
754 /* take any loop into account. we can't read past the end of the loop. */
756 if (loc && (loop_end - start < cnt)) {
757 this_read = loop_end - start;
764 if (this_read == 0) {
768 this_read = min(cnt,this_read);
770 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
771 error << string_compose(_("DiskReader %1: cannot read %2 from playlist at frame %3"), id(), this_read,
778 swap_by_ptr (buf, buf + this_read - 1);
782 /* if we read to the end of the loop, go back to the beginning */
799 DiskReader::_do_refill_with_alloc (bool partial_fill)
801 /* We limit disk reads to at most 4MB chunks, which with floating point
802 samples would be 1M samples. But we might use 16 or 14 bit samples,
803 in which case 4MB is more samples than that. Therefore size this for
804 the smallest sample value .. 4MB = 2M samples (16 bit).
808 std::auto_ptr<Sample> mix_buf (new Sample[2*1048576]);
809 std::auto_ptr<float> gain_buf (new float[2*1048576]);
811 int ret = refill_audio (mix_buf.get(), gain_buf.get(), (partial_fill ? _chunk_frames : 0));
818 return refill_midi ();
822 DiskReader::refill (Sample* mixdown_buffer, float* gain_buffer, framecnt_t fill_level)
824 int ret = refill_audio (mixdown_buffer, gain_buffer, fill_level);
830 return refill_midi ();
834 /** Get some more data from disk and put it in our channels' bufs,
835 * if there is suitable space in them.
837 * If fill_level is non-zero, then we will refill the buffer so that there is
838 * still at least fill_level samples of space left to be filled. This is used
839 * after locates so that we do not need to wait to fill the entire buffer.
844 DiskReader::refill_audio (Sample* mixdown_buffer, float* gain_buffer, framecnt_t fill_level)
846 /* do not read from disk while session is marked as Loading, to avoid
847 useless redundant I/O.
850 if (_session.loading()) {
856 RingBufferNPT<Sample>::rw_vector vector;
857 bool const reversed = _session.transport_speed() < 0.0f;
858 framecnt_t total_space;
859 framecnt_t zero_fill;
861 ChannelList::iterator i;
862 boost::shared_ptr<ChannelList> c = channels.reader();
869 assert(mixdown_buffer);
877 c->front()->buf->get_write_vector (&vector);
879 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
880 DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1: no space to refill\n", name()));
881 /* nowhere to write to */
886 if (fill_level < total_space) {
887 total_space -= fill_level;
889 /* we can't do anything with it */
894 /* if we're running close to normal speed and there isn't enough
895 space to do disk_read_chunk_frames of I/O, then don't bother.
897 at higher speeds, just do it because the sync between butler
898 and audio thread may not be good enough.
900 Note: it is a design assumption that disk_read_chunk_frames is smaller
901 than the playback buffer size, so this check should never trip when
902 the playback buffer is empty.
905 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()));
906 if ((total_space < _chunk_frames) && fabs (_session.transport_speed()) < 2.0f) {
910 /* when slaved, don't try to get too close to the read pointer. this
911 leaves space for the buffer reversal to have something useful to
915 if (_slaved && total_space < (framecnt_t) (c->front()->buf->bufsize() / 2)) {
916 DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1: not enough to refill while slaved\n", this));
920 framepos_t ffa = file_frame[DataType::AUDIO];
926 /* at start: nothing to do but fill with silence */
928 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
930 ChannelInfo* chan (*i);
931 chan->buf->get_write_vector (&vector);
932 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
934 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
936 chan->buf->increment_write_ptr (vector.len[0] + vector.len[1]);
941 if (ffa < total_space) {
943 /* too close to the start: read what we can,
944 and then zero fill the rest
947 zero_fill = total_space - ffa;
957 if (ffa == max_framepos) {
959 /* at end: nothing to do but fill with silence */
961 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
963 ChannelInfo* chan (*i);
964 chan->buf->get_write_vector (&vector);
965 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
967 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
969 chan->buf->increment_write_ptr (vector.len[0] + vector.len[1]);
974 if (ffa > max_framepos - total_space) {
976 /* to close to the end: read what we can, and zero fill the rest */
978 zero_fill = total_space - (max_framepos - ffa);
979 total_space = max_framepos - ffa;
986 framepos_t file_frame_tmp = 0;
988 /* total_space is in samples. We want to optimize read sizes in various sizes using bytes */
990 const size_t bits_per_sample = format_data_width (_session.config.get_native_file_data_format());
991 size_t total_bytes = total_space * bits_per_sample / 8;
993 /* chunk size range is 256kB to 4MB. Bigger is faster in terms of MB/sec, but bigger chunk size always takes longer
995 size_t byte_size_for_read = max ((size_t) (256 * 1024), min ((size_t) (4 * 1048576), total_bytes));
997 /* find nearest (lower) multiple of 16384 */
999 byte_size_for_read = (byte_size_for_read / 16384) * 16384;
1001 /* now back to samples */
1003 framecnt_t samples_to_read = byte_size_for_read / (bits_per_sample / 8);
1005 DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1: will refill %2 channels with %3 samples\n", name(), c->size(), total_space));
1007 // uint64_t before = g_get_monotonic_time ();
1008 // uint64_t elapsed;
1010 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1012 ChannelInfo* chan (*i);
1015 framecnt_t len1, len2;
1017 chan->buf->get_write_vector (&vector);
1019 if ((framecnt_t) vector.len[0] > samples_to_read) {
1021 /* we're not going to fill the first chunk, so certainly do not bother with the
1022 other part. it won't be connected with the part we do fill, as in:
1024 .... => writable space
1025 ++++ => readable space
1026 ^^^^ => 1 x disk_read_chunk_frames that would be filled
1028 |......|+++++++++++++|...............................|
1033 So, just pretend that the buf1 part isn't there.
1043 file_frame_tmp = ffa;
1045 buf1 = vector.buf[0];
1046 len1 = vector.len[0];
1047 buf2 = vector.buf[1];
1048 len2 = vector.len[1];
1050 to_read = min (ts, len1);
1051 to_read = min (to_read, (framecnt_t) samples_to_read);
1053 assert (to_read >= 0);
1057 if (audio_read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1061 chan->buf->increment_write_ptr (to_read);
1065 to_read = min (ts, len2);
1069 /* we read all of vector.len[0], but it wasn't the
1070 entire samples_to_read of data, so read some or
1071 all of vector.len[1] as well.
1074 if (audio_read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1079 chan->buf->increment_write_ptr (to_read);
1083 /* XXX: do something */
1088 // elapsed = g_get_monotonic_time () - before;
1089 // cerr << '\t' << name() << ": bandwidth = " << (byte_size_for_read / 1048576.0) / (elapsed/1000000.0) << "MB/sec\n";
1091 file_frame[DataType::AUDIO] = file_frame_tmp;
1092 assert (file_frame[DataType::AUDIO] >= 0);
1094 ret = ((total_space - samples_to_read) > _chunk_frames);
1096 c->front()->buf->get_write_vector (&vector);
1103 DiskReader::playlist_ranges_moved (list< Evoral::RangeMove<framepos_t> > const & movements_frames, bool from_undo)
1105 /* If we're coming from an undo, it will have handled
1106 automation undo (it must, since automation-follows-regions
1107 can lose automation data). Hence we can do nothing here.
1114 if (!_route || Config->get_automation_follows_regions () == false) {
1118 list< Evoral::RangeMove<double> > movements;
1120 for (list< Evoral::RangeMove<framepos_t> >::const_iterator i = movements_frames.begin();
1121 i != movements_frames.end();
1124 movements.push_back(Evoral::RangeMove<double>(i->from, i->length, i->to));
1127 /* move panner automation */
1128 boost::shared_ptr<Pannable> pannable = _route->pannable();
1129 Evoral::ControlSet::Controls& c (pannable->controls());
1131 for (Evoral::ControlSet::Controls::iterator ci = c.begin(); ci != c.end(); ++ci) {
1132 boost::shared_ptr<AutomationControl> ac = boost::dynamic_pointer_cast<AutomationControl>(ci->second);
1136 boost::shared_ptr<AutomationList> alist = ac->alist();
1137 if (!alist->size()) {
1140 XMLNode & before = alist->get_state ();
1141 bool const things_moved = alist->move_ranges (movements);
1143 _session.add_command (new MementoCommand<AutomationList> (
1144 *alist.get(), &before, &alist->get_state ()));
1147 /* move processor automation */
1148 _route->foreach_processor (boost::bind (&DiskReader::move_processor_automation, this, _1, movements_frames));
1152 DiskReader::move_processor_automation (boost::weak_ptr<Processor> p, list< Evoral::RangeMove<framepos_t> > const & movements_frames)
1154 boost::shared_ptr<Processor> processor (p.lock ());
1159 list< Evoral::RangeMove<double> > movements;
1160 for (list< Evoral::RangeMove<framepos_t> >::const_iterator i = movements_frames.begin(); i != movements_frames.end(); ++i) {
1161 movements.push_back(Evoral::RangeMove<double>(i->from, i->length, i->to));
1164 set<Evoral::Parameter> const a = processor->what_can_be_automated ();
1166 for (set<Evoral::Parameter>::const_iterator i = a.begin (); i != a.end (); ++i) {
1167 boost::shared_ptr<AutomationList> al = processor->automation_control(*i)->alist();
1171 XMLNode & before = al->get_state ();
1172 bool const things_moved = al->move_ranges (movements);
1174 _session.add_command (
1175 new MementoCommand<AutomationList> (
1176 *al.get(), &before, &al->get_state ()
1183 boost::shared_ptr<MidiBuffer>
1184 DiskReader::get_gui_feed_buffer () const
1186 boost::shared_ptr<MidiBuffer> b (new MidiBuffer (AudioEngine::instance()->raw_buffer_size (DataType::MIDI)));
1188 Glib::Threads::Mutex::Lock lm (_gui_feed_buffer_mutex);
1189 b->copy (_gui_feed_buffer);
1194 DiskReader::reset_tracker ()
1196 _midi_buf->reset_tracker ();
1198 boost::shared_ptr<MidiPlaylist> mp (midi_playlist());
1201 mp->reset_note_trackers ();
1206 DiskReader::resolve_tracker (Evoral::EventSink<framepos_t>& buffer, framepos_t time)
1208 _midi_buf->resolve_tracker(buffer, time);
1210 boost::shared_ptr<MidiPlaylist> mp (midi_playlist());
1213 mp->reset_note_trackers ();
1217 /** Writes playback events from playback_sample for nframes to dst, translating time stamps
1218 * so that an event at playback_sample has time = 0
1221 DiskReader::get_midi_playback (MidiBuffer& dst, framecnt_t nframes, MonitorState ms, BufferSet& scratch_bufs, double speed, framecnt_t playback_distance)
1225 if ((ms & MonitoringInput) == 0) {
1229 target = &scratch_bufs.get_midi (0);
1232 if (ms & MonitoringDisk) {
1233 /* no disk data needed */
1235 Location* loc = loop_location;
1237 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose (
1238 "%1 MDS pre-read read %8 offset = %9 @ %4..%5 from %2 write to %3, LOOPED ? %6 .. %7\n", _name,
1239 _midi_buf->get_read_ptr(), _midi_buf->get_write_ptr(), playback_sample, playback_sample + nframes,
1240 (loc ? loc->start() : -1), (loc ? loc->end() : -1), nframes, Port::port_offset()));
1242 //cerr << "======== PRE ========\n";
1243 //_midi_buf->dump (cerr);
1244 //cerr << "----------------\n";
1246 size_t events_read = 0;
1249 framepos_t effective_start;
1251 Evoral::Range<framepos_t> loop_range (loc->start(), loc->end() - 1);
1252 effective_start = loop_range.squish (playback_sample);
1254 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("looped, effective start adjusted to %1\n", effective_start));
1256 if (effective_start == loc->start()) {
1257 /* We need to turn off notes that may extend
1258 beyond the loop end.
1261 _midi_buf->resolve_tracker (*target, 0);
1264 /* for split-cycles we need to offset the events */
1266 if (loc->end() >= effective_start && loc->end() < effective_start + nframes) {
1268 /* end of loop is within the range we are reading, so
1269 split the read in two, and lie about the location
1273 framecnt_t first, second;
1275 first = loc->end() - effective_start;
1276 second = nframes - first;
1278 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read for eff %1 end %2: %3 and %4, cycle offset %5\n",
1279 effective_start, loc->end(), first, second));
1282 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read #1, from %1 for %2\n",
1283 effective_start, first));
1284 events_read = _midi_buf->read (*target, effective_start, first);
1288 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read #2, from %1 for %2\n",
1289 loc->start(), second));
1290 events_read += _midi_buf->read (*target, loc->start(), second);
1294 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read #3, adjusted start as %1 for %2\n",
1295 effective_start, nframes));
1296 events_read = _midi_buf->read (*target, effective_start, effective_start + nframes);
1299 const size_t n_skipped = _midi_buf->skip_to (playback_sample);
1300 if (n_skipped > 0) {
1301 warning << string_compose(_("MidiDiskstream %1: skipped %2 events, possible underflow"), id(), n_skipped) << endmsg;
1303 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("playback buffer read, from %1 to %2 (%3)", playback_sample, playback_sample + nframes, nframes));
1304 events_read = _midi_buf->read (*target, playback_sample, playback_sample + nframes);
1307 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose (
1308 "%1 MDS events read %2 range %3 .. %4 rspace %5 wspace %6 r@%7 w@%8\n",
1309 _name, events_read, playback_sample, playback_sample + nframes,
1310 _midi_buf->read_space(), _midi_buf->write_space(),
1311 _midi_buf->get_read_ptr(), _midi_buf->get_write_ptr()));
1314 g_atomic_int_add (&_frames_read_from_ringbuffer, nframes);
1318 if (speed != 0.0 && fabsf (speed) != 1.0f) {
1319 for (MidiBuffer::iterator i = target->begin(); i != target->end(); ++i) {
1320 MidiBuffer::TimeType *tme = i.timeptr();
1321 *tme = (*tme) * nframes / playback_distance;
1325 if (ms & MonitoringInput) {
1326 dst.merge_from (*target, nframes);
1329 //cerr << "======== POST ========\n";
1330 //_midi_buf->dump (cerr);
1331 //cerr << "----------------\n";
1334 /** @a start is set to the new frame position (TIME) read up to */
1336 DiskReader::midi_read (framepos_t& start, framecnt_t dur, bool reversed)
1338 framecnt_t this_read = 0;
1339 framepos_t loop_end = 0;
1340 framepos_t loop_start = 0;
1341 framecnt_t loop_length = 0;
1342 Location* loc = loop_location;
1343 framepos_t effective_start = start;
1344 Evoral::Range<framepos_t>* loop_range (0);
1346 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("MDS::midi_read @ %1 cnt %2\n", start, dur));
1348 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack>(_route);
1349 MidiChannelFilter* filter = mt ? &mt->playback_filter() : 0;
1350 frameoffset_t loop_offset = 0;
1352 if (!reversed && loc) {
1353 get_location_times (loc, &loop_start, &loop_end, &loop_length);
1358 /* take any loop into account. we can't read past the end of the loop. */
1360 if (loc && !reversed) {
1363 loop_range = new Evoral::Range<framepos_t> (loop_start, loop_end-1); // inclusive semantics require -1
1366 /* if we are (seamlessly) looping, ensure that the first frame we read is at the correct
1367 position within the loop.
1370 effective_start = loop_range->squish (effective_start);
1372 if ((loop_end - effective_start) <= dur) {
1373 /* too close to end of loop to read "dur", so
1376 this_read = loop_end - effective_start;
1385 if (this_read == 0) {
1389 this_read = min (dur,this_read);
1391 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("MDS ::read at %1 for %2 loffset %3\n", effective_start, this_read, loop_offset));
1393 if (midi_playlist()->read (*_midi_buf, effective_start, this_read, loop_range, 0, filter) != this_read) {
1394 error << string_compose(
1395 _("MidiDiskstream %1: cannot read %2 from playlist at frame %3"),
1396 id(), this_read, start) << endmsg;
1400 g_atomic_int_add (&_frames_written_to_ringbuffer, this_read);
1404 // Swap note ons with note offs here. etc?
1405 // Fully reversing MIDI requires look-ahead (well, behind) to find previous
1406 // CC values etc. hard.
1410 /* adjust passed-by-reference argument (note: this is
1411 monotonic and does not reflect looping.
1415 /* similarly adjust effective_start, but this may be
1416 readjusted for seamless looping as we continue around
1419 effective_start += this_read;
1423 //offset += this_read;
1430 DiskReader::refill_midi ()
1432 if (!_playlists[DataType::MIDI]) {
1436 size_t write_space = _midi_buf->write_space();
1437 const bool reversed = _session.transport_speed() < 0.0f;
1439 DEBUG_TRACE (DEBUG::DiskIO, string_compose ("MIDI refill, write space = %1 file frame = %2\n", write_space, file_frame[DataType::MIDI]));
1441 /* no space to write */
1442 if (write_space == 0) {
1450 /* at end: nothing to do */
1452 framepos_t ffm = file_frame[DataType::MIDI];
1454 if (ffm == max_framepos) {
1459 const uint32_t frames_read = g_atomic_int_get (&_frames_read_from_ringbuffer);
1460 const uint32_t frames_written = g_atomic_int_get (&_frames_written_to_ringbuffer);
1462 if ((frames_read < frames_written) && (frames_written - frames_read) >= midi_readahead) {
1466 framecnt_t to_read = midi_readahead - ((framecnt_t)frames_written - (framecnt_t)frames_read);
1468 to_read = min (to_read, (framecnt_t) (max_framepos - ffm));
1469 to_read = min (to_read, (framecnt_t) write_space);
1471 if (midi_read (ffm, to_read, reversed)) {
1475 file_frame[DataType::MIDI] = ffm;
1481 DiskReader::set_no_disk_output (bool yn)
1483 /* this MUST be called as part of the process call tree, before any
1484 disk readers are invoked. We use it when the session needs the
1485 transport (and thus effective read position for DiskReaders) to keep
1486 advancing as part of syncing up with a transport master, but we
1487 don't want any actual disk output yet because we are still not
1490 no_disk_output = yn;