switch from std::auto_ptr<> (deprecated) to boost::scoped_ptr<>
[ardour.git] / libs / ardour / disk_reader.cc
1 /*
2     Copyright (C) 2009-2016 Paul Davis
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include <boost/smart_ptr/scoped_ptr.hpp>
21
22 #include "pbd/enumwriter.h"
23 #include "pbd/memento_command.h"
24
25 #include "ardour/audioengine.h"
26 #include "ardour/audioplaylist.h"
27 #include "ardour/audio_buffer.h"
28 #include "ardour/butler.h"
29 #include "ardour/debug.h"
30 #include "ardour/disk_reader.h"
31 #include "ardour/midi_ring_buffer.h"
32 #include "ardour/midi_playlist.h"
33 #include "ardour/midi_track.h"
34 #include "ardour/pannable.h"
35 #include "ardour/playlist.h"
36 #include "ardour/playlist_factory.h"
37 #include "ardour/session.h"
38 #include "ardour/session_playlists.h"
39
40 #include "pbd/i18n.h"
41
42 using namespace ARDOUR;
43 using namespace PBD;
44 using namespace std;
45
46 ARDOUR::samplecnt_t DiskReader::_chunk_samples = default_chunk_samples ();
47 PBD::Signal0<void> DiskReader::Underrun;
48 Sample* DiskReader::_mixdown_buffer = 0;
49 gain_t* DiskReader::_gain_buffer = 0;
50 samplecnt_t DiskReader::midi_readahead = 4096;
51 bool DiskReader::_no_disk_output = false;
52
53 DiskReader::DiskReader (Session& s, string const & str, DiskIOProcessor::Flag f)
54         : DiskIOProcessor (s, str, f)
55         , overwrite_sample (0)
56         , overwrite_offset (0)
57         , _pending_overwrite (false)
58         , overwrite_queued (false)
59 {
60         file_sample[DataType::AUDIO] = 0;
61         file_sample[DataType::MIDI] = 0;
62 }
63
64 DiskReader::~DiskReader ()
65 {
66         DEBUG_TRACE (DEBUG::Destruction, string_compose ("DiskReader %1 @ %2 deleted\n", _name, this));
67
68         for (uint32_t n = 0; n < DataType::num_types; ++n) {
69                 if (_playlists[n]) {
70                         _playlists[n]->release ();
71                 }
72         }
73
74         {
75                 RCUWriter<ChannelList> writer (channels);
76                 boost::shared_ptr<ChannelList> c = writer.get_copy();
77
78                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
79                         delete *chan;
80                 }
81
82                 c->clear();
83         }
84
85         channels.flush ();
86
87         delete _midi_buf;
88 }
89
90 void
91 DiskReader::allocate_working_buffers()
92 {
93         /* with varifill buffer refilling, we compute the read size in bytes (to optimize
94            for disk i/o bandwidth) and then convert back into samples. These buffers
95            need to reflect the maximum size we could use, which is 4MB reads, or 2M samples
96            using 16 bit samples.
97         */
98         _mixdown_buffer       = new Sample[2*1048576];
99         _gain_buffer          = new gain_t[2*1048576];
100 }
101
102 void
103 DiskReader::free_working_buffers()
104 {
105         delete [] _mixdown_buffer;
106         delete [] _gain_buffer;
107         _mixdown_buffer       = 0;
108         _gain_buffer          = 0;
109 }
110
111 samplecnt_t
112 DiskReader::default_chunk_samples()
113 {
114         return 65536;
115 }
116
117 bool
118 DiskReader::set_name (string const & str)
119 {
120         string my_name = X_("player:");
121         my_name += str;
122
123         if (_name != my_name) {
124                 SessionObject::set_name (my_name);
125         }
126
127         return true;
128 }
129
130 XMLNode&
131 DiskReader::state ()
132 {
133         XMLNode& node (DiskIOProcessor::state ());
134         node.set_property(X_("type"), X_("diskreader"));
135         return node;
136 }
137
138 int
139 DiskReader::set_state (const XMLNode& node, int version)
140 {
141         if (DiskIOProcessor::set_state (node, version)) {
142                 return -1;
143         }
144
145         return 0;
146 }
147
148 void
149 DiskReader::realtime_handle_transport_stopped ()
150 {
151 }
152
153 void
154 DiskReader::realtime_locate ()
155 {
156 }
157
158 float
159 DiskReader::buffer_load () const
160 {
161         /* Note: for MIDI it's not trivial to differentiate the following two cases:
162
163            1.  The playback buffer is empty because the system has run out of time to fill it.
164            2.  The playback buffer is empty because there is no more data on the playlist.
165
166            If we use a simple buffer load computation, we will report that the MIDI diskstream
167            cannot keep up when #2 happens, when in fact it can.  Since MIDI data rates
168            are so low compared to audio, just use the audio value here.
169         */
170
171         boost::shared_ptr<ChannelList> c = channels.reader();
172
173         if (c->empty ()) {
174                 /* no channels, so no buffers, so completely full and ready to playback, sir! */
175                 return 1.0;
176         }
177
178         PBD::RingBufferNPT<Sample> * b = c->front()->buf;
179         return (float) ((double) b->read_space() / (double) b->bufsize());
180 }
181
182 void
183 DiskReader::adjust_buffering ()
184 {
185         boost::shared_ptr<ChannelList> c = channels.reader();
186
187         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
188                 (*chan)->resize (_session.butler()->audio_diskstream_playback_buffer_size());
189         }
190 }
191
192 void
193 DiskReader::playlist_changed (const PropertyChange&)
194 {
195         playlist_modified ();
196 }
197
198 void
199 DiskReader::playlist_modified ()
200 {
201         if (!i_am_the_modifier && !overwrite_queued) {
202                 _session.request_overwrite_buffer (_route);
203                 overwrite_queued = true;
204         }
205 }
206
207 int
208 DiskReader::use_playlist (DataType dt, boost::shared_ptr<Playlist> playlist)
209 {
210         bool prior_playlist = false;
211
212         if (_playlists[dt]) {
213                 prior_playlist = true;
214         }
215
216         if (DiskIOProcessor::use_playlist (dt, playlist)) {
217                 return -1;
218         }
219
220         /* don't do this if we've already asked for it *or* if we are setting up
221            the diskstream for the very first time - the input changed handling will
222            take care of the buffer refill.
223         */
224
225         if (!overwrite_queued && (prior_playlist || _session.loading())) {
226                 _session.request_overwrite_buffer (_route);
227                 overwrite_queued = true;
228         }
229
230         return 0;
231 }
232
233 void
234 DiskReader::run (BufferSet& bufs, samplepos_t start_sample, samplepos_t end_sample,
235                  double speed, pframes_t nframes, bool result_required)
236 {
237         uint32_t n;
238         boost::shared_ptr<ChannelList> c = channels.reader();
239         ChannelList::iterator chan;
240         sampleoffset_t disk_samples_to_consume;
241         MonitorState ms = _route->monitoring_state ();
242
243         if (_active) {
244                 if (!_pending_active) {
245                         _active = false;
246                         return;
247                 }
248         } else {
249                 if (_pending_active) {
250                         _active = true;
251                 } else {
252                         return;
253                 }
254         }
255
256         if ((speed == 0.0) && (ms == MonitoringDisk)) {
257                 /* no channels, or stopped. Don't accidentally pass any data
258                  * from disk into our outputs (e.g. via interpolation)
259                  */
260                 return;
261         }
262
263         BufferSet& scratch_bufs (_session.get_scratch_buffers (bufs.count()));
264         const bool still_locating = _session.global_locate_pending();
265
266         if (c->empty()) {
267                 /* do nothing with audio */
268                 goto midi;
269         }
270
271         if (speed != 1.0f && speed != -1.0f) {
272                 interpolation.set_speed (speed);
273                 disk_samples_to_consume = interpolation.distance (nframes);
274                 if (speed < 0.0) {
275                         disk_samples_to_consume = -disk_samples_to_consume;
276                 }
277         } else {
278                 disk_samples_to_consume = nframes;
279         }
280
281
282         if (!result_required || ((ms & MonitoringDisk) == 0) || still_locating || _no_disk_output) {
283
284                 /* no need for actual disk data, just advance read pointer and return */
285
286                 if (!still_locating || _no_disk_output) {
287                         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
288                                 (*chan)->buf->increment_read_ptr (disk_samples_to_consume);
289                         }
290                 }
291
292                 /* if monitoring disk but locating put silence in the buffers */
293
294                 if ((_no_disk_output || still_locating) && (ms == MonitoringDisk)) {
295                         bufs.silence (nframes, 0);
296                 }
297
298         } else {
299
300                 /* we need audio data from disk */
301
302                 size_t n_buffers = bufs.count().n_audio();
303                 size_t n_chans = c->size();
304                 gain_t scaling;
305
306                 if (n_chans > n_buffers) {
307                         scaling = ((float) n_buffers)/n_chans;
308                 } else {
309                         scaling = 1.0;
310                 }
311
312                 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
313
314                         ChannelInfo* chaninfo (*chan);
315                         AudioBuffer& output (bufs.get_audio (n%n_buffers));
316                         Sample* disk_signal = 0; /* assignment not really needed but it keeps the compiler quiet and helps track bugs */
317
318                         if (ms & MonitoringInput) {
319                                 /* put disk stream in scratch buffer, blend at end */
320                                 disk_signal = scratch_bufs.get_audio(n).data ();
321                         } else {
322                                 /* no input stream needed, just overwrite buffers */
323                                 disk_signal = output.data ();
324                         }
325
326                         if (speed > 0) {
327                                 if (start_sample < playback_sample) {
328                                         cerr << owner()->name() << " SS = " << start_sample << " PS = " << playback_sample << endl;
329                                         abort ();
330                                 }
331                         } else if (speed < 0) {
332                                 if (playback_sample < start_sample) {
333                                         cerr << owner()->name() << " SS = " << start_sample << " PS = " << playback_sample << " REVERSE" << endl;
334                                         abort ();
335                                 }
336                         }
337
338                         if ((speed > 0) && (start_sample != playback_sample)) {
339                                 cerr << owner()->name() << " playback not aligned, jump ahead " << (start_sample - playback_sample) << endl;
340
341                                 if (can_internal_playback_seek (start_sample - playback_sample)) {
342                                         internal_playback_seek (start_sample - playback_sample);
343                                 } else {
344                                         cerr << owner()->name() << " playback not possible: ss = " << start_sample << " ps = " << playback_sample << endl;
345                                         goto midi;
346                                 }
347                         }
348
349                         chaninfo->buf->get_read_vector (&(*chan)->rw_vector);
350
351                         if (disk_samples_to_consume <= (samplecnt_t) chaninfo->rw_vector.len[0]) {
352
353                                 if (fabsf (speed) != 1.0f) {
354                                         samplecnt_t ocnt = nframes;
355                                         samplecnt_t icnt = chaninfo->rw_vector.len[0];
356                                         (void) interpolation.interpolate (n, icnt, chaninfo->rw_vector.buf[0], ocnt, disk_signal);
357                                 } else if (speed != 0.0) {
358                                         memcpy (disk_signal, chaninfo->rw_vector.buf[0], sizeof (Sample) * disk_samples_to_consume);
359                                 }
360
361                         } else {
362
363                                 const samplecnt_t total = chaninfo->rw_vector.len[0] + chaninfo->rw_vector.len[1];
364
365                                 if (disk_samples_to_consume <= total) {
366
367                                         if (fabsf (speed) != 1.0f) {
368                                                 samplecnt_t ocnt = nframes;
369                                                 samplecnt_t icnt = interpolation.interpolate (n, chaninfo->rw_vector.len[0], chaninfo->rw_vector.buf[0], ocnt, disk_signal);
370
371                                                 if (ocnt < nframes) {
372                                                         disk_signal += ocnt;
373                                                         ocnt = nframes - ocnt;
374                                                         icnt = interpolation.interpolate (n, chaninfo->rw_vector.len[1], chaninfo->rw_vector.buf[1], ocnt, disk_signal);
375                                                 }
376
377                                         } else if (speed != 0.0) {
378
379                                                 memcpy (disk_signal,
380                                                         chaninfo->rw_vector.buf[0],
381                                                         chaninfo->rw_vector.len[0] * sizeof (Sample));
382                                                 memcpy (disk_signal + chaninfo->rw_vector.len[0],
383                                                         chaninfo->rw_vector.buf[1],
384                                                         (disk_samples_to_consume - chaninfo->rw_vector.len[0]) * sizeof (Sample));
385                                         }
386
387                                 } else {
388
389                                         cerr << _name << " Need " << disk_samples_to_consume << " total = " << total << endl;
390                                         cerr << "underrun for " << _name << endl;
391                                         DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 underrun in %2, total space = %3\n",
392                                                                                     DEBUG_THREAD_SELF, name(), total));
393                                         Underrun ();
394                                         return;
395
396                                 }
397                         }
398
399                         if (scaling != 1.0f && speed != 0.0) {
400                                 apply_gain_to_buffer (disk_signal, disk_samples_to_consume, scaling);
401                         }
402
403                         chaninfo->buf->increment_read_ptr (disk_samples_to_consume);
404
405                   monitor_mix:
406
407                         if (ms & MonitoringInput) {
408                                 /* mix the disk signal into the input signal (already in bufs) */
409                                 mix_buffers_no_gain (output.data(), disk_signal, disk_samples_to_consume);
410                         }
411                 }
412         }
413
414         /* MIDI data handling */
415
416   midi:
417         if (!_session.declick_out_pending() && bufs.count().n_midi()) {
418                 MidiBuffer* dst;
419
420                 if (_no_disk_output) {
421                         dst = &scratch_bufs.get_midi(0);
422                 } else {
423                         dst = &bufs.get_midi (0);
424                 }
425
426                 if ((ms & MonitoringDisk) && !still_locating) {
427                         get_midi_playback (*dst, start_sample, end_sample, ms, scratch_bufs, speed, disk_samples_to_consume);
428                 }
429         }
430
431         if (!still_locating) {
432
433                 bool butler_required = false;
434
435                 if (speed < 0.0) {
436                         playback_sample -= disk_samples_to_consume;
437                 } else {
438                         playback_sample += disk_samples_to_consume;
439                 }
440
441                 if (_playlists[DataType::AUDIO]) {
442                         if (!c->empty()) {
443                                 if (_slaved) {
444                                         if (c->front()->buf->write_space() >= c->front()->buf->bufsize() / 2) {
445                                                 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1: slaved, write space = %2 of %3\n", name(), c->front()->buf->write_space(),
446                                                                                             c->front()->buf->bufsize()));
447                                                 butler_required = true;
448                                         }
449                                 } else {
450                                         if ((samplecnt_t) c->front()->buf->write_space() >= _chunk_samples) {
451                                                 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1: write space = %2 of %3\n", name(), c->front()->buf->write_space(),
452                                                                                             _chunk_samples));
453                                                 butler_required = true;
454                                         }
455                                 }
456                         }
457                 }
458
459                 if (_playlists[DataType::MIDI]) {
460                         /* MIDI butler needed part */
461
462                         uint32_t samples_read = g_atomic_int_get(const_cast<gint*>(&_samples_read_from_ringbuffer));
463                         uint32_t samples_written = g_atomic_int_get(const_cast<gint*>(&_samples_written_to_ringbuffer));
464
465                         /*
466                           cerr << name() << " MDS written: " << samples_written << " - read: " << samples_read <<
467                           " = " << samples_written - samples_read
468                           << " + " << disk_samples_to_consume << " < " << midi_readahead << " = " << need_butler << ")" << endl;
469                         */
470
471                         /* samples_read will generally be less than samples_written, but
472                          * immediately after an overwrite, we can end up having read some data
473                          * before we've written any. we don't need to trip an assert() on this,
474                          * but we do need to check so that the decision on whether or not we
475                          * need the butler is done correctly.
476                          */
477
478                         /* furthermore..
479                          *
480                          * Doing heavy GUI operations[1] can stall also the butler.
481                          * The RT-thread meanwhile will happily continue and
482                          * â€˜samples_read’ (from buffer to output) will become larger
483                          * than â€˜samples_written’ (from disk to buffer).
484                          *
485                          * The disk-stream is now behind..
486                          *
487                          * In those cases the butler needs to be summed to refill the buffer (done now)
488                          * AND we need to skip (samples_read - samples_written). ie remove old events
489                          * before playback_sample from the rinbuffer.
490                          *
491                          * [1] one way to do so is described at #6170.
492                          * For me just popping up the context-menu on a MIDI-track header
493                          * of a track with a large (think beethoven :) midi-region also did the
494                          * trick. The playhead stalls for 2 or 3 sec, until the context-menu shows.
495                          *
496                          * In both cases the root cause is that redrawing MIDI regions on the GUI is still very slow
497                          * and can stall
498                          */
499                         if (samples_read <= samples_written) {
500                                 if ((samples_written - samples_read) + disk_samples_to_consume < midi_readahead) {
501                                         butler_required = true;
502                                 }
503                         } else {
504                                 butler_required = true;
505                         }
506
507                 }
508
509                 _need_butler = butler_required;
510         }
511
512         // DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 reader run, needs butler = %2\n", name(), _need_butler));
513 }
514
515 void
516 DiskReader::set_pending_overwrite (bool yn)
517 {
518         /* called from audio thread, so we can use the read ptr and playback sample as we wish */
519
520         _pending_overwrite = yn;
521
522         overwrite_sample = playback_sample;
523
524         boost::shared_ptr<ChannelList> c = channels.reader ();
525         if (!c->empty ()) {
526                 overwrite_offset = c->front()->buf->get_read_ptr();
527         }
528 }
529
530 int
531 DiskReader::overwrite_existing_buffers ()
532 {
533         int ret = -1;
534
535         boost::shared_ptr<ChannelList> c = channels.reader();
536
537         overwrite_queued = false;
538
539         DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1 overwriting existing buffers at %2\n", overwrite_sample));
540
541         if (!c->empty ()) {
542
543                 /* AUDIO */
544
545                 const bool reversed = _session.transport_speed() < 0.0f;
546
547                 /* assume all are the same size */
548                 samplecnt_t size = c->front()->buf->bufsize();
549
550                 boost::scoped_ptr<Sample> mixdown_buffer (new Sample[size]);
551                 boost::scoped_ptr<float> gain_buffer (new float[size]);
552
553                 /* reduce size so that we can fill the buffer correctly (ringbuffers
554                    can only handle size-1, otherwise they appear to be empty)
555                 */
556                 size--;
557
558                 uint32_t n=0;
559                 samplepos_t start;
560
561                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
562
563                         start = overwrite_sample;
564                         samplecnt_t cnt = size;
565
566                         /* to fill the buffer without resetting the playback sample, we need to
567                            do it one or two chunks (normally two).
568
569                            |----------------------------------------------------------------------|
570
571                            ^
572                            overwrite_offset
573                            |<- second chunk->||<----------------- first chunk ------------------>|
574
575                         */
576
577                         samplecnt_t to_read = size - overwrite_offset;
578
579                         if (audio_read ((*chan)->buf->buffer() + overwrite_offset, mixdown_buffer.get(), gain_buffer.get(), start, to_read, n, reversed)) {
580                                 error << string_compose(_("DiskReader %1: when refilling, cannot read %2 from playlist at sample %3"),
581                                                         id(), size, playback_sample) << endmsg;
582                                 goto midi;
583                         }
584
585                         if (cnt > to_read) {
586
587                                 cnt -= to_read;
588
589                                 if (audio_read ((*chan)->buf->buffer(), mixdown_buffer.get(), gain_buffer.get(), start, cnt, n, reversed)) {
590                                         error << string_compose(_("DiskReader %1: when refilling, cannot read %2 from playlist at sample %3"),
591                                                                 id(), size, playback_sample) << endmsg;
592                                         goto midi;
593                                 }
594                         }
595                 }
596
597                 ret = 0;
598
599         }
600
601   midi:
602
603         if (_midi_buf && _playlists[DataType::MIDI]) {
604
605                 /* Clear the playback buffer contents.  This is safe as long as the butler
606                    thread is suspended, which it should be.
607                 */
608                 _midi_buf->reset ();
609                 _midi_buf->reset_tracker ();
610
611                 g_atomic_int_set (&_samples_read_from_ringbuffer, 0);
612                 g_atomic_int_set (&_samples_written_to_ringbuffer, 0);
613
614                 /* Resolve all currently active notes in the playlist.  This is more
615                    aggressive than it needs to be: ideally we would only resolve what is
616                    absolutely necessary, but this seems difficult and/or impossible without
617                    having the old data or knowing what change caused the overwrite.
618                 */
619                 midi_playlist()->resolve_note_trackers (*_midi_buf, overwrite_sample);
620
621                 midi_read (overwrite_sample, _chunk_samples, false);
622                 file_sample[DataType::MIDI] = overwrite_sample; // overwrite_sample was adjusted by ::midi_read() to the new position
623         }
624
625         _pending_overwrite = false;
626
627         return ret;
628 }
629
630 int
631 DiskReader::seek (samplepos_t sample, bool complete_refill)
632 {
633         uint32_t n;
634         int ret = -1;
635         ChannelList::iterator chan;
636         boost::shared_ptr<ChannelList> c = channels.reader();
637
638         //sample = std::max ((samplecnt_t)0, sample -_session.worst_output_latency ());
639
640         for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
641                 (*chan)->buf->reset ();
642         }
643
644         if (g_atomic_int_get (&_samples_read_from_ringbuffer) == 0) {
645                 /* we haven't read anything since the last seek,
646                    so flush all note trackers to prevent
647                    wierdness
648                 */
649                 reset_tracker ();
650         }
651
652         _midi_buf->reset();
653         g_atomic_int_set(&_samples_read_from_ringbuffer, 0);
654         g_atomic_int_set(&_samples_written_to_ringbuffer, 0);
655
656         playback_sample = sample;
657         file_sample[DataType::AUDIO] = sample;
658         file_sample[DataType::MIDI] = sample;
659
660         if (complete_refill) {
661                 /* call _do_refill() to refill the entire buffer, using
662                    the largest reads possible.
663                 */
664                 while ((ret = do_refill_with_alloc (false)) > 0) ;
665         } else {
666                 /* call _do_refill() to refill just one chunk, and then
667                    return.
668                 */
669                 ret = do_refill_with_alloc (true);
670         }
671
672
673         return ret;
674 }
675
676 int
677 DiskReader::can_internal_playback_seek (samplecnt_t distance)
678 {
679         /* 1. Audio */
680
681         ChannelList::iterator chan;
682         boost::shared_ptr<ChannelList> c = channels.reader();
683
684         for (chan = c->begin(); chan != c->end(); ++chan) {
685                 if ((*chan)->buf->read_space() < (size_t) distance) {
686                         return false;
687                 }
688         }
689
690         /* 2. MIDI */
691
692         uint32_t samples_read    = g_atomic_int_get(&_samples_read_from_ringbuffer);
693         uint32_t samples_written = g_atomic_int_get(&_samples_written_to_ringbuffer);
694
695         return ((samples_written - samples_read) < distance);
696 }
697
698 int
699 DiskReader::internal_playback_seek (samplecnt_t distance)
700 {
701         ChannelList::iterator chan;
702         boost::shared_ptr<ChannelList> c = channels.reader();
703
704         for (chan = c->begin(); chan != c->end(); ++chan) {
705                 (*chan)->buf->increment_read_ptr (::llabs(distance));
706         }
707
708         playback_sample += distance;
709
710         return 0;
711 }
712
713 static
714 void swap_by_ptr (Sample *first, Sample *last)
715 {
716         while (first < last) {
717                 Sample tmp = *first;
718                 *first++ = *last;
719                 *last-- = tmp;
720         }
721 }
722
723 /** Read some data for 1 channel from our playlist into a buffer.
724  *  @param buf Buffer to write to.
725  *  @param start Session sample to start reading from; updated to where we end up
726  *         after the read.
727  *  @param cnt Count of samples to read.
728  *  @param reversed true if we are running backwards, otherwise false.
729  */
730 int
731 DiskReader::audio_read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer,
732                         samplepos_t& start, samplecnt_t cnt,
733                         int channel, bool reversed)
734 {
735         samplecnt_t this_read = 0;
736         bool reloop = false;
737         samplepos_t loop_end = 0;
738         samplepos_t loop_start = 0;
739         samplecnt_t offset = 0;
740         Location *loc = 0;
741
742         if (!_playlists[DataType::AUDIO]) {
743                 memset (buf, 0, sizeof (Sample) * cnt);
744                 return 0;
745         }
746
747         /* XXX we don't currently play loops in reverse. not sure why */
748
749         if (!reversed) {
750
751                 samplecnt_t loop_length = 0;
752
753                 /* Make the use of a Location atomic for this read operation.
754
755                    Note: Locations don't get deleted, so all we care about
756                    when I say "atomic" is that we are always pointing to
757                    the same one and using a start/length values obtained
758                    just once.
759                 */
760
761                 if ((loc = loop_location) != 0) {
762                         loop_start = loc->start();
763                         loop_end = loc->end();
764                         loop_length = loop_end - loop_start;
765                 }
766
767                 /* if we are looping, ensure that the first sample we read is at the correct
768                    position within the loop.
769                 */
770
771                 if (loc && start >= loop_end) {
772                         start = loop_start + ((start - loop_start) % loop_length);
773                 }
774
775         }
776
777         if (reversed) {
778                 start -= cnt;
779         }
780
781         /* We need this while loop in case we hit a loop boundary, in which case our read from
782            the playlist must be split into more than one section.
783         */
784
785         while (cnt) {
786
787                 /* take any loop into account. we can't read past the end of the loop. */
788
789                 if (loc && (loop_end - start < cnt)) {
790                         this_read = loop_end - start;
791                         reloop = true;
792                 } else {
793                         reloop = false;
794                         this_read = cnt;
795                 }
796
797                 if (this_read == 0) {
798                         break;
799                 }
800
801                 this_read = min(cnt,this_read);
802
803                 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
804                         error << string_compose(_("DiskReader %1: cannot read %2 from playlist at sample %3"), id(), this_read,
805                                          start) << endmsg;
806                         return -1;
807                 }
808
809                 if (reversed) {
810
811                         swap_by_ptr (buf, buf + this_read - 1);
812
813                 } else {
814
815                         /* if we read to the end of the loop, go back to the beginning */
816
817                         if (reloop) {
818                                 start = loop_start;
819                         } else {
820                                 start += this_read;
821                         }
822                 }
823
824                 cnt -= this_read;
825                 offset += this_read;
826         }
827
828         return 0;
829 }
830
831 int
832 DiskReader::_do_refill_with_alloc (bool partial_fill)
833 {
834         /* We limit disk reads to at most 4MB chunks, which with floating point
835            samples would be 1M samples. But we might use 16 or 14 bit samples,
836            in which case 4MB is more samples than that. Therefore size this for
837            the smallest sample value .. 4MB = 2M samples (16 bit).
838         */
839
840         {
841                 boost::scoped_ptr<Sample> mix_buf (new Sample[2*1048576]);
842                 boost::scoped_ptr<float>  gain_buf (new float[2*1048576]);
843
844                 int ret = refill_audio (mix_buf.get(), gain_buf.get(), (partial_fill ? _chunk_samples : 0));
845
846                 if (ret) {
847                         return ret;
848                 }
849         }
850
851         return refill_midi ();
852 }
853
854 int
855 DiskReader::refill (Sample* mixdown_buffer, float* gain_buffer, samplecnt_t fill_level)
856 {
857         int ret = refill_audio (mixdown_buffer, gain_buffer, fill_level);
858
859         if (ret) {
860                 return ret;
861         }
862
863         return refill_midi ();
864 }
865
866
867 /** Get some more data from disk and put it in our channels' bufs,
868  *  if there is suitable space in them.
869  *
870  * If fill_level is non-zero, then we will refill the buffer so that there is
871  * still at least fill_level samples of space left to be filled. This is used
872  * after locates so that we do not need to wait to fill the entire buffer.
873  *
874  */
875
876 int
877 DiskReader::refill_audio (Sample* mixdown_buffer, float* gain_buffer, samplecnt_t fill_level)
878 {
879         /* do not read from disk while session is marked as Loading, to avoid
880            useless redundant I/O.
881         */
882
883         if (_session.loading()) {
884                 return 0;
885         }
886
887         int32_t ret = 0;
888         samplecnt_t to_read;
889         RingBufferNPT<Sample>::rw_vector vector;
890         bool const reversed = _session.transport_speed() < 0.0f;
891         samplecnt_t total_space;
892         samplecnt_t zero_fill;
893         uint32_t chan_n;
894         ChannelList::iterator i;
895         boost::shared_ptr<ChannelList> c = channels.reader();
896         samplecnt_t ts;
897
898         if (c->empty()) {
899                 return 0;
900         }
901
902         assert(mixdown_buffer);
903         assert(gain_buffer);
904
905         vector.buf[0] = 0;
906         vector.len[0] = 0;
907         vector.buf[1] = 0;
908         vector.len[1] = 0;
909
910         c->front()->buf->get_write_vector (&vector);
911
912         if ((total_space = vector.len[0] + vector.len[1]) == 0) {
913                 DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1: no space to refill\n", name()));
914                 /* nowhere to write to */
915                 return 0;
916         }
917
918         if (fill_level) {
919                 if (fill_level < total_space) {
920                         total_space -= fill_level;
921                 } else {
922                         /* we can't do anything with it */
923                         fill_level = 0;
924                 }
925         }
926
927         /* if we're running close to normal speed and there isn't enough
928            space to do disk_read_chunk_samples of I/O, then don't bother.
929
930            at higher speeds, just do it because the sync between butler
931            and audio thread may not be good enough.
932
933            Note: it is a design assumption that disk_read_chunk_samples is smaller
934            than the playback buffer size, so this check should never trip when
935            the playback buffer is empty.
936         */
937
938         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()));
939         if ((total_space < _chunk_samples) && fabs (_session.transport_speed()) < 2.0f) {
940                 return 0;
941         }
942
943         /* when slaved, don't try to get too close to the read pointer. this
944            leaves space for the buffer reversal to have something useful to
945            work with.
946         */
947
948         if (_slaved && total_space < (samplecnt_t) (c->front()->buf->bufsize() / 2)) {
949                 DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1: not enough to refill while slaved\n", this));
950                 return 0;
951         }
952
953         samplepos_t ffa = file_sample[DataType::AUDIO];
954
955         if (reversed) {
956
957                 if (ffa == 0) {
958
959                         /* at start: nothing to do but fill with silence */
960
961                         for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
962
963                                 ChannelInfo* chan (*i);
964                                 chan->buf->get_write_vector (&vector);
965                                 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
966                                 if (vector.len[1]) {
967                                         memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
968                                 }
969                                 chan->buf->increment_write_ptr (vector.len[0] + vector.len[1]);
970                         }
971                         return 0;
972                 }
973
974                 if (ffa < total_space) {
975
976                         /* too close to the start: read what we can,
977                            and then zero fill the rest
978                         */
979
980                         zero_fill = total_space - ffa;
981                         total_space = ffa;
982
983                 } else {
984
985                         zero_fill = 0;
986                 }
987
988         } else {
989
990                 if (ffa == max_samplepos) {
991
992                         /* at end: nothing to do but fill with silence */
993
994                         for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
995
996                                 ChannelInfo* chan (*i);
997                                 chan->buf->get_write_vector (&vector);
998                                 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
999                                 if (vector.len[1]) {
1000                                         memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1001                                 }
1002                                 chan->buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1003                         }
1004                         return 0;
1005                 }
1006
1007                 if (ffa > max_samplepos - total_space) {
1008
1009                         /* to close to the end: read what we can, and zero fill the rest */
1010
1011                         zero_fill = total_space - (max_samplepos - ffa);
1012                         total_space = max_samplepos - ffa;
1013
1014                 } else {
1015                         zero_fill = 0;
1016                 }
1017         }
1018
1019         samplepos_t file_sample_tmp = 0;
1020
1021         /* total_space is in samples. We want to optimize read sizes in various sizes using bytes */
1022
1023         const size_t bits_per_sample = format_data_width (_session.config.get_native_file_data_format());
1024         size_t total_bytes = total_space * bits_per_sample / 8;
1025
1026         /* chunk size range is 256kB to 4MB. Bigger is faster in terms of MB/sec, but bigger chunk size always takes longer
1027          */
1028         size_t byte_size_for_read = max ((size_t) (256 * 1024), min ((size_t) (4 * 1048576), total_bytes));
1029
1030         /* find nearest (lower) multiple of 16384 */
1031
1032         byte_size_for_read = (byte_size_for_read / 16384) * 16384;
1033
1034         /* now back to samples */
1035
1036         samplecnt_t samples_to_read = byte_size_for_read / (bits_per_sample / 8);
1037
1038         DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1: will refill %2 channels with %3 samples\n", name(), c->size(), total_space));
1039
1040         // uint64_t before = g_get_monotonic_time ();
1041         // uint64_t elapsed;
1042
1043         for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1044
1045                 ChannelInfo* chan (*i);
1046                 Sample* buf1;
1047                 Sample* buf2;
1048                 samplecnt_t len1, len2;
1049
1050                 chan->buf->get_write_vector (&vector);
1051
1052                 if ((samplecnt_t) vector.len[0] > samples_to_read) {
1053
1054                         /* we're not going to fill the first chunk, so certainly do not bother with the
1055                            other part. it won't be connected with the part we do fill, as in:
1056
1057                            .... => writable space
1058                            ++++ => readable space
1059                            ^^^^ => 1 x disk_read_chunk_samples that would be filled
1060
1061                            |......|+++++++++++++|...............................|
1062                            buf1                buf0
1063                                                 ^^^^^^^^^^^^^^^
1064
1065
1066                            So, just pretend that the buf1 part isn't there.
1067
1068                         */
1069
1070                         vector.buf[1] = 0;
1071                         vector.len[1] = 0;
1072
1073                 }
1074
1075                 ts = total_space;
1076                 file_sample_tmp = ffa;
1077
1078                 buf1 = vector.buf[0];
1079                 len1 = vector.len[0];
1080                 buf2 = vector.buf[1];
1081                 len2 = vector.len[1];
1082
1083                 to_read = min (ts, len1);
1084                 to_read = min (to_read, (samplecnt_t) samples_to_read);
1085
1086                 assert (to_read >= 0);
1087
1088                 if (to_read) {
1089
1090                         if (audio_read (buf1, mixdown_buffer, gain_buffer, file_sample_tmp, to_read, chan_n, reversed)) {
1091                                 ret = -1;
1092                                 goto out;
1093                         }
1094                         chan->buf->increment_write_ptr (to_read);
1095                         ts -= to_read;
1096                 }
1097
1098                 to_read = min (ts, len2);
1099
1100                 if (to_read) {
1101
1102                         /* we read all of vector.len[0], but it wasn't the
1103                            entire samples_to_read of data, so read some or
1104                            all of vector.len[1] as well.
1105                         */
1106
1107                         if (audio_read (buf2, mixdown_buffer, gain_buffer, file_sample_tmp, to_read, chan_n, reversed)) {
1108                                 ret = -1;
1109                                 goto out;
1110                         }
1111
1112                         chan->buf->increment_write_ptr (to_read);
1113                 }
1114
1115                 if (zero_fill) {
1116                         /* XXX: do something */
1117                 }
1118
1119         }
1120
1121         // elapsed = g_get_monotonic_time () - before;
1122         // cerr << '\t' << name() << ": bandwidth = " << (byte_size_for_read / 1048576.0) / (elapsed/1000000.0) << "MB/sec\n";
1123
1124         file_sample[DataType::AUDIO] = file_sample_tmp;
1125         assert (file_sample[DataType::AUDIO] >= 0);
1126
1127         ret = ((total_space - samples_to_read) > _chunk_samples);
1128
1129         c->front()->buf->get_write_vector (&vector);
1130
1131   out:
1132         return ret;
1133 }
1134
1135 void
1136 DiskReader::playlist_ranges_moved (list< Evoral::RangeMove<samplepos_t> > const & movements_samples, bool from_undo)
1137 {
1138         /* If we're coming from an undo, it will have handled
1139            automation undo (it must, since automation-follows-regions
1140            can lose automation data).  Hence we can do nothing here.
1141         */
1142
1143         if (from_undo) {
1144                 return;
1145         }
1146
1147         if (!_route || Config->get_automation_follows_regions () == false) {
1148                 return;
1149         }
1150
1151         list< Evoral::RangeMove<double> > movements;
1152
1153         for (list< Evoral::RangeMove<samplepos_t> >::const_iterator i = movements_samples.begin();
1154              i != movements_samples.end();
1155              ++i) {
1156
1157                 movements.push_back(Evoral::RangeMove<double>(i->from, i->length, i->to));
1158         }
1159
1160         /* move panner automation */
1161         boost::shared_ptr<Pannable> pannable = _route->pannable();
1162         Evoral::ControlSet::Controls& c (pannable->controls());
1163
1164         for (Evoral::ControlSet::Controls::iterator ci = c.begin(); ci != c.end(); ++ci) {
1165                 boost::shared_ptr<AutomationControl> ac = boost::dynamic_pointer_cast<AutomationControl>(ci->second);
1166                 if (!ac) {
1167                         continue;
1168                 }
1169                 boost::shared_ptr<AutomationList> alist = ac->alist();
1170                 if (!alist->size()) {
1171                         continue;
1172                 }
1173                 XMLNode & before = alist->get_state ();
1174                 bool const things_moved = alist->move_ranges (movements);
1175                 if (things_moved) {
1176                         _session.add_command (new MementoCommand<AutomationList> (
1177                                                       *alist.get(), &before, &alist->get_state ()));
1178                 }
1179         }
1180         /* move processor automation */
1181         _route->foreach_processor (boost::bind (&DiskReader::move_processor_automation, this, _1, movements_samples));
1182 }
1183
1184 void
1185 DiskReader::move_processor_automation (boost::weak_ptr<Processor> p, list< Evoral::RangeMove<samplepos_t> > const & movements_samples)
1186 {
1187         boost::shared_ptr<Processor> processor (p.lock ());
1188         if (!processor) {
1189                 return;
1190         }
1191
1192         list< Evoral::RangeMove<double> > movements;
1193         for (list< Evoral::RangeMove<samplepos_t> >::const_iterator i = movements_samples.begin(); i != movements_samples.end(); ++i) {
1194                 movements.push_back(Evoral::RangeMove<double>(i->from, i->length, i->to));
1195         }
1196
1197         set<Evoral::Parameter> const a = processor->what_can_be_automated ();
1198
1199         for (set<Evoral::Parameter>::const_iterator i = a.begin (); i != a.end (); ++i) {
1200                 boost::shared_ptr<AutomationList> al = processor->automation_control(*i)->alist();
1201                 if (!al->size()) {
1202                         continue;
1203                 }
1204                 XMLNode & before = al->get_state ();
1205                 bool const things_moved = al->move_ranges (movements);
1206                 if (things_moved) {
1207                         _session.add_command (
1208                                 new MementoCommand<AutomationList> (
1209                                         *al.get(), &before, &al->get_state ()
1210                                         )
1211                                 );
1212                 }
1213         }
1214 }
1215
1216 void
1217 DiskReader::reset_tracker ()
1218 {
1219         _midi_buf->reset_tracker ();
1220
1221         boost::shared_ptr<MidiPlaylist> mp (midi_playlist());
1222
1223         if (mp) {
1224                 mp->reset_note_trackers ();
1225         }
1226 }
1227
1228 void
1229 DiskReader::resolve_tracker (Evoral::EventSink<samplepos_t>& buffer, samplepos_t time)
1230 {
1231         _midi_buf->resolve_tracker(buffer, time);
1232
1233         boost::shared_ptr<MidiPlaylist> mp (midi_playlist());
1234
1235         if (mp) {
1236                 mp->reset_note_trackers ();
1237         }
1238 }
1239
1240 /** Writes playback events from playback_sample for nframes to dst, translating time stamps
1241  *  so that an event at playback_sample has time = 0
1242  */
1243 void
1244 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)
1245 {
1246         MidiBuffer* target;
1247         samplepos_t nframes = end_sample - start_sample;
1248
1249         if ((ms & MonitoringInput) == 0) {
1250                 /* Route::process_output_buffers() clears the buffer as-needed */
1251                 target = &dst;
1252         } else {
1253                 target = &scratch_bufs.get_midi (0);
1254         }
1255
1256         if (ms & MonitoringDisk) {
1257                 /* disk data needed */
1258
1259                 Location* loc = loop_location;
1260
1261                 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose (
1262                                      "%1 MDS pre-read read %8 offset = %9 @ %4..%5 from %2 write to %3, LOOPED ? %6 .. %7\n", _name,
1263                                      _midi_buf->get_read_ptr(), _midi_buf->get_write_ptr(), start_sample, end_sample,
1264                                      (loc ? loc->start() : -1), (loc ? loc->end() : -1), nframes, Port::port_offset()));
1265
1266                 //cerr << "======== PRE ========\n";
1267                 //_midi_buf->dump (cerr);
1268                 //cerr << "----------------\n";
1269
1270                 size_t events_read = 0;
1271
1272                 if (loc) {
1273                         samplepos_t effective_start;
1274
1275                         Evoral::Range<samplepos_t> loop_range (loc->start(), loc->end() - 1);
1276                         effective_start = loop_range.squish (start_sample);
1277
1278                         DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("looped, effective start adjusted to %1\n", effective_start));
1279
1280                         if (effective_start == loc->start()) {
1281                                 /* We need to turn off notes that may extend
1282                                    beyond the loop end.
1283                                 */
1284
1285                                 _midi_buf->resolve_tracker (*target, 0);
1286                         }
1287
1288                         /* for split-cycles we need to offset the events */
1289
1290                         if (loc->end() >= effective_start && loc->end() < effective_start + nframes) {
1291
1292                                 /* end of loop is within the range we are reading, so
1293                                    split the read in two, and lie about the location
1294                                    for the 2nd read
1295                                 */
1296
1297                                 samplecnt_t first, second;
1298
1299                                 first = loc->end() - effective_start;
1300                                 second = nframes - first;
1301
1302                                 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read for eff %1 end %2: %3 and %4, cycle offset %5\n",
1303                                                                                       effective_start, loc->end(), first, second));
1304
1305                                 if (first) {
1306                                         DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read #1, from %1 for %2\n",
1307                                                                                               effective_start, first));
1308                                         events_read = _midi_buf->read (*target, effective_start, first);
1309                                 }
1310
1311                                 if (second) {
1312                                         DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read #2, from %1 for %2\n",
1313                                                                                               loc->start(), second));
1314                                         events_read += _midi_buf->read (*target, loc->start(), second);
1315                                 }
1316
1317                         } else {
1318                                 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read #3, adjusted start as %1 for %2\n",
1319                                                                                       effective_start, nframes));
1320                                 events_read = _midi_buf->read (*target, effective_start, effective_start + nframes);
1321                         }
1322                 } else {
1323                         const size_t n_skipped = _midi_buf->skip_to (start_sample);
1324                         if (n_skipped > 0) {
1325                                 warning << string_compose(_("MidiDiskstream %1: skipped %2 events, possible underflow"), id(), n_skipped) << endmsg;
1326                         }
1327                         DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("playback buffer read, from %1 to %2 (%3)", start_sample, end_sample, nframes));
1328                         events_read = _midi_buf->read (*target, start_sample, end_sample, Port::port_offset ());
1329                 }
1330
1331                 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose (
1332                                      "%1 MDS events read %2 range %3 .. %4 rspace %5 wspace %6 r@%7 w@%8\n",
1333                                      _name, events_read, playback_sample, playback_sample + nframes,
1334                                      _midi_buf->read_space(), _midi_buf->write_space(),
1335                                      _midi_buf->get_read_ptr(), _midi_buf->get_write_ptr()));
1336         }
1337
1338         g_atomic_int_add (&_samples_read_from_ringbuffer, nframes);
1339
1340         /* vari-speed */
1341         if (speed != 0.0 && fabsf (speed) != 1.0f) {
1342                 for (MidiBuffer::iterator i = target->begin(); i != target->end(); ++i) {
1343                         MidiBuffer::TimeType *tme = i.timeptr();
1344                         // XXX need to subtract port offsets before scaling
1345                         // also we must only scale events read from disk
1346                         // and not existing input data in the buffer.
1347                         *tme = (*tme) * nframes / disk_samples_to_consume;
1348                 }
1349         }
1350
1351         if (ms & MonitoringInput) {
1352                 dst.merge_from (*target, nframes);
1353         }
1354
1355 #if 0
1356         if (!target->empty ()) {
1357                 cerr << "======== MIDI OUT ========\n";
1358                 for (MidiBuffer::iterator i = target->begin(); i != target->end(); ++i) {
1359                         const Evoral::Event<MidiBuffer::TimeType> ev (*i, false);
1360                         cerr << "MIDI EVENT (from disk) @ " << ev.time();
1361                         for (size_t xx = 0; xx < ev.size(); ++xx) {
1362                                 cerr << ' ' << hex << (int) ev.buffer()[xx];
1363                         }
1364                         cerr << dec << endl;
1365                 }
1366                 cerr << "----------------\n";
1367         }
1368 #endif
1369 #if 0
1370         cerr << "======== MIDI Disk Buffer ========\n";
1371         _midi_buf->dump (cerr);
1372         cerr << "----------------\n";
1373 #endif
1374 }
1375
1376 /** @a start is set to the new sample position (TIME) read up to */
1377 int
1378 DiskReader::midi_read (samplepos_t& start, samplecnt_t dur, bool reversed)
1379 {
1380         samplecnt_t this_read   = 0;
1381         samplepos_t loop_end    = 0;
1382         samplepos_t loop_start  = 0;
1383         samplecnt_t loop_length = 0;
1384         Location*  loc         = loop_location;
1385         samplepos_t effective_start = start;
1386         Evoral::Range<samplepos_t>*  loop_range (0);
1387
1388         DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("MDS::midi_read @ %1 cnt %2\n", start, dur));
1389
1390         boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack>(_route);
1391         MidiChannelFilter* filter = mt ? &mt->playback_filter() : 0;
1392         sampleoffset_t loop_offset = 0;
1393
1394         if (!reversed && loc) {
1395                 get_location_times (loc, &loop_start, &loop_end, &loop_length);
1396         }
1397
1398         while (dur) {
1399
1400                 /* take any loop into account. we can't read past the end of the loop. */
1401
1402                 if (loc && !reversed) {
1403
1404                         if (!loop_range) {
1405                                 loop_range = new Evoral::Range<samplepos_t> (loop_start, loop_end-1); // inclusive semantics require -1
1406                         }
1407
1408                         /* if we are (seamlessly) looping, ensure that the first sample we read is at the correct
1409                            position within the loop.
1410                         */
1411
1412                         effective_start = loop_range->squish (effective_start);
1413
1414                         if ((loop_end - effective_start) <= dur) {
1415                                 /* too close to end of loop to read "dur", so
1416                                    shorten it.
1417                                 */
1418                                 this_read = loop_end - effective_start;
1419                         } else {
1420                                 this_read = dur;
1421                         }
1422
1423                 } else {
1424                         this_read = dur;
1425                 }
1426
1427                 if (this_read == 0) {
1428                         break;
1429                 }
1430
1431                 this_read = min (dur,this_read);
1432
1433                 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("MDS ::read at %1 for %2 loffset %3\n", effective_start, this_read, loop_offset));
1434
1435                 if (midi_playlist()->read (*_midi_buf, effective_start, this_read, loop_range, 0, filter) != this_read) {
1436                         error << string_compose(
1437                                         _("MidiDiskstream %1: cannot read %2 from playlist at sample %3"),
1438                                         id(), this_read, start) << endmsg;
1439                         return -1;
1440                 }
1441
1442                 g_atomic_int_add (&_samples_written_to_ringbuffer, this_read);
1443
1444                 if (reversed) {
1445
1446                         // Swap note ons with note offs here.  etc?
1447                         // Fully reversing MIDI requires look-ahead (well, behind) to find previous
1448                         // CC values etc.  hard.
1449
1450                 } else {
1451
1452                         /* adjust passed-by-reference argument (note: this is
1453                            monotonic and does not reflect looping.
1454                         */
1455                         start += this_read;
1456
1457                         /* similarly adjust effective_start, but this may be
1458                            readjusted for seamless looping as we continue around
1459                            the loop.
1460                         */
1461                         effective_start += this_read;
1462                 }
1463
1464                 dur -= this_read;
1465         }
1466
1467         return 0;
1468 }
1469
1470 int
1471 DiskReader::refill_midi ()
1472 {
1473         if (!_playlists[DataType::MIDI]) {
1474                 return 0;
1475         }
1476
1477         const size_t  write_space = _midi_buf->write_space();
1478         const bool reversed    = _session.transport_speed() < 0.0f;
1479
1480         DEBUG_TRACE (DEBUG::DiskIO, string_compose ("MIDI refill, write space = %1 file sample = %2\n", write_space, file_sample[DataType::MIDI]));
1481
1482         /* no space to write */
1483         if (write_space == 0) {
1484                 return 0;
1485         }
1486
1487         if (reversed) {
1488                 return 0;
1489         }
1490
1491         /* at end: nothing to do */
1492
1493         samplepos_t ffm = file_sample[DataType::MIDI];
1494
1495         if (ffm == max_samplepos) {
1496                 return 0;
1497         }
1498
1499         int ret = 0;
1500         const uint32_t samples_read = g_atomic_int_get (&_samples_read_from_ringbuffer);
1501         const uint32_t samples_written = g_atomic_int_get (&_samples_written_to_ringbuffer);
1502
1503         if ((samples_read < samples_written) && (samples_written - samples_read) >= midi_readahead) {
1504                 return 0;
1505         }
1506
1507         samplecnt_t to_read = midi_readahead - ((samplecnt_t)samples_written - (samplecnt_t)samples_read);
1508
1509         to_read = min (to_read, (samplecnt_t) (max_samplepos - ffm));
1510         to_read = min (to_read, (samplecnt_t) write_space);
1511
1512         if (midi_read (ffm, to_read, reversed)) {
1513                 ret = -1;
1514         }
1515
1516         file_sample[DataType::MIDI] = ffm;
1517
1518         return ret;
1519 }
1520
1521 void
1522 DiskReader::set_no_disk_output (bool yn)
1523 {
1524         /* this MUST be called as part of the process call tree, before any
1525            disk readers are invoked. We use it when the session needs the
1526            transport (and thus effective read position for DiskReaders) to keep
1527            advancing as part of syncing up with a transport master, but we
1528            don't want any actual disk output yet because we are still not
1529            synced.
1530         */
1531         _no_disk_output = yn;
1532 }