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