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