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