do not try to process audio in a diskreader with no audio playlist
[ardour.git] / libs / ardour / disk_reader.cc
1 /*
2  * Copyright (C) 2017-2018 Paul Davis <paul@linuxaudiosystems.com>
3  * Copyright (C) 2017-2019 Robin Gareus <robin@gareus.org>
4  *
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.
9  *
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.
14  *
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.
18  */
19
20 #include <boost/smart_ptr/scoped_array.hpp>
21
22 #include "pbd/enumwriter.h"
23 #include "pbd/memento_command.h"
24 #include "pbd/playback_buffer.h"
25
26 #include "evoral/Range.h"
27
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"
43
44 #include "pbd/i18n.h"
45
46 using namespace ARDOUR;
47 using namespace PBD;
48 using namespace std;
49
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);
59
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 ())
65         , _declick_offs (0)
66 {
67         file_sample[DataType::AUDIO] = 0;
68         file_sample[DataType::MIDI] = 0;
69         g_atomic_int_set (&_pending_overwrite, 0);
70 }
71
72 DiskReader::~DiskReader ()
73 {
74         DEBUG_TRACE (DEBUG::Destruction, string_compose ("DiskReader %1 @ %2 deleted\n", _name, this));
75 }
76
77 void
78 DiskReader::ReaderChannelInfo::resize (samplecnt_t bufsize)
79 {
80         delete rbuf; rbuf = 0;
81
82         rbuf = new PlaybackBuffer<Sample> (bufsize);
83         /* touch memory to lock it */
84         memset (rbuf->buffer(), 0, sizeof (Sample) * rbuf->bufsize());
85 }
86
87 void
88 DiskReader::ReaderChannelInfo::resize_preloop (samplecnt_t bufsize)
89 {
90         if (bufsize == 0) {
91                 return;
92         }
93
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;
98         }
99 }
100
101 int
102 DiskReader::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
103 {
104         while (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",
107                                                             name(),
108                                                             c->back()->rbuf->write_space(),
109                                                             c->back()->rbuf->read_space()));
110         }
111
112         return 0;
113 }
114
115 void
116 DiskReader::allocate_working_buffers()
117 {
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.
122         */
123         _sum_buffer           = new Sample[2*1048576];
124         _mixdown_buffer       = new Sample[2*1048576];
125         _gain_buffer          = new gain_t[2*1048576];
126 }
127
128 void
129 DiskReader::free_working_buffers()
130 {
131         delete [] _sum_buffer;
132         delete [] _mixdown_buffer;
133         delete [] _gain_buffer;
134         _sum_buffer     = 0;
135         _mixdown_buffer = 0;
136         _gain_buffer    = 0;
137 }
138
139 samplecnt_t
140 DiskReader::default_chunk_samples()
141 {
142         return 65536;
143 }
144
145 bool
146 DiskReader::set_name (string const & str)
147 {
148         string my_name = X_("player:");
149         my_name += str;
150
151         if (_name != my_name) {
152                 SessionObject::set_name (my_name);
153         }
154
155         return true;
156 }
157
158 XMLNode&
159 DiskReader::state ()
160 {
161         XMLNode& node (DiskIOProcessor::state ());
162         node.set_property(X_("type"), X_("diskreader"));
163         return node;
164 }
165
166 int
167 DiskReader::set_state (const XMLNode& node, int version)
168 {
169         if (DiskIOProcessor::set_state (node, version)) {
170                 return -1;
171         }
172
173         return 0;
174 }
175
176 void
177 DiskReader::realtime_handle_transport_stopped ()
178 {
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.
183          */
184 }
185
186 void
187 DiskReader::realtime_locate (bool for_loop_end)
188 {
189         if (!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);
193         } else {
194                 std::cerr << name() << "skip note resolve on locate for loop\n";
195         }
196 }
197
198 float
199 DiskReader::buffer_load () const
200 {
201         /* Note: for MIDI it's not trivial to differentiate the following two cases:
202
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.
205
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.
209         */
210
211         boost::shared_ptr<ChannelList> c = channels.reader();
212
213         if (c->empty ()) {
214                 /* no channels, so no buffers, so completely full and ready to playback, sir! */
215                 return 1.0;
216         }
217
218         PBD::PlaybackBuffer<Sample>* b = c->front()->rbuf;
219         return (float) ((double) b->read_space() / (double) b->bufsize());
220 }
221
222 void
223 DiskReader::adjust_buffering ()
224 {
225         boost::shared_ptr<ChannelList> c = channels.reader();
226
227         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
228                 (*chan)->resize (_session.butler()->audio_playback_buffer_size());
229         }
230 }
231
232 void
233 DiskReader::playlist_modified ()
234 {
235         _session.request_overwrite_buffer (_track, PlaylistModified);
236 }
237
238 int
239 DiskReader::use_playlist (DataType dt, boost::shared_ptr<Playlist> playlist)
240 {
241         bool prior_playlist = false;
242
243         if (_playlists[dt]) {
244                 prior_playlist = true;
245         }
246
247         if (DiskIOProcessor::use_playlist (dt, playlist)) {
248                 return -1;
249         }
250
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.
254         */
255
256         if (!(g_atomic_int_get (&_pending_overwrite) & PlaylistChanged) || prior_playlist) {
257                 _session.request_overwrite_buffer (_track, PlaylistChanged);
258         }
259
260         return 0;
261 }
262
263 void
264 DiskReader::run (BufferSet& bufs, samplepos_t start_sample, samplepos_t end_sample, double speed, pframes_t nframes, bool result_required)
265 {
266         uint32_t n;
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 ();
271
272         // std::cerr << name() << " run " << start_sample << " .. " << end_sample << " speed = " << speed << std::endl;
273         if (_active) {
274                 if (!_pending_active) {
275                         _active = false;
276                         return;
277                 }
278         } else {
279                 if (_pending_active) {
280                         _active = true;
281                 } else {
282                         return;
283                 }
284         }
285
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;
289
290         if (!_session.cfg ()->get_use_transport_fades ()) {
291                 _declick_amp.set_gain (target_gain);
292         }
293
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)
297                  */
298                 return;
299         }
300
301         BufferSet& scratch_bufs (_session.get_scratch_buffers (bufs.count()));
302         const bool still_locating = _session.global_locate_pending();
303
304         assert (speed == -1 || speed == 0 || speed == 1);
305
306         if (speed == 0) {
307                 disk_samples_to_consume = 0;
308         } else {
309                 disk_samples_to_consume = nframes;
310         }
311
312         if (c->empty() || !_playlists[DataType::AUDIO]) {
313                 /* do nothing with audio */
314                 goto midi;
315         }
316
317         if (declick_out) {
318                 /* fade-out */
319
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());
321
322                 ms = MonitorState (ms | MonitoringDisk);
323                 assert (result_required);
324                 result_required = true;
325         } else {
326                 _declick_offs = 0;
327         }
328
329         if (!result_required || ((ms & MonitoringDisk) == 0) || still_locating || _no_disk_output) {
330
331                 /* no need for actual disk data, just advance read pointer */
332
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);
337                         }
338                 }
339
340                 /* if monitoring disk but locating put silence in the buffers */
341
342                 if ((_no_disk_output || still_locating) && (ms == MonitoringDisk)) {
343                         bufs.silence (nframes, 0);
344                 }
345
346         } else {
347
348                 /* we need audio data from disk */
349
350                 size_t n_buffers = bufs.count().n_audio();
351                 size_t n_chans = c->size();
352                 gain_t scaling;
353
354                 if (n_chans > n_buffers) {
355                         scaling = ((float) n_buffers) / n_chans;
356                 } else {
357                         scaling = 1.0;
358                 }
359
360                 const float initial_declick_gain = _declick_amp.gain ();
361                 const sampleoffset_t declick_offs = _declick_offs;
362
363                 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
364
365                         ChannelInfo* chaninfo (*chan);
366                         AudioBuffer& output (bufs.get_audio (n % n_buffers));
367
368                         AudioBuffer& disk_buf ((ms & MonitoringInput) ? scratch_bufs.get_audio(n) : output);
369
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);
374                                 } else {
375                                         disk_samples_to_consume = 0; /* will force an underrun below */
376                                 }
377                         }
378
379                         /* reset _declick_amp to the correct gain before processing this channel. */
380                         if (declick_out) {
381                                 _declick_amp.set_gain (initial_declick_gain);
382                         }
383
384
385                         if (!declick_out) {
386
387                                 const samplecnt_t total = chaninfo->rbuf->read (disk_buf.data(), disk_samples_to_consume);
388
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));
394                                         Underrun ();
395                                         return;
396                                 }
397
398                         } else if (_declick_amp.gain() != target_gain) {
399
400                                 assert (target_gain == 0);
401
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
408                                    to ::run()
409                                 */
410
411                                 const samplecnt_t total = chaninfo->rbuf->read (disk_buf.data(), nframes, false, declick_offs);
412
413                                 if (n == 0) {
414                                         _declick_offs += total;
415                                 }
416                         }
417
418                         _declick_amp.apply_gain (disk_buf, nframes, target_gain);
419
420                         /* _declick_amp is now left with the correct gain after
421                          * processing nframes
422                          */
423
424                         Amp::apply_simple_gain (disk_buf, nframes, scaling);
425
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);
429                         }
430                 }
431         }
432
433   midi:
434         /* MIDI data handling */
435
436         const bool midi_data_available = !(pending_overwrite() & PlaylistModified);
437
438         if (bufs.count().n_midi()) {
439
440                 MidiBuffer& dst (bufs.get_midi (0));
441
442                 if (run_must_resolve) {
443                         resolve_tracker (dst, 0);
444                         run_must_resolve = false;
445                 }
446
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);
449                 }
450         }
451
452         /* decide if we need the butler */
453
454         if (!still_locating && midi_data_available) {
455
456                 bool butler_required = false;
457
458                 if (speed < 0.0) {
459                         playback_sample -= disk_samples_to_consume;
460                 } else {
461                         playback_sample += disk_samples_to_consume;
462                 }
463
464                 Location* loc = _loop_location;
465                 if (loc) {
466                         Evoral::Range<samplepos_t> loop_range (loc->start(), loc->end() - 1);
467                         playback_sample = loop_range.squish (playback_sample);
468                 }
469
470                 if (_playlists[DataType::AUDIO]) {
471                         if (!c->empty()) {
472                                 if (_slaved) {
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;
476                                         }
477                                 } else {
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(),
480                                                                                             _chunk_samples));
481                                                 butler_required = true;
482                                         }
483                                 }
484                         }
485                 }
486
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.
489                  */
490
491                 _need_butler = butler_required;
492         }
493
494         DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 reader run, needs butler = %2\n", name(), _need_butler));
495 }
496
497 bool
498 DiskReader::declick_in_progress () const
499 {
500         return _declick_amp.gain() != 0; // declick-out
501 }
502
503 bool
504 DiskReader::pending_overwrite () const
505 {
506         return g_atomic_int_get (&_pending_overwrite) != 0;
507 }
508
509 void
510 DiskReader::set_pending_overwrite (OverwriteReason why)
511 {
512         /* called from audio thread, so we can use the read ptr and playback sample as we wish */
513
514         overwrite_sample = playback_sample;
515         boost::shared_ptr<ChannelList> c = channels.reader ();
516         if (!c->empty ()) {
517                 overwrite_offset = c->front()->rbuf->read_ptr();
518         }
519
520         if (why & (LoopChanged|PlaylistModified|PlaylistChanged)) {
521                 run_must_resolve = true;
522         }
523
524         while (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)) {
528                         break;
529                 }
530         }
531
532 }
533
534 bool
535 DiskReader::overwrite_existing_audio ()
536 {
537         boost::shared_ptr<ChannelList> c = channels.reader();
538
539         if (c->empty () || !_playlists[DataType::AUDIO]) {
540                 return true;
541         }
542
543         const bool reversed = _session.transport_speed() < 0.0f;
544
545         /* assume all are the same size */
546
547         samplecnt_t size = c->front()->rbuf->bufsize () - c->front()->rbuf->reserved_size() - 1;
548         assert (size > 0);
549
550         boost::scoped_array<Sample> mixdown_buffer (new Sample[size]);
551         boost::scoped_array<float> gain_buffer (new float[size]);
552         uint32_t n = 0;
553         bool ret = true;
554
555         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
556
557                 samplepos_t start = overwrite_sample;
558
559                 /* to fill the buffer without resetting the playback sample, we need to
560                    do it one or two chunks (normally two).
561
562                    |----------------------------------------------------------------------|
563                                      ^               ^
564                                          RESERVED    overwrite_offset  (old read_ptr)
565                    |<- second chunk->|<-------------><---- first chunk ------------------>|
566
567                 */
568
569                 samplecnt_t to_read = size - overwrite_offset;
570                 Sample* buf = (*chan)->rbuf->buffer();
571                 ReaderChannelInfo* rci = dynamic_cast<ReaderChannelInfo*> (*chan);
572                 samplecnt_t nread;
573
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;
576                         ret = false;
577                         continue;
578                 }
579
580                 if (size > to_read) {
581
582                         to_read = size - to_read;
583
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;
586                                 ret = false;
587                         }
588                 }
589         }
590
591         return ret;
592 }
593
594 bool
595 DiskReader::overwrite_existing_midi ()
596 {
597         RTMidiBuffer* mbuf = rt_midibuffer ();
598
599         if (mbuf) {
600                 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack>(_track);
601                 MidiChannelFilter* filter = mt ? &mt->playback_filter() : 0;
602
603                 PBD::Timing minsert;
604                 minsert.start();
605
606                 midi_playlist()->render (filter);
607
608                 minsert.update();
609                 assert (midi_playlist()->rendered());
610                 cerr << "Reading " << name()  << " took " << minsert.elapsed() << " microseconds, final size = " << midi_playlist()->rendered()->size() << endl;
611         }
612
613         return true;
614 }
615
616 bool
617 DiskReader::overwrite_existing_buffers ()
618 {
619         /* called from butler thread */
620
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));
622
623         bool ret = true;
624
625         if (g_atomic_int_get (&_pending_overwrite) & (PlaylistModified|LoopDisabled|LoopChanged|PlaylistChanged)) {
626                 if (!overwrite_existing_audio ()) {
627                         ret = false;
628                 }
629         }
630
631         if (g_atomic_int_get (&_pending_overwrite) & (PlaylistModified|PlaylistChanged)) {
632                 if (!overwrite_existing_midi ()) {
633                         ret = false;
634                 }
635         }
636
637         g_atomic_int_set (&_pending_overwrite, 0);
638
639         return ret;
640 }
641
642 int
643 DiskReader::seek (samplepos_t sample, bool complete_refill)
644 {
645         /* called via non_realtime_locate() from butler thread */
646
647         uint32_t n;
648         int ret = -1;
649         ChannelList::iterator chan;
650         boost::shared_ptr<ChannelList> c = channels.reader();
651
652         if (sample == playback_sample && !complete_refill) {
653                 return 0; // XXX double-check this
654         }
655
656         g_atomic_int_set (&_pending_overwrite, 0);
657
658         DEBUG_TRACE (DEBUG::DiskIO, string_compose ("DiskReader::seek %s %ld -> %ld refill=%d\n", owner()->name().c_str(), playback_sample, sample, complete_refill));
659
660         const samplecnt_t distance = sample - playback_sample;
661         if (!complete_refill && can_internal_playback_seek (distance)) {
662                 internal_playback_seek (distance);
663                 return 0;
664         }
665
666         for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
667                 (*chan)->rbuf->reset ();
668         }
669
670         playback_sample = sample;
671         file_sample[DataType::AUDIO] = sample;
672         file_sample[DataType::MIDI] = sample;
673
674         if (complete_refill) {
675                 /* call _do_refill() to refill the entire buffer, using
676                    the largest reads possible.
677                 */
678                 while ((ret = do_refill_with_alloc (false)) > 0) ;
679         } else {
680                 /* call _do_refill() to refill just one chunk, and then
681                    return.
682                 */
683                 ret = do_refill_with_alloc (true);
684         }
685
686         return ret;
687 }
688
689 bool
690 DiskReader::can_internal_playback_seek (sampleoffset_t distance)
691 {
692         /* 1. Audio */
693
694         ChannelList::iterator chan;
695         boost::shared_ptr<ChannelList> c = channels.reader();
696
697         for (chan = c->begin(); chan != c->end(); ++chan) {
698                 if (!(*chan)->rbuf->can_seek (distance)) {
699                         return false;
700                 }
701         }
702
703         /* 2. MIDI can always seek any distance */
704
705         return true;
706 }
707
708 void
709 DiskReader::internal_playback_seek (sampleoffset_t distance)
710 {
711         if (distance == 0) {
712                 return;
713         }
714
715         sampleoffset_t off = distance;
716
717         ChannelList::iterator chan;
718         boost::shared_ptr<ChannelList> c = channels.reader();
719         for (chan = c->begin(); chan != c->end(); ++chan) {
720                 if (distance < 0) {
721                         off = 0 - (sampleoffset_t) (*chan)->rbuf->decrement_read_ptr (::llabs (distance));
722                 } else {
723                         off = (*chan)->rbuf->increment_read_ptr (distance);
724                 }
725         }
726
727         playback_sample += off;
728 }
729
730 static
731 void swap_by_ptr (Sample *first, Sample *last)
732 {
733         while (first < last) {
734                 Sample tmp = *first;
735                 *first++ = *last;
736                 *last-- = tmp;
737         }
738 }
739
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
743  *         after the read.
744  *  @param cnt Count of samples to read.
745  *  @param reversed true if we are running backwards, otherwise false.
746  */
747 samplecnt_t
748 DiskReader::audio_read (Sample* sum_buffer,
749                         Sample* mixdown_buffer,
750                         float* gain_buffer,
751                         samplepos_t& start,
752                         samplecnt_t cnt,
753                         ReaderChannelInfo* rci,
754                         int channel,
755                         bool reversed)
756 {
757         samplecnt_t this_read = 0;
758         bool reloop = false;
759         samplepos_t loop_end = 0;
760         samplepos_t loop_start = 0;
761         Location *loc = 0;
762         const samplecnt_t rcnt = cnt;
763
764         /* XXX we don't currently play loops in reverse. not sure why */
765
766         if (!reversed) {
767
768                 samplecnt_t loop_length = 0;
769
770                 /* Make the use of a Location atomic for this read operation.
771
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
775                    just once.
776                 */
777
778                 if ((loc = _loop_location) != 0) {
779                         loop_start = loc->start();
780                         loop_end = loc->end();
781                         loop_length = loop_end - loop_start;
782                 }
783
784                 /* if we are looping, ensure that the first sample we read is at the correct
785                    position within the loop.
786                 */
787
788                 if (loc && start >= loop_end) {
789                         start = loop_start + ((start - loop_start) % loop_length);
790                 }
791
792         }
793
794         if (reversed) {
795                 start -= cnt;
796         }
797
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.
800         */
801
802         while (cnt) {
803
804                 /* take any loop into account. we can't read past the end of the loop. */
805
806                 if (loc && (loop_end - start < cnt)) {
807                         this_read = loop_end - start;
808                         reloop = true;
809                 } else {
810                         reloop = false;
811                         this_read = cnt;
812                 }
813
814                 if (this_read == 0) {
815                         break;
816                 }
817
818                 this_read = min (cnt, this_read);
819
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()
823                  */
824
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;
827                         return 0;
828                 }
829
830                 if (loc) {
831
832                         /* Looping: do something (maybe) about the loop boundaries */
833
834                         switch (Config->get_loop_fade_choice()) {
835                         case NoLoopFade:
836                                 break;
837                         case BothLoopFade:
838                                 loop_declick_in.run (sum_buffer, start, start + this_read);
839                                 loop_declick_out.run (sum_buffer, start, start + this_read);
840                                 break;
841                         case EndLoopFade:
842                                 loop_declick_out.run (sum_buffer, start, start + this_read);
843                                 break;
844                         case XFadeLoop:
845                                 maybe_xfade_loop (sum_buffer, start, start + this_read, rci);
846                                 break;
847                         }
848                 }
849
850                 if (reversed) {
851
852                         swap_by_ptr (sum_buffer, sum_buffer + this_read - 1);
853
854                 } else {
855
856                         /* if we read to the end of the loop, go back to the beginning */
857
858                         if (reloop) {
859                                 start = loop_start;
860                         } else {
861                                 start += this_read;
862                         }
863                 }
864
865                 cnt -= this_read;
866                 sum_buffer += this_read;
867         }
868
869         return rcnt;
870 }
871
872 int
873 DiskReader::_do_refill_with_alloc (bool partial_fill)
874 {
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).
879         */
880
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]);
884
885         return refill_audio (sum_buf.get(), mix_buf.get(), gain_buf.get(), (partial_fill ? _chunk_samples : 0));
886 }
887
888 int
889 DiskReader::refill (Sample* sum_buffer, Sample* mixdown_buffer, float* gain_buffer, samplecnt_t fill_level)
890 {
891         if (refill_audio (sum_buffer, mixdown_buffer, gain_buffer, fill_level)) {
892                 return -1;
893         }
894
895         if (rt_midibuffer() && (_session.transport_speed() < 0.0f) != rt_midibuffer()->reversed()) {
896                 rt_midibuffer()->reverse ();
897         }
898
899         return 0;
900 }
901
902
903 /** Get some more data from disk and put it in our channels' bufs,
904  *  if there is suitable space in them.
905  *
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.
909  *
910  */
911
912 int
913 DiskReader::refill_audio (Sample* sum_buffer, Sample* mixdown_buffer, float* gain_buffer, samplecnt_t fill_level)
914 {
915         /* do not read from disk while session is marked as Loading, to avoid
916            useless redundant I/O.
917         */
918
919         if (_session.loading()) {
920                 return 0;
921         }
922
923         int32_t ret = 0;
924         bool const reversed = _session.transport_speed() < 0.0f;
925         samplecnt_t zero_fill;
926         uint32_t chan_n;
927         ChannelList::iterator i;
928         boost::shared_ptr<ChannelList> c = channels.reader();
929
930         if (c->empty()) {
931                 return 0;
932         }
933
934         assert(mixdown_buffer);
935         assert(gain_buffer);
936
937         samplecnt_t total_space = c->front()->rbuf->write_space();
938
939         if (total_space == 0) {
940                 DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1: no space to refill\n", name()));
941                 /* nowhere to write to */
942                 return 0;
943         }
944
945         if (fill_level) {
946                 if (fill_level < total_space) {
947                         total_space -= fill_level;
948                 } else {
949                         /* we can't do anything with it */
950                         fill_level = 0;
951                 }
952         }
953
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.
956
957            at higher speeds, just do it because the sync between butler
958            and audio thread may not be good enough.
959
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.
963         */
964
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) {
967                 return 0;
968         }
969
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
972            work with.
973         */
974
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));
977                 return 0;
978         }
979
980         samplepos_t ffa = file_sample[DataType::AUDIO];
981
982         if (reversed) {
983
984                 if (ffa == 0) {
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 ());
989                         }
990                         return 0;
991                 }
992
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;
996                         total_space = ffa;
997                 } else {
998                         zero_fill = 0;
999                 }
1000
1001         } else {
1002
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 ());
1008                         }
1009                         return 0;
1010                 }
1011
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;
1016
1017                 } else {
1018                         zero_fill = 0;
1019                 }
1020         }
1021
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;
1025
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));
1028
1029         /* find nearest (lower) multiple of 16384 */
1030
1031         byte_size_for_read = (byte_size_for_read / 16384) * 16384;
1032
1033         /* now back to samples */
1034         samplecnt_t samples_to_read = byte_size_for_read / (bits_per_sample / 8);
1035
1036         DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1: will refill %2 channels with %3 samples\n", name(), c->size(), total_space));
1037
1038         samplepos_t file_sample_tmp = ffa;
1039
1040         for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1041
1042                 ChannelInfo* chan (*i);
1043                 file_sample_tmp = ffa;
1044                 samplecnt_t ts = total_space;
1045
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);
1049
1050                 // cerr << owner()->name() << " to-read: " << to_read << endl;
1051
1052                 if (to_read) {
1053                         ReaderChannelInfo* rci = dynamic_cast<ReaderChannelInfo*> (chan);
1054                         samplecnt_t nread;
1055
1056                         if (!_playlists[DataType::AUDIO]) {
1057
1058                                 chan->rbuf->write_zero (to_read);
1059
1060                         } else {
1061
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;
1064                                         ret = -1;
1065                                         goto out;
1066                                 }
1067
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;
1070                                         ret = -1;
1071                                 }
1072                         }
1073                 }
1074
1075                 if (zero_fill) {
1076                         /* not sure if action is needed,
1077                          * we'll later hit the "to close to the end" case
1078                          */
1079                         //chan->rbuf->write_zero (zero_fill);
1080                 }
1081         }
1082
1083         // elapsed = g_get_monotonic_time () - before;
1084         // cerr << '\t' << name() << ": bandwidth = " << (byte_size_for_read / 1048576.0) / (elapsed/1000000.0) << "MB/sec\n";
1085
1086         file_sample[DataType::AUDIO] = file_sample_tmp;
1087         assert (file_sample[DataType::AUDIO] >= 0);
1088
1089         ret = ((total_space - samples_to_read) > _chunk_samples);
1090
1091   out:
1092         return ret;
1093 }
1094
1095 void
1096 DiskReader::playlist_ranges_moved (list< Evoral::RangeMove<samplepos_t> > const & movements_samples, bool from_undo_or_shift)
1097 {
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.
1101          *
1102          * Likewise when shifting regions (insert/remove time)
1103          * automation is taken care of separately (busses with
1104          * automation have no disk-reader).
1105          */
1106
1107         if (from_undo_or_shift) {
1108                 return;
1109         }
1110
1111         if (!_track || Config->get_automation_follows_regions () == false) {
1112                 return;
1113         }
1114
1115         list< Evoral::RangeMove<double> > movements;
1116
1117         for (list< Evoral::RangeMove<samplepos_t> >::const_iterator i = movements_samples.begin();
1118              i != movements_samples.end();
1119              ++i) {
1120
1121                 movements.push_back(Evoral::RangeMove<double>(i->from, i->length, i->to));
1122         }
1123
1124         /* move panner automation */
1125         boost::shared_ptr<Pannable> pannable = _track->pannable();
1126         Evoral::ControlSet::Controls& c (pannable->controls());
1127
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);
1130                 if (!ac) {
1131                         continue;
1132                 }
1133                 boost::shared_ptr<AutomationList> alist = ac->alist();
1134                 if (!alist->size()) {
1135                         continue;
1136                 }
1137                 XMLNode & before = alist->get_state ();
1138                 bool const things_moved = alist->move_ranges (movements);
1139                 if (things_moved) {
1140                         _session.add_command (new MementoCommand<AutomationList> (
1141                                                       *alist.get(), &before, &alist->get_state ()));
1142                 }
1143         }
1144         /* move processor automation */
1145         _track->foreach_processor (boost::bind (&DiskReader::move_processor_automation, this, _1, movements_samples));
1146 }
1147
1148 void
1149 DiskReader::move_processor_automation (boost::weak_ptr<Processor> p, list< Evoral::RangeMove<samplepos_t> > const & movements_samples)
1150 {
1151         boost::shared_ptr<Processor> processor (p.lock ());
1152         if (!processor) {
1153                 return;
1154         }
1155
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));
1159         }
1160
1161         set<Evoral::Parameter> const a = processor->what_can_be_automated ();
1162
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();
1165                 if (!al->size()) {
1166                         continue;
1167                 }
1168                 XMLNode & before = al->get_state ();
1169                 bool const things_moved = al->move_ranges (movements);
1170                 if (things_moved) {
1171                         _session.add_command (
1172                                 new MementoCommand<AutomationList> (
1173                                         *al.get(), &before, &al->get_state ()
1174                                         )
1175                                 );
1176                 }
1177         }
1178 }
1179
1180 void
1181 DiskReader::reset_tracker ()
1182 {
1183         _tracker.reset ();
1184 }
1185
1186 void
1187 DiskReader::resolve_tracker (Evoral::EventSink<samplepos_t>& buffer, samplepos_t time)
1188 {
1189         _tracker.resolve_notes (buffer, time);
1190 }
1191
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
1194  */
1195 void
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)
1197 {
1198         RTMidiBuffer* rtmb = rt_midibuffer();
1199
1200         if (!rtmb || (rtmb->size() == 0)) {
1201                 /* no data to read, so do nothing */
1202                 return;
1203         }
1204
1205         MidiBuffer* target;
1206
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
1212                    then merge later.
1213                 */
1214
1215                 target = &scratch_bufs.get_midi (0);
1216         } else {
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.
1220                  */
1221                 target = &dst;
1222         }
1223
1224         if (!_no_disk_output) {
1225
1226                 const samplecnt_t nframes = abs (end_sample - start_sample);
1227
1228                 if (ms & MonitoringDisk) {
1229
1230                         /* disk data needed
1231                          */
1232
1233                         Location* loc = _loop_location;
1234
1235                         if (loc) {
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;
1240
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));
1242
1243                                 do {
1244
1245                                         samplepos_t effective_end;
1246
1247                                         effective_start = loop_range.squish (effective_start);
1248                                         effective_end = min (effective_start + cnt, loc->end());
1249                                         assert (effective_end > effective_start);
1250
1251                                         const samplecnt_t this_read = effective_end - effective_start;
1252
1253                                         DEBUG_TRACE (DEBUG::MidiDiskIO, string_compose ("playback buffer LOOP read, from %1 to %2 (%3)\n", effective_start, effective_end, this_read));
1254
1255                                         size_t events_read = rtmb->read (*target, effective_start, effective_end, _tracker);
1256                                         cnt -= this_read;
1257                                         effective_start += this_read;
1258
1259                                         DEBUG_TRACE (DEBUG::MidiDiskIO, string_compose ("%1 MDS events LOOP read %2 cnt now %3\n", _name, events_read, cnt));
1260
1261                                         if (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.
1264                                                  */
1265                                                 _tracker.resolve_notes (*target, effective_end - start_sample);
1266                                         }
1267
1268                                 } while (cnt);
1269
1270                         } else {
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));
1274                         }
1275                 }
1276
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).
1281                         */
1282                         dst.merge_from (*target, nframes);
1283                 }
1284         }
1285
1286 #if 0
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];
1294                         }
1295                         cerr << dec << endl;
1296                 }
1297                 cerr << "----------------\n";
1298         }
1299 #endif
1300 }
1301 void
1302 DiskReader::inc_no_disk_output ()
1303 {
1304         g_atomic_int_inc (&_no_disk_output);
1305 }
1306
1307 void
1308 DiskReader::dec_no_disk_output ()
1309 {
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.
1314         */
1315
1316         do {
1317                 gint v  = g_atomic_int_get (&_no_disk_output);
1318                 if (v > 0) {
1319                         if (g_atomic_int_compare_and_exchange (&_no_disk_output, v, v - 1)) {
1320                                 break;
1321                         }
1322                 } else {
1323                         break;
1324                 }
1325         } while (true);
1326 }
1327
1328 DiskReader::DeclickAmp::DeclickAmp (samplecnt_t sample_rate)
1329 {
1330         _a = 4550.f / (gain_t)sample_rate;
1331         _l = -log1p (_a);
1332         _g = 0;
1333 }
1334
1335 void
1336 DiskReader::DeclickAmp::apply_gain (AudioBuffer& buf, samplecnt_t n_samples, const float target, sampleoffset_t buffer_offset)
1337 {
1338         if (n_samples == 0) {
1339                 return;
1340         }
1341         float g = _g;
1342
1343         if (g == target) {
1344                 assert (buffer_offset == 0);
1345                 Amp::apply_simple_gain (buf, n_samples, target, 0);
1346                 return;
1347         }
1348
1349         const float a = _a;
1350         Sample* const buffer = buf.data ();
1351
1352         const int max_nproc = 16;
1353         uint32_t remain = n_samples;
1354         uint32_t offset = buffer_offset;
1355
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;
1360                 }
1361 #if 1
1362                 g += a * (target - g);
1363 #else /* accurate exponential fade */
1364                 if (n_proc == max_nproc) {
1365                         g += a * (target - g);
1366                 } else {
1367                         g = target - (target - g) * expf (_l * n_proc / max_nproc);
1368                 }
1369 #endif
1370                 remain -= n_proc;
1371                 offset += n_proc;
1372         }
1373
1374         if (fabsf (g - target) < /* GAIN_COEFF_DELTA */ 1e-5) {
1375                 _g = target;
1376         } else {
1377                 _g = g;
1378         }
1379 }
1380
1381 DiskReader::Declicker::Declicker ()
1382         : fade_start (0)
1383         , fade_end (0)
1384         , fade_length (0)
1385         , vec (0)
1386 {
1387 }
1388
1389 DiskReader::Declicker::~Declicker ()
1390 {
1391         delete [] vec;
1392 }
1393
1394 void
1395 DiskReader::Declicker::alloc (samplecnt_t sr, bool fadein)
1396 {
1397         delete [] vec;
1398         vec = new Sample[loop_fade_length];
1399
1400         const float a = 1024.0f / sr;
1401
1402         /* build a psuedo-exponential (linear-volume) shape for the fade */
1403
1404         samplecnt_t n;
1405
1406 #define GAIN_COEFF_DELTA (1e-5)
1407
1408         if (fadein) {
1409                 gain_t g = 0.0;
1410                 for (n = 0; (n < sr) && ((1.0 - g) > GAIN_COEFF_DELTA); ++n) {
1411                         vec[n] = g;
1412                         g += a * (1.0 - g);
1413                 }
1414         } else {
1415                 gain_t g = 1.0;
1416                 for (n = 0; (n < sr) && (g > GAIN_COEFF_DELTA); ++n) {
1417                         vec[n] = g;
1418                         g += a * -g;
1419                 }
1420         }
1421
1422         fade_length = n;
1423
1424         /* zero out the rest just to be safe */
1425
1426         memset (&vec[n], 0, sizeof (gain_t) * (loop_fade_length - n));
1427
1428 #undef GAIN_COEFF_DELTA
1429 }
1430
1431 void
1432 DiskReader::Declicker::reset (samplepos_t loop_start, samplepos_t loop_end, bool fadein, samplecnt_t sr)
1433 {
1434         if (loop_start == loop_end) {
1435                 fade_start = 0;
1436                 fade_end = 0;
1437                 return;
1438         }
1439
1440         /* adjust the position of the fade (this is absolute (global) timeline units) */
1441
1442         if (fadein) {
1443                 fade_start = loop_start;
1444                 fade_end = loop_start + fade_length;
1445         } else {
1446                 fade_start = loop_end - fade_length;
1447                 fade_end = loop_end;
1448         }
1449
1450 }
1451
1452 void
1453 DiskReader::Declicker::run (Sample* buf, samplepos_t read_start, samplepos_t read_end)
1454 {
1455         samplecnt_t n;     /* how many samples to process */
1456         sampleoffset_t bo; /* offset into buffer */
1457         sampleoffset_t vo; /* offset into gain vector */
1458
1459         if (fade_start == fade_end) {
1460                 return;
1461         }
1462
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.
1465         */
1466
1467         switch (Evoral::coverage (fade_start, fade_end, read_start, read_end)) {
1468
1469         case Evoral::OverlapInternal:
1470                 /* note: start and end points cannot coincide (see evoral/Range.h)
1471                  *
1472                  * read range is entirely within fade range
1473                  */
1474                 bo = 0;
1475                 vo = read_start - fade_start;
1476                 n = read_end - read_start;
1477                 break;
1478
1479         case Evoral::OverlapExternal:
1480                 /* read range extends on either side of fade range
1481                  *
1482                  * External allows coincidental start & end points, so check for that
1483                  */
1484                 if (fade_start == read_start && fade_end == read_end) {
1485                         /* fade entire read ... this is SO unlikely ! */
1486                         bo = 0;
1487                         vo = 0;
1488                         n = fade_end - fade_start;
1489                 } else {
1490                         bo = fade_start - read_start;
1491                         vo = 0;
1492                         n = fade_end - fade_start;
1493                 }
1494                 break;
1495
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;
1499                 vo = 0;
1500                 bo = fade_start - read_start;
1501                 break;
1502
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) {
1506                         /* nothing to do */
1507                         return;
1508                 }
1509                 bo = 0;
1510                 vo = read_start - fade_start;
1511                 n = fade_end - read_start;
1512                 break;
1513
1514         case Evoral::OverlapNone:
1515                 /* no overlap ... nothing to do */
1516                 return;
1517         }
1518
1519         Sample* b = &buf[bo];
1520         gain_t* g = &vec[vo];
1521
1522         for (sampleoffset_t i = 0; i < n; ++i) {
1523                 b[i] *= g[i];
1524         }
1525 }
1526
1527 void
1528 DiskReader::maybe_xfade_loop (Sample* buf, samplepos_t read_start, samplepos_t read_end, ReaderChannelInfo* chan)
1529 {
1530         samplecnt_t n;     /* how many samples to process */
1531         sampleoffset_t bo; /* offset into buffer */
1532         sampleoffset_t vo; /* offset into gain vector */
1533
1534         const samplepos_t fade_start = loop_declick_out.fade_start;
1535         const samplepos_t fade_end = loop_declick_out.fade_end;
1536
1537         if (fade_start == fade_end) {
1538                 return;
1539         }
1540
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.
1543         */
1544
1545         switch (Evoral::coverage (fade_start, fade_end, read_start, read_end)) {
1546
1547         case Evoral::OverlapInternal:
1548                 /* note: start and end points cannot coincide (see evoral/Range.h)
1549                  *
1550                  * read range is entirely within fade range
1551                  */
1552                 bo = 0;
1553                 vo = read_start - fade_start;
1554                 n = read_end - read_start;
1555                 break;
1556
1557         case Evoral::OverlapExternal:
1558                 /* read range extends on either side of fade range
1559                  *
1560                  * External allows coincidental start & end points, so check for that
1561                  */
1562                 if (fade_start == read_start && fade_end == read_end) {
1563                         /* fade entire read ... this is SO unlikely ! */
1564                         bo = 0;
1565                         vo = 0;
1566                         n = fade_end - fade_start;
1567                 } else {
1568                         bo = fade_start - read_start;
1569                         vo = 0;
1570                         n = fade_end - fade_start;
1571                 }
1572                 break;
1573
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;
1577                 vo = 0;
1578                 bo = fade_start - read_start;
1579                 break;
1580
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) {
1584                         /* nothing to do */
1585                         return;
1586                 }
1587                 bo = 0;
1588                 vo = read_start - fade_start;
1589                 n = fade_end - read_start;
1590                 break;
1591
1592         case Evoral::OverlapNone:
1593                 /* no overlap ... nothing to do */
1594                 return;
1595         }
1596
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 */
1601
1602         for (sampleoffset_t i = 0; i < n; ++i) {
1603                 b[i] = (b[i] * og[i]) + (sbuf[i] * ig[i]);
1604         }
1605 }
1606
1607 RTMidiBuffer*
1608 DiskReader::rt_midibuffer ()
1609 {
1610         boost::shared_ptr<Playlist> pl = _playlists[DataType::MIDI];
1611
1612         if (!pl) {
1613                 return 0;
1614         }
1615
1616         boost::shared_ptr<MidiPlaylist> mpl = boost::dynamic_pointer_cast<MidiPlaylist> (pl);
1617
1618         if (!mpl) {
1619                 /* error, but whatever ... */
1620                 return 0;
1621         }
1622
1623         return mpl->rendered();
1624 }
1625
1626 void
1627 DiskReader::alloc_loop_declick (samplecnt_t sr)
1628 {
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);
1632 }
1633
1634 void
1635 DiskReader::reset_loop_declick (Location* loc, samplecnt_t sr)
1636 {
1637         if (loc) {
1638                 loop_declick_in.reset (loc->start(), loc->end(), true, sr);
1639                 loop_declick_out.reset (loc->start(), loc->end(), false, sr);
1640         } else {
1641                 loop_declick_in.reset (0, 0, true, sr);
1642                 loop_declick_out.reset (0, 0, false, sr);
1643         }
1644 }
1645
1646 void
1647 DiskReader::set_loop (Location* loc)
1648 {
1649         Processor::set_loop (loc);
1650
1651         if (!loc) {
1652                 return;
1653         }
1654
1655         reload_loop ();
1656 }
1657
1658 void
1659 DiskReader::reload_loop ()
1660 {
1661         if (!_loop_location) {
1662                 return;
1663         }
1664
1665         boost::shared_ptr<ChannelList> c = channels.reader();
1666
1667         if (c->empty() || !_playlists[DataType::MIDI]) {
1668                 return;
1669         }
1670
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]);
1674
1675         uint32_t channel = 0;
1676
1677         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++channel) {
1678
1679                 ReaderChannelInfo* rci = dynamic_cast<ReaderChannelInfo*> (*chan);
1680
1681                 rci->resize_preloop (loop_fade_length);
1682
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);
1685                 } else {
1686                         memset (rci->pre_loop_buffer, 0, sizeof (Sample) * loop_fade_length);
1687                 }
1688
1689         }
1690 }
1691
1692 bool
1693 DiskReader::can_support_io_configuration (const ChanCount& in, ChanCount& out)
1694 {
1695         if (!DiskIOProcessor::can_support_io_configuration (in, out)) {
1696                 return false;
1697         }
1698
1699         /* DiskIO might have done this too, but do it again anyway as a
1700          * starting point.
1701          */
1702
1703         out == in;
1704
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);
1709                 }
1710         }
1711
1712         if (_playlists[DataType::MIDI]) {
1713                 if (out.n_midi() != 1) {
1714                         out.set (DataType::MIDI, 1);
1715                 }
1716         }
1717
1718         return true;
1719 }