various adjustments so that a MidiPlaylist gets re-rendered whenever it changes.
[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 "ardour/amp.h"
27 #include "ardour/audioengine.h"
28 #include "ardour/audioplaylist.h"
29 #include "ardour/audio_buffer.h"
30 #include "ardour/butler.h"
31 #include "ardour/debug.h"
32 #include "ardour/disk_reader.h"
33 #include "ardour/midi_ring_buffer.h"
34 #include "ardour/midi_playlist.h"
35 #include "ardour/midi_track.h"
36 #include "ardour/pannable.h"
37 #include "ardour/playlist.h"
38 #include "ardour/playlist_factory.h"
39 #include "ardour/session.h"
40 #include "ardour/session_playlists.h"
41
42 #include "pbd/i18n.h"
43
44 using namespace ARDOUR;
45 using namespace PBD;
46 using namespace std;
47
48 ARDOUR::samplecnt_t DiskReader::_chunk_samples = default_chunk_samples ();
49 PBD::Signal0<void> DiskReader::Underrun;
50 Sample* DiskReader::_sum_buffer = 0;
51 Sample* DiskReader::_mixdown_buffer = 0;
52 gain_t* DiskReader::_gain_buffer = 0;
53 samplecnt_t DiskReader::midi_readahead = 4096;
54 gint DiskReader::_no_disk_output (0);
55
56 DiskReader::DiskReader (Session& s, string const & str, DiskIOProcessor::Flag f)
57         : DiskIOProcessor (s, str, f)
58         , overwrite_sample (0)
59         , overwrite_queued (false)
60         , run_must_resolve (false)
61         , _declick_amp (s.nominal_sample_rate ())
62         , _declick_offs (0)
63 {
64         file_sample[DataType::AUDIO] = 0;
65         file_sample[DataType::MIDI] = 0;
66         g_atomic_int_set (&_pending_overwrite, 0);
67 }
68
69 DiskReader::~DiskReader ()
70 {
71         DEBUG_TRACE (DEBUG::Destruction, string_compose ("DiskReader %1 @ %2 deleted\n", _name, this));
72 }
73
74 void
75 DiskReader::ReaderChannelInfo::resize (samplecnt_t bufsize)
76 {
77         delete rbuf;
78         rbuf = new PlaybackBuffer<Sample> (bufsize);
79         /* touch memory to lock it */
80         memset (rbuf->buffer(), 0, sizeof (Sample) * rbuf->bufsize());
81 }
82
83 int
84 DiskReader::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
85 {
86         while (how_many--) {
87                 c->push_back (new ReaderChannelInfo (_session.butler()->audio_diskstream_playback_buffer_size()));
88                 DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1: new reader channel, write space = %2 read = %3\n",
89                                                             name(),
90                                                             c->back()->rbuf->write_space(),
91                                                             c->back()->rbuf->read_space()));
92         }
93
94         return 0;
95 }
96
97 void
98 DiskReader::allocate_working_buffers()
99 {
100         /* with varifill buffer refilling, we compute the read size in bytes (to optimize
101            for disk i/o bandwidth) and then convert back into samples. These buffers
102            need to reflect the maximum size we could use, which is 4MB reads, or 2M samples
103            using 16 bit samples.
104         */
105         _sum_buffer           = new Sample[2*1048576];
106         _mixdown_buffer       = new Sample[2*1048576];
107         _gain_buffer          = new gain_t[2*1048576];
108 }
109
110 void
111 DiskReader::free_working_buffers()
112 {
113         delete [] _sum_buffer;
114         delete [] _mixdown_buffer;
115         delete [] _gain_buffer;
116         _sum_buffer     = 0;
117         _mixdown_buffer = 0;
118         _gain_buffer    = 0;
119 }
120
121 samplecnt_t
122 DiskReader::default_chunk_samples()
123 {
124         return 65536;
125 }
126
127 bool
128 DiskReader::set_name (string const & str)
129 {
130         string my_name = X_("player:");
131         my_name += str;
132
133         if (_name != my_name) {
134                 SessionObject::set_name (my_name);
135         }
136
137         return true;
138 }
139
140 XMLNode&
141 DiskReader::state ()
142 {
143         XMLNode& node (DiskIOProcessor::state ());
144         node.set_property(X_("type"), X_("diskreader"));
145         return node;
146 }
147
148 int
149 DiskReader::set_state (const XMLNode& node, int version)
150 {
151         if (DiskIOProcessor::set_state (node, version)) {
152                 return -1;
153         }
154
155         return 0;
156 }
157
158 void
159 DiskReader::realtime_handle_transport_stopped ()
160 {
161         /* can't do the resolve here because we don't have a place to put the
162          * note resolving data. Defer to
163          * MidiTrack::realtime_handle_transport_stopped() which will call
164          * ::resolve_tracker() and put the output in its _immediate_events store.
165          */
166 }
167
168 void
169 DiskReader::realtime_locate ()
170 {
171 }
172
173 float
174 DiskReader::buffer_load () const
175 {
176         /* Note: for MIDI it's not trivial to differentiate the following two cases:
177
178            1.  The playback buffer is empty because the system has run out of time to fill it.
179            2.  The playback buffer is empty because there is no more data on the playlist.
180
181            If we use a simple buffer load computation, we will report that the MIDI diskstream
182            cannot keep up when #2 happens, when in fact it can.  Since MIDI data rates
183            are so low compared to audio, just use the audio value here.
184         */
185
186         boost::shared_ptr<ChannelList> c = channels.reader();
187
188         if (c->empty ()) {
189                 /* no channels, so no buffers, so completely full and ready to playback, sir! */
190                 return 1.0;
191         }
192
193         PBD::PlaybackBuffer<Sample>* b = c->front()->rbuf;
194         return (float) ((double) b->read_space() / (double) b->bufsize());
195 }
196
197 void
198 DiskReader::adjust_buffering ()
199 {
200         boost::shared_ptr<ChannelList> c = channels.reader();
201
202         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
203                 (*chan)->resize (_session.butler()->audio_diskstream_playback_buffer_size());
204         }
205 }
206
207 void
208 DiskReader::playlist_modified ()
209 {
210         if (!overwrite_queued) {
211                 _session.request_overwrite_buffer (_track);
212                 overwrite_queued = true;
213         }
214 }
215
216 int
217 DiskReader::use_playlist (DataType dt, boost::shared_ptr<Playlist> playlist)
218 {
219         bool prior_playlist = false;
220
221         if (_playlists[dt]) {
222                 prior_playlist = true;
223         }
224
225         if (DiskIOProcessor::use_playlist (dt, playlist)) {
226                 return -1;
227         }
228
229         /* don't do this if we've already asked for it *or* if we are setting up
230            the diskstream for the very first time - the input changed handling will
231            take care of the buffer refill.
232         */
233
234         cerr << "DR " << _track->name() << " using playlist, loading ? " << _session.loading() << endl;
235
236         if (!overwrite_queued && (prior_playlist || _session.loading())) {
237                 _session.request_overwrite_buffer (_track);
238                 overwrite_queued = true;
239         }
240
241         return 0;
242 }
243
244 void
245 DiskReader::run (BufferSet& bufs, samplepos_t start_sample, samplepos_t end_sample,
246                  double speed, pframes_t nframes, bool result_required)
247 {
248         uint32_t n;
249         boost::shared_ptr<ChannelList> c = channels.reader();
250         ChannelList::iterator chan;
251         sampleoffset_t disk_samples_to_consume;
252         MonitorState ms = _track->monitoring_state ();
253
254         if (run_must_resolve) {
255                 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (_track);
256                 if (mt) {
257                         resolve_tracker (mt->immediate_events(), start_sample);
258                 }
259                 run_must_resolve = false;
260         }
261
262         if (_active) {
263                 if (!_pending_active) {
264                         _active = false;
265                         return;
266                 }
267         } else {
268                 if (_pending_active) {
269                         _active = true;
270                 } else {
271                         return;
272                 }
273         }
274
275         const bool declick_out = _session.declick_in_progress();
276         const gain_t target_gain = (declick_out || (speed == 0.0) || ((ms & MonitoringDisk) == 0)) ? 0.0 : 1.0;
277
278         if (!_session.cfg ()->get_use_transport_fades ()) {
279                 _declick_amp.set_gain (target_gain);
280         }
281
282         if (declick_out && (ms == MonitoringDisk) && _declick_amp.gain () == target_gain) {
283                 /* no channels, or stopped. Don't accidentally pass any data
284                  * from disk into our outputs (e.g. via interpolation)
285                  */
286                 return;
287         }
288
289         BufferSet& scratch_bufs (_session.get_scratch_buffers (bufs.count()));
290         const bool still_locating = _session.global_locate_pending() || pending_overwrite ();
291
292         assert (speed == -1 || speed == 0 || speed == 1);
293
294         if (speed == 0) {
295                 disk_samples_to_consume = 0;
296         } else {
297                 disk_samples_to_consume = nframes;
298         }
299
300         if (c->empty()) {
301                 /* do nothing with audio */
302                 goto midi;
303         }
304
305         if (_declick_amp.gain () != target_gain && target_gain == 0) {
306                 /* fade-out */
307 #if 0
308                 printf ("DR fade-out speed=%.1f gain=%.3f off=%ld start=%ld playpos=%ld (%s)\n",
309                                 speed, _declick_amp.gain (), _declick_offs, start_sample, playback_sample, owner()->name().c_str());
310 #endif
311                 ms = MonitorState (ms | MonitoringDisk);
312                 assert (result_required);
313                 result_required = true;
314         } else {
315                 _declick_offs = 0;
316         }
317
318         if (!result_required || ((ms & MonitoringDisk) == 0) || still_locating || _no_disk_output) {
319
320                 /* no need for actual disk data, just advance read pointer and return */
321
322                 if (!still_locating || _no_disk_output) {
323                         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
324                                 (*chan)->rbuf->increment_read_ptr (disk_samples_to_consume);
325                         }
326                 }
327
328                 /* if monitoring disk but locating put silence in the buffers */
329
330                 if ((_no_disk_output || still_locating) && (ms == MonitoringDisk)) {
331                         bufs.silence (nframes, 0);
332                 }
333
334         } else {
335
336                 /* we need audio data from disk */
337
338                 size_t n_buffers = bufs.count().n_audio();
339                 size_t n_chans = c->size();
340                 gain_t scaling;
341
342                 if (n_chans > n_buffers) {
343                         scaling = ((float) n_buffers) / n_chans;
344                 } else {
345                         scaling = 1.0;
346                 }
347
348                 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
349
350                         ChannelInfo* chaninfo (*chan);
351                         AudioBuffer& output (bufs.get_audio (n % n_buffers));
352
353                         AudioBuffer& disk_buf ((ms & MonitoringInput) ? scratch_bufs.get_audio(n) : output);
354
355                         if (start_sample != playback_sample && target_gain != 0) {
356                                 if (can_internal_playback_seek (start_sample - playback_sample)) {
357                                         internal_playback_seek (start_sample - playback_sample);
358                                 } else {
359                                         disk_samples_to_consume = 0; /* will force an underrun below */
360                                 }
361                         }
362
363                         if (!declick_out) {
364                                 const samplecnt_t total = chaninfo->rbuf->read (disk_buf.data(), disk_samples_to_consume);
365                                 if (disk_samples_to_consume > total) {
366                                         cerr << _name << " Need " << total << " have only " << disk_samples_to_consume << endl;
367                                         cerr << "underrun for " << _name << endl;
368                                         DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 underrun in %2, total space = %3\n",
369                                                                                     DEBUG_THREAD_SELF, name(), total));
370                                         Underrun ();
371                                         return;
372                                 }
373                         } else if (_declick_amp.gain () != target_gain) {
374                                 assert (target_gain == 0);
375                                 const samplecnt_t total = chaninfo->rbuf->read (disk_buf.data(), nframes, false, _declick_offs);
376                                 _declick_offs += total;
377                         }
378
379                         _declick_amp.apply_gain (disk_buf, nframes, target_gain);
380
381                         Amp::apply_simple_gain (disk_buf, nframes, scaling);
382
383                         if (ms & MonitoringInput) {
384                                 /* mix the disk signal into the input signal (already in bufs) */
385                                 mix_buffers_no_gain (output.data(), disk_buf.data(), nframes);
386                         }
387                 }
388         }
389
390         /* MIDI data handling */
391
392   midi:
393         if (!declick_in_progress() && bufs.count().n_midi()) {
394                 MidiBuffer* dst;
395
396                 if (_no_disk_output) {
397                         dst = &scratch_bufs.get_midi(0);
398                 } else {
399                         dst = &bufs.get_midi (0);
400                 }
401
402                 if ((ms & MonitoringDisk) && !still_locating && speed) {
403                         get_midi_playback (*dst, start_sample, end_sample, ms, scratch_bufs, speed, disk_samples_to_consume);
404                 }
405         }
406
407         if (!still_locating) {
408
409                 bool butler_required = false;
410
411                 if (speed < 0.0) {
412                         playback_sample -= disk_samples_to_consume;
413                 } else {
414                         playback_sample += disk_samples_to_consume;
415                 }
416
417                 Location* loc = _loop_location;
418                 if (loc) {
419                         Evoral::Range<samplepos_t> loop_range (loc->start(), loc->end() - 1);
420                         playback_sample = loop_range.squish (playback_sample);
421                 }
422
423                 if (_playlists[DataType::AUDIO]) {
424                         if (!c->empty()) {
425                                 if (_slaved) {
426                                         if (c->front()->rbuf->write_space() >= c->front()->rbuf->bufsize() / 2) {
427                                                 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1: slaved, write space = %2 of %3\n", name(), c->front()->rbuf->write_space(), c->front()->rbuf->bufsize()));
428                                                 butler_required = true;
429                                         }
430                                 } else {
431                                         if ((samplecnt_t) c->front()->rbuf->write_space() >= _chunk_samples) {
432                                                 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1: write space = %2 of %3\n", name(), c->front()->rbuf->write_space(),
433                                                                                             _chunk_samples));
434                                                 butler_required = true;
435                                         }
436                                 }
437                         }
438                 }
439
440                 /* All of MIDI is in RAM, no need to call the butler unless we
441                  * have to overwrite buffers because of a playlist change.
442                  */
443
444                 _need_butler = butler_required;
445         }
446
447         // DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 reader run, needs butler = %2\n", name(), _need_butler));
448 }
449
450 bool
451 DiskReader::declick_in_progress () const
452 {
453         return _declick_amp.gain() != 0; // declick-out
454 }
455
456 bool
457 DiskReader::pending_overwrite () const {
458         return g_atomic_int_get (&_pending_overwrite) != 0;
459 }
460
461 void
462 DiskReader::set_pending_overwrite ()
463 {
464         /* called from audio thread, so we can use the read ptr and playback sample as we wish */
465
466         assert (!pending_overwrite ());
467         overwrite_sample = playback_sample;
468
469         boost::shared_ptr<ChannelList> c = channels.reader ();
470         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
471                 (*chan)->rbuf->read_flush ();
472         }
473
474         g_atomic_int_set (&_pending_overwrite, 1);
475         run_must_resolve = true;
476 }
477
478 bool
479 DiskReader::overwrite_existing_buffers ()
480 {
481         /* called from butler thread */
482         assert (pending_overwrite ());
483         overwrite_queued = false;
484
485         DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1 overwriting existing buffers at %2\n", overwrite_sample));
486
487         boost::shared_ptr<ChannelList> c = channels.reader();
488         if (!c->empty ()) {
489                 /* AUDIO */
490
491                 const bool reversed = _session.transport_speed() < 0.0f;
492
493                 /* assume all are the same size */
494                 samplecnt_t size = c->front()->rbuf->write_space ();
495                 assert (size > 0);
496
497                 boost::scoped_array<Sample> sum_buffer (new Sample[size]);
498                 boost::scoped_array<Sample> mixdown_buffer (new Sample[size]);
499                 boost::scoped_array<float> gain_buffer (new float[size]);
500
501                 /* reduce size so that we can fill the buffer correctly (ringbuffers
502                  * can only handle size-1, otherwise they appear to be empty)
503                  */
504                 size--;
505
506                 uint32_t n=0;
507
508                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
509
510                         samplepos_t start = overwrite_sample;
511                         samplecnt_t to_read = size;
512
513                         if (audio_read ((*chan)->rbuf, sum_buffer.get(), mixdown_buffer.get(), gain_buffer.get(), start, to_read, n, reversed)) {
514                                 error << string_compose(_("DiskReader %1: when refilling, cannot read %2 from playlist at sample %3"), id(), size, overwrite_sample) << endmsg;
515                                 goto midi;
516                         }
517                 }
518         }
519
520   midi:
521
522         RTMidiBuffer* mbuf = rt_midibuffer ();
523
524         if (mbuf) {
525                 PBD::Timing minsert;
526                 minsert.start();
527                 midi_playlist()->render (0);
528                 minsert.update();
529                 assert (midi_playlist()->rendered());
530                 // cerr << "Reading " << name()  << " took " << minsert.elapsed() << " microseconds, final size = " << midi_playlist()->rendered()->size() << endl;
531                 // midi_playlist()->rendered()->dump (100);
532         }
533
534         g_atomic_int_set (&_pending_overwrite, 0);
535
536         return true;
537 }
538
539 int
540 DiskReader::seek (samplepos_t sample, bool complete_refill)
541 {
542         /* called via non_realtime_locate() from butler thread */
543
544         uint32_t n;
545         int ret = -1;
546         ChannelList::iterator chan;
547         boost::shared_ptr<ChannelList> c = channels.reader();
548
549 #ifndef NDEBUG
550         if (_declick_amp.gain() != 0) {
551                 /* this should not happen. new transport should postponse seeking
552                  * until de-click is complete */
553                 printf ("LOCATE WITHOUT DECLICK (gain=%f) at %ld seek-to %ld\n", _declick_amp.gain (), playback_sample, sample);
554                 //return -1;
555         }
556         if (sample == playback_sample && !complete_refill) {
557                 return 0; // XXX double-check this
558         }
559 #endif
560
561         g_atomic_int_set (&_pending_overwrite, 0);
562
563         DEBUG_TRACE (DEBUG::DiskIO, string_compose ("DiskReader::seek %s %ld -> %ld refill=%d\n", owner()->name().c_str(), playback_sample, sample, complete_refill));
564
565         const samplecnt_t distance = sample - playback_sample;
566         if (!complete_refill && can_internal_playback_seek (distance)) {
567                 internal_playback_seek (distance);
568                 return 0;
569         }
570
571         for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
572                 (*chan)->rbuf->reset ();
573         }
574
575         playback_sample = sample;
576         file_sample[DataType::AUDIO] = sample;
577         file_sample[DataType::MIDI] = sample;
578
579         if (complete_refill) {
580                 /* call _do_refill() to refill the entire buffer, using
581                    the largest reads possible.
582                 */
583                 while ((ret = do_refill_with_alloc (false)) > 0) ;
584         } else {
585                 /* call _do_refill() to refill just one chunk, and then
586                    return.
587                 */
588                 ret = do_refill_with_alloc (true);
589         }
590
591         return ret;
592 }
593
594 bool
595 DiskReader::can_internal_playback_seek (sampleoffset_t distance)
596 {
597         /* 1. Audio */
598
599         ChannelList::iterator chan;
600         boost::shared_ptr<ChannelList> c = channels.reader();
601
602         for (chan = c->begin(); chan != c->end(); ++chan) {
603                 if (!(*chan)->rbuf->can_seek (distance)) {
604                         return false;
605                 }
606         }
607
608         /* 2. MIDI can always seek any distance */
609
610         return true;
611 }
612
613 void
614 DiskReader::internal_playback_seek (sampleoffset_t distance)
615 {
616         if (distance == 0) {
617                 return;
618         }
619
620         sampleoffset_t off = distance;
621
622         ChannelList::iterator chan;
623         boost::shared_ptr<ChannelList> c = channels.reader();
624         for (chan = c->begin(); chan != c->end(); ++chan) {
625                 if (distance < 0) {
626                         off = 0 - (sampleoffset_t) (*chan)->rbuf->decrement_read_ptr (::llabs (distance));
627                 } else {
628                         off = (*chan)->rbuf->increment_read_ptr (distance);
629                 }
630         }
631
632         playback_sample += off;
633 }
634
635 static
636 void swap_by_ptr (Sample *first, Sample *last)
637 {
638         while (first < last) {
639                 Sample tmp = *first;
640                 *first++ = *last;
641                 *last-- = tmp;
642         }
643 }
644
645 /** Read some data for 1 channel from our playlist into a buffer.
646  *  @param buf Buffer to write to.
647  *  @param start Session sample to start reading from; updated to where we end up
648  *         after the read.
649  *  @param cnt Count of samples to read.
650  *  @param reversed true if we are running backwards, otherwise false.
651  */
652 int
653 DiskReader::audio_read (PBD::PlaybackBuffer<Sample>*rb,
654                         Sample* sum_buffer,
655                         Sample* mixdown_buffer,
656                         float* gain_buffer,
657                         samplepos_t& start, samplecnt_t cnt,
658                         int channel, bool reversed)
659 {
660         samplecnt_t this_read = 0;
661         bool reloop = false;
662         samplepos_t loop_end = 0;
663         samplepos_t loop_start = 0;
664         Location *loc = 0;
665
666         if (!_playlists[DataType::AUDIO]) {
667                 rb->write_zero (cnt);
668                 return 0;
669         }
670
671         /* XXX we don't currently play loops in reverse. not sure why */
672
673         if (!reversed) {
674
675                 samplecnt_t loop_length = 0;
676
677                 /* Make the use of a Location atomic for this read operation.
678
679                    Note: Locations don't get deleted, so all we care about
680                    when I say "atomic" is that we are always pointing to
681                    the same one and using a start/length values obtained
682                    just once.
683                 */
684
685                 if ((loc = _loop_location) != 0) {
686                         loop_start = loc->start();
687                         loop_end = loc->end();
688                         loop_length = loop_end - loop_start;
689                 }
690
691                 /* if we are looping, ensure that the first sample we read is at the correct
692                    position within the loop.
693                 */
694
695                 if (loc && start >= loop_end) {
696                         start = loop_start + ((start - loop_start) % loop_length);
697                 }
698
699         }
700
701         if (reversed) {
702                 start -= cnt;
703         }
704
705         /* We need this while loop in case we hit a loop boundary, in which case our read from
706            the playlist must be split into more than one section.
707         */
708
709         while (cnt) {
710
711                 /* take any loop into account. we can't read past the end of the loop. */
712
713                 if (loc && (loop_end - start < cnt)) {
714                         this_read = loop_end - start;
715                         reloop = true;
716                 } else {
717                         reloop = false;
718                         this_read = cnt;
719                 }
720
721                 if (this_read == 0) {
722                         break;
723                 }
724
725                 this_read = min (cnt, this_read);
726
727                 if (audio_playlist()->read (sum_buffer, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
728                         error << string_compose(_("DiskReader %1: cannot read %2 from playlist at sample %3"), id(), this_read, start) << endmsg;
729                         return -1;
730                 }
731
732                 if (reversed) {
733
734                         swap_by_ptr (sum_buffer, sum_buffer + this_read - 1);
735
736                 } else {
737
738                         /* if we read to the end of the loop, go back to the beginning */
739
740                         if (reloop) {
741                                 start = loop_start;
742                         } else {
743                                 start += this_read;
744                         }
745                 }
746
747                 if (rb->write (sum_buffer, this_read) != this_read) {
748                         cerr << owner()->name() << " Ringbuffer Write overrun" << endl;
749                 }
750
751                 cnt -= this_read;
752         }
753
754         return 0;
755 }
756
757 int
758 DiskReader::_do_refill_with_alloc (bool partial_fill)
759 {
760         /* We limit disk reads to at most 4MB chunks, which with floating point
761            samples would be 1M samples. But we might use 16 or 14 bit samples,
762            in which case 4MB is more samples than that. Therefore size this for
763            the smallest sample value .. 4MB = 2M samples (16 bit).
764         */
765
766         {
767                 boost::scoped_array<Sample> sum_buf (new Sample[2*1048576]);
768                 boost::scoped_array<Sample> mix_buf (new Sample[2*1048576]);
769                 boost::scoped_array<float>  gain_buf (new float[2*1048576]);
770
771                 int ret = refill_audio (sum_buf.get(), mix_buf.get(), gain_buf.get(), (partial_fill ? _chunk_samples : 0));
772
773                 if (ret) {
774                         return ret;
775                 }
776         }
777
778         return refill_midi ();
779 }
780
781 int
782 DiskReader::refill (Sample* sum_buffer, Sample* mixdown_buffer, float* gain_buffer, samplecnt_t fill_level)
783 {
784         int ret = refill_audio (sum_buffer, mixdown_buffer, gain_buffer, fill_level);
785
786         if (ret) {
787                 return ret;
788         }
789
790         return refill_midi ();
791 }
792
793
794 /** Get some more data from disk and put it in our channels' bufs,
795  *  if there is suitable space in them.
796  *
797  * If fill_level is non-zero, then we will refill the buffer so that there is
798  * still at least fill_level samples of space left to be filled. This is used
799  * after locates so that we do not need to wait to fill the entire buffer.
800  *
801  */
802
803 int
804 DiskReader::refill_audio (Sample* sum_buffer, Sample* mixdown_buffer, float* gain_buffer, samplecnt_t fill_level)
805 {
806         /* do not read from disk while session is marked as Loading, to avoid
807            useless redundant I/O.
808         */
809
810         if (_session.loading()) {
811                 return 0;
812         }
813
814         int32_t ret = 0;
815         bool const reversed = _session.transport_speed() < 0.0f;
816         samplecnt_t zero_fill;
817         uint32_t chan_n;
818         ChannelList::iterator i;
819         boost::shared_ptr<ChannelList> c = channels.reader();
820
821         if (c->empty()) {
822                 return 0;
823         }
824
825         assert(mixdown_buffer);
826         assert(gain_buffer);
827
828         samplecnt_t total_space = c->front()->rbuf->write_space();
829
830         if (total_space == 0) {
831                 DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1: no space to refill\n", name()));
832                 /* nowhere to write to */
833                 return 0;
834         }
835
836         if (fill_level) {
837                 if (fill_level < total_space) {
838                         total_space -= fill_level;
839                 } else {
840                         /* we can't do anything with it */
841                         fill_level = 0;
842                 }
843         }
844
845         /* if we're running close to normal speed and there isn't enough
846            space to do disk_read_chunk_samples of I/O, then don't bother.
847
848            at higher speeds, just do it because the sync between butler
849            and audio thread may not be good enough.
850
851            Note: it is a design assumption that disk_read_chunk_samples is smaller
852            than the playback buffer size, so this check should never trip when
853            the playback buffer is empty.
854         */
855
856         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()));
857         if ((total_space < _chunk_samples) && fabs (_session.transport_speed()) < 2.0f) {
858                 return 0;
859         }
860
861         /* when slaved, don't try to get too close to the read pointer. this
862            leaves space for the buffer reversal to have something useful to
863            work with.
864         */
865
866         if (_slaved && total_space < (samplecnt_t) (c->front()->rbuf->bufsize() / 2)) {
867                 DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1: not enough to refill while slaved\n", this));
868                 return 0;
869         }
870
871         samplepos_t ffa = file_sample[DataType::AUDIO];
872
873         if (reversed) {
874
875                 if (ffa == 0) {
876                         /* at start: nothing to do but fill with silence */
877                         for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
878                                 ChannelInfo* chan (*i);
879                                 chan->rbuf->write_zero (chan->rbuf->write_space ());
880                         }
881                         return 0;
882                 }
883
884                 if (ffa < total_space) {
885                         /* too close to the start: read what we can, and then zero fill the rest */
886                         zero_fill = total_space - ffa;
887                         total_space = ffa;
888                 } else {
889                         zero_fill = 0;
890                 }
891
892         } else {
893
894                 if (ffa == max_samplepos) {
895                         /* at end: nothing to do but fill with silence */
896                         for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
897                                 ChannelInfo* chan (*i);
898                                 chan->rbuf->write_zero (chan->rbuf->write_space ());
899                         }
900                         return 0;
901                 }
902
903                 if (ffa > max_samplepos - total_space) {
904                         /* to close to the end: read what we can, and zero fill the rest */
905                         zero_fill = total_space - (max_samplepos - ffa);
906                         total_space = max_samplepos - ffa;
907
908                 } else {
909                         zero_fill = 0;
910                 }
911         }
912
913         /* total_space is in samples. We want to optimize read sizes in various sizes using bytes */
914         const size_t bits_per_sample = format_data_width (_session.config.get_native_file_data_format());
915         size_t total_bytes = total_space * bits_per_sample / 8;
916
917         /* chunk size range is 256kB to 4MB. Bigger is faster in terms of MB/sec, but bigger chunk size always takes longer */
918         size_t byte_size_for_read = max ((size_t) (256 * 1024), min ((size_t) (4 * 1048576), total_bytes));
919
920         /* find nearest (lower) multiple of 16384 */
921
922         byte_size_for_read = (byte_size_for_read / 16384) * 16384;
923
924         /* now back to samples */
925         samplecnt_t samples_to_read = byte_size_for_read / (bits_per_sample / 8);
926
927         DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1: will refill %2 channels with %3 samples\n", name(), c->size(), total_space));
928
929         samplepos_t file_sample_tmp = ffa;
930
931         for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
932                 ChannelInfo* chan (*i);
933                 file_sample_tmp = ffa;
934                 samplecnt_t ts = total_space;
935
936                 samplecnt_t to_read = min (ts, (samplecnt_t) chan->rbuf->write_space ());
937                 to_read = min (to_read, samples_to_read);
938                 assert (to_read >= 0);
939
940                 // cerr << owner()->name() << " to-read: " << to_read << endl;
941
942                 if (to_read) {
943                         if (audio_read (chan->rbuf, sum_buffer, mixdown_buffer, gain_buffer, file_sample_tmp, to_read, chan_n, reversed)) {
944                                 error << string_compose(_("DiskReader %1: when refilling, cannot read %2 from playlist at sample %3"), id(), to_read, ffa) << endmsg;
945                                 ret = -1;
946                                 goto out;
947                         }
948                 }
949
950                 if (zero_fill) {
951                         /* not sure if action is needed,
952                          * we'll later hit the "to close to the end" case
953                          */
954                         //chan->rbuf->write_zero (zero_fill);
955                 }
956         }
957
958         // elapsed = g_get_monotonic_time () - before;
959         // cerr << '\t' << name() << ": bandwidth = " << (byte_size_for_read / 1048576.0) / (elapsed/1000000.0) << "MB/sec\n";
960
961         file_sample[DataType::AUDIO] = file_sample_tmp;
962         assert (file_sample[DataType::AUDIO] >= 0);
963
964         ret = ((total_space - samples_to_read) > _chunk_samples);
965
966   out:
967         return ret;
968 }
969
970 void
971 DiskReader::playlist_ranges_moved (list< Evoral::RangeMove<samplepos_t> > const & movements_samples, bool from_undo_or_shift)
972 {
973         /* If we're coming from an undo, it will have handled
974          * automation undo (it must, since automation-follows-regions
975          * can lose automation data).  Hence we can do nothing here.
976          *
977          * Likewise when shifting regions (insert/remove time)
978          * automation is taken care of separately (busses with
979          * automation have no disk-reader).
980          */
981
982         if (from_undo_or_shift) {
983                 return;
984         }
985
986         if (!_track || Config->get_automation_follows_regions () == false) {
987                 return;
988         }
989
990         list< Evoral::RangeMove<double> > movements;
991
992         for (list< Evoral::RangeMove<samplepos_t> >::const_iterator i = movements_samples.begin();
993              i != movements_samples.end();
994              ++i) {
995
996                 movements.push_back(Evoral::RangeMove<double>(i->from, i->length, i->to));
997         }
998
999         /* move panner automation */
1000         boost::shared_ptr<Pannable> pannable = _track->pannable();
1001         Evoral::ControlSet::Controls& c (pannable->controls());
1002
1003         for (Evoral::ControlSet::Controls::iterator ci = c.begin(); ci != c.end(); ++ci) {
1004                 boost::shared_ptr<AutomationControl> ac = boost::dynamic_pointer_cast<AutomationControl>(ci->second);
1005                 if (!ac) {
1006                         continue;
1007                 }
1008                 boost::shared_ptr<AutomationList> alist = ac->alist();
1009                 if (!alist->size()) {
1010                         continue;
1011                 }
1012                 XMLNode & before = alist->get_state ();
1013                 bool const things_moved = alist->move_ranges (movements);
1014                 if (things_moved) {
1015                         _session.add_command (new MementoCommand<AutomationList> (
1016                                                       *alist.get(), &before, &alist->get_state ()));
1017                 }
1018         }
1019         /* move processor automation */
1020         _track->foreach_processor (boost::bind (&DiskReader::move_processor_automation, this, _1, movements_samples));
1021 }
1022
1023 void
1024 DiskReader::move_processor_automation (boost::weak_ptr<Processor> p, list< Evoral::RangeMove<samplepos_t> > const & movements_samples)
1025 {
1026         boost::shared_ptr<Processor> processor (p.lock ());
1027         if (!processor) {
1028                 return;
1029         }
1030
1031         list< Evoral::RangeMove<double> > movements;
1032         for (list< Evoral::RangeMove<samplepos_t> >::const_iterator i = movements_samples.begin(); i != movements_samples.end(); ++i) {
1033                 movements.push_back(Evoral::RangeMove<double>(i->from, i->length, i->to));
1034         }
1035
1036         set<Evoral::Parameter> const a = processor->what_can_be_automated ();
1037
1038         for (set<Evoral::Parameter>::const_iterator i = a.begin (); i != a.end (); ++i) {
1039                 boost::shared_ptr<AutomationList> al = processor->automation_control(*i)->alist();
1040                 if (!al->size()) {
1041                         continue;
1042                 }
1043                 XMLNode & before = al->get_state ();
1044                 bool const things_moved = al->move_ranges (movements);
1045                 if (things_moved) {
1046                         _session.add_command (
1047                                 new MementoCommand<AutomationList> (
1048                                         *al.get(), &before, &al->get_state ()
1049                                         )
1050                                 );
1051                 }
1052         }
1053 }
1054
1055 void
1056 DiskReader::reset_tracker ()
1057 {
1058         _tracker.reset ();
1059 }
1060
1061 void
1062 DiskReader::resolve_tracker (Evoral::EventSink<samplepos_t>& buffer, samplepos_t time)
1063 {
1064         _tracker.resolve_notes (buffer, time);
1065 }
1066
1067 /** Writes playback events from playback_sample for nframes to dst, translating time stamps
1068  *  so that an event at playback_sample has time = 0
1069  */
1070 void
1071 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)
1072 {
1073         MidiBuffer* target;
1074         samplepos_t nframes = ::llabs (end_sample - start_sample);
1075
1076         RTMidiBuffer* mbuf = rt_midibuffer();
1077
1078         if (!mbuf || (mbuf->size() == 0)) {
1079                 /* no data to read, so do nothing */
1080                 return;
1081         }
1082
1083         if ((ms & MonitoringInput) == 0) {
1084                 /* Route::process_output_buffers() clears the buffer as-needed */
1085                 target = &dst;
1086         } else {
1087                 target = &scratch_bufs.get_midi (0);
1088         }
1089
1090         size_t events_read = 0;
1091
1092         if (!pending_overwrite() && (ms & MonitoringDisk)) {
1093
1094                 /* disk data needed */
1095
1096                 Location* loc = _loop_location;
1097
1098                 if (loc) {
1099                         samplepos_t effective_start;
1100
1101                         Evoral::Range<samplepos_t> loop_range (loc->start(), loc->end() - 1);
1102                         effective_start = loop_range.squish (start_sample);
1103
1104                         DEBUG_TRACE (DEBUG::MidiDiskIO, string_compose ("looped, effective start adjusted to %1\n", effective_start));
1105
1106                         if (effective_start == loc->start()) {
1107                                 /* We need to turn off notes that may extend
1108                                    beyond the loop end.
1109                                 */
1110
1111                                 _tracker.resolve_notes (*target, 0);
1112                         }
1113
1114                         /* for split-cycles we need to offset the events */
1115
1116                         if (loc->end() >= effective_start && loc->end() < effective_start + nframes) {
1117
1118                                 /* end of loop is within the range we are reading, so
1119                                    split the read in two, and lie about the location
1120                                    for the 2nd read
1121                                 */
1122
1123                                 samplecnt_t first, second;
1124
1125                                 first = loc->end() - effective_start;
1126                                 second = nframes - first;
1127
1128                                 DEBUG_TRACE (DEBUG::MidiDiskIO, string_compose ("loop read for eff %1 end %2: %3 and %4, cycle offset %5\n",
1129                                                                                       effective_start, loc->end(), first, second));
1130
1131                                 if (first) {
1132                                         DEBUG_TRACE (DEBUG::MidiDiskIO, string_compose ("loop read #1, from %1 for %2\n",
1133                                                                                               effective_start, first));
1134                                         events_read = mbuf->read (*target, effective_start, effective_start + first, _tracker);
1135                                 }
1136
1137                                 if (second) {
1138                                         DEBUG_TRACE (DEBUG::MidiDiskIO, string_compose ("loop read #2, from %1 for %2\n",
1139                                                                                               loc->start(), second));
1140                                         events_read += mbuf->read (*target, loc->start(), loc->start() + second, _tracker);
1141                                 }
1142
1143                         } else {
1144                                 DEBUG_TRACE (DEBUG::MidiDiskIO, string_compose ("loop read #3, adjusted start as %1 for %2\n",
1145                                                                                 effective_start, nframes));
1146                                 events_read = mbuf->read (*target, effective_start, effective_start + nframes, _tracker);
1147                         }
1148                 } else {
1149                         DEBUG_TRACE (DEBUG::MidiDiskIO, string_compose ("playback buffer read, from %1 to %2 (%3)", start_sample, end_sample, nframes));
1150                         events_read = mbuf->read (*target, start_sample, end_sample, _tracker, Port::port_offset ());
1151                 }
1152
1153                 DEBUG_TRACE (DEBUG::MidiDiskIO, string_compose ("%1 MDS events read %2 range %3 .. %4\n", _name, events_read, playback_sample, playback_sample + nframes));
1154         }
1155
1156
1157         if (!_no_disk_output && (ms & MonitoringInput)) {
1158                 dst.merge_from (*target, nframes);
1159         }
1160
1161 #if 0
1162         if (!target->empty ()) {
1163                 cerr << "======== MIDI OUT ========\n";
1164                 for (MidiBuffer::iterator i = target->begin(); i != target->end(); ++i) {
1165                         const Evoral::Event<MidiBuffer::TimeType> ev (*i, false);
1166                         cerr << "MIDI EVENT (from disk) @ " << ev.time();
1167                         for (size_t xx = 0; xx < ev.size(); ++xx) {
1168                                 cerr << ' ' << hex << (int) ev.buffer()[xx];
1169                         }
1170                         cerr << dec << endl;
1171                 }
1172                 cerr << "----------------\n";
1173         }
1174 #endif
1175 }
1176
1177 /** @a start is set to the new sample position (TIME) read up to */
1178 int
1179 DiskReader::midi_read (samplepos_t& start, samplecnt_t dur, bool reversed)
1180 {
1181         return 0;
1182 }
1183
1184 int
1185 DiskReader::refill_midi ()
1186 {
1187         /* nothing to do ... it's all in RAM thanks to overwrite */
1188         return 0;
1189 }
1190
1191 void
1192 DiskReader::dec_no_disk_output ()
1193 {
1194         /* this is called unconditionally when things happen that ought to end
1195            a period of "no disk output". It's OK for that to happen when there
1196            was no corresponding call to ::inc_no_disk_output(), but we must
1197            stop the value from becoming negative.
1198         */
1199
1200         do {
1201                 gint v  = g_atomic_int_get (&_no_disk_output);
1202                 if (v > 0) {
1203                         if (g_atomic_int_compare_and_exchange (&_no_disk_output, v, v - 1)) {
1204                                 break;
1205                         }
1206                 } else {
1207                         break;
1208                 }
1209         } while (true);
1210 }
1211
1212 DiskReader::DeclickAmp::DeclickAmp (samplecnt_t sample_rate)
1213 {
1214         _a = 4550.f / (gain_t)sample_rate;
1215         _l = -log1p (_a);
1216         _g = 0;
1217 }
1218
1219 void
1220 DiskReader::DeclickAmp::apply_gain (AudioBuffer& buf, samplecnt_t n_samples, const float target)
1221 {
1222         if (n_samples == 0) {
1223                 return;
1224         }
1225         float g = _g;
1226
1227         if (g == target) {
1228                 Amp::apply_simple_gain (buf, n_samples, target, 0);
1229                 return;
1230         }
1231
1232         const float a = _a;
1233         Sample* const buffer = buf.data ();
1234
1235         const int max_nproc = 16;
1236         uint32_t remain = n_samples;
1237         uint32_t offset = 0;
1238         while (remain > 0) {
1239                 uint32_t n_proc = remain > max_nproc ? max_nproc : remain;
1240                 for (uint32_t i = 0; i < n_proc; ++i) {
1241                         buffer[offset + i] *= g;
1242                 }
1243 #if 1
1244                 g += a * (target - g);
1245 #else /* accurate exponential fade */
1246                 if (n_proc == max_nproc) {
1247                         g += a * (target - g);
1248                 } else {
1249                         g = target - (target - g) * expf (_l * n_proc / max_nproc);
1250                 }
1251 #endif
1252                 remain -= n_proc;
1253                 offset += n_proc;
1254         }
1255
1256         if (fabsf (g - target) < /* GAIN_COEFF_DELTA */ 1e-5) {
1257                 _g = target;
1258         } else {
1259                 _g = g;
1260         }
1261 }
1262
1263 RTMidiBuffer*
1264 DiskReader::rt_midibuffer ()
1265 {
1266         boost::shared_ptr<Playlist> pl = _playlists[DataType::MIDI];
1267
1268         if (!pl) {
1269                 return 0;
1270         }
1271
1272         boost::shared_ptr<MidiPlaylist> mpl = boost::dynamic_pointer_cast<MidiPlaylist> (pl);
1273
1274         if (!mpl) {
1275                 /* error, but whatever ... */
1276                 return 0;
1277         }
1278
1279         return mpl->rendered();
1280 }