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