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