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