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