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