2 * Copyright (C) 2017-2018 Paul Davis <paul@linuxaudiosystems.com>
3 * Copyright (C) 2017-2019 Robin Gareus <robin@gareus.org>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include <boost/smart_ptr/scoped_array.hpp>
22 #include "pbd/enumwriter.h"
23 #include "pbd/memento_command.h"
24 #include "pbd/playback_buffer.h"
26 #include "evoral/Range.h"
28 #include "ardour/amp.h"
29 #include "ardour/audioengine.h"
30 #include "ardour/audioplaylist.h"
31 #include "ardour/audio_buffer.h"
32 #include "ardour/butler.h"
33 #include "ardour/debug.h"
34 #include "ardour/disk_reader.h"
35 #include "ardour/midi_ring_buffer.h"
36 #include "ardour/midi_playlist.h"
37 #include "ardour/midi_track.h"
38 #include "ardour/pannable.h"
39 #include "ardour/playlist.h"
40 #include "ardour/playlist_factory.h"
41 #include "ardour/session.h"
42 #include "ardour/session_playlists.h"
46 using namespace ARDOUR;
50 ARDOUR::samplecnt_t DiskReader::_chunk_samples = default_chunk_samples ();
51 PBD::Signal0<void> DiskReader::Underrun;
52 Sample* DiskReader::_sum_buffer = 0;
53 Sample* DiskReader::_mixdown_buffer = 0;
54 gain_t* DiskReader::_gain_buffer = 0;
55 gint DiskReader::_no_disk_output (0);
56 DiskReader::Declicker DiskReader::loop_declick_in;
57 DiskReader::Declicker DiskReader::loop_declick_out;
58 samplecnt_t DiskReader::loop_fade_length (0);
60 DiskReader::DiskReader (Session& s, string const & str, DiskIOProcessor::Flag f)
61 : DiskIOProcessor (s, str, f)
62 , overwrite_sample (0)
63 , run_must_resolve (false)
64 , _declick_amp (s.nominal_sample_rate ())
67 file_sample[DataType::AUDIO] = 0;
68 file_sample[DataType::MIDI] = 0;
69 g_atomic_int_set (&_pending_overwrite, 0);
72 DiskReader::~DiskReader ()
74 DEBUG_TRACE (DEBUG::Destruction, string_compose ("DiskReader %1 @ %2 deleted\n", _name, this));
78 DiskReader::ReaderChannelInfo::resize (samplecnt_t bufsize)
80 delete rbuf; rbuf = 0;
82 rbuf = new PlaybackBuffer<Sample> (bufsize);
83 /* touch memory to lock it */
84 memset (rbuf->buffer(), 0, sizeof (Sample) * rbuf->bufsize());
88 DiskReader::ReaderChannelInfo::resize_preloop (samplecnt_t bufsize)
94 if (bufsize > pre_loop_buffer_size) {
95 delete [] pre_loop_buffer;
96 pre_loop_buffer = new Sample[bufsize];
97 pre_loop_buffer_size = bufsize;
102 DiskReader::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
105 c->push_back (new ReaderChannelInfo (_session.butler()->audio_playback_buffer_size(), loop_fade_length));
106 DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1: new reader channel, write space = %2 read = %3\n",
108 c->back()->rbuf->write_space(),
109 c->back()->rbuf->read_space()));
116 DiskReader::allocate_working_buffers()
118 /* with varifill buffer refilling, we compute the read size in bytes (to optimize
119 for disk i/o bandwidth) and then convert back into samples. These buffers
120 need to reflect the maximum size we could use, which is 4MB reads, or 2M samples
121 using 16 bit samples.
123 _sum_buffer = new Sample[2*1048576];
124 _mixdown_buffer = new Sample[2*1048576];
125 _gain_buffer = new gain_t[2*1048576];
129 DiskReader::free_working_buffers()
131 delete [] _sum_buffer;
132 delete [] _mixdown_buffer;
133 delete [] _gain_buffer;
140 DiskReader::default_chunk_samples()
146 DiskReader::set_name (string const & str)
148 string my_name = X_("player:");
151 if (_name != my_name) {
152 SessionObject::set_name (my_name);
161 XMLNode& node (DiskIOProcessor::state ());
162 node.set_property(X_("type"), X_("diskreader"));
167 DiskReader::set_state (const XMLNode& node, int version)
169 if (DiskIOProcessor::set_state (node, version)) {
177 DiskReader::realtime_handle_transport_stopped ()
179 /* can't do the resolve here because we don't have a place to put the
180 * note resolving data. Defer to
181 * MidiTrack::realtime_handle_transport_stopped() which will call
182 * ::resolve_tracker() and put the output in its _immediate_events store.
187 DiskReader::realtime_locate (bool for_loop_end)
190 std::cerr << name() << "DO note resolve on locate for loop\n";
191 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack>(_track);
192 _tracker.resolve_notes (mt->immediate_events(), 0);
194 std::cerr << name() << "skip note resolve on locate for loop\n";
199 DiskReader::buffer_load () const
201 /* Note: for MIDI it's not trivial to differentiate the following two cases:
203 1. The playback buffer is empty because the system has run out of time to fill it.
204 2. The playback buffer is empty because there is no more data on the playlist.
206 If we use a simple buffer load computation, we will report that the MIDI diskstream
207 cannot keep up when #2 happens, when in fact it can. Since MIDI data rates
208 are so low compared to audio, just use the audio value here.
211 boost::shared_ptr<ChannelList> c = channels.reader();
214 /* no channels, so no buffers, so completely full and ready to playback, sir! */
218 PBD::PlaybackBuffer<Sample>* b = c->front()->rbuf;
219 return (float) ((double) b->read_space() / (double) b->bufsize());
223 DiskReader::adjust_buffering ()
225 boost::shared_ptr<ChannelList> c = channels.reader();
227 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
228 (*chan)->resize (_session.butler()->audio_playback_buffer_size());
233 DiskReader::playlist_modified ()
235 _session.request_overwrite_buffer (_track, PlaylistModified);
239 DiskReader::use_playlist (DataType dt, boost::shared_ptr<Playlist> playlist)
241 bool prior_playlist = false;
243 if (_playlists[dt]) {
244 prior_playlist = true;
247 if (DiskIOProcessor::use_playlist (dt, playlist)) {
251 /* don't do this if we've already asked for it *or* if we are setting up
252 the diskstream for the very first time - the input changed handling will
253 take care of the buffer refill.
256 if (!(g_atomic_int_get (&_pending_overwrite) & PlaylistChanged) || prior_playlist) {
257 _session.request_overwrite_buffer (_track, PlaylistChanged);
264 DiskReader::run (BufferSet& bufs, samplepos_t start_sample, samplepos_t end_sample, double speed, pframes_t nframes, bool result_required)
267 boost::shared_ptr<ChannelList> c = channels.reader();
268 ChannelList::iterator chan;
269 sampleoffset_t disk_samples_to_consume;
270 MonitorState ms = _track->monitoring_state ();
272 // std::cerr << name() << " run " << start_sample << " .. " << end_sample << " speed = " << speed << std::endl;
274 if (!_pending_active) {
279 if (_pending_active) {
286 const gain_t target_gain = ((speed == 0.0) || ((ms & MonitoringDisk) == 0)) ? 0.0 : 1.0;
287 const bool declicked_out = (_declick_amp.gain() == target_gain) && target_gain == 0.0;
288 const bool declick_out = (_declick_amp.gain() != target_gain) && target_gain == 0.0;
290 if (!_session.cfg ()->get_use_transport_fades ()) {
291 _declick_amp.set_gain (target_gain);
294 if (declicked_out && (ms == MonitoringDisk)) {
295 /* Stopped and declicking has finished. Don't accidentally pass
296 * any data from disk into our outputs (e.g. via interpolation)
301 BufferSet& scratch_bufs (_session.get_scratch_buffers (bufs.count()));
302 const bool still_locating = _session.global_locate_pending();
304 assert (speed == -1 || speed == 0 || speed == 1);
307 disk_samples_to_consume = 0;
309 disk_samples_to_consume = nframes;
312 if (c->empty() || !_playlists[DataType::AUDIO]) {
313 /* do nothing with audio */
320 // printf ("DR fade-out speed=%.1f gain=%.3f off=%ld start=%ld playpos=%ld (%s)\n", speed, _declick_amp.gain (), _declick_offs, start_sample, playback_sample, owner()->name().c_str());
322 ms = MonitorState (ms | MonitoringDisk);
323 assert (result_required);
324 result_required = true;
329 if (!result_required || ((ms & MonitoringDisk) == 0) || still_locating || _no_disk_output) {
331 /* no need for actual disk data, just advance read pointer */
333 if (!still_locating || _no_disk_output) {
334 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
335 assert ((*chan)->rbuf);
336 (*chan)->rbuf->increment_read_ptr (disk_samples_to_consume);
340 /* if monitoring disk but locating put silence in the buffers */
342 if ((_no_disk_output || still_locating) && (ms == MonitoringDisk)) {
343 bufs.silence (nframes, 0);
348 /* we need audio data from disk */
350 size_t n_buffers = bufs.count().n_audio();
351 size_t n_chans = c->size();
354 if (n_chans > n_buffers) {
355 scaling = ((float) n_buffers) / n_chans;
360 const float initial_declick_gain = _declick_amp.gain ();
361 const sampleoffset_t declick_offs = _declick_offs;
363 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
365 ChannelInfo* chaninfo (*chan);
366 AudioBuffer& output (bufs.get_audio (n % n_buffers));
368 AudioBuffer& disk_buf ((ms & MonitoringInput) ? scratch_bufs.get_audio(n) : output);
370 if (start_sample != playback_sample && target_gain != 0) {
371 cerr << name() << " Not at start (" << start_sample << ") ps = " << playback_sample << " iseek (" << start_sample - playback_sample << endl;
372 if (can_internal_playback_seek (start_sample - playback_sample)) {
373 internal_playback_seek (start_sample - playback_sample);
375 disk_samples_to_consume = 0; /* will force an underrun below */
379 /* reset _declick_amp to the correct gain before processing this channel. */
381 _declick_amp.set_gain (initial_declick_gain);
387 const samplecnt_t total = chaninfo->rbuf->read (disk_buf.data(), disk_samples_to_consume);
389 if (disk_samples_to_consume > total) {
390 cerr << _name << " Need " << total << " have only " << disk_samples_to_consume << endl;
391 cerr << "underrun for " << _name << endl;
392 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 underrun in %2, total space = %3\n",
393 DEBUG_THREAD_SELF, name(), total));
398 } else if (_declick_amp.gain() != target_gain) {
400 assert (target_gain == 0);
402 /* note that this is a non-committing read: it
403 retrieves data from the ringbuffer but does not
404 advance the read pointer. As a result,
405 subsequent calls (as we declick) need to
406 pass in an offset describing where to read
407 from. We maintain _declick_offs across calls
411 const samplecnt_t total = chaninfo->rbuf->read (disk_buf.data(), nframes, false, declick_offs);
414 _declick_offs += total;
418 _declick_amp.apply_gain (disk_buf, nframes, target_gain);
420 /* _declick_amp is now left with the correct gain after
424 Amp::apply_simple_gain (disk_buf, nframes, scaling);
426 if (ms & MonitoringInput) {
427 /* mix the disk signal into the input signal (already in bufs) */
428 mix_buffers_no_gain (output.data(), disk_buf.data(), nframes);
434 /* MIDI data handling */
436 const bool midi_data_available = !(pending_overwrite() & PlaylistModified);
438 if (bufs.count().n_midi()) {
440 MidiBuffer& dst (bufs.get_midi (0));
442 if (run_must_resolve) {
443 resolve_tracker (dst, 0);
444 run_must_resolve = false;
447 if (!_no_disk_output && !declick_in_progress() && (ms & MonitoringDisk) && !still_locating && midi_data_available && speed) {
448 get_midi_playback (dst, start_sample, end_sample, ms, scratch_bufs, speed, disk_samples_to_consume);
452 /* decide if we need the butler */
454 if (!still_locating && midi_data_available) {
456 bool butler_required = false;
459 playback_sample -= disk_samples_to_consume;
461 playback_sample += disk_samples_to_consume;
464 Location* loc = _loop_location;
466 Evoral::Range<samplepos_t> loop_range (loc->start(), loc->end() - 1);
467 playback_sample = loop_range.squish (playback_sample);
470 if (_playlists[DataType::AUDIO]) {
473 if (c->front()->rbuf->write_space() >= c->front()->rbuf->bufsize() / 2) {
474 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1: slaved, write space = %2 of %3\n", name(), c->front()->rbuf->write_space(), c->front()->rbuf->bufsize()));
475 butler_required = true;
478 if ((samplecnt_t) c->front()->rbuf->write_space() >= _chunk_samples) {
479 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1: write space = %2 of %3\n", name(), c->front()->rbuf->write_space(),
481 butler_required = true;
487 /* All of MIDI is in RAM, no need to call the butler unless we
488 * have to overwrite buffers because of a playlist change.
491 _need_butler = butler_required;
494 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 reader run, needs butler = %2\n", name(), _need_butler));
498 DiskReader::declick_in_progress () const
500 return _declick_amp.gain() != 0; // declick-out
504 DiskReader::pending_overwrite () const
506 return g_atomic_int_get (&_pending_overwrite) != 0;
510 DiskReader::set_pending_overwrite (OverwriteReason why)
512 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
514 overwrite_sample = playback_sample;
515 boost::shared_ptr<ChannelList> c = channels.reader ();
517 overwrite_offset = c->front()->rbuf->read_ptr();
520 if (why & (LoopChanged|PlaylistModified|PlaylistChanged)) {
521 run_must_resolve = true;
525 OverwriteReason current = OverwriteReason (g_atomic_int_get (&_pending_overwrite));
526 OverwriteReason next = OverwriteReason (current | why);
527 if (g_atomic_int_compare_and_exchange (&_pending_overwrite, current, next)) {
535 DiskReader::overwrite_existing_audio ()
537 boost::shared_ptr<ChannelList> c = channels.reader();
539 if (c->empty () || !_playlists[DataType::AUDIO]) {
543 const bool reversed = _session.transport_speed() < 0.0f;
545 /* assume all are the same size */
547 samplecnt_t size = c->front()->rbuf->bufsize () - c->front()->rbuf->reserved_size() - 1;
550 boost::scoped_array<Sample> mixdown_buffer (new Sample[size]);
551 boost::scoped_array<float> gain_buffer (new float[size]);
555 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
557 samplepos_t start = overwrite_sample;
559 /* to fill the buffer without resetting the playback sample, we need to
560 do it one or two chunks (normally two).
562 |----------------------------------------------------------------------|
564 RESERVED overwrite_offset (old read_ptr)
565 |<- second chunk->|<-------------><---- first chunk ------------------>|
569 samplecnt_t to_read = size - overwrite_offset;
570 Sample* buf = (*chan)->rbuf->buffer();
571 ReaderChannelInfo* rci = dynamic_cast<ReaderChannelInfo*> (*chan);
574 if ((nread = audio_read (buf + overwrite_offset, mixdown_buffer.get(), gain_buffer.get(), start, to_read, rci, n, reversed)) != to_read) {
575 error << string_compose(_("DiskReader %1: when overwriting(1), cannot read %2 from playlist at sample %3"), id(), to_read, overwrite_sample) << endmsg;
580 if (size > to_read) {
582 to_read = size - to_read;
584 if ((nread = audio_read (buf, mixdown_buffer.get(), gain_buffer.get(), start, to_read, rci, n, reversed)) != to_read) {
585 error << string_compose(_("DiskReader %1: when overwriting(2), cannot read %2 from playlist at sample %3"), id(), to_read, overwrite_sample) << endmsg;
595 DiskReader::overwrite_existing_midi ()
597 RTMidiBuffer* mbuf = rt_midibuffer ();
600 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack>(_track);
601 MidiChannelFilter* filter = mt ? &mt->playback_filter() : 0;
606 midi_playlist()->render (filter);
609 assert (midi_playlist()->rendered());
610 cerr << "Reading " << name() << " took " << minsert.elapsed() << " microseconds, final size = " << midi_playlist()->rendered()->size() << endl;
617 DiskReader::overwrite_existing_buffers ()
619 /* called from butler thread */
621 DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1 overwriting existing buffers at %2 (because %3%4%5\n", owner()->name(), overwrite_sample, std::hex, g_atomic_int_get (&_pending_overwrite), std::dec));
625 if (g_atomic_int_get (&_pending_overwrite) & (PlaylistModified|LoopDisabled|LoopChanged|PlaylistChanged)) {
626 if (!overwrite_existing_audio ()) {
631 if (g_atomic_int_get (&_pending_overwrite) & (PlaylistModified|PlaylistChanged)) {
632 if (!overwrite_existing_midi ()) {
637 g_atomic_int_set (&_pending_overwrite, 0);
643 DiskReader::seek (samplepos_t sample, bool complete_refill)
645 /* called via non_realtime_locate() from butler thread */
649 ChannelList::iterator chan;
650 boost::shared_ptr<ChannelList> c = channels.reader();
652 if (sample == playback_sample && !complete_refill) {
653 return 0; // XXX double-check this
656 g_atomic_int_set (&_pending_overwrite, 0);
658 DEBUG_TRACE (DEBUG::DiskIO, string_compose ("DiskReader::seek %s %ld -> %ld refill=%d\n", owner()->name().c_str(), playback_sample, sample, complete_refill));
660 const samplecnt_t distance = sample - playback_sample;
661 if (!complete_refill && can_internal_playback_seek (distance)) {
662 internal_playback_seek (distance);
666 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
667 (*chan)->rbuf->reset ();
670 playback_sample = sample;
671 file_sample[DataType::AUDIO] = sample;
672 file_sample[DataType::MIDI] = sample;
674 if (complete_refill) {
675 /* call _do_refill() to refill the entire buffer, using
676 the largest reads possible.
678 while ((ret = do_refill_with_alloc (false)) > 0) ;
680 /* call _do_refill() to refill just one chunk, and then
683 ret = do_refill_with_alloc (true);
690 DiskReader::can_internal_playback_seek (sampleoffset_t distance)
694 ChannelList::iterator chan;
695 boost::shared_ptr<ChannelList> c = channels.reader();
697 for (chan = c->begin(); chan != c->end(); ++chan) {
698 if (!(*chan)->rbuf->can_seek (distance)) {
703 /* 2. MIDI can always seek any distance */
709 DiskReader::internal_playback_seek (sampleoffset_t distance)
715 sampleoffset_t off = distance;
717 ChannelList::iterator chan;
718 boost::shared_ptr<ChannelList> c = channels.reader();
719 for (chan = c->begin(); chan != c->end(); ++chan) {
721 off = 0 - (sampleoffset_t) (*chan)->rbuf->decrement_read_ptr (::llabs (distance));
723 off = (*chan)->rbuf->increment_read_ptr (distance);
727 playback_sample += off;
731 void swap_by_ptr (Sample *first, Sample *last)
733 while (first < last) {
740 /** Read some data for 1 channel from our playlist into a buffer.
741 * @param buf Buffer to write to.
742 * @param start Session sample to start reading from; updated to where we end up
744 * @param cnt Count of samples to read.
745 * @param reversed true if we are running backwards, otherwise false.
748 DiskReader::audio_read (Sample* sum_buffer,
749 Sample* mixdown_buffer,
753 ReaderChannelInfo* rci,
757 samplecnt_t this_read = 0;
759 samplepos_t loop_end = 0;
760 samplepos_t loop_start = 0;
762 const samplecnt_t rcnt = cnt;
764 /* XXX we don't currently play loops in reverse. not sure why */
768 samplecnt_t loop_length = 0;
770 /* Make the use of a Location atomic for this read operation.
772 Note: Locations don't get deleted, so all we care about
773 when I say "atomic" is that we are always pointing to
774 the same one and using a start/length values obtained
778 if ((loc = _loop_location) != 0) {
779 loop_start = loc->start();
780 loop_end = loc->end();
781 loop_length = loop_end - loop_start;
784 /* if we are looping, ensure that the first sample we read is at the correct
785 position within the loop.
788 if (loc && start >= loop_end) {
789 start = loop_start + ((start - loop_start) % loop_length);
798 /* We need this while loop in case we hit a loop boundary, in which case our read from
799 the playlist must be split into more than one section.
804 /* take any loop into account. we can't read past the end of the loop. */
806 if (loc && (loop_end - start < cnt)) {
807 this_read = loop_end - start;
814 if (this_read == 0) {
818 this_read = min (cnt, this_read);
820 /* note that the mixdown and gain buffers are purely for the
821 * internal use of the playlist, and cannot be considered
822 * useful after the return from AudioPlayback::read()
825 if (audio_playlist()->read (sum_buffer, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
826 error << string_compose(_("DiskReader %1: cannot read %2 from playlist at sample %3"), id(), this_read, start) << endmsg;
832 /* Looping: do something (maybe) about the loop boundaries */
834 switch (Config->get_loop_fade_choice()) {
838 loop_declick_in.run (sum_buffer, start, start + this_read);
839 loop_declick_out.run (sum_buffer, start, start + this_read);
842 loop_declick_out.run (sum_buffer, start, start + this_read);
845 maybe_xfade_loop (sum_buffer, start, start + this_read, rci);
852 swap_by_ptr (sum_buffer, sum_buffer + this_read - 1);
856 /* if we read to the end of the loop, go back to the beginning */
866 sum_buffer += this_read;
873 DiskReader::_do_refill_with_alloc (bool partial_fill)
875 /* We limit disk reads to at most 4MB chunks, which with floating point
876 samples would be 1M samples. But we might use 16 or 14 bit samples,
877 in which case 4MB is more samples than that. Therefore size this for
878 the smallest sample value .. 4MB = 2M samples (16 bit).
881 boost::scoped_array<Sample> sum_buf (new Sample[2*1048576]);
882 boost::scoped_array<Sample> mix_buf (new Sample[2*1048576]);
883 boost::scoped_array<float> gain_buf (new float[2*1048576]);
885 return refill_audio (sum_buf.get(), mix_buf.get(), gain_buf.get(), (partial_fill ? _chunk_samples : 0));
889 DiskReader::refill (Sample* sum_buffer, Sample* mixdown_buffer, float* gain_buffer, samplecnt_t fill_level)
891 if (refill_audio (sum_buffer, mixdown_buffer, gain_buffer, fill_level)) {
895 if (rt_midibuffer() && (_session.transport_speed() < 0.0f) != rt_midibuffer()->reversed()) {
896 rt_midibuffer()->reverse ();
903 /** Get some more data from disk and put it in our channels' bufs,
904 * if there is suitable space in them.
906 * If fill_level is non-zero, then we will refill the buffer so that there is
907 * still at least fill_level samples of space left to be filled. This is used
908 * after locates so that we do not need to wait to fill the entire buffer.
913 DiskReader::refill_audio (Sample* sum_buffer, Sample* mixdown_buffer, float* gain_buffer, samplecnt_t fill_level)
915 /* do not read from disk while session is marked as Loading, to avoid
916 useless redundant I/O.
919 if (_session.loading()) {
924 bool const reversed = _session.transport_speed() < 0.0f;
925 samplecnt_t zero_fill;
927 ChannelList::iterator i;
928 boost::shared_ptr<ChannelList> c = channels.reader();
934 assert(mixdown_buffer);
937 samplecnt_t total_space = c->front()->rbuf->write_space();
939 if (total_space == 0) {
940 DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1: no space to refill\n", name()));
941 /* nowhere to write to */
946 if (fill_level < total_space) {
947 total_space -= fill_level;
949 /* we can't do anything with it */
954 /* if we're running close to normal speed and there isn't enough
955 space to do disk_read_chunk_samples of I/O, then don't bother.
957 at higher speeds, just do it because the sync between butler
958 and audio thread may not be good enough.
960 Note: it is a design assumption that disk_read_chunk_samples is smaller
961 than the playback buffer size, so this check should never trip when
962 the playback buffer is empty.
965 DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1: space to refill %2 vs. chunk %3 (speed = %4)\n", name(), total_space, _chunk_samples, _session.transport_speed()));
966 if ((total_space < _chunk_samples) && fabs (_session.transport_speed()) < 2.0f) {
970 /* when slaved, don't try to get too close to the read pointer. this
971 leaves space for the buffer reversal to have something useful to
975 if (_slaved && total_space < (samplecnt_t) (c->front()->rbuf->bufsize() / 2)) {
976 DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1: not enough to refill while slaved\n", this));
980 samplepos_t ffa = file_sample[DataType::AUDIO];
985 /* at start: nothing to do but fill with silence */
986 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
987 ChannelInfo* chan (*i);
988 chan->rbuf->write_zero (chan->rbuf->write_space ());
993 if (ffa < total_space) {
994 /* too close to the start: read what we can, and then zero fill the rest */
995 zero_fill = total_space - ffa;
1003 if (ffa == max_samplepos) {
1004 /* at end: nothing to do but fill with silence */
1005 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1006 ChannelInfo* chan (*i);
1007 chan->rbuf->write_zero (chan->rbuf->write_space ());
1012 if (ffa > max_samplepos - total_space) {
1013 /* to close to the end: read what we can, and zero fill the rest */
1014 zero_fill = total_space - (max_samplepos - ffa);
1015 total_space = max_samplepos - ffa;
1022 /* total_space is in samples. We want to optimize read sizes in various sizes using bytes */
1023 const size_t bits_per_sample = format_data_width (_session.config.get_native_file_data_format());
1024 size_t total_bytes = total_space * bits_per_sample / 8;
1026 /* chunk size range is 256kB to 4MB. Bigger is faster in terms of MB/sec, but bigger chunk size always takes longer */
1027 size_t byte_size_for_read = max ((size_t) (256 * 1024), min ((size_t) (4 * 1048576), total_bytes));
1029 /* find nearest (lower) multiple of 16384 */
1031 byte_size_for_read = (byte_size_for_read / 16384) * 16384;
1033 /* now back to samples */
1034 samplecnt_t samples_to_read = byte_size_for_read / (bits_per_sample / 8);
1036 DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1: will refill %2 channels with %3 samples\n", name(), c->size(), total_space));
1038 samplepos_t file_sample_tmp = ffa;
1040 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1042 ChannelInfo* chan (*i);
1043 file_sample_tmp = ffa;
1044 samplecnt_t ts = total_space;
1046 samplecnt_t to_read = min (ts, (samplecnt_t) chan->rbuf->write_space ());
1047 to_read = min (to_read, samples_to_read);
1048 assert (to_read >= 0);
1050 // cerr << owner()->name() << " to-read: " << to_read << endl;
1053 ReaderChannelInfo* rci = dynamic_cast<ReaderChannelInfo*> (chan);
1056 if (!_playlists[DataType::AUDIO]) {
1058 chan->rbuf->write_zero (to_read);
1062 if ((nread = audio_read (sum_buffer, mixdown_buffer, gain_buffer, file_sample_tmp, to_read, rci, chan_n, reversed)) != to_read) {
1063 error << string_compose(_("DiskReader %1: when refilling, cannot read %2 from playlist at sample %3"), name(), to_read, ffa) << endmsg;
1068 if (chan->rbuf->write (sum_buffer, nread) != nread) {
1069 error << string_compose(_("DiskReader %1: when refilling, cannot write %2 into buffer"), name(), nread) << endmsg;
1076 /* not sure if action is needed,
1077 * we'll later hit the "to close to the end" case
1079 //chan->rbuf->write_zero (zero_fill);
1083 // elapsed = g_get_monotonic_time () - before;
1084 // cerr << '\t' << name() << ": bandwidth = " << (byte_size_for_read / 1048576.0) / (elapsed/1000000.0) << "MB/sec\n";
1086 file_sample[DataType::AUDIO] = file_sample_tmp;
1087 assert (file_sample[DataType::AUDIO] >= 0);
1089 ret = ((total_space - samples_to_read) > _chunk_samples);
1096 DiskReader::playlist_ranges_moved (list< Evoral::RangeMove<samplepos_t> > const & movements_samples, bool from_undo_or_shift)
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.
1102 * Likewise when shifting regions (insert/remove time)
1103 * automation is taken care of separately (busses with
1104 * automation have no disk-reader).
1107 if (from_undo_or_shift) {
1111 if (!_track || Config->get_automation_follows_regions () == false) {
1115 list< Evoral::RangeMove<double> > movements;
1117 for (list< Evoral::RangeMove<samplepos_t> >::const_iterator i = movements_samples.begin();
1118 i != movements_samples.end();
1121 movements.push_back(Evoral::RangeMove<double>(i->from, i->length, i->to));
1124 /* move panner automation */
1125 boost::shared_ptr<Pannable> pannable = _track->pannable();
1126 Evoral::ControlSet::Controls& c (pannable->controls());
1128 for (Evoral::ControlSet::Controls::iterator ci = c.begin(); ci != c.end(); ++ci) {
1129 boost::shared_ptr<AutomationControl> ac = boost::dynamic_pointer_cast<AutomationControl>(ci->second);
1133 boost::shared_ptr<AutomationList> alist = ac->alist();
1134 if (!alist->size()) {
1137 XMLNode & before = alist->get_state ();
1138 bool const things_moved = alist->move_ranges (movements);
1140 _session.add_command (new MementoCommand<AutomationList> (
1141 *alist.get(), &before, &alist->get_state ()));
1144 /* move processor automation */
1145 _track->foreach_processor (boost::bind (&DiskReader::move_processor_automation, this, _1, movements_samples));
1149 DiskReader::move_processor_automation (boost::weak_ptr<Processor> p, list< Evoral::RangeMove<samplepos_t> > const & movements_samples)
1151 boost::shared_ptr<Processor> processor (p.lock ());
1156 list< Evoral::RangeMove<double> > movements;
1157 for (list< Evoral::RangeMove<samplepos_t> >::const_iterator i = movements_samples.begin(); i != movements_samples.end(); ++i) {
1158 movements.push_back(Evoral::RangeMove<double>(i->from, i->length, i->to));
1161 set<Evoral::Parameter> const a = processor->what_can_be_automated ();
1163 for (set<Evoral::Parameter>::const_iterator i = a.begin (); i != a.end (); ++i) {
1164 boost::shared_ptr<AutomationList> al = processor->automation_control(*i)->alist();
1168 XMLNode & before = al->get_state ();
1169 bool const things_moved = al->move_ranges (movements);
1171 _session.add_command (
1172 new MementoCommand<AutomationList> (
1173 *al.get(), &before, &al->get_state ()
1181 DiskReader::reset_tracker ()
1187 DiskReader::resolve_tracker (Evoral::EventSink<samplepos_t>& buffer, samplepos_t time)
1189 _tracker.resolve_notes (buffer, time);
1192 /** Writes playback events from playback_sample for nframes to dst, translating time stamps
1193 * so that an event at playback_sample has time = 0
1196 DiskReader::get_midi_playback (MidiBuffer& dst, samplepos_t start_sample, samplepos_t end_sample, MonitorState ms, BufferSet& scratch_bufs, double speed, samplecnt_t disk_samples_to_consume)
1198 RTMidiBuffer* rtmb = rt_midibuffer();
1200 if (!rtmb || (rtmb->size() == 0)) {
1201 /* no data to read, so do nothing */
1207 if (ms & MonitoringInput) {
1208 /* data from disk needs to be *merged* not written into the
1209 dst, because it may contain input data that we want to
1210 monitor. Since RTMidiBuffer currently (Oct 2019) has no
1211 suitable method, put the disk data into a scratch buffer and
1215 target = &scratch_bufs.get_midi (0);
1217 /* No need to preserve the contents of the input buffer. But
1218 * Route::process_output_buffers() clears the buffer as-needed
1219 * so know we do not need to clear it.
1224 if (!_no_disk_output) {
1226 const samplecnt_t nframes = abs (end_sample - start_sample);
1228 if (ms & MonitoringDisk) {
1233 Location* loc = _loop_location;
1236 /* Evoral::Range has inclusive range semantics. Ugh. Hence the -1 */
1237 const Evoral::Range<samplepos_t> loop_range (loc->start(), loc->end() - 1);
1238 samplepos_t effective_start = start_sample;
1239 samplecnt_t cnt = nframes;
1241 DEBUG_TRACE (DEBUG::MidiDiskIO, string_compose ("LOOP read, loop is %1..%2 range is %3..%4\n", loc->start(), loc->end(), start_sample, end_sample));
1245 samplepos_t effective_end;
1247 effective_start = loop_range.squish (effective_start);
1248 effective_end = min (effective_start + cnt, loc->end());
1249 assert (effective_end > effective_start);
1251 const samplecnt_t this_read = effective_end - effective_start;
1253 DEBUG_TRACE (DEBUG::MidiDiskIO, string_compose ("playback buffer LOOP read, from %1 to %2 (%3)\n", effective_start, effective_end, this_read));
1255 size_t events_read = rtmb->read (*target, effective_start, effective_end, _tracker);
1257 effective_start += this_read;
1259 DEBUG_TRACE (DEBUG::MidiDiskIO, string_compose ("%1 MDS events LOOP read %2 cnt now %3\n", _name, events_read, cnt));
1262 /* We re going to have to read across the loop end. Resolve any notes the extend across the loop end.
1263 * Time is relative to start_sample.
1265 _tracker.resolve_notes (*target, effective_end - start_sample);
1271 DEBUG_TRACE (DEBUG::MidiDiskIO, string_compose ("playback buffer read, from %1 to %2 (%3)\n", start_sample, end_sample, nframes));
1272 size_t events_read = rtmb->read (*target, start_sample, end_sample, _tracker);
1273 DEBUG_TRACE (DEBUG::MidiDiskIO, string_compose ("%1 MDS events read %2 range %3 .. %4\n", _name, events_read, playback_sample, playback_sample + nframes));
1277 if (ms & MonitoringInput) {
1278 /* merges data from disk (in "target", which is a scratch
1279 buffer in this case) into the actual destination buffer
1280 (which holds existing input data).
1282 dst.merge_from (*target, nframes);
1287 if (!target->empty ()) {
1288 cerr << "======== MIDI OUT ========\n";
1289 for (MidiBuffer::iterator i = target->begin(); i != target->end(); ++i) {
1290 const Evoral::Event<MidiBuffer::TimeType> ev (*i, false);
1291 cerr << "MIDI EVENT (from disk) @ " << ev.time();
1292 for (size_t xx = 0; xx < ev.size(); ++xx) {
1293 cerr << ' ' << hex << (int) ev.buffer()[xx];
1295 cerr << dec << endl;
1297 cerr << "----------------\n";
1302 DiskReader::inc_no_disk_output ()
1304 g_atomic_int_inc (&_no_disk_output);
1308 DiskReader::dec_no_disk_output ()
1310 /* this is called unconditionally when things happen that ought to end
1311 a period of "no disk output". It's OK for that to happen when there
1312 was no corresponding call to ::inc_no_disk_output(), but we must
1313 stop the value from becoming negative.
1317 gint v = g_atomic_int_get (&_no_disk_output);
1319 if (g_atomic_int_compare_and_exchange (&_no_disk_output, v, v - 1)) {
1328 DiskReader::DeclickAmp::DeclickAmp (samplecnt_t sample_rate)
1330 _a = 4550.f / (gain_t)sample_rate;
1336 DiskReader::DeclickAmp::apply_gain (AudioBuffer& buf, samplecnt_t n_samples, const float target, sampleoffset_t buffer_offset)
1338 if (n_samples == 0) {
1344 assert (buffer_offset == 0);
1345 Amp::apply_simple_gain (buf, n_samples, target, 0);
1350 Sample* const buffer = buf.data ();
1352 const int max_nproc = 16;
1353 uint32_t remain = n_samples;
1354 uint32_t offset = buffer_offset;
1356 while (remain > 0) {
1357 uint32_t n_proc = remain > max_nproc ? max_nproc : remain;
1358 for (uint32_t i = 0; i < n_proc; ++i) {
1359 buffer[offset + i] *= g;
1362 g += a * (target - g);
1363 #else /* accurate exponential fade */
1364 if (n_proc == max_nproc) {
1365 g += a * (target - g);
1367 g = target - (target - g) * expf (_l * n_proc / max_nproc);
1374 if (fabsf (g - target) < /* GAIN_COEFF_DELTA */ 1e-5) {
1381 DiskReader::Declicker::Declicker ()
1389 DiskReader::Declicker::~Declicker ()
1395 DiskReader::Declicker::alloc (samplecnt_t sr, bool fadein)
1398 vec = new Sample[loop_fade_length];
1400 const float a = 1024.0f / sr;
1402 /* build a psuedo-exponential (linear-volume) shape for the fade */
1406 #define GAIN_COEFF_DELTA (1e-5)
1410 for (n = 0; (n < sr) && ((1.0 - g) > GAIN_COEFF_DELTA); ++n) {
1416 for (n = 0; (n < sr) && (g > GAIN_COEFF_DELTA); ++n) {
1424 /* zero out the rest just to be safe */
1426 memset (&vec[n], 0, sizeof (gain_t) * (loop_fade_length - n));
1428 #undef GAIN_COEFF_DELTA
1432 DiskReader::Declicker::reset (samplepos_t loop_start, samplepos_t loop_end, bool fadein, samplecnt_t sr)
1434 if (loop_start == loop_end) {
1440 /* adjust the position of the fade (this is absolute (global) timeline units) */
1443 fade_start = loop_start;
1444 fade_end = loop_start + fade_length;
1446 fade_start = loop_end - fade_length;
1447 fade_end = loop_end;
1453 DiskReader::Declicker::run (Sample* buf, samplepos_t read_start, samplepos_t read_end)
1455 samplecnt_t n; /* how many samples to process */
1456 sampleoffset_t bo; /* offset into buffer */
1457 sampleoffset_t vo; /* offset into gain vector */
1459 if (fade_start == fade_end) {
1463 /* Determine how the read range overlaps with the fade range, so we can determine which part of the fade gain vector
1464 to apply to which part of the buffer.
1467 switch (Evoral::coverage (fade_start, fade_end, read_start, read_end)) {
1469 case Evoral::OverlapInternal:
1470 /* note: start and end points cannot coincide (see evoral/Range.h)
1472 * read range is entirely within fade range
1475 vo = read_start - fade_start;
1476 n = read_end - read_start;
1479 case Evoral::OverlapExternal:
1480 /* read range extends on either side of fade range
1482 * External allows coincidental start & end points, so check for that
1484 if (fade_start == read_start && fade_end == read_end) {
1485 /* fade entire read ... this is SO unlikely ! */
1488 n = fade_end - fade_start;
1490 bo = fade_start - read_start;
1492 n = fade_end - fade_start;
1496 case Evoral::OverlapStart:
1497 /* read range starts before and ends within fade or at same end as fade */
1498 n = fade_end - read_start;
1500 bo = fade_start - read_start;
1503 case Evoral::OverlapEnd:
1504 /* read range starts within fade range, but possibly at it's end, so check */
1505 if (read_start == fade_end) {
1510 vo = read_start - fade_start;
1511 n = fade_end - read_start;
1514 case Evoral::OverlapNone:
1515 /* no overlap ... nothing to do */
1519 Sample* b = &buf[bo];
1520 gain_t* g = &vec[vo];
1522 for (sampleoffset_t i = 0; i < n; ++i) {
1528 DiskReader::maybe_xfade_loop (Sample* buf, samplepos_t read_start, samplepos_t read_end, ReaderChannelInfo* chan)
1530 samplecnt_t n; /* how many samples to process */
1531 sampleoffset_t bo; /* offset into buffer */
1532 sampleoffset_t vo; /* offset into gain vector */
1534 const samplepos_t fade_start = loop_declick_out.fade_start;
1535 const samplepos_t fade_end = loop_declick_out.fade_end;
1537 if (fade_start == fade_end) {
1541 /* Determine how the read range overlaps with the fade range, so we can determine which part of the fade gain vector
1542 to apply to which part of the buffer.
1545 switch (Evoral::coverage (fade_start, fade_end, read_start, read_end)) {
1547 case Evoral::OverlapInternal:
1548 /* note: start and end points cannot coincide (see evoral/Range.h)
1550 * read range is entirely within fade range
1553 vo = read_start - fade_start;
1554 n = read_end - read_start;
1557 case Evoral::OverlapExternal:
1558 /* read range extends on either side of fade range
1560 * External allows coincidental start & end points, so check for that
1562 if (fade_start == read_start && fade_end == read_end) {
1563 /* fade entire read ... this is SO unlikely ! */
1566 n = fade_end - fade_start;
1568 bo = fade_start - read_start;
1570 n = fade_end - fade_start;
1574 case Evoral::OverlapStart:
1575 /* read range starts before and ends within fade or at same end as fade */
1576 n = fade_end - read_start;
1578 bo = fade_start - read_start;
1581 case Evoral::OverlapEnd:
1582 /* read range starts within fade range, but possibly at it's end, so check */
1583 if (read_start == fade_end) {
1588 vo = read_start - fade_start;
1589 n = fade_end - read_start;
1592 case Evoral::OverlapNone:
1593 /* no overlap ... nothing to do */
1597 Sample* b = &buf[bo]; /* data to be faded out */
1598 Sample* sbuf = &chan->pre_loop_buffer[vo]; /* pre-loop (maybe silence) to be faded in */
1599 gain_t* og = &loop_declick_out.vec[vo]; /* fade out gain vector */
1600 gain_t* ig = &loop_declick_in.vec[vo]; /* fade in gain vector */
1602 for (sampleoffset_t i = 0; i < n; ++i) {
1603 b[i] = (b[i] * og[i]) + (sbuf[i] * ig[i]);
1608 DiskReader::rt_midibuffer ()
1610 boost::shared_ptr<Playlist> pl = _playlists[DataType::MIDI];
1616 boost::shared_ptr<MidiPlaylist> mpl = boost::dynamic_pointer_cast<MidiPlaylist> (pl);
1619 /* error, but whatever ... */
1623 return mpl->rendered();
1627 DiskReader::alloc_loop_declick (samplecnt_t sr)
1629 loop_fade_length = lrintf (ceil (-log (1e-5) / (1024.f/sr)));
1630 loop_declick_in.alloc (sr, true);
1631 loop_declick_out.alloc (sr, false);
1635 DiskReader::reset_loop_declick (Location* loc, samplecnt_t sr)
1638 loop_declick_in.reset (loc->start(), loc->end(), true, sr);
1639 loop_declick_out.reset (loc->start(), loc->end(), false, sr);
1641 loop_declick_in.reset (0, 0, true, sr);
1642 loop_declick_out.reset (0, 0, false, sr);
1647 DiskReader::set_loop (Location* loc)
1649 Processor::set_loop (loc);
1659 DiskReader::reload_loop ()
1661 if (!_loop_location) {
1665 boost::shared_ptr<ChannelList> c = channels.reader();
1667 if (c->empty() || !_playlists[DataType::MIDI]) {
1671 Location* loc = _loop_location;
1672 boost::scoped_array<Sample> mix_buf (new Sample [loop_fade_length]);
1673 boost::scoped_array<Sample> gain_buf (new Sample [loop_fade_length]);
1675 uint32_t channel = 0;
1677 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++channel) {
1679 ReaderChannelInfo* rci = dynamic_cast<ReaderChannelInfo*> (*chan);
1681 rci->resize_preloop (loop_fade_length);
1683 if (loc->start() > loop_fade_length) {
1684 audio_playlist()->read (rci->pre_loop_buffer, mix_buf.get(), gain_buf.get(), loc->start() - loop_declick_out.fade_length, loop_declick_out.fade_length, channel);
1686 memset (rci->pre_loop_buffer, 0, sizeof (Sample) * loop_fade_length);
1693 DiskReader::can_support_io_configuration (const ChanCount& in, ChanCount& out)
1695 if (!DiskIOProcessor::can_support_io_configuration (in, out)) {
1699 /* DiskIO might have done this too, but do it again anyway as a
1705 if (_playlists[DataType::AUDIO]) {
1706 ChannelList::size_type naudio = max (ChannelList::size_type (1), channels.reader()->size());
1707 if (out.n_audio() < naudio) {
1708 out.set (DataType::AUDIO, naudio);
1712 if (_playlists[DataType::MIDI]) {
1713 if (out.n_midi() != 1) {
1714 out.set (DataType::MIDI, 1);