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