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