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