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