move need-butler from DiskReader to DiskIOProcessor
[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/playlist.h"
32 #include "ardour/playlist_factory.h"
33 #include "ardour/session.h"
34 #include "ardour/session_playlists.h"
35
36 using namespace ARDOUR;
37 using namespace PBD;
38 using namespace std;
39
40 ARDOUR::framecnt_t DiskReader::_chunk_frames = default_chunk_frames ();
41
42 DiskReader::DiskReader (Session& s, string const & str, DiskIOProcessor::Flag f)
43         : DiskIOProcessor (s, str, f)
44         , _roll_delay (0)
45         , loop_location (0)
46         , overwrite_frame (0)
47         , overwrite_offset (0)
48         , _pending_overwrite (false)
49         , overwrite_queued (false)
50         , file_frame (0)
51         , playback_sample (0)
52         , _monitoring_choice (MonitorDisk)
53         , _gui_feed_buffer (AudioEngine::instance()->raw_buffer_size (DataType::MIDI))
54         , _frames_written_to_ringbuffer (0)
55         , _frames_read_from_ringbuffer (0)
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 int
135 DiskReader::set_state (const XMLNode& node, int version)
136 {
137         XMLProperty const * prop;
138
139         if (DiskIOProcessor::set_state (node, version)) {
140                 return -1;
141         }
142
143         if ((prop = node.property ("audio-playlist")) == 0) {
144                 return -1;
145         }
146
147         if (find_and_use_playlist (DataType::AUDIO, prop->value())) {
148                 return -1;
149         }
150
151         if ((prop = node.property ("midi-playlist")) == 0) {
152                 return -1;
153         }
154
155         if (find_and_use_playlist (DataType::MIDI, prop->value())) {
156                 return -1;
157         }
158
159         return 0;
160 }
161
162 /* Processor interface */
163
164 bool
165 DiskReader::configure_io (ChanCount in, ChanCount out)
166 {
167         Glib::Threads::Mutex::Lock lm (state_lock);
168
169         RCUWriter<ChannelList> writer (channels);
170         boost::shared_ptr<ChannelList> c = writer.get_copy();
171
172         uint32_t n_audio = in.n_audio();
173
174         if (n_audio > c->size()) {
175                 add_channel_to (c, n_audio - c->size());
176         } else if (n_audio < c->size()) {
177                 remove_channel_from (c, c->size() - n_audio);
178         }
179
180         if (in.n_midi() > 0 && !_midi_buf) {
181                 const size_t size = _session.butler()->midi_diskstream_buffer_size();
182                 _midi_buf = new MidiRingBuffer<framepos_t>(size);
183                 midi_interpolation.add_channel_to (0,0);
184         }
185
186         Processor::configure_io (in, out);
187
188         return true;
189 }
190
191 bool
192 DiskReader::can_support_io_configuration (const ChanCount& in, ChanCount& out)
193 {
194         if (in.n_midi() != 0 && in.n_midi() != 1) {
195                 /* we only support zero or 1 MIDI stream */
196                 return false;
197         }
198
199         if (in != out) {
200                 /* currently no way to deliver different channels that we receive */
201                 return false;
202         }
203
204         return true;
205 }
206
207 void
208 DiskReader::realtime_handle_transport_stopped ()
209 {
210 }
211
212 void
213 DiskReader::realtime_locate ()
214 {
215 }
216
217 int
218 DiskReader::set_loop (Location *location)
219 {
220         if (location) {
221                 if (location->start() >= location->end()) {
222                         error << string_compose(_("Location \"%1\" not valid for track loop (start >= end)"), location->name()) << endl;
223                         return -1;
224                 }
225         }
226
227         loop_location = location;
228
229         LoopSet (location); /* EMIT SIGNAL */
230         return 0;
231 }
232
233 float
234 DiskReader::buffer_load () const
235 {
236         /* Note: for MIDI it's not trivial to differentiate the following two cases:
237
238            1.  The playback buffer is empty because the system has run out of time to fill it.
239            2.  The playback buffer is empty because there is no more data on the playlist.
240
241            If we use a simple buffer load computation, we will report that the MIDI diskstream
242            cannot keep up when #2 happens, when in fact it can.  Since MIDI data rates
243            are so low compared to audio, just use the audio value here.
244         */
245
246         boost::shared_ptr<ChannelList> c = channels.reader();
247
248         if (c->empty ()) {
249                 /* no channels, so no buffers, so completely full and ready to playback, sir! */
250                 return 1.0;
251         }
252
253         PBD::RingBufferNPT<Sample> * b = c->front()->buf;
254         return (float) ((double) b->read_space() / (double) b->bufsize());
255 }
256
257 void
258 DiskReader::adjust_buffering ()
259 {
260         boost::shared_ptr<ChannelList> c = channels.reader();
261
262         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
263                 (*chan)->resize (_session.butler()->audio_diskstream_playback_buffer_size());
264         }
265 }
266
267 DiskReader::ChannelInfo::ChannelInfo (framecnt_t bufsize, framecnt_t speed_size, framecnt_t wrap_size)
268 {
269         current_buffer = 0;
270
271         speed_buffer = new Sample[speed_size];
272         wrap_buffer = new Sample[wrap_size];
273
274         buf = new RingBufferNPT<Sample> (bufsize);
275
276         /* touch the ringbuffer buffer, which will cause
277            them to be mapped into locked physical RAM if
278            we're running with mlockall(). this doesn't do
279            much if we're not.
280         */
281
282         memset (buf->buffer(), 0, sizeof (Sample) * buf->bufsize());
283 }
284
285 void
286 DiskReader::ChannelInfo::resize (framecnt_t bufsize)
287 {
288         delete buf;
289         buf = new RingBufferNPT<Sample> (bufsize);
290         memset (buf->buffer(), 0, sizeof (Sample) * buf->bufsize());
291 }
292
293 DiskReader::ChannelInfo::~ChannelInfo ()
294 {
295         delete [] speed_buffer;
296         speed_buffer = 0;
297
298         delete [] wrap_buffer;
299         wrap_buffer = 0;
300
301         delete buf;
302         buf = 0;
303 }
304
305 int
306 DiskReader::set_block_size (pframes_t /*nframes*/)
307 {
308         if (_session.get_block_size() > speed_buffer_size) {
309                 speed_buffer_size = _session.get_block_size();
310                 boost::shared_ptr<ChannelList> c = channels.reader();
311
312                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
313                         delete [] (*chan)->speed_buffer;
314                         (*chan)->speed_buffer = new Sample[speed_buffer_size];
315                 }
316         }
317         allocate_temporary_buffers ();
318         return 0;
319 }
320
321 void
322 DiskReader::allocate_temporary_buffers ()
323 {
324         /* make sure the wrap buffer is at least large enough to deal
325            with the speeds up to 1.2, to allow for micro-variation
326            when slaving to MTC, Timecode etc.
327         */
328
329         double const sp = max (fabs (_actual_speed), 1.2);
330         framecnt_t required_wrap_size = (framecnt_t) ceil (_session.get_block_size() * sp) + 2;
331
332         if (required_wrap_size > wrap_buffer_size) {
333
334                 boost::shared_ptr<ChannelList> c = channels.reader();
335
336                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
337                         if ((*chan)->wrap_buffer) {
338                                 delete [] (*chan)->wrap_buffer;
339                         }
340                         (*chan)->wrap_buffer = new Sample[required_wrap_size];
341                 }
342
343                 wrap_buffer_size = required_wrap_size;
344         }
345 }
346
347
348 void
349 DiskReader::playlist_changed (const PropertyChange&)
350 {
351         playlist_modified ();
352 }
353
354 void
355 DiskReader::playlist_modified ()
356 {
357         if (!i_am_the_modifier && !overwrite_queued) {
358                 // !!!! _session.request_overwrite_buffer (this);
359                 overwrite_queued = true;
360         }
361 }
362
363 void
364 DiskReader::playlist_deleted (boost::weak_ptr<Playlist> wpl)
365 {
366         boost::shared_ptr<Playlist> pl (wpl.lock());
367
368         if (!pl) {
369                 return;
370         }
371
372         for (uint32_t n = 0; n < DataType::num_types; ++n) {
373                 if (pl == _playlists[n]) {
374
375                         /* this catches an ordering issue with session destruction. playlists
376                            are destroyed before disk readers. we have to invalidate any handles
377                            we have to the playlist.
378                         */
379                         _playlists[n].reset ();
380                         break;
381                 }
382         }
383 }
384
385 boost::shared_ptr<AudioPlaylist>
386 DiskReader::audio_playlist () const
387 {
388         return boost::dynamic_pointer_cast<AudioPlaylist> (_playlists[DataType::AUDIO]);
389 }
390
391 boost::shared_ptr<MidiPlaylist>
392 DiskReader::midi_playlist () const
393 {
394         return boost::dynamic_pointer_cast<MidiPlaylist> (_playlists[DataType::MIDI]);
395 }
396
397 int
398 DiskReader::use_playlist (DataType dt, boost::shared_ptr<Playlist> playlist)
399 {
400         if (!playlist) {
401                 return 0;
402         }
403
404         bool prior_playlist = false;
405
406         {
407                 Glib::Threads::Mutex::Lock lm (state_lock);
408
409                 if (playlist == _playlists[dt]) {
410                         return 0;
411                 }
412
413                 playlist_connections.drop_connections ();
414
415                 if (_playlists[dt]) {
416                         _playlists[dt]->release();
417                         prior_playlist = true;
418                 }
419
420                 _playlists[dt] = playlist;
421                 playlist->use();
422
423                 playlist->ContentsChanged.connect_same_thread (playlist_connections, boost::bind (&DiskReader::playlist_modified, this));
424                 playlist->LayeringChanged.connect_same_thread (playlist_connections, boost::bind (&DiskReader::playlist_modified, this));
425                 playlist->DropReferences.connect_same_thread (playlist_connections, boost::bind (&DiskReader::playlist_deleted, this, boost::weak_ptr<Playlist>(playlist)));
426                 playlist->RangesMoved.connect_same_thread (playlist_connections, boost::bind (&DiskReader::playlist_ranges_moved, this, _1, _2));
427         }
428
429         /* don't do this if we've already asked for it *or* if we are setting up
430            the diskstream for the very first time - the input changed handling will
431            take care of the buffer refill.
432         */
433
434         if (!overwrite_queued && prior_playlist) {
435                 // !!! _session.request_overwrite_buffer (this);
436                 overwrite_queued = true;
437         }
438
439         PlaylistChanged (dt); /* EMIT SIGNAL */
440         _session.set_dirty ();
441
442         return 0;
443 }
444
445 int
446 DiskReader::find_and_use_playlist (DataType dt, const string& name)
447 {
448         boost::shared_ptr<Playlist> playlist;
449
450         if ((playlist = _session.playlists->by_name (name)) == 0) {
451                 playlist = PlaylistFactory::create (dt, _session, name);
452         }
453
454         if (!playlist) {
455                 error << string_compose(_("DiskReader: \"%1\" isn't an playlist"), name) << endmsg;
456                 return -1;
457         }
458
459         return use_playlist (dt, playlist);
460 }
461
462 int
463 DiskReader::use_new_playlist (DataType dt)
464 {
465         string newname;
466         boost::shared_ptr<Playlist> playlist = _playlists[dt];
467
468         if (playlist) {
469                 newname = Playlist::bump_name (playlist->name(), _session);
470         } else {
471                 newname = Playlist::bump_name (_name, _session);
472         }
473
474         playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (dt, _session, newname, hidden()));
475
476         if (!playlist) {
477                 return -1;
478         }
479
480         return use_playlist (dt, playlist);
481 }
482
483 int
484 DiskReader::use_copy_playlist (DataType dt)
485 {
486         assert (_playlists[dt]);
487
488         if (_playlists[dt] == 0) {
489                 error << string_compose(_("DiskReader %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
490                 return -1;
491         }
492
493         string newname;
494         boost::shared_ptr<Playlist> playlist;
495
496         newname = Playlist::bump_name (_playlists[dt]->name(), _session);
497
498         if ((playlist = PlaylistFactory::create (_playlists[dt], newname)) == 0) {
499                 return -1;
500         }
501
502         playlist->reset_shares();
503
504         return use_playlist (dt, playlist);
505 }
506
507
508 /** Do some record stuff [not described in this comment!]
509  *
510  *  Also:
511  *    - Setup playback_distance with the nframes, or nframes adjusted
512  *      for current varispeed, if appropriate.
513  *    - Setup current_buffer in each ChannelInfo to point to data
514  *      that someone can read playback_distance worth of data from.
515  */
516 void
517 DiskReader::run (BufferSet& bufs, framepos_t start_frame, framepos_t end_frame,
518                  double speed, pframes_t nframes, bool result_required)
519 {
520         uint32_t n;
521         boost::shared_ptr<ChannelList> c = channels.reader();
522         ChannelList::iterator chan;
523         framecnt_t playback_distance = 0;
524
525         Glib::Threads::Mutex::Lock sm (state_lock, Glib::Threads::TRY_LOCK);
526
527         if (!sm.locked()) {
528                 return;
529         }
530
531         for (chan = c->begin(); chan != c->end(); ++chan) {
532                 (*chan)->current_buffer = 0;
533         }
534
535         const bool need_disk_signal = result_required || _monitoring_choice == MonitorDisk || _monitoring_choice == MonitorCue;
536
537         if (need_disk_signal) {
538
539                 /* we're doing playback */
540
541                 framecnt_t necessary_samples;
542
543                 if (_actual_speed != 1.0) {
544                         necessary_samples = (framecnt_t) ceil ((nframes * fabs (_actual_speed))) + 2;
545                 } else {
546                         necessary_samples = nframes;
547                 }
548
549                 for (chan = c->begin(); chan != c->end(); ++chan) {
550                         (*chan)->buf->get_read_vector (&(*chan)->read_vector);
551                 }
552
553                 n = 0;
554
555                 /* Setup current_buffer in each ChannelInfo to point to data that someone
556                    can read necessary_samples (== nframes at a transport speed of 1) worth of data
557                    from right now.
558                 */
559
560                 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
561
562                         ChannelInfo* chaninfo (*chan);
563
564                         if (necessary_samples <= (framecnt_t) chaninfo->read_vector.len[0]) {
565                                 /* There are enough samples in the first part of the ringbuffer */
566                                 chaninfo->current_buffer = chaninfo->read_vector.buf[0];
567
568                         } else {
569                                 framecnt_t total = chaninfo->read_vector.len[0] + chaninfo->read_vector.len[1];
570
571                                 if (necessary_samples > total) {
572                                         cerr << _name << " Need " << necessary_samples << " total = " << total << endl;
573                                         cerr << "underrun for " << _name << endl;
574                                         DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 underrun in %2, total space = %3\n",
575                                                                                     DEBUG_THREAD_SELF, name(), total));
576                                         Underrun ();
577                                         return;
578
579                                 } else {
580
581                                         /* We have enough samples, but not in one lump.  Coalesce the two parts
582                                            into one in wrap_buffer in our ChannelInfo, and specify that
583                                            as our current_buffer.
584                                         */
585
586                                         assert(wrap_buffer_size >= necessary_samples);
587
588                                         /* Copy buf[0] from buf */
589                                         memcpy ((char *) chaninfo->wrap_buffer,
590                                                         chaninfo->read_vector.buf[0],
591                                                         chaninfo->read_vector.len[0] * sizeof (Sample));
592
593                                         /* Copy buf[1] from buf */
594                                         memcpy (chaninfo->wrap_buffer + chaninfo->read_vector.len[0],
595                                                         chaninfo->read_vector.buf[1],
596                                                         (necessary_samples - chaninfo->read_vector.len[0])
597                                                                         * sizeof (Sample));
598
599                                         chaninfo->current_buffer = chaninfo->wrap_buffer;
600                                 }
601                         }
602                 }
603
604                 if (_actual_speed != 1.0f && _actual_speed != -1.0f) {
605
606                         interpolation.set_speed (_target_speed);
607
608                         int channel = 0;
609                         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++channel) {
610                                 ChannelInfo* chaninfo (*chan);
611
612                                 playback_distance = interpolation.interpolate (
613                                         channel, nframes, chaninfo->current_buffer, chaninfo->speed_buffer);
614
615                                 chaninfo->current_buffer = chaninfo->speed_buffer;
616                         }
617
618                 } else {
619                         playback_distance = nframes;
620                 }
621
622                 _speed = _target_speed;
623         }
624
625         if (need_disk_signal) {
626
627                 /* copy data over to buffer set */
628
629                 size_t n_buffers = bufs.count().n_audio();
630                 size_t n_chans = c->size();
631                 gain_t scaling = 1.0f;
632
633                 if (n_chans > n_buffers) {
634                         scaling = ((float) n_buffers)/n_chans;
635                 }
636
637                 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
638
639                         AudioBuffer& buf (bufs.get_audio (n%n_buffers));
640                         ChannelInfo* chaninfo (*chan);
641
642                         if (n < n_chans) {
643                                 if (scaling != 1.0f) {
644                                         buf.read_from_with_gain (chaninfo->current_buffer, nframes, scaling);
645                                 } else {
646                                         buf.read_from (chaninfo->current_buffer, nframes);
647                                 }
648                         } else {
649                                 if (scaling != 1.0f) {
650                                         buf.accumulate_with_gain_from (chaninfo->current_buffer, nframes, scaling);
651                                 } else {
652                                         buf.accumulate_from (chaninfo->current_buffer, nframes);
653                                 }
654                         }
655                 }
656
657                 /* extra buffers will already be silent, so leave them alone */
658         }
659
660         _need_butler = false;
661
662         if (_actual_speed < 0.0) {
663                 playback_sample -= playback_distance;
664         } else {
665                 playback_sample += playback_distance;
666         }
667
668         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
669                 (*chan)->buf->increment_read_ptr (playback_distance);
670         }
671
672         if (!c->empty()) {
673                 if (_slaved) {
674                         if (c->front()->buf->write_space() >= c->front()->buf->bufsize() / 2) {
675                                 _need_butler = true;
676                         }
677                 } else {
678                         if ((framecnt_t) c->front()->buf->write_space() >= _chunk_frames) {
679                                 _need_butler = true;
680                         }
681                 }
682         }
683
684         /* MIDI data handling */
685
686         if (_actual_speed != 1.0f && _target_speed > 0) {
687
688                 interpolation.set_speed (_target_speed);
689
690                 playback_distance = midi_interpolation.distance  (nframes);
691
692         } else {
693                 playback_distance = nframes;
694         }
695
696         if (need_disk_signal && !_session.declick_out_pending()) {
697
698                 /* copy the diskstream data to all output buffers */
699
700                 MidiBuffer& mbuf (bufs.get_midi (0));
701                 get_playback (mbuf, playback_distance);
702
703                 /* leave the audio count alone */
704                 ChanCount cnt (DataType::MIDI, 1);
705                 cnt.set (DataType::AUDIO, bufs.count().n_audio());
706                 bufs.set_count (cnt);
707
708                 /* vari-speed */
709                 if (_target_speed > 0 && _actual_speed != 1.0f) {
710                         MidiBuffer& mbuf (bufs.get_midi (0));
711                         for (MidiBuffer::iterator i = mbuf.begin(); i != mbuf.end(); ++i) {
712                                 MidiBuffer::TimeType *tme = i.timeptr();
713                                 *tme = (*tme) * nframes / playback_distance;
714                         }
715                 }
716         }
717
718         /* MIDI butler needed part */
719
720         uint32_t frames_read = g_atomic_int_get(const_cast<gint*>(&_frames_read_from_ringbuffer));
721         uint32_t frames_written = g_atomic_int_get(const_cast<gint*>(&_frames_written_to_ringbuffer));
722
723         /*
724           cerr << name() << " MDS written: " << frames_written << " - read: " << frames_read <<
725           " = " << frames_written - frames_read
726           << " + " << playback_distance << " < " << midi_readahead << " = " << need_butler << ")" << endl;
727         */
728
729         /* frames_read will generally be less than frames_written, but
730          * immediately after an overwrite, we can end up having read some data
731          * before we've written any. we don't need to trip an assert() on this,
732          * but we do need to check so that the decision on whether or not we
733          * need the butler is done correctly.
734          */
735
736         /* furthermore..
737          *
738          * Doing heavy GUI operations[1] can stall also the butler.
739          * The RT-thread meanwhile will happily continue and
740          * â€˜frames_read’ (from buffer to output) will become larger
741          * than â€˜frames_written’ (from disk to buffer).
742          *
743          * The disk-stream is now behind..
744          *
745          * In those cases the butler needs to be summed to refill the buffer (done now)
746          * AND we need to skip (frames_read - frames_written). ie remove old events
747          * before playback_sample from the rinbuffer.
748          *
749          * [1] one way to do so is described at #6170.
750          * For me just popping up the context-menu on a MIDI-track header
751          * of a track with a large (think beethoven :) midi-region also did the
752          * trick. The playhead stalls for 2 or 3 sec, until the context-menu shows.
753          *
754          * In both cases the root cause is that redrawing MIDI regions on the GUI is still very slow
755          * and can stall
756          */
757         if (frames_read <= frames_written) {
758                 if ((frames_written - frames_read) + playback_distance < midi_readahead) {
759                         _need_butler = true;
760                 }
761         } else {
762                 _need_butler = true;
763         }
764
765         /* make sure bufs shows whatever data we had available */
766
767         ChanCount cnt;
768         cnt.set (DataType::MIDI, 1);
769         cnt.set (DataType::AUDIO, bufs.count().n_audio());
770         bufs.set_count (cnt);
771 }
772
773 frameoffset_t
774 DiskReader::calculate_playback_distance (pframes_t nframes)
775 {
776         frameoffset_t playback_distance = nframes;
777
778         if (_actual_speed != 1.0f && _actual_speed != -1.0f) {
779                 interpolation.set_speed (_target_speed);
780                 boost::shared_ptr<ChannelList> c = channels.reader();
781                 int channel = 0;
782                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++channel) {
783                         playback_distance = interpolation.interpolate (channel, nframes, NULL, NULL);
784                 }
785         } else {
786                 playback_distance = nframes;
787         }
788
789         if (_actual_speed < 0.0) {
790                 return -playback_distance;
791         } else {
792                 return playback_distance;
793         }
794 }
795
796 void
797 DiskReader::set_pending_overwrite (bool yn)
798 {
799         /* called from audio thread, so we can use the read ptr and playback sample as we wish */
800
801         _pending_overwrite = yn;
802
803         overwrite_frame = playback_sample;
804
805         boost::shared_ptr<ChannelList> c = channels.reader ();
806         if (!c->empty ()) {
807                 overwrite_offset = c->front()->buf->get_read_ptr();
808         }
809 }
810
811 int
812 DiskReader::overwrite_existing_buffers ()
813 {
814         int ret = -1;
815
816         boost::shared_ptr<ChannelList> c = channels.reader();
817
818         overwrite_queued = false;
819
820         if (!c->empty ()) {
821
822                 /* AUDIO */
823
824                 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
825
826                 /* assume all are the same size */
827                 framecnt_t size = c->front()->buf->bufsize();
828
829                 std::auto_ptr<Sample> mixdown_buffer (new Sample[size]);
830                 std::auto_ptr<float> gain_buffer (new float[size]);
831
832                 /* reduce size so that we can fill the buffer correctly (ringbuffers
833                    can only handle size-1, otherwise they appear to be empty)
834                 */
835                 size--;
836
837                 uint32_t n=0;
838                 framepos_t start;
839
840                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
841
842                         start = overwrite_frame;
843                         framecnt_t cnt = size;
844
845                         /* to fill the buffer without resetting the playback sample, we need to
846                            do it one or two chunks (normally two).
847
848                            |----------------------------------------------------------------------|
849
850                            ^
851                            overwrite_offset
852                            |<- second chunk->||<----------------- first chunk ------------------>|
853
854                         */
855
856                         framecnt_t to_read = size - overwrite_offset;
857
858                         if (audio_read ((*chan)->buf->buffer() + overwrite_offset, mixdown_buffer.get(), gain_buffer.get(), start, to_read, n, reversed)) {
859                                 error << string_compose(_("DiskReader %1: when refilling, cannot read %2 from playlist at frame %3"),
860                                                         id(), size, playback_sample) << endmsg;
861                                 goto midi;
862                         }
863
864                         if (cnt > to_read) {
865
866                                 cnt -= to_read;
867
868                                 if (audio_read ((*chan)->buf->buffer(), mixdown_buffer.get(), gain_buffer.get(), start, cnt, n, reversed)) {
869                                         error << string_compose(_("DiskReader %1: when refilling, cannot read %2 from playlist at frame %3"),
870                                                                 id(), size, playback_sample) << endmsg;
871                                         goto midi;
872                                 }
873                         }
874                 }
875
876                 ret = 0;
877
878         }
879
880   midi:
881
882         if (_midi_buf && _playlists[DataType::MIDI]) {
883
884                 /* Clear the playback buffer contents.  This is safe as long as the butler
885                    thread is suspended, which it should be.
886                 */
887                 _midi_buf->reset ();
888                 _midi_buf->reset_tracker ();
889
890                 g_atomic_int_set (&_frames_read_from_ringbuffer, 0);
891                 g_atomic_int_set (&_frames_written_to_ringbuffer, 0);
892
893                 /* Resolve all currently active notes in the playlist.  This is more
894                    aggressive than it needs to be: ideally we would only resolve what is
895                    absolutely necessary, but this seems difficult and/or impossible without
896                    having the old data or knowing what change caused the overwrite.
897                 */
898                 midi_playlist()->resolve_note_trackers (*_midi_buf, overwrite_frame);
899
900                 midi_read (overwrite_frame, _chunk_frames, false);
901
902                 file_frame = overwrite_frame; // it was adjusted by ::midi_read()
903         }
904
905         _pending_overwrite = false;
906
907         return ret;
908 }
909
910 void
911 DiskReader::non_realtime_locate (framepos_t location)
912 {
913         /* now refill channel buffers */
914
915         if (speed() != 1.0f || speed() != -1.0f) {
916                 seek ((framepos_t) (location * (double) speed()), true);
917         } else {
918                 seek (location, true);
919         }
920 }
921
922 int
923 DiskReader::seek (framepos_t frame, bool complete_refill)
924 {
925         uint32_t n;
926         int ret = -1;
927         ChannelList::iterator chan;
928         boost::shared_ptr<ChannelList> c = channels.reader();
929
930         Glib::Threads::Mutex::Lock lm (state_lock);
931
932         for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
933                 (*chan)->buf->reset ();
934         }
935
936         if (g_atomic_int_get (&_frames_read_from_ringbuffer) == 0) {
937                 /* we haven't read anything since the last seek,
938                    so flush all note trackers to prevent
939                    wierdness
940                 */
941                 reset_tracker ();
942         }
943
944         _midi_buf->reset();
945         g_atomic_int_set(&_frames_read_from_ringbuffer, 0);
946         g_atomic_int_set(&_frames_written_to_ringbuffer, 0);
947
948         playback_sample = frame;
949         file_frame = frame;
950
951         if (complete_refill) {
952                 /* call _do_refill() to refill the entire buffer, using
953                    the largest reads possible.
954                 */
955                 while ((ret = do_refill_with_alloc (false)) > 0) ;
956         } else {
957                 /* call _do_refill() to refill just one chunk, and then
958                    return.
959                 */
960                 ret = do_refill_with_alloc (true);
961         }
962
963
964         return ret;
965 }
966
967 int
968 DiskReader::can_internal_playback_seek (framecnt_t distance)
969 {
970         /* 1. Audio */
971
972         ChannelList::iterator chan;
973         boost::shared_ptr<ChannelList> c = channels.reader();
974
975         for (chan = c->begin(); chan != c->end(); ++chan) {
976                 if ((*chan)->buf->read_space() < (size_t) distance) {
977                         return false;
978                 }
979         }
980
981         /* 2. MIDI */
982
983         uint32_t frames_read    = g_atomic_int_get(&_frames_read_from_ringbuffer);
984         uint32_t frames_written = g_atomic_int_get(&_frames_written_to_ringbuffer);
985
986         return ((frames_written - frames_read) < distance);
987 }
988
989 int
990 DiskReader::internal_playback_seek (framecnt_t distance)
991 {
992         ChannelList::iterator chan;
993         boost::shared_ptr<ChannelList> c = channels.reader();
994
995         for (chan = c->begin(); chan != c->end(); ++chan) {
996                 (*chan)->buf->increment_read_ptr (::llabs(distance));
997         }
998
999         playback_sample += distance;
1000
1001         return 0;
1002 }
1003
1004 static
1005 void swap_by_ptr (Sample *first, Sample *last)
1006 {
1007         while (first < last) {
1008                 Sample tmp = *first;
1009                 *first++ = *last;
1010                 *last-- = tmp;
1011         }
1012 }
1013
1014 /** Read some data for 1 channel from our playlist into a buffer.
1015  *  @param buf Buffer to write to.
1016  *  @param start Session frame to start reading from; updated to where we end up
1017  *         after the read.
1018  *  @param cnt Count of samples to read.
1019  *  @param reversed true if we are running backwards, otherwise false.
1020  */
1021 int
1022 DiskReader::audio_read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer,
1023                         framepos_t& start, framecnt_t cnt,
1024                         int channel, bool reversed)
1025 {
1026         framecnt_t this_read = 0;
1027         bool reloop = false;
1028         framepos_t loop_end = 0;
1029         framepos_t loop_start = 0;
1030         framecnt_t offset = 0;
1031         Location *loc = 0;
1032
1033         /* XXX we don't currently play loops in reverse. not sure why */
1034
1035         if (!reversed) {
1036
1037                 framecnt_t loop_length = 0;
1038
1039                 /* Make the use of a Location atomic for this read operation.
1040
1041                    Note: Locations don't get deleted, so all we care about
1042                    when I say "atomic" is that we are always pointing to
1043                    the same one and using a start/length values obtained
1044                    just once.
1045                 */
1046
1047                 if ((loc = loop_location) != 0) {
1048                         loop_start = loc->start();
1049                         loop_end = loc->end();
1050                         loop_length = loop_end - loop_start;
1051                 }
1052
1053                 /* if we are looping, ensure that the first frame we read is at the correct
1054                    position within the loop.
1055                 */
1056
1057                 if (loc && start >= loop_end) {
1058                         start = loop_start + ((start - loop_start) % loop_length);
1059                 }
1060
1061         }
1062
1063         if (reversed) {
1064                 start -= cnt;
1065         }
1066
1067         /* We need this while loop in case we hit a loop boundary, in which case our read from
1068            the playlist must be split into more than one section.
1069         */
1070
1071         while (cnt) {
1072
1073                 /* take any loop into account. we can't read past the end of the loop. */
1074
1075                 if (loc && (loop_end - start < cnt)) {
1076                         this_read = loop_end - start;
1077                         reloop = true;
1078                 } else {
1079                         reloop = false;
1080                         this_read = cnt;
1081                 }
1082
1083                 if (this_read == 0) {
1084                         break;
1085                 }
1086
1087                 this_read = min(cnt,this_read);
1088
1089                 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
1090                         error << string_compose(_("DiskReader %1: cannot read %2 from playlist at frame %3"), id(), this_read,
1091                                          start) << endmsg;
1092                         return -1;
1093                 }
1094
1095                 if (reversed) {
1096
1097                         swap_by_ptr (buf, buf + this_read - 1);
1098
1099                 } else {
1100
1101                         /* if we read to the end of the loop, go back to the beginning */
1102
1103                         if (reloop) {
1104                                 start = loop_start;
1105                         } else {
1106                                 start += this_read;
1107                         }
1108                 }
1109
1110                 cnt -= this_read;
1111                 offset += this_read;
1112         }
1113
1114         return 0;
1115 }
1116
1117 int
1118 DiskReader::_do_refill_with_alloc (bool partial_fill)
1119 {
1120         /* We limit disk reads to at most 4MB chunks, which with floating point
1121            samples would be 1M samples. But we might use 16 or 14 bit samples,
1122            in which case 4MB is more samples than that. Therefore size this for
1123            the smallest sample value .. 4MB = 2M samples (16 bit).
1124         */
1125
1126         {
1127                 std::auto_ptr<Sample> mix_buf (new Sample[2*1048576]);
1128                 std::auto_ptr<float>  gain_buf (new float[2*1048576]);
1129
1130                 int ret = refill_audio (mix_buf.get(), gain_buf.get(), (partial_fill ? _chunk_frames : 0));
1131
1132                 if (ret) {
1133                         return ret;
1134                 }
1135         }
1136
1137         return refill_midi ();
1138 }
1139
1140 int
1141 DiskReader::refill (Sample* mixdown_buffer, float* gain_buffer, framecnt_t fill_level)
1142 {
1143         int ret = refill_audio (mixdown_buffer, gain_buffer, fill_level);
1144
1145         if (ret) {
1146                 return ret;
1147         }
1148
1149         return refill_midi ();
1150 }
1151
1152
1153 /** Get some more data from disk and put it in our channels' bufs,
1154  *  if there is suitable space in them.
1155  *
1156  * If fill_level is non-zero, then we will refill the buffer so that there is
1157  * still at least fill_level samples of space left to be filled. This is used
1158  * after locates so that we do not need to wait to fill the entire buffer.
1159  *
1160  */
1161
1162 int
1163 DiskReader::refill_audio (Sample* mixdown_buffer, float* gain_buffer, framecnt_t fill_level)
1164 {
1165         if (_session.state_of_the_state() & Session::Loading) {
1166                 return 0;
1167         }
1168
1169         int32_t ret = 0;
1170         framecnt_t to_read;
1171         RingBufferNPT<Sample>::rw_vector vector;
1172         bool const reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1173         framecnt_t total_space;
1174         framecnt_t zero_fill;
1175         uint32_t chan_n;
1176         ChannelList::iterator i;
1177         boost::shared_ptr<ChannelList> c = channels.reader();
1178         framecnt_t ts;
1179
1180         /* do not read from disk while session is marked as Loading, to avoid
1181            useless redundant I/O.
1182         */
1183
1184         if (c->empty()) {
1185                 return 0;
1186         }
1187
1188         assert(mixdown_buffer);
1189         assert(gain_buffer);
1190
1191         vector.buf[0] = 0;
1192         vector.len[0] = 0;
1193         vector.buf[1] = 0;
1194         vector.len[1] = 0;
1195
1196         c->front()->buf->get_write_vector (&vector);
1197
1198         if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1199                 /* nowhere to write to */
1200                 return 0;
1201         }
1202
1203         if (fill_level) {
1204                 if (fill_level < total_space) {
1205                         total_space -= fill_level;
1206                 } else {
1207                         /* we can't do anything with it */
1208                         fill_level = 0;
1209                 }
1210         }
1211
1212         /* if we're running close to normal speed and there isn't enough
1213            space to do disk_read_chunk_frames of I/O, then don't bother.
1214
1215            at higher speeds, just do it because the sync between butler
1216            and audio thread may not be good enough.
1217
1218            Note: it is a design assumption that disk_read_chunk_frames is smaller
1219            than the playback buffer size, so this check should never trip when
1220            the playback buffer is empty.
1221         */
1222
1223         if ((total_space < _chunk_frames) && fabs (_actual_speed) < 2.0f) {
1224                 return 0;
1225         }
1226
1227         /* when slaved, don't try to get too close to the read pointer. this
1228            leaves space for the buffer reversal to have something useful to
1229            work with.
1230         */
1231
1232         if (_slaved && total_space < (framecnt_t) (c->front()->buf->bufsize() / 2)) {
1233                 return 0;
1234         }
1235
1236         if (reversed) {
1237
1238                 if (file_frame == 0) {
1239
1240                         /* at start: nothing to do but fill with silence */
1241
1242                         for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1243
1244                                 ChannelInfo* chan (*i);
1245                                 chan->buf->get_write_vector (&vector);
1246                                 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1247                                 if (vector.len[1]) {
1248                                         memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1249                                 }
1250                                 chan->buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1251                         }
1252                         return 0;
1253                 }
1254
1255                 if (file_frame < total_space) {
1256
1257                         /* too close to the start: read what we can,
1258                            and then zero fill the rest
1259                         */
1260
1261                         zero_fill = total_space - file_frame;
1262                         total_space = file_frame;
1263
1264                 } else {
1265
1266                         zero_fill = 0;
1267                 }
1268
1269         } else {
1270
1271                 if (file_frame == max_framepos) {
1272
1273                         /* at end: nothing to do but fill with silence */
1274
1275                         for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1276
1277                                 ChannelInfo* chan (*i);
1278                                 chan->buf->get_write_vector (&vector);
1279                                 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1280                                 if (vector.len[1]) {
1281                                         memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1282                                 }
1283                                 chan->buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1284                         }
1285                         return 0;
1286                 }
1287
1288                 if (file_frame > max_framepos - total_space) {
1289
1290                         /* to close to the end: read what we can, and zero fill the rest */
1291
1292                         zero_fill = total_space - (max_framepos - file_frame);
1293                         total_space = max_framepos - file_frame;
1294
1295                 } else {
1296                         zero_fill = 0;
1297                 }
1298         }
1299
1300         framepos_t file_frame_tmp = 0;
1301
1302         /* total_space is in samples. We want to optimize read sizes in various sizes using bytes */
1303
1304         const size_t bits_per_sample = format_data_width (_session.config.get_native_file_data_format());
1305         size_t total_bytes = total_space * bits_per_sample / 8;
1306
1307         /* chunk size range is 256kB to 4MB. Bigger is faster in terms of MB/sec, but bigger chunk size always takes longer
1308          */
1309         size_t byte_size_for_read = max ((size_t) (256 * 1024), min ((size_t) (4 * 1048576), total_bytes));
1310
1311         /* find nearest (lower) multiple of 16384 */
1312
1313         byte_size_for_read = (byte_size_for_read / 16384) * 16384;
1314
1315         /* now back to samples */
1316
1317         framecnt_t samples_to_read = byte_size_for_read / (bits_per_sample / 8);
1318
1319         //cerr << name() << " will read " << byte_size_for_read << " out of total bytes " << total_bytes << " in buffer of "
1320         // << c->front()->buf->bufsize() * bits_per_sample / 8 << " bps = " << bits_per_sample << endl;
1321         // cerr << name () << " read samples = " << samples_to_read << " out of total space " << total_space << " in buffer of " << c->front()->buf->bufsize() << " samples\n";
1322
1323         // uint64_t before = g_get_monotonic_time ();
1324         // uint64_t elapsed;
1325
1326         for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1327
1328                 ChannelInfo* chan (*i);
1329                 Sample* buf1;
1330                 Sample* buf2;
1331                 framecnt_t len1, len2;
1332
1333                 chan->buf->get_write_vector (&vector);
1334
1335                 if ((framecnt_t) vector.len[0] > samples_to_read) {
1336
1337                         /* we're not going to fill the first chunk, so certainly do not bother with the
1338                            other part. it won't be connected with the part we do fill, as in:
1339
1340                            .... => writable space
1341                            ++++ => readable space
1342                            ^^^^ => 1 x disk_read_chunk_frames that would be filled
1343
1344                            |......|+++++++++++++|...............................|
1345                            buf1                buf0
1346                                                 ^^^^^^^^^^^^^^^
1347
1348
1349                            So, just pretend that the buf1 part isn't there.
1350
1351                         */
1352
1353                         vector.buf[1] = 0;
1354                         vector.len[1] = 0;
1355
1356                 }
1357
1358                 ts = total_space;
1359                 file_frame_tmp = file_frame;
1360
1361                 buf1 = vector.buf[0];
1362                 len1 = vector.len[0];
1363                 buf2 = vector.buf[1];
1364                 len2 = vector.len[1];
1365
1366                 to_read = min (ts, len1);
1367                 to_read = min (to_read, (framecnt_t) samples_to_read);
1368
1369                 assert (to_read >= 0);
1370
1371                 if (to_read) {
1372
1373                         if (audio_read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1374                                 ret = -1;
1375                                 goto out;
1376                         }
1377
1378                         chan->buf->increment_write_ptr (to_read);
1379                         ts -= to_read;
1380                 }
1381
1382                 to_read = min (ts, len2);
1383
1384                 if (to_read) {
1385
1386                         /* we read all of vector.len[0], but it wasn't the
1387                            entire samples_to_read of data, so read some or
1388                            all of vector.len[1] as well.
1389                         */
1390
1391                         if (audio_read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1392                                 ret = -1;
1393                                 goto out;
1394                         }
1395
1396                         chan->buf->increment_write_ptr (to_read);
1397                 }
1398
1399                 if (zero_fill) {
1400                         /* XXX: do something */
1401                 }
1402
1403         }
1404
1405         // elapsed = g_get_monotonic_time () - before;
1406         // cerr << "\tbandwidth = " << (byte_size_for_read / 1048576.0) / (elapsed/1000000.0) << "MB/sec\n";
1407
1408         file_frame = file_frame_tmp;
1409         assert (file_frame >= 0);
1410
1411         ret = ((total_space - samples_to_read) > _chunk_frames);
1412
1413         c->front()->buf->get_write_vector (&vector);
1414
1415   out:
1416         return ret;
1417 }
1418
1419 void
1420 DiskReader::playlist_ranges_moved (list< Evoral::RangeMove<framepos_t> > const & movements_frames, bool from_undo)
1421 {
1422         /* If we're coming from an undo, it will have handled
1423            automation undo (it must, since automation-follows-regions
1424            can lose automation data).  Hence we can do nothing here.
1425         */
1426
1427         if (from_undo) {
1428                 return;
1429         }
1430
1431 #if 0
1432         if (!_track || Config->get_automation_follows_regions () == false) {
1433                 return;
1434         }
1435
1436         list< Evoral::RangeMove<double> > movements;
1437
1438         for (list< Evoral::RangeMove<framepos_t> >::const_iterator i = movements_frames.begin();
1439              i != movements_frames.end();
1440              ++i) {
1441
1442                 movements.push_back(Evoral::RangeMove<double>(i->from, i->length, i->to));
1443         }
1444
1445         /* move panner automation */
1446         boost::shared_ptr<Pannable> pannable = _track->pannable();
1447         Evoral::ControlSet::Controls& c (pannable->controls());
1448
1449         for (Evoral::ControlSet::Controls::iterator ci = c.begin(); ci != c.end(); ++ci) {
1450                 boost::shared_ptr<AutomationControl> ac = boost::dynamic_pointer_cast<AutomationControl>(ci->second);
1451                 if (!ac) {
1452                         continue;
1453                 }
1454                 boost::shared_ptr<AutomationList> alist = ac->alist();
1455                 if (!alist->size()) {
1456                         continue;
1457                 }
1458                 XMLNode & before = alist->get_state ();
1459                 bool const things_moved = alist->move_ranges (movements);
1460                 if (things_moved) {
1461                         _session.add_command (new MementoCommand<AutomationList> (
1462                                                       *alist.get(), &before, &alist->get_state ()));
1463                 }
1464         }
1465         /* move processor automation */
1466         _track->foreach_processor (boost::bind (&Diskstream::move_processor_automation, this, _1, movements_frames));
1467 #endif
1468 }
1469
1470 void
1471 DiskReader::move_processor_automation (boost::weak_ptr<Processor> p, list< Evoral::RangeMove<framepos_t> > const & movements_frames)
1472 {
1473         boost::shared_ptr<Processor> processor (p.lock ());
1474         if (!processor) {
1475                 return;
1476         }
1477
1478         list< Evoral::RangeMove<double> > movements;
1479         for (list< Evoral::RangeMove<framepos_t> >::const_iterator i = movements_frames.begin(); i != movements_frames.end(); ++i) {
1480                 movements.push_back(Evoral::RangeMove<double>(i->from, i->length, i->to));
1481         }
1482
1483         set<Evoral::Parameter> const a = processor->what_can_be_automated ();
1484
1485         for (set<Evoral::Parameter>::const_iterator i = a.begin (); i != a.end (); ++i) {
1486                 boost::shared_ptr<AutomationList> al = processor->automation_control(*i)->alist();
1487                 if (!al->size()) {
1488                         continue;
1489                 }
1490                 XMLNode & before = al->get_state ();
1491                 bool const things_moved = al->move_ranges (movements);
1492                 if (things_moved) {
1493                         _session.add_command (
1494                                 new MementoCommand<AutomationList> (
1495                                         *al.get(), &before, &al->get_state ()
1496                                         )
1497                                 );
1498                 }
1499         }
1500 }
1501
1502 boost::shared_ptr<MidiBuffer>
1503 DiskReader::get_gui_feed_buffer () const
1504 {
1505         boost::shared_ptr<MidiBuffer> b (new MidiBuffer (AudioEngine::instance()->raw_buffer_size (DataType::MIDI)));
1506
1507         Glib::Threads::Mutex::Lock lm (_gui_feed_buffer_mutex);
1508         b->copy (_gui_feed_buffer);
1509         return b;
1510 }
1511
1512 void
1513 DiskReader::reset_tracker ()
1514 {
1515         _midi_buf->reset_tracker ();
1516
1517         boost::shared_ptr<MidiPlaylist> mp (midi_playlist());
1518
1519         if (mp) {
1520                 mp->reset_note_trackers ();
1521         }
1522 }
1523
1524 void
1525 DiskReader::resolve_tracker (Evoral::EventSink<framepos_t>& buffer, framepos_t time)
1526 {
1527         _midi_buf->resolve_tracker(buffer, time);
1528
1529         boost::shared_ptr<MidiPlaylist> mp (midi_playlist());
1530
1531         if (mp) {
1532                 mp->reset_note_trackers ();
1533         }
1534 }
1535
1536 void
1537 DiskReader::flush_playback (framepos_t start, framepos_t end)
1538 {
1539         _midi_buf->flush (start, end);
1540         g_atomic_int_add (&_frames_read_from_ringbuffer, end - start);
1541 }
1542
1543 /** Writes playback events from playback_sample for nframes to dst, translating time stamps
1544  *  so that an event at playback_sample has time = 0
1545  */
1546 void
1547 DiskReader::get_playback (MidiBuffer& dst, framecnt_t nframes)
1548 {
1549         dst.clear();
1550
1551         Location* loc = loop_location;
1552
1553         DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose (
1554                              "%1 MDS pre-read read %8 offset = %9 @ %4..%5 from %2 write to %3, LOOPED ? %6 .. %7\n", _name,
1555                              _midi_buf->get_read_ptr(), _midi_buf->get_write_ptr(), playback_sample, playback_sample + nframes,
1556                              (loc ? loc->start() : -1), (loc ? loc->end() : -1), nframes, Port::port_offset()));
1557
1558         //cerr << "======== PRE ========\n";
1559         //_midi_buf->dump (cerr);
1560         //cerr << "----------------\n";
1561
1562         size_t events_read = 0;
1563
1564         if (loc) {
1565                 framepos_t effective_start;
1566
1567                 Evoral::Range<framepos_t> loop_range (loc->start(), loc->end() - 1);
1568                 effective_start = loop_range.squish (playback_sample);
1569
1570                 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("looped, effective start adjusted to %1\n", effective_start));
1571
1572                 if (effective_start == loc->start()) {
1573                         /* We need to turn off notes that may extend
1574                            beyond the loop end.
1575                         */
1576
1577                         _midi_buf->resolve_tracker (dst, 0);
1578                 }
1579
1580                 /* for split-cycles we need to offset the events */
1581
1582                 if (loc->end() >= effective_start && loc->end() < effective_start + nframes) {
1583
1584                         /* end of loop is within the range we are reading, so
1585                            split the read in two, and lie about the location
1586                            for the 2nd read
1587                         */
1588
1589                         framecnt_t first, second;
1590
1591                         first = loc->end() - effective_start;
1592                         second = nframes - first;
1593
1594                         DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read for eff %1 end %2: %3 and %4, cycle offset %5\n",
1595                                                                               effective_start, loc->end(), first, second));
1596
1597                         if (first) {
1598                                 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read #1, from %1 for %2\n",
1599                                                                                       effective_start, first));
1600                                 events_read = _midi_buf->read (dst, effective_start, first);
1601                         }
1602
1603                         if (second) {
1604                                 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read #2, from %1 for %2\n",
1605                                                                                       loc->start(), second));
1606                                 events_read += _midi_buf->read (dst, loc->start(), second);
1607                         }
1608
1609                 } else {
1610                         DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read #3, adjusted start as %1 for %2\n",
1611                                                                               effective_start, nframes));
1612                         events_read = _midi_buf->read (dst, effective_start, effective_start + nframes);
1613                 }
1614         } else {
1615                 const size_t n_skipped = _midi_buf->skip_to (playback_sample);
1616                 if (n_skipped > 0) {
1617                         warning << string_compose(_("MidiDiskstream %1: skipped %2 events, possible underflow"), id(), n_skipped) << endmsg;
1618                 }
1619                 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("playback buffer read, from %1 to %2 (%3)", playback_sample, playback_sample + nframes, nframes));
1620                 events_read = _midi_buf->read (dst, playback_sample, playback_sample + nframes);
1621         }
1622
1623         DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose (
1624                              "%1 MDS events read %2 range %3 .. %4 rspace %5 wspace %6 r@%7 w@%8\n",
1625                              _name, events_read, playback_sample, playback_sample + nframes,
1626                              _midi_buf->read_space(), _midi_buf->write_space(),
1627                              _midi_buf->get_read_ptr(), _midi_buf->get_write_ptr()));
1628
1629         g_atomic_int_add (&_frames_read_from_ringbuffer, nframes);
1630
1631         //cerr << "======== POST ========\n";
1632         //_midi_buf->dump (cerr);
1633         //cerr << "----------------\n";
1634 }
1635
1636 /** Get the start, end, and length of a location "atomically".
1637  *
1638  * Note: Locations don't get deleted, so all we care about when I say "atomic"
1639  * is that we are always pointing to the same one and using start/length values
1640  * obtained just once.  Use this function to achieve this since location being
1641  * a parameter achieves this.
1642  */
1643 static void
1644 get_location_times(const Location* location,
1645                    framepos_t*     start,
1646                    framepos_t*     end,
1647                    framepos_t*     length)
1648 {
1649         if (location) {
1650                 *start  = location->start();
1651                 *end    = location->end();
1652                 *length = *end - *start;
1653         }
1654 }
1655
1656 /** @a start is set to the new frame position (TIME) read up to */
1657 int
1658 DiskReader::midi_read (framepos_t& start, framecnt_t dur, bool reversed)
1659 {
1660         framecnt_t this_read   = 0;
1661         framepos_t loop_end    = 0;
1662         framepos_t loop_start  = 0;
1663         framecnt_t loop_length = 0;
1664         Location*  loc         = loop_location;
1665         framepos_t effective_start = start;
1666         Evoral::Range<framepos_t>*  loop_range (0);
1667
1668 //      MidiTrack*         mt     = dynamic_cast<MidiTrack*>(_track);
1669 //      MidiChannelFilter* filter = mt ? &mt->playback_filter() : 0;
1670         MidiChannelFilter* filter = 0;
1671
1672         frameoffset_t loop_offset = 0;
1673
1674         if (!reversed && loc) {
1675                 get_location_times (loc, &loop_start, &loop_end, &loop_length);
1676         }
1677
1678         while (dur) {
1679
1680                 /* take any loop into account. we can't read past the end of the loop. */
1681
1682                 if (loc && !reversed) {
1683
1684                         if (!loop_range) {
1685                                 loop_range = new Evoral::Range<framepos_t> (loop_start, loop_end-1); // inclusive semantics require -1
1686                         }
1687
1688                         /* if we are (seamlessly) looping, ensure that the first frame we read is at the correct
1689                            position within the loop.
1690                         */
1691
1692                         effective_start = loop_range->squish (effective_start);
1693
1694                         if ((loop_end - effective_start) <= dur) {
1695                                 /* too close to end of loop to read "dur", so
1696                                    shorten it.
1697                                 */
1698                                 this_read = loop_end - effective_start;
1699                         } else {
1700                                 this_read = dur;
1701                         }
1702
1703                 } else {
1704                         this_read = dur;
1705                 }
1706
1707                 if (this_read == 0) {
1708                         break;
1709                 }
1710
1711                 this_read = min (dur,this_read);
1712
1713                 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("MDS ::read at %1 for %2 loffset %3\n", effective_start, this_read, loop_offset));
1714
1715                 if (midi_playlist()->read (*_midi_buf, effective_start, this_read, loop_range, 0, filter) != this_read) {
1716                         error << string_compose(
1717                                         _("MidiDiskstream %1: cannot read %2 from playlist at frame %3"),
1718                                         id(), this_read, start) << endmsg;
1719                         return -1;
1720                 }
1721
1722                 g_atomic_int_add (&_frames_written_to_ringbuffer, this_read);
1723
1724                 if (reversed) {
1725
1726                         // Swap note ons with note offs here.  etc?
1727                         // Fully reversing MIDI requires look-ahead (well, behind) to find previous
1728                         // CC values etc.  hard.
1729
1730                 } else {
1731
1732                         /* adjust passed-by-reference argument (note: this is
1733                            monotonic and does not reflect looping.
1734                         */
1735                         start += this_read;
1736
1737                         /* similarly adjust effective_start, but this may be
1738                            readjusted for seamless looping as we continue around
1739                            the loop.
1740                         */
1741                         effective_start += this_read;
1742                 }
1743
1744                 dur -= this_read;
1745                 //offset += this_read;
1746         }
1747
1748         return 0;
1749 }
1750
1751 int
1752 DiskReader::refill_midi ()
1753 {
1754         int     ret         = 0;
1755         size_t  write_space = _midi_buf->write_space();
1756         bool    reversed    = (_visible_speed * _session.transport_speed()) < 0.0f;
1757
1758         DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("MDS refill, write space = %1 file frame = %2\n",
1759                                                               write_space, file_frame));
1760
1761         /* no space to write */
1762         if (write_space == 0) {
1763                 return 0;
1764         }
1765
1766         if (reversed) {
1767                 return 0;
1768         }
1769
1770         /* at end: nothing to do */
1771         if (file_frame == max_framepos) {
1772                 return 0;
1773         }
1774
1775         uint32_t frames_read = g_atomic_int_get (&_frames_read_from_ringbuffer);
1776         uint32_t frames_written = g_atomic_int_get (&_frames_written_to_ringbuffer);
1777
1778         if ((frames_read < frames_written) && (frames_written - frames_read) >= midi_readahead) {
1779                 return 0;
1780         }
1781
1782         framecnt_t to_read = midi_readahead - ((framecnt_t)frames_written - (framecnt_t)frames_read);
1783
1784         to_read = min (to_read, (framecnt_t) (max_framepos - file_frame));
1785         to_read = min (to_read, (framecnt_t) write_space);
1786
1787         if (midi_read (file_frame, to_read, reversed)) {
1788                 ret = -1;
1789         }
1790
1791         return ret;
1792 }