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 samplecnt_t DiskReader::midi_readahead = 4096;
56 gint DiskReader::_no_disk_output (0);
57 DiskReader::Declicker DiskReader::loop_declick_in;
58 DiskReader::Declicker DiskReader::loop_declick_out;
59 samplecnt_t DiskReader::loop_fade_length (0);
61 DiskReader::DiskReader (Session& s, string const & str, DiskIOProcessor::Flag f)
62 : DiskIOProcessor (s, str, f)
63 , overwrite_sample (0)
64 , overwrite_queued (false)
65 , run_must_resolve (false)
66 , _declick_amp (s.nominal_sample_rate ())
69 file_sample[DataType::AUDIO] = 0;
70 file_sample[DataType::MIDI] = 0;
71 g_atomic_int_set (&_pending_overwrite, 0);
74 DiskReader::~DiskReader ()
76 DEBUG_TRACE (DEBUG::Destruction, string_compose ("DiskReader %1 @ %2 deleted\n", _name, this));
80 DiskReader::ReaderChannelInfo::resize (samplecnt_t bufsize)
82 /* caller must hold rbuf lock */
84 delete rbuf; rbuf = 0;
86 rbuf = new PlaybackBuffer<Sample> (bufsize);
87 /* touch memory to lock it */
88 memset (rbuf->buffer(), 0, sizeof (Sample) * rbuf->bufsize());
92 DiskReader::ReaderChannelInfo::resize_preloop (samplecnt_t bufsize)
98 if (bufsize > pre_loop_buffer_size) {
99 delete [] pre_loop_buffer;
100 pre_loop_buffer = new Sample[bufsize];
101 pre_loop_buffer_size = bufsize;
106 DiskReader::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
109 c->push_back (new ReaderChannelInfo (_session.butler()->audio_diskstream_playback_buffer_size(), loop_fade_length));
110 DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1: new reader channel, write space = %2 read = %3\n",
112 c->back()->rbuf->write_space(),
113 c->back()->rbuf->read_space()));
120 DiskReader::allocate_working_buffers()
122 /* with varifill buffer refilling, we compute the read size in bytes (to optimize
123 for disk i/o bandwidth) and then convert back into samples. These buffers
124 need to reflect the maximum size we could use, which is 4MB reads, or 2M samples
125 using 16 bit samples.
127 _sum_buffer = new Sample[2*1048576];
128 _mixdown_buffer = new Sample[2*1048576];
129 _gain_buffer = new gain_t[2*1048576];
133 DiskReader::free_working_buffers()
135 delete [] _sum_buffer;
136 delete [] _mixdown_buffer;
137 delete [] _gain_buffer;
144 DiskReader::default_chunk_samples()
150 DiskReader::set_name (string const & str)
152 string my_name = X_("player:");
155 if (_name != my_name) {
156 SessionObject::set_name (my_name);
165 XMLNode& node (DiskIOProcessor::state ());
166 node.set_property(X_("type"), X_("diskreader"));
171 DiskReader::set_state (const XMLNode& node, int version)
173 if (DiskIOProcessor::set_state (node, version)) {
181 DiskReader::realtime_handle_transport_stopped ()
183 /* can't do the resolve here because we don't have a place to put the
184 * note resolving data. Defer to
185 * MidiTrack::realtime_handle_transport_stopped() which will call
186 * ::resolve_tracker() and put the output in its _immediate_events store.
191 DiskReader::realtime_locate (bool for_loop_end)
194 std::cerr << name() << "DO note resolve on locate for loop\n";
195 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack>(_track);
196 _tracker.resolve_notes (mt->immediate_events(), 0);
198 std::cerr << name() << "skip note resolve on locate for loop\n";
203 DiskReader::buffer_load () const
205 /* Note: for MIDI it's not trivial to differentiate the following two cases:
207 1. The playback buffer is empty because the system has run out of time to fill it.
208 2. The playback buffer is empty because there is no more data on the playlist.
210 If we use a simple buffer load computation, we will report that the MIDI diskstream
211 cannot keep up when #2 happens, when in fact it can. Since MIDI data rates
212 are so low compared to audio, just use the audio value here.
215 boost::shared_ptr<ChannelList> c = channels.reader();
218 /* no channels, so no buffers, so completely full and ready to playback, sir! */
222 PBD::PlaybackBuffer<Sample>* b = c->front()->rbuf;
223 return (float) ((double) b->read_space() / (double) b->bufsize());
227 DiskReader::adjust_buffering ()
229 Glib::Threads::Mutex::Lock lm (rbuf_lock);
230 boost::shared_ptr<ChannelList> c = channels.reader();
232 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
233 (*chan)->resize (_session.butler()->audio_diskstream_playback_buffer_size());
238 DiskReader::playlist_modified ()
240 if (!overwrite_queued) {
241 _session.request_overwrite_buffer (_track, PlaylistModified);
242 overwrite_queued = true;
247 DiskReader::use_playlist (DataType dt, boost::shared_ptr<Playlist> playlist)
249 bool prior_playlist = false;
251 if (_playlists[dt]) {
252 prior_playlist = true;
255 if (DiskIOProcessor::use_playlist (dt, playlist)) {
259 /* don't do this if we've already asked for it *or* if we are setting up
260 the diskstream for the very first time - the input changed handling will
261 take care of the buffer refill.
264 if (!overwrite_queued && (prior_playlist || _session.loading())) {
265 _session.request_overwrite_buffer (_track, PlaylistModified);
266 overwrite_queued = true;
273 DiskReader::run (BufferSet& bufs, samplepos_t start_sample, samplepos_t end_sample, double speed, pframes_t nframes, bool result_required)
276 boost::shared_ptr<ChannelList> c = channels.reader();
277 ChannelList::iterator chan;
278 sampleoffset_t disk_samples_to_consume;
279 MonitorState ms = _track->monitoring_state ();
281 // std::cerr << name() << " run " << start_sample << " .. " << end_sample << " speed = " << speed << std::endl;
283 if (!_pending_active) {
288 if (_pending_active) {
295 const gain_t target_gain = ((speed == 0.0) || ((ms & MonitoringDisk) == 0)) ? 0.0 : 1.0;
296 const bool declicked_out = (_declick_amp.gain() == target_gain) && target_gain == 0.0;
297 const bool declick_out = (_declick_amp.gain() != target_gain) && target_gain == 0.0;
299 if (!_session.cfg ()->get_use_transport_fades ()) {
300 _declick_amp.set_gain (target_gain);
303 if (declicked_out && (ms == MonitoringDisk)) {
304 /* Stopped and declicking has finished. Don't accidentally pass
305 * any data from disk into our outputs (e.g. via interpolation)
310 BufferSet& scratch_bufs (_session.get_scratch_buffers (bufs.count()));
311 const bool still_locating = _session.global_locate_pending();
313 assert (speed == -1 || speed == 0 || speed == 1);
316 disk_samples_to_consume = 0;
318 disk_samples_to_consume = nframes;
322 /* do nothing with audio */
329 // 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());
331 ms = MonitorState (ms | MonitoringDisk);
332 assert (result_required);
333 result_required = true;
338 if (!result_required || ((ms & MonitoringDisk) == 0) || still_locating || _no_disk_output) {
340 /* no need for actual disk data, just advance read pointer */
342 if (!still_locating || _no_disk_output) {
343 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
344 assert ((*chan)->rbuf);
345 (*chan)->rbuf->increment_read_ptr (disk_samples_to_consume);
349 /* if monitoring disk but locating put silence in the buffers */
351 if ((_no_disk_output || still_locating) && (ms == MonitoringDisk)) {
352 bufs.silence (nframes, 0);
357 /* we need audio data from disk */
359 size_t n_buffers = bufs.count().n_audio();
360 size_t n_chans = c->size();
363 if (n_chans > n_buffers) {
364 scaling = ((float) n_buffers) / n_chans;
369 const float initial_declick_gain = _declick_amp.gain ();
370 const sampleoffset_t declick_offs = _declick_offs;
372 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
374 ChannelInfo* chaninfo (*chan);
375 AudioBuffer& output (bufs.get_audio (n % n_buffers));
377 AudioBuffer& disk_buf ((ms & MonitoringInput) ? scratch_bufs.get_audio(n) : output);
379 if (start_sample != playback_sample && target_gain != 0) {
380 cerr << name() << " Not at start (" << start_sample << ") ps = " << playback_sample << " iseek (" << start_sample - playback_sample << endl;
381 if (can_internal_playback_seek (start_sample - playback_sample)) {
382 internal_playback_seek (start_sample - playback_sample);
384 disk_samples_to_consume = 0; /* will force an underrun below */
388 /* reset _declick_amp to the correct gain before processing this channel. */
390 _declick_amp.set_gain (initial_declick_gain);
396 const samplecnt_t total = chaninfo->rbuf->read (disk_buf.data(), disk_samples_to_consume);
398 if (disk_samples_to_consume > total) {
399 cerr << _name << " Need " << total << " have only " << disk_samples_to_consume << endl;
400 cerr << "underrun for " << _name << endl;
401 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 underrun in %2, total space = %3\n",
402 DEBUG_THREAD_SELF, name(), total));
407 } else if (_declick_amp.gain() != target_gain) {
409 assert (target_gain == 0);
411 /* note that this is a non-committing read: it
412 retrieves data from the ringbuffer but does not
413 advance the read pointer. As a result,
414 subsequent calls (as we declick) need to
415 pass in an offset describing where to read
416 from. We maintain _declick_offs across calls
420 const samplecnt_t total = chaninfo->rbuf->read (disk_buf.data(), nframes, false, declick_offs);
423 _declick_offs += total;
427 _declick_amp.apply_gain (disk_buf, nframes, target_gain);
429 /* _declick_amp is now left with the correct gain after
433 Amp::apply_simple_gain (disk_buf, nframes, scaling);
435 if (ms & MonitoringInput) {
436 /* mix the disk signal into the input signal (already in bufs) */
437 mix_buffers_no_gain (output.data(), disk_buf.data(), nframes);
443 /* MIDI data handling */
445 const bool midi_data_available = !(pending_overwrite() & PlaylistModified);
447 if (bufs.count().n_midi()) {
449 MidiBuffer& dst (bufs.get_midi (0));
451 if (run_must_resolve) {
452 resolve_tracker (dst, 0);
453 run_must_resolve = false;
456 if (!_no_disk_output && !declick_in_progress() && (ms & MonitoringDisk) && !still_locating && speed) {
457 get_midi_playback (dst, start_sample, end_sample, ms, scratch_bufs, speed, disk_samples_to_consume);
461 /* decide if we need the butler */
463 if (!still_locating && midi_data_available) {
465 bool butler_required = false;
468 playback_sample -= disk_samples_to_consume;
470 playback_sample += disk_samples_to_consume;
473 Location* loc = _loop_location;
475 Evoral::Range<samplepos_t> loop_range (loc->start(), loc->end() - 1);
476 playback_sample = loop_range.squish (playback_sample);
479 if (_playlists[DataType::AUDIO]) {
482 if (c->front()->rbuf->write_space() >= c->front()->rbuf->bufsize() / 2) {
483 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1: slaved, write space = %2 of %3\n", name(), c->front()->rbuf->write_space(), c->front()->rbuf->bufsize()));
484 butler_required = true;
487 if ((samplecnt_t) c->front()->rbuf->write_space() >= _chunk_samples) {
488 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1: write space = %2 of %3\n", name(), c->front()->rbuf->write_space(),
490 butler_required = true;
496 /* All of MIDI is in RAM, no need to call the butler unless we
497 * have to overwrite buffers because of a playlist change.
500 _need_butler = butler_required;
503 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 reader run, needs butler = %2\n", name(), _need_butler));
507 DiskReader::declick_in_progress () const
509 return _declick_amp.gain() != 0; // declick-out
513 DiskReader::pending_overwrite () const
515 return g_atomic_int_get (&_pending_overwrite) != 0;
519 DiskReader::set_pending_overwrite (OverwriteReason why)
521 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
523 overwrite_sample = playback_sample;
524 boost::shared_ptr<ChannelList> c = channels.reader ();
526 overwrite_offset = c->front()->rbuf->read_ptr();
530 OverwriteReason current = OverwriteReason (g_atomic_int_get (&_pending_overwrite));
531 OverwriteReason next = OverwriteReason (current | why);
532 if (g_atomic_int_compare_and_exchange (&_pending_overwrite, current, next)) {
537 run_must_resolve = true;
541 DiskReader::overwrite_existing_audio ()
543 boost::shared_ptr<ChannelList> c = channels.reader();
549 const bool reversed = _session.transport_speed() < 0.0f;
551 /* assume all are the same size */
553 samplecnt_t size = c->front()->rbuf->bufsize () - c->front()->rbuf->reserved_size() - 1;
556 boost::scoped_array<Sample> mixdown_buffer (new Sample[size]);
557 boost::scoped_array<float> gain_buffer (new float[size]);
561 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
563 samplepos_t start = overwrite_sample;
565 /* to fill the buffer without resetting the playback sample, we need to
566 do it one or two chunks (normally two).
568 |----------------------------------------------------------------------|
570 RESERVED overwrite_offset (old read_ptr)
571 |<- second chunk->|<-------------><---- first chunk ------------------>|
575 samplecnt_t to_read = size - overwrite_offset;
576 Sample* buf = (*chan)->rbuf->buffer();
577 ReaderChannelInfo* rci = dynamic_cast<ReaderChannelInfo*> (*chan);
580 if ((nread = audio_read (buf + overwrite_offset, mixdown_buffer.get(), gain_buffer.get(), start, to_read, rci, n, reversed)) != to_read) {
581 error << string_compose(_("DiskReader %1: when overwriting(1), cannot read %2 from playlist at sample %3"), id(), to_read, overwrite_sample) << endmsg;
586 if (size > to_read) {
588 to_read = size - to_read;
590 if ((nread = audio_read (buf, mixdown_buffer.get(), gain_buffer.get(), start, to_read, rci, n, reversed)) != to_read) {
591 error << string_compose(_("DiskReader %1: when overwriting(2), cannot read %2 from playlist at sample %3"), id(), to_read, overwrite_sample) << endmsg;
601 DiskReader::overwrite_existing_midi ()
603 RTMidiBuffer* mbuf = rt_midibuffer ();
606 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack>(_track);
607 MidiChannelFilter* filter = mt ? &mt->playback_filter() : 0;
612 midi_playlist()->render (filter);
615 assert (midi_playlist()->rendered());
616 cerr << "Reading " << name() << " took " << minsert.elapsed() << " microseconds, final size = " << midi_playlist()->rendered()->size() << endl;
623 DiskReader::overwrite_existing_buffers ()
625 /* called from butler thread */
627 DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1 overwriting existing buffers at %2\n", owner()->name(), overwrite_sample));
630 if (g_atomic_int_get (&_pending_overwrite) & (PlaylistModified|LoopDisabled|LoopChanged)) {
631 if (!overwrite_existing_audio ()) {
636 if (g_atomic_int_get (&_pending_overwrite) & (LoopChanged|LoopDisabled)) {
637 if (!overwrite_existing_midi ()) {
642 g_atomic_int_set (&_pending_overwrite, 0);
648 DiskReader::seek (samplepos_t sample, bool complete_refill)
650 /* called via non_realtime_locate() from butler thread */
654 ChannelList::iterator chan;
655 boost::shared_ptr<ChannelList> c = channels.reader();
657 if (sample == playback_sample && !complete_refill) {
658 return 0; // XXX double-check this
661 g_atomic_int_set (&_pending_overwrite, 0);
663 DEBUG_TRACE (DEBUG::DiskIO, string_compose ("DiskReader::seek %s %ld -> %ld refill=%d\n", owner()->name().c_str(), playback_sample, sample, complete_refill));
665 const samplecnt_t distance = sample - playback_sample;
666 if (!complete_refill && can_internal_playback_seek (distance)) {
667 internal_playback_seek (distance);
671 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
672 (*chan)->rbuf->reset ();
675 playback_sample = sample;
676 file_sample[DataType::AUDIO] = sample;
677 file_sample[DataType::MIDI] = sample;
679 if (complete_refill) {
680 /* call _do_refill() to refill the entire buffer, using
681 the largest reads possible.
683 while ((ret = do_refill_with_alloc (false)) > 0) ;
685 /* call _do_refill() to refill just one chunk, and then
688 ret = do_refill_with_alloc (true);
695 DiskReader::can_internal_playback_seek (sampleoffset_t distance)
699 ChannelList::iterator chan;
700 boost::shared_ptr<ChannelList> c = channels.reader();
702 for (chan = c->begin(); chan != c->end(); ++chan) {
703 if (!(*chan)->rbuf->can_seek (distance)) {
708 /* 2. MIDI can always seek any distance */
714 DiskReader::internal_playback_seek (sampleoffset_t distance)
720 sampleoffset_t off = distance;
722 ChannelList::iterator chan;
723 boost::shared_ptr<ChannelList> c = channels.reader();
724 for (chan = c->begin(); chan != c->end(); ++chan) {
726 off = 0 - (sampleoffset_t) (*chan)->rbuf->decrement_read_ptr (::llabs (distance));
728 off = (*chan)->rbuf->increment_read_ptr (distance);
732 playback_sample += off;
736 void swap_by_ptr (Sample *first, Sample *last)
738 while (first < last) {
745 /** Read some data for 1 channel from our playlist into a buffer.
746 * @param buf Buffer to write to.
747 * @param start Session sample to start reading from; updated to where we end up
749 * @param cnt Count of samples to read.
750 * @param reversed true if we are running backwards, otherwise false.
753 DiskReader::audio_read (Sample* sum_buffer,
754 Sample* mixdown_buffer,
758 ReaderChannelInfo* rci,
762 samplecnt_t this_read = 0;
764 samplepos_t loop_end = 0;
765 samplepos_t loop_start = 0;
767 const samplecnt_t rcnt = cnt;
769 /* XXX we don't currently play loops in reverse. not sure why */
773 samplecnt_t loop_length = 0;
775 /* Make the use of a Location atomic for this read operation.
777 Note: Locations don't get deleted, so all we care about
778 when I say "atomic" is that we are always pointing to
779 the same one and using a start/length values obtained
783 if ((loc = _loop_location) != 0) {
784 loop_start = loc->start();
785 loop_end = loc->end();
786 loop_length = loop_end - loop_start;
789 /* if we are looping, ensure that the first sample we read is at the correct
790 position within the loop.
793 if (loc && start >= loop_end) {
794 start = loop_start + ((start - loop_start) % loop_length);
803 /* We need this while loop in case we hit a loop boundary, in which case our read from
804 the playlist must be split into more than one section.
809 /* take any loop into account. we can't read past the end of the loop. */
811 if (loc && (loop_end - start < cnt)) {
812 this_read = loop_end - start;
819 if (this_read == 0) {
823 this_read = min (cnt, this_read);
825 /* note that the mixdown and gain buffers are purely for the
826 * internal use of the playlist, and cannot be considered
827 * useful after the return from AudioPlayback::read()
830 if (audio_playlist()->read (sum_buffer, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
831 error << string_compose(_("DiskReader %1: cannot read %2 from playlist at sample %3"), id(), this_read, start) << endmsg;
837 /* Looping: do something (maybe) about the loop boundaries */
839 switch (Config->get_loop_fade_choice()) {
843 loop_declick_in.run (sum_buffer, start, start + this_read);
844 loop_declick_out.run (sum_buffer, start, start + this_read);
847 loop_declick_out.run (sum_buffer, start, start + this_read);
850 maybe_xfade_loop (sum_buffer, start, start + this_read, rci);
857 swap_by_ptr (sum_buffer, sum_buffer + this_read - 1);
861 /* if we read to the end of the loop, go back to the beginning */
871 sum_buffer += this_read;
878 DiskReader::_do_refill_with_alloc (bool partial_fill)
880 /* We limit disk reads to at most 4MB chunks, which with floating point
881 samples would be 1M samples. But we might use 16 or 14 bit samples,
882 in which case 4MB is more samples than that. Therefore size this for
883 the smallest sample value .. 4MB = 2M samples (16 bit).
886 boost::scoped_array<Sample> sum_buf (new Sample[2*1048576]);
887 boost::scoped_array<Sample> mix_buf (new Sample[2*1048576]);
888 boost::scoped_array<float> gain_buf (new float[2*1048576]);
890 return refill_audio (sum_buf.get(), mix_buf.get(), gain_buf.get(), (partial_fill ? _chunk_samples : 0));
894 DiskReader::refill (Sample* sum_buffer, Sample* mixdown_buffer, float* gain_buffer, samplecnt_t fill_level)
896 if (refill_audio (sum_buffer, mixdown_buffer, gain_buffer, fill_level)) {
900 if (rt_midibuffer() && (_session.transport_speed() < 0.0f) != rt_midibuffer()->reversed()) {
901 rt_midibuffer()->reverse ();
908 /** Get some more data from disk and put it in our channels' bufs,
909 * if there is suitable space in them.
911 * If fill_level is non-zero, then we will refill the buffer so that there is
912 * still at least fill_level samples of space left to be filled. This is used
913 * after locates so that we do not need to wait to fill the entire buffer.
918 DiskReader::refill_audio (Sample* sum_buffer, Sample* mixdown_buffer, float* gain_buffer, samplecnt_t fill_level)
920 /* do not read from disk while session is marked as Loading, to avoid
921 useless redundant I/O.
924 if (_session.loading()) {
929 bool const reversed = _session.transport_speed() < 0.0f;
930 samplecnt_t zero_fill;
932 ChannelList::iterator i;
933 boost::shared_ptr<ChannelList> c = channels.reader();
939 assert(mixdown_buffer);
942 samplecnt_t total_space = c->front()->rbuf->write_space();
944 if (total_space == 0) {
945 DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1: no space to refill\n", name()));
946 /* nowhere to write to */
951 if (fill_level < total_space) {
952 total_space -= fill_level;
954 /* we can't do anything with it */
959 /* if we're running close to normal speed and there isn't enough
960 space to do disk_read_chunk_samples of I/O, then don't bother.
962 at higher speeds, just do it because the sync between butler
963 and audio thread may not be good enough.
965 Note: it is a design assumption that disk_read_chunk_samples is smaller
966 than the playback buffer size, so this check should never trip when
967 the playback buffer is empty.
970 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()));
971 if ((total_space < _chunk_samples) && fabs (_session.transport_speed()) < 2.0f) {
975 /* when slaved, don't try to get too close to the read pointer. this
976 leaves space for the buffer reversal to have something useful to
980 if (_slaved && total_space < (samplecnt_t) (c->front()->rbuf->bufsize() / 2)) {
981 DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1: not enough to refill while slaved\n", this));
985 samplepos_t ffa = file_sample[DataType::AUDIO];
990 /* at start: nothing to do but fill with silence */
991 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
992 ChannelInfo* chan (*i);
993 chan->rbuf->write_zero (chan->rbuf->write_space ());
998 if (ffa < total_space) {
999 /* too close to the start: read what we can, and then zero fill the rest */
1000 zero_fill = total_space - ffa;
1008 if (ffa == max_samplepos) {
1009 /* at end: nothing to do but fill with silence */
1010 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1011 ChannelInfo* chan (*i);
1012 chan->rbuf->write_zero (chan->rbuf->write_space ());
1017 if (ffa > max_samplepos - total_space) {
1018 /* to close to the end: read what we can, and zero fill the rest */
1019 zero_fill = total_space - (max_samplepos - ffa);
1020 total_space = max_samplepos - ffa;
1027 /* total_space is in samples. We want to optimize read sizes in various sizes using bytes */
1028 const size_t bits_per_sample = format_data_width (_session.config.get_native_file_data_format());
1029 size_t total_bytes = total_space * bits_per_sample / 8;
1031 /* chunk size range is 256kB to 4MB. Bigger is faster in terms of MB/sec, but bigger chunk size always takes longer */
1032 size_t byte_size_for_read = max ((size_t) (256 * 1024), min ((size_t) (4 * 1048576), total_bytes));
1034 /* find nearest (lower) multiple of 16384 */
1036 byte_size_for_read = (byte_size_for_read / 16384) * 16384;
1038 /* now back to samples */
1039 samplecnt_t samples_to_read = byte_size_for_read / (bits_per_sample / 8);
1041 DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1: will refill %2 channels with %3 samples\n", name(), c->size(), total_space));
1043 samplepos_t file_sample_tmp = ffa;
1045 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1047 ChannelInfo* chan (*i);
1048 file_sample_tmp = ffa;
1049 samplecnt_t ts = total_space;
1051 samplecnt_t to_read = min (ts, (samplecnt_t) chan->rbuf->write_space ());
1052 to_read = min (to_read, samples_to_read);
1053 assert (to_read >= 0);
1055 // cerr << owner()->name() << " to-read: " << to_read << endl;
1058 ReaderChannelInfo* rci = dynamic_cast<ReaderChannelInfo*> (chan);
1061 cerr << name() << ' ' << chan_n << " refill read @ " << file_sample_tmp << " tr " << to_read << " ts was " << ts << "scnt " << samples_to_read << " ws " << chan->rbuf->write_space() << endl;
1063 if (!_playlists[DataType::AUDIO]) {
1065 chan->rbuf->write_zero (to_read);
1069 if ((nread = audio_read (sum_buffer, mixdown_buffer, gain_buffer, file_sample_tmp, to_read, rci, chan_n, reversed)) != to_read) {
1070 error << string_compose(_("DiskReader %1: when refilling, cannot read %2 from playlist at sample %3"), name(), to_read, ffa) << endmsg;
1075 if (chan->rbuf->write (sum_buffer, nread) != nread) {
1076 error << string_compose(_("DiskReader %1: when refilling, cannot write %2 into buffer"), name(), nread) << endmsg;
1083 /* not sure if action is needed,
1084 * we'll later hit the "to close to the end" case
1086 //chan->rbuf->write_zero (zero_fill);
1090 // elapsed = g_get_monotonic_time () - before;
1091 // cerr << '\t' << name() << ": bandwidth = " << (byte_size_for_read / 1048576.0) / (elapsed/1000000.0) << "MB/sec\n";
1093 file_sample[DataType::AUDIO] = file_sample_tmp;
1094 assert (file_sample[DataType::AUDIO] >= 0);
1096 ret = ((total_space - samples_to_read) > _chunk_samples);
1103 DiskReader::playlist_ranges_moved (list< Evoral::RangeMove<samplepos_t> > const & movements_samples, bool from_undo_or_shift)
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.
1109 * Likewise when shifting regions (insert/remove time)
1110 * automation is taken care of separately (busses with
1111 * automation have no disk-reader).
1114 if (from_undo_or_shift) {
1118 if (!_track || Config->get_automation_follows_regions () == false) {
1122 list< Evoral::RangeMove<double> > movements;
1124 for (list< Evoral::RangeMove<samplepos_t> >::const_iterator i = movements_samples.begin();
1125 i != movements_samples.end();
1128 movements.push_back(Evoral::RangeMove<double>(i->from, i->length, i->to));
1131 /* move panner automation */
1132 boost::shared_ptr<Pannable> pannable = _track->pannable();
1133 Evoral::ControlSet::Controls& c (pannable->controls());
1135 for (Evoral::ControlSet::Controls::iterator ci = c.begin(); ci != c.end(); ++ci) {
1136 boost::shared_ptr<AutomationControl> ac = boost::dynamic_pointer_cast<AutomationControl>(ci->second);
1140 boost::shared_ptr<AutomationList> alist = ac->alist();
1141 if (!alist->size()) {
1144 XMLNode & before = alist->get_state ();
1145 bool const things_moved = alist->move_ranges (movements);
1147 _session.add_command (new MementoCommand<AutomationList> (
1148 *alist.get(), &before, &alist->get_state ()));
1151 /* move processor automation */
1152 _track->foreach_processor (boost::bind (&DiskReader::move_processor_automation, this, _1, movements_samples));
1156 DiskReader::move_processor_automation (boost::weak_ptr<Processor> p, list< Evoral::RangeMove<samplepos_t> > const & movements_samples)
1158 boost::shared_ptr<Processor> processor (p.lock ());
1163 list< Evoral::RangeMove<double> > movements;
1164 for (list< Evoral::RangeMove<samplepos_t> >::const_iterator i = movements_samples.begin(); i != movements_samples.end(); ++i) {
1165 movements.push_back(Evoral::RangeMove<double>(i->from, i->length, i->to));
1168 set<Evoral::Parameter> const a = processor->what_can_be_automated ();
1170 for (set<Evoral::Parameter>::const_iterator i = a.begin (); i != a.end (); ++i) {
1171 boost::shared_ptr<AutomationList> al = processor->automation_control(*i)->alist();
1175 XMLNode & before = al->get_state ();
1176 bool const things_moved = al->move_ranges (movements);
1178 _session.add_command (
1179 new MementoCommand<AutomationList> (
1180 *al.get(), &before, &al->get_state ()
1188 DiskReader::reset_tracker ()
1194 DiskReader::resolve_tracker (Evoral::EventSink<samplepos_t>& buffer, samplepos_t time)
1196 _tracker.resolve_notes (buffer, time);
1199 /** Writes playback events from playback_sample for nframes to dst, translating time stamps
1200 * so that an event at playback_sample has time = 0
1203 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)
1205 RTMidiBuffer* rtmb = rt_midibuffer();
1207 if (!rtmb || (rtmb->size() == 0)) {
1208 /* no data to read, so do nothing */
1214 if (ms & MonitoringInput) {
1215 /* data from disk needs to be *merged* not written into the
1216 dst, because it may contain input data that we want to
1217 monitor. Since RTMidiBuffer currently (Oct 2019) has no
1218 suitable method, put the disk data into a scratch buffer and
1222 target = &scratch_bufs.get_midi (0);
1224 /* No need to preserve the contents of the input buffer. But
1225 * Route::process_output_buffers() clears the buffer as-needed
1226 * so know we do not need to clear it.
1231 if (!_no_disk_output) {
1233 const samplecnt_t nframes = abs (end_sample - start_sample);
1235 if (ms & MonitoringDisk) {
1240 Location* loc = _loop_location;
1243 /* Evoral::Range has inclusive range semantics. Ugh. Hence the -1 */
1244 const Evoral::Range<samplepos_t> loop_range (loc->start(), loc->end() - 1);
1245 samplepos_t effective_start = start_sample;
1246 samplecnt_t cnt = nframes;
1248 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));
1252 samplepos_t effective_end;
1254 effective_start = loop_range.squish (effective_start);
1255 effective_end = min (effective_start + cnt, loc->end());
1256 assert (effective_end > effective_start);
1258 const samplecnt_t this_read = effective_end - effective_start;
1260 DEBUG_TRACE (DEBUG::MidiDiskIO, string_compose ("playback buffer LOOP read, from %1 to %2 (%3)\n", effective_start, effective_end, this_read));
1262 size_t events_read = rtmb->read (*target, effective_start, effective_end, _tracker);
1264 effective_start += this_read;
1266 DEBUG_TRACE (DEBUG::MidiDiskIO, string_compose ("%1 MDS events LOOP read %2 cnt now %3\n", _name, events_read, cnt));
1269 /* We re going to have to read across the loop end. Resolve any notes the extend across the loop end.
1270 * Time is relative to start_sample.
1272 _tracker.resolve_notes (*target, effective_end - start_sample);
1278 DEBUG_TRACE (DEBUG::MidiDiskIO, string_compose ("playback buffer read, from %1 to %2 (%3)\n", start_sample, end_sample, nframes));
1279 size_t events_read = rtmb->read (*target, start_sample, end_sample, _tracker);
1280 DEBUG_TRACE (DEBUG::MidiDiskIO, string_compose ("%1 MDS events read %2 range %3 .. %4\n", _name, events_read, playback_sample, playback_sample + nframes));
1284 if (ms & MonitoringInput) {
1285 /* merges data from disk (in "target", which is a scratch
1286 buffer in this case) into the actual destination buffer
1287 (which holds existing input data).
1289 dst.merge_from (*target, nframes);
1294 if (!target->empty ()) {
1295 cerr << "======== MIDI OUT ========\n";
1296 for (MidiBuffer::iterator i = target->begin(); i != target->end(); ++i) {
1297 const Evoral::Event<MidiBuffer::TimeType> ev (*i, false);
1298 cerr << "MIDI EVENT (from disk) @ " << ev.time();
1299 for (size_t xx = 0; xx < ev.size(); ++xx) {
1300 cerr << ' ' << hex << (int) ev.buffer()[xx];
1302 cerr << dec << endl;
1304 cerr << "----------------\n";
1309 DiskReader::inc_no_disk_output ()
1311 g_atomic_int_inc (&_no_disk_output);
1315 DiskReader::dec_no_disk_output ()
1317 /* this is called unconditionally when things happen that ought to end
1318 a period of "no disk output". It's OK for that to happen when there
1319 was no corresponding call to ::inc_no_disk_output(), but we must
1320 stop the value from becoming negative.
1324 gint v = g_atomic_int_get (&_no_disk_output);
1326 if (g_atomic_int_compare_and_exchange (&_no_disk_output, v, v - 1)) {
1335 DiskReader::DeclickAmp::DeclickAmp (samplecnt_t sample_rate)
1337 _a = 4550.f / (gain_t)sample_rate;
1343 DiskReader::DeclickAmp::apply_gain (AudioBuffer& buf, samplecnt_t n_samples, const float target, sampleoffset_t buffer_offset)
1345 if (n_samples == 0) {
1351 assert (buffer_offset == 0);
1352 Amp::apply_simple_gain (buf, n_samples, target, 0);
1357 Sample* const buffer = buf.data ();
1359 const int max_nproc = 16;
1360 uint32_t remain = n_samples;
1361 uint32_t offset = buffer_offset;
1363 while (remain > 0) {
1364 uint32_t n_proc = remain > max_nproc ? max_nproc : remain;
1365 for (uint32_t i = 0; i < n_proc; ++i) {
1366 buffer[offset + i] *= g;
1369 g += a * (target - g);
1370 #else /* accurate exponential fade */
1371 if (n_proc == max_nproc) {
1372 g += a * (target - g);
1374 g = target - (target - g) * expf (_l * n_proc / max_nproc);
1381 if (fabsf (g - target) < /* GAIN_COEFF_DELTA */ 1e-5) {
1388 DiskReader::Declicker::Declicker ()
1396 DiskReader::Declicker::~Declicker ()
1402 DiskReader::Declicker::alloc (samplecnt_t sr, bool fadein)
1405 vec = new Sample[loop_fade_length];
1407 const float a = 1024.0f / sr;
1409 /* build a psuedo-exponential (linear-volume) shape for the fade */
1413 #define GAIN_COEFF_DELTA (1e-5)
1417 for (n = 0; (n < sr) && ((1.0 - g) > GAIN_COEFF_DELTA); ++n) {
1423 for (n = 0; (n < sr) && (g > GAIN_COEFF_DELTA); ++n) {
1431 /* zero out the rest just to be safe */
1433 memset (&vec[n], 0, sizeof (gain_t) * (loop_fade_length - n));
1435 #undef GAIN_COEFF_DELTA
1439 DiskReader::Declicker::reset (samplepos_t loop_start, samplepos_t loop_end, bool fadein, samplecnt_t sr)
1441 if (loop_start == loop_end) {
1447 /* adjust the position of the fade (this is absolute (global) timeline units) */
1450 fade_start = loop_start;
1451 fade_end = loop_start + fade_length;
1453 fade_start = loop_end - fade_length;
1454 fade_end = loop_end;
1460 DiskReader::Declicker::run (Sample* buf, samplepos_t read_start, samplepos_t read_end)
1462 samplecnt_t n; /* how many samples to process */
1463 sampleoffset_t bo; /* offset into buffer */
1464 sampleoffset_t vo; /* offset into gain vector */
1466 if (fade_start == fade_end) {
1470 /* Determine how the read range overlaps with the fade range, so we can determine which part of the fade gain vector
1471 to apply to which part of the buffer.
1474 switch (Evoral::coverage (fade_start, fade_end, read_start, read_end)) {
1476 case Evoral::OverlapInternal:
1477 /* note: start and end points cannot coincide (see evoral/Range.h)
1479 * read range is entirely within fade range
1482 vo = read_start - fade_start;
1483 n = read_end - read_start;
1486 case Evoral::OverlapExternal:
1487 /* read range extends on either side of fade range
1489 * External allows coincidental start & end points, so check for that
1491 if (fade_start == read_start && fade_end == read_end) {
1492 /* fade entire read ... this is SO unlikely ! */
1495 n = fade_end - fade_start;
1497 bo = fade_start - read_start;
1499 n = fade_end - fade_start;
1503 case Evoral::OverlapStart:
1504 /* read range starts before and ends within fade or at same end as fade */
1505 n = fade_end - read_start;
1507 bo = fade_start - read_start;
1510 case Evoral::OverlapEnd:
1511 /* read range starts within fade range, but possibly at it's end, so check */
1512 if (read_start == fade_end) {
1517 vo = read_start - fade_start;
1518 n = fade_end - read_start;
1521 case Evoral::OverlapNone:
1522 /* no overlap ... nothing to do */
1526 Sample* b = &buf[bo];
1527 gain_t* g = &vec[vo];
1529 for (sampleoffset_t i = 0; i < n; ++i) {
1535 DiskReader::maybe_xfade_loop (Sample* buf, samplepos_t read_start, samplepos_t read_end, ReaderChannelInfo* chan)
1537 samplecnt_t n; /* how many samples to process */
1538 sampleoffset_t bo; /* offset into buffer */
1539 sampleoffset_t vo; /* offset into gain vector */
1541 const samplepos_t fade_start = loop_declick_out.fade_start;
1542 const samplepos_t fade_end = loop_declick_out.fade_end;
1544 if (fade_start == fade_end) {
1548 /* Determine how the read range overlaps with the fade range, so we can determine which part of the fade gain vector
1549 to apply to which part of the buffer.
1552 switch (Evoral::coverage (fade_start, fade_end, read_start, read_end)) {
1554 case Evoral::OverlapInternal:
1555 /* note: start and end points cannot coincide (see evoral/Range.h)
1557 * read range is entirely within fade range
1560 vo = read_start - fade_start;
1561 n = read_end - read_start;
1564 case Evoral::OverlapExternal:
1565 /* read range extends on either side of fade range
1567 * External allows coincidental start & end points, so check for that
1569 if (fade_start == read_start && fade_end == read_end) {
1570 /* fade entire read ... this is SO unlikely ! */
1573 n = fade_end - fade_start;
1575 bo = fade_start - read_start;
1577 n = fade_end - fade_start;
1581 case Evoral::OverlapStart:
1582 /* read range starts before and ends within fade or at same end as fade */
1583 n = fade_end - read_start;
1585 bo = fade_start - read_start;
1588 case Evoral::OverlapEnd:
1589 /* read range starts within fade range, but possibly at it's end, so check */
1590 if (read_start == fade_end) {
1595 vo = read_start - fade_start;
1596 n = fade_end - read_start;
1599 case Evoral::OverlapNone:
1600 /* no overlap ... nothing to do */
1604 Sample* b = &buf[bo]; /* data to be faded out */
1605 Sample* sbuf = &chan->pre_loop_buffer[vo]; /* pre-loop (maybe silence) to be faded in */
1606 gain_t* og = &loop_declick_out.vec[vo]; /* fade out gain vector */
1607 gain_t* ig = &loop_declick_in.vec[vo]; /* fade in gain vector */
1609 for (sampleoffset_t i = 0; i < n; ++i) {
1610 b[i] = (b[i] * og[i]) + (sbuf[i] * ig[i]);
1615 DiskReader::rt_midibuffer ()
1617 boost::shared_ptr<Playlist> pl = _playlists[DataType::MIDI];
1623 boost::shared_ptr<MidiPlaylist> mpl = boost::dynamic_pointer_cast<MidiPlaylist> (pl);
1626 /* error, but whatever ... */
1630 return mpl->rendered();
1634 DiskReader::alloc_loop_declick (samplecnt_t sr)
1636 loop_fade_length = lrintf (ceil (-log (1e-5) / (1024.f/sr)));
1637 loop_declick_in.alloc (sr, true);
1638 loop_declick_out.alloc (sr, false);
1642 DiskReader::reset_loop_declick (Location* loc, samplecnt_t sr)
1645 loop_declick_in.reset (loc->start(), loc->end(), true, sr);
1646 loop_declick_out.reset (loc->start(), loc->end(), false, sr);
1648 loop_declick_in.reset (0, 0, true, sr);
1649 loop_declick_out.reset (0, 0, false, sr);
1654 DiskReader::set_loop (Location* loc)
1656 Processor::set_loop (loc);
1666 DiskReader::reload_loop ()
1668 if (!_loop_location) {
1672 Location* loc = _loop_location;
1673 boost::scoped_array<Sample> mix_buf (new Sample [loop_fade_length]);
1674 boost::scoped_array<Sample> gain_buf (new Sample [loop_fade_length]);
1676 boost::shared_ptr<ChannelList> c = channels.reader();
1677 uint32_t channel = 0;
1679 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++channel) {
1681 ReaderChannelInfo* rci = dynamic_cast<ReaderChannelInfo*> (*chan);
1683 rci->resize_preloop (loop_fade_length);
1685 if (loc->start() > loop_fade_length) {
1686 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);
1688 memset (rci->pre_loop_buffer, 0, sizeof (Sample) * loop_fade_length);