more work on the new all-Processor-all-The-Time redesign of Route - LOTS OF BREAKAGE...
[ardour.git] / libs / ardour / midi_diskstream.cc
1 /*
2     Copyright (C) 2000-2003 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 #include <fstream>
20 #include <cstdio>
21 #include <unistd.h>
22 #include <cmath>
23 #include <cerrno>
24 #include <string>
25 #include <climits>
26 #include <fcntl.h>
27 #include <cstdlib>
28 #include <ctime>
29 #include <sys/stat.h>
30 #include <sys/mman.h>
31
32 #include "pbd/error.h"
33 #include "pbd/basename.h"
34 #include <glibmm/thread.h>
35 #include "pbd/xml++.h"
36 #include "pbd/memento_command.h"
37 #include "pbd/enumwriter.h"
38
39 #include "ardour/ardour.h"
40 #include "ardour/audioengine.h"
41 #include "ardour/configuration.h"
42 #include "ardour/cycle_timer.h"
43 #include "ardour/io.h"
44 #include "ardour/midi_diskstream.h"
45 #include "ardour/midi_playlist.h"
46 #include "ardour/midi_port.h"
47 #include "ardour/midi_region.h"
48 #include "ardour/playlist_factory.h"
49 #include "ardour/region_factory.h"
50 #include "ardour/send.h"
51 #include "ardour/session.h"
52 #include "ardour/smf_source.h"
53 #include "ardour/utils.h"
54
55 #include "midi++/types.h"
56
57 #include "i18n.h"
58 #include <locale.h>
59
60 using namespace std;
61 using namespace ARDOUR;
62 using namespace PBD;
63
64 nframes_t MidiDiskstream::midi_readahead = 4096;
65
66 MidiDiskstream::MidiDiskstream (Session &sess, const string &name, Diskstream::Flag flag)
67         : Diskstream(sess, name, flag)
68         , _playback_buf(0)
69         , _capture_buf(0)
70         , _source_port(0)
71         , _last_flush_frame(0)
72         , _note_mode(Sustained)
73         , _frames_written_to_ringbuffer(0)
74         , _frames_read_from_ringbuffer(0)
75 {
76         /* prevent any write sources from being created */
77
78         in_set_state = true;
79
80         init(flag);
81         use_new_playlist ();
82
83         in_set_state = false;
84
85         assert(!destructive());
86 }
87         
88 MidiDiskstream::MidiDiskstream (Session& sess, const XMLNode& node)
89         : Diskstream(sess, node)
90         , _playback_buf(0)
91         , _capture_buf(0)
92         , _source_port(0)
93         , _last_flush_frame(0)
94         , _note_mode(Sustained)
95         , _frames_written_to_ringbuffer(0)
96         , _frames_read_from_ringbuffer(0)
97 {
98         in_set_state = true;
99         init (Recordable);
100
101         if (set_state (node)) {
102                 in_set_state = false;
103                 throw failed_constructor();
104         }
105
106         in_set_state = false;
107
108         if (destructive()) {
109                 use_destructive_playlist ();
110         }
111 }
112
113 void
114 MidiDiskstream::init (Diskstream::Flag f)
115 {
116         Diskstream::init(f);
117
118         /* there are no channels at this point, so these
119            two calls just get speed_buffer_size and wrap_buffer
120            size setup without duplicating their code.
121         */
122
123         set_block_size (_session.get_block_size());
124         allocate_temporary_buffers ();
125
126         const size_t size = _session.midi_diskstream_buffer_size();
127         _playback_buf = new MidiRingBuffer<nframes_t>(size);
128         _capture_buf = new MidiRingBuffer<nframes_t>(size);
129         
130         _n_channels = ChanCount(DataType::MIDI, 1);
131
132         assert(recordable());
133 }
134
135 MidiDiskstream::~MidiDiskstream ()
136 {
137         Glib::Mutex::Lock lm (state_lock);
138 }
139
140         
141 void
142 MidiDiskstream::non_realtime_locate (nframes_t position)
143 {
144         if (_write_source) {
145                 _write_source->set_timeline_position (position);
146         }
147         seek(position, false);
148 }
149
150
151 void
152 MidiDiskstream::non_realtime_input_change ()
153 {
154         { 
155                 Glib::Mutex::Lock lm (state_lock);
156
157                 if (input_change_pending == NoChange) {
158                         return;
159                 }
160
161                 if (input_change_pending & ConfigurationChanged) {
162                         if (_io->n_inputs().n_midi() != _n_channels.n_midi()) {
163                                 error << "Can not feed IO " << _io->n_inputs()
164                                         << " with diskstream " << _n_channels << endl;
165                         }
166                 } 
167
168                 get_input_sources ();
169                 set_capture_offset ();
170
171                 if (first_input_change) {
172                         set_align_style (_persistent_alignment_style);
173                         first_input_change = false;
174                 } else {
175                         set_align_style_from_io ();
176                 }
177
178                 input_change_pending = NoChange;
179                 
180                 /* implicit unlock */
181         }
182
183         /* reset capture files */
184
185         reset_write_sources (false);
186
187         /* now refill channel buffers */
188
189         if (speed() != 1.0f || speed() != -1.0f) {
190                 seek ((nframes_t) (_session.transport_frame() * (double) speed()));
191         }
192         else {
193                 seek (_session.transport_frame());
194         }
195
196         _last_flush_frame = _session.transport_frame();
197 }
198
199 void
200 MidiDiskstream::get_input_sources ()
201 {
202         uint32_t ni = _io->n_inputs().n_midi();
203
204         if (ni == 0) {
205                 return;
206         }
207
208         // This is all we do for now at least
209         assert(ni == 1);
210
211         _source_port = _io->midi_input(0);
212
213         // do... stuff?
214 }               
215
216 int
217 MidiDiskstream::find_and_use_playlist (const string& name)
218 {
219         boost::shared_ptr<MidiPlaylist> playlist;
220                 
221         if ((playlist = boost::dynamic_pointer_cast<MidiPlaylist> (_session.playlist_by_name (name))) == 0) {
222                 playlist = boost::dynamic_pointer_cast<MidiPlaylist> (PlaylistFactory::create (DataType::MIDI, _session, name));
223         }
224
225         if (!playlist) {
226                 error << string_compose(_("MidiDiskstream: Playlist \"%1\" isn't an midi playlist"), name) << endmsg;
227                 return -1;
228         }
229
230         return use_playlist (playlist);
231 }
232
233 int
234 MidiDiskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
235 {       
236         assert(boost::dynamic_pointer_cast<MidiPlaylist>(playlist));
237
238         Diskstream::use_playlist(playlist);
239
240         return 0;
241 }
242
243 int
244 MidiDiskstream::use_new_playlist ()
245 {       
246         string newname;
247         boost::shared_ptr<MidiPlaylist> playlist;
248
249         if (!in_set_state && destructive()) {
250                 return 0;
251         }
252
253         if (_playlist) {
254                 newname = Playlist::bump_name (_playlist->name(), _session);
255         } else {
256                 newname = Playlist::bump_name (_name, _session);
257         }
258
259         if ((playlist = boost::dynamic_pointer_cast<MidiPlaylist> (PlaylistFactory::create (
260                         DataType::MIDI, _session, newname, hidden()))) != 0) {
261                 
262                 playlist->set_orig_diskstream_id (id());
263                 return use_playlist (playlist);
264
265         } else { 
266                 return -1;
267         }
268 }
269
270 int
271 MidiDiskstream::use_copy_playlist ()
272 {
273         assert(midi_playlist());
274
275         if (destructive()) {
276                 return 0;
277         }
278
279         if (_playlist == 0) {
280                 error << string_compose(_("MidiDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
281                 return -1;
282         }
283
284         string newname;
285         boost::shared_ptr<MidiPlaylist> playlist;
286
287         newname = Playlist::bump_name (_playlist->name(), _session);
288         
289         if ((playlist  = boost::dynamic_pointer_cast<MidiPlaylist>(PlaylistFactory::create (midi_playlist(), newname))) != 0) {
290                 playlist->set_orig_diskstream_id (id());
291                 return use_playlist (playlist);
292         } else { 
293                 return -1;
294         }
295 }
296
297 /** Overloaded from parent to die horribly
298  */
299 int
300 MidiDiskstream::set_destructive (bool yn)
301 {
302         assert( ! destructive());
303         assert( ! yn);
304         return -1;
305 }
306         
307 void
308 MidiDiskstream::set_note_mode (NoteMode m)
309 {
310         _note_mode = m;
311         midi_playlist()->set_note_mode(m);
312         if (_write_source && _write_source->model())
313                 _write_source->model()->set_note_mode(m);
314 }
315
316 void
317 MidiDiskstream::check_record_status (nframes_t transport_frame, nframes_t nframes, bool can_record)
318 {
319         // FIXME: waaay too much code to duplicate (AudioDiskstream)
320         
321         int possibly_recording;
322         int rolling;
323         int change;
324         const int transport_rolling = 0x4;
325         const int track_rec_enabled = 0x2;
326         const int global_rec_enabled = 0x1;
327
328         /* merge together the 3 factors that affect record status, and compute
329            what has changed.
330         */
331
332         rolling = _session.transport_speed() != 0.0f;
333         possibly_recording = (rolling << 2) | (record_enabled() << 1) | can_record;
334         change = possibly_recording ^ last_possibly_recording;
335
336         if (possibly_recording == last_possibly_recording) {
337                 return;
338         }
339
340         /* change state */
341
342         /* if per-track or global rec-enable turned on while the other was already on, we've started recording */
343
344         if (((change & track_rec_enabled) && record_enabled() && (!(change & global_rec_enabled) && can_record)) || 
345             ((change & global_rec_enabled) && can_record && (!(change & track_rec_enabled) && record_enabled()))) {
346                 
347                 /* starting to record: compute first+last frames */
348
349                 first_recordable_frame = transport_frame + _capture_offset;
350                 last_recordable_frame = max_frames;
351                 capture_start_frame = transport_frame;
352
353                 if (!(last_possibly_recording & transport_rolling) && (possibly_recording & transport_rolling)) {
354
355                         /* was stopped, now rolling (and recording) */
356
357                         if (_alignment_style == ExistingMaterial) {
358                                 first_recordable_frame += _session.worst_output_latency();
359                         } else {
360                                 first_recordable_frame += _roll_delay;
361                         }
362                 
363                 } else {
364
365                         /* was rolling, but record state changed */
366
367                         if (_alignment_style == ExistingMaterial) {
368
369
370                                 if (!Config->get_punch_in()) {
371
372                                         /* manual punch in happens at the correct transport frame
373                                            because the user hit a button. but to get alignment correct 
374                                            we have to back up the position of the new region to the 
375                                            appropriate spot given the roll delay.
376                                         */
377
378                                         capture_start_frame -= _roll_delay;
379
380                                         /* XXX paul notes (august 2005): i don't know why
381                                            this is needed.
382                                         */
383
384                                         first_recordable_frame += _capture_offset;
385
386                                 } else {
387
388                                         /* autopunch toggles recording at the precise
389                                            transport frame, and then the DS waits
390                                            to start recording for a time that depends
391                                            on the output latency.
392                                         */
393
394                                         first_recordable_frame += _session.worst_output_latency();
395                                 }
396
397                         } else {
398
399                                 if (Config->get_punch_in()) {
400                                         first_recordable_frame += _roll_delay;
401                                 } else {
402                                         capture_start_frame -= _roll_delay;
403                                 }
404                         }
405                         
406                 }
407
408         } else if (!record_enabled() || !can_record) {
409                 
410                 /* stop recording */
411
412                 last_recordable_frame = transport_frame + _capture_offset;
413                 
414                 if (_alignment_style == ExistingMaterial) {
415                         last_recordable_frame += _session.worst_output_latency();
416                 } else {
417                         last_recordable_frame += _roll_delay;
418                 }
419         }
420
421         last_possibly_recording = possibly_recording;
422 }
423
424 static void
425 trace_midi (ostream& o, MIDI::byte *msg, size_t len)
426 {
427         using namespace MIDI;
428         eventType type;
429         const char trace_prefix = ':';
430         
431         type = (eventType) (msg[0]&0xF0);
432
433         switch (type) {
434         case off:
435                 o << trace_prefix
436                    << "Channel "
437                    << (msg[0]&0xF)+1
438                    << " NoteOff NoteNum "
439                    << (int) msg[1]
440                    << " Vel "
441                    << (int) msg[2]
442                    << endl;
443                 break;
444                 
445         case on:
446                 o << trace_prefix
447                    << "Channel "
448                    << (msg[0]&0xF)+1
449                    << " NoteOn NoteNum "
450                    << (int) msg[1]
451                    << " Vel "
452                    << (int) msg[2]
453                    << endl;
454                 break;
455             
456         case polypress:
457                 o << trace_prefix
458                    << "Channel "
459                    << (msg[0]&0xF)+1
460                    << " PolyPressure"
461                    << (int) msg[1]
462                    << endl;
463                 break;
464             
465         case MIDI::controller:
466                 o << trace_prefix
467                    << "Channel "
468                    << (msg[0]&0xF)+1
469                    << " Controller "
470                    << (int) msg[1]
471                    << " Value "
472                    << (int) msg[2]
473                    << endl;
474                 break;
475                 
476         case program:
477                 o << trace_prefix 
478                    << "Channel "
479                    << (msg[0]&0xF)+1
480                    <<  " Program Change ProgNum "
481                    << (int) msg[1]
482                    << endl;
483                 break;
484                 
485         case chanpress:
486                 o << trace_prefix 
487                    << "Channel "
488                    << (msg[0]&0xF)+1
489                    << " Channel Pressure "
490                    << (int) msg[1]
491                    << endl;
492                 break;
493             
494         case MIDI::pitchbend:
495                 o << trace_prefix
496                    << "Channel "
497                    << (msg[0]&0xF)+1
498                    << " Pitch Bend "
499                    << ((msg[2]<<7)|msg[1])
500                    << endl;
501                 break;
502             
503         case MIDI::sysex:
504                 if (len == 1) {
505                         switch (msg[0]) {
506                         case 0xf8:
507                                 o << trace_prefix
508                                    << "Clock"
509                                    << endl;
510                                 break;
511                         case 0xfa:
512                                 o << trace_prefix
513                                    << "Start"
514                                    << endl;
515                                 break;
516                         case 0xfb:
517                                 o << trace_prefix
518                                    << "Continue"
519                                    << endl;
520                                 break;
521                         case 0xfc:
522                                 o << trace_prefix
523                                    << "Stop"
524                                    << endl;
525                                 break;
526                         case 0xfe:
527                                 o << trace_prefix
528                                    << "Active Sense"
529                                    << endl;
530                                 break;
531                         case 0xff:
532                                 o << trace_prefix
533                                    << "System Reset"
534                                    << endl;
535                                 break;
536                         default:
537                                 o << trace_prefix
538                                    << "System Exclusive (1 byte : " << hex << (int) *msg << dec << ')'
539                                    << endl;             
540                                 break;
541                         } 
542                 } else {
543                         o << trace_prefix
544                            << "System Exclusive (" << len << ") = [ " << hex;
545                         for (unsigned int i = 0; i < len; ++i) {
546                                 o << (int) msg[i] << ' ';
547                         }
548                         o << dec << ']' << endl;
549                         
550                 }
551                 break;
552             
553         case MIDI::song:
554                 o << trace_prefix << "Song" << endl;
555                 break;
556             
557         case MIDI::tune:
558                 o << trace_prefix << "Tune" << endl;
559                 break;
560             
561         case MIDI::eox:
562                 o << trace_prefix << "End-of-System Exclusive" << endl;
563                 break;
564             
565         case MIDI::timing:
566                 o << trace_prefix << "Timing" << endl;
567                 break;
568             
569         case MIDI::start:
570                 o << trace_prefix << "Start" << endl;
571                 break;
572             
573         case MIDI::stop:
574                 o << trace_prefix << "Stop" << endl;
575                 break;
576             
577         case MIDI::contineu:
578                 o << trace_prefix << "Continue" << endl;
579                 break;
580             
581         case active:
582                 o << trace_prefix << "Active Sense" << endl;
583                 break;
584             
585         default:
586                 o << trace_prefix << "Unrecognized MIDI message" << endl;
587                 break;
588         }
589 }
590
591 int
592 MidiDiskstream::process (nframes_t transport_frame, nframes_t nframes, bool can_record, bool rec_monitors_input)
593 {
594         // FIXME: waay too much code to duplicate (AudioDiskstream::process)
595         int       ret = -1;
596         nframes_t rec_offset = 0;
597         nframes_t rec_nframes = 0;
598         bool      nominally_recording;
599         bool      re = record_enabled ();
600         bool      collect_playback = true;
601
602         /* if we've already processed the frames corresponding to this call,
603            just return. this allows multiple routes that are taking input
604            from this diskstream to call our ::process() method, but have
605            this stuff only happen once. more commonly, it allows both
606            the AudioTrack that is using this AudioDiskstream *and* the Session
607            to call process() without problems.
608            */
609
610         if (_processed) {
611                 return 0;
612         }
613         
614         commit_should_unlock = false;
615
616         check_record_status (transport_frame, nframes, can_record);
617
618         nominally_recording = (can_record && re);
619
620         if (nframes == 0) {
621                 _processed = true;
622                 return 0;
623         }
624
625         /* This lock is held until the end of ::commit, so these two functions
626            must always be called as a pair. The only exception is if this function
627            returns a non-zero value, in which case, ::commit should not be called.
628            */
629
630         // If we can't take the state lock return.
631         if (!state_lock.trylock()) {
632                 return 1;
633         }
634         commit_should_unlock = true;
635         adjust_capture_position = 0;
636
637         if (nominally_recording || (_session.get_record_enabled() && Config->get_punch_in())) {
638                 OverlapType ot;
639
640                 ot = coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
641
642                 switch (ot) {
643                         case OverlapNone:
644                                 rec_nframes = 0;
645                                 break;
646
647                         case OverlapInternal:
648                                 /*     ----------    recrange
649                                            |---|       transrange
650                                            */
651                                 rec_nframes = nframes;
652                                 rec_offset = 0;
653                                 break;
654
655                         case OverlapStart:
656                                 /*    |--------|    recrange
657                                           -----|          transrange
658                                           */
659                                 rec_nframes = transport_frame + nframes - first_recordable_frame;
660                                 if (rec_nframes) {
661                                         rec_offset = first_recordable_frame - transport_frame;
662                                 }
663                                 break;
664
665                         case OverlapEnd:
666                                 /*    |--------|    recrange
667                                           |--------  transrange
668                                           */
669                                 rec_nframes = last_recordable_frame - transport_frame;
670                                 rec_offset = 0;
671                                 break;
672
673                         case OverlapExternal:
674                                 /*    |--------|    recrange
675                                           --------------  transrange
676                                           */
677                                 rec_nframes = last_recordable_frame - last_recordable_frame;
678                                 rec_offset = first_recordable_frame - transport_frame;
679                                 break;
680                 }
681
682                 if (rec_nframes && !was_recording) {
683                         capture_captured = 0;
684                         was_recording = true;
685                 }
686         }
687
688
689         if (can_record && !_last_capture_regions.empty()) {
690                 _last_capture_regions.clear ();
691         }
692
693         if (nominally_recording || rec_nframes) {
694
695                 // Pump entire port buffer into the ring buffer (FIXME: split cycles?)
696                 MidiBuffer& buf = _source_port->get_midi_buffer(nframes);
697                 for (MidiBuffer::iterator i = buf.begin(); i != buf.end(); ++i) {
698                         const Evoral::MIDIEvent<MidiBuffer::TimeType> ev(*i, false);
699                         assert(ev.buffer());
700                         _capture_buf->write(ev.time() + transport_frame, ev.type(), ev.size(), ev.buffer());
701                 }
702         
703         } else {
704
705                 if (was_recording) {
706                         finish_capture (rec_monitors_input);
707                 }
708
709         }
710
711         if (rec_nframes) {
712
713                 /* data will be written to disk */
714
715                 if (rec_nframes == nframes && rec_offset == 0) {
716                         playback_distance = nframes;
717                 }
718
719                 adjust_capture_position = rec_nframes;
720
721         } else if (nominally_recording) {
722
723                 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
724
725                 playback_distance = nframes;
726                 collect_playback = false;
727
728         }
729
730         if (collect_playback) {
731
732                 /* we're doing playback */
733
734                 nframes_t necessary_samples;
735
736                 /* no varispeed playback if we're recording, because the output .... TBD */
737
738                 if (rec_nframes == 0 && _actual_speed != 1.0f) {
739                         necessary_samples = (nframes_t) floor ((nframes * fabs (_actual_speed))) + 1;
740                 } else {
741                         necessary_samples = nframes;
742                 }
743
744                 // Pump entire port buffer into playback buffer (FIXME: split cycles?)
745                 MidiBuffer& buf = _source_port->get_midi_buffer(nframes);
746                 for (MidiBuffer::iterator i = buf.begin(); i != buf.end(); ++i) {
747                         const Evoral::MIDIEvent<MidiBuffer::TimeType> ev(*i, false);
748                         assert(ev.buffer());
749                         _playback_buf->write(ev.time() + transport_frame, ev.type(), ev.size(), ev.buffer());
750                 }
751         }
752
753         ret = 0;
754
755         _processed = true;
756
757         if (ret) {
758
759                 /* we're exiting with failure, so ::commit will not
760                    be called. unlock the state lock.
761                    */
762
763                 commit_should_unlock = false;
764                 state_lock.unlock();
765         } 
766
767         return ret;
768 }
769
770 bool
771 MidiDiskstream::commit (nframes_t nframes)
772 {
773         bool need_butler = false;
774
775         if (_actual_speed < 0.0) {
776                 playback_sample -= playback_distance;
777         } else {
778                 playback_sample += playback_distance;
779         }
780
781         if (adjust_capture_position != 0) {
782                 capture_captured += adjust_capture_position;
783                 adjust_capture_position = 0;
784         }
785
786         uint32_t frames_read = g_atomic_int_get(&_frames_read_from_ringbuffer);
787         uint32_t frames_written = g_atomic_int_get(&_frames_written_to_ringbuffer);
788         if ((frames_written - frames_read) + nframes < midi_readahead) {
789                 need_butler = true;
790         }
791
792         /*cerr << "MDS written: " << frames_written << " - read: " << frames_read <<
793                 " = " << frames_written - frames_read
794                 << " + " << nframes << " < " << midi_readahead << " = " << need_butler << ")" << endl;*/
795         
796         if (commit_should_unlock) {
797                 state_lock.unlock();
798         }
799
800         _processed = false;
801
802         return need_butler;
803 }
804
805 void
806 MidiDiskstream::set_pending_overwrite (bool yn)
807 {
808         /* called from audio thread, so we can use the read ptr and playback sample as we wish */
809         
810         pending_overwrite = yn;
811         
812         overwrite_frame = playback_sample;
813 }
814
815 int
816 MidiDiskstream::overwrite_existing_buffers ()
817 {
818         //read(overwrite_frame, disk_io_chunk_frames, false);
819         overwrite_queued = false;
820         pending_overwrite = false;
821
822         return 0;
823 }
824
825 int
826 MidiDiskstream::seek (nframes_t frame, bool complete_refill)
827 {
828         Glib::Mutex::Lock lm (state_lock);
829         int ret = -1;
830         
831         _playback_buf->reset();
832         _capture_buf->reset();
833         g_atomic_int_set(&_frames_read_from_ringbuffer, 0);
834         g_atomic_int_set(&_frames_written_to_ringbuffer, 0);
835
836         playback_sample = frame;
837         file_frame = frame;
838
839         if (complete_refill) {
840                 while ((ret = do_refill_with_alloc ()) > 0) ;
841         } else {
842                 ret = do_refill_with_alloc ();
843         }
844
845         return ret;
846 }
847
848 int
849 MidiDiskstream::can_internal_playback_seek (nframes_t distance)
850 {
851         uint32_t frames_read    = g_atomic_int_get(&_frames_read_from_ringbuffer);
852         uint32_t frames_written = g_atomic_int_get(&_frames_written_to_ringbuffer);
853         return ((frames_written - frames_read) < distance);
854 }
855
856 int
857 MidiDiskstream::internal_playback_seek (nframes_t distance)
858 {
859         cerr << "MDS: internal_playback_seek " << distance << endl;
860
861         first_recordable_frame += distance;
862         playback_sample += distance;
863
864         return 0;
865 }
866
867 /** @a start is set to the new frame position (TIME) read up to */
868 int
869 MidiDiskstream::read (nframes_t& start, nframes_t dur, bool reversed)
870 {       
871         nframes_t this_read = 0;
872         bool reloop = false;
873         nframes_t loop_end = 0;
874         nframes_t loop_start = 0;
875         nframes_t loop_length = 0;
876         Location *loc = 0;
877
878         if (!reversed) {
879                 /* Make the use of a Location atomic for this read operation.
880                    
881                    Note: Locations don't get deleted, so all we care about
882                    when I say "atomic" is that we are always pointing to
883                    the same one and using a start/length values obtained
884                    just once.
885                 */
886                 
887                 if ((loc = loop_location) != 0) {
888                         loop_start = loc->start();
889                         loop_end = loc->end();
890                         loop_length = loop_end - loop_start;
891                 }
892                 
893                 /* if we are looping, ensure that the first frame we read is at the correct
894                    position within the loop.
895                 */
896                 
897                 if (loc && (start >= loop_end)) {
898                         //cerr << "start adjusted from " << start;
899                         start = loop_start + ((start - loop_start) % loop_length);
900                         //cerr << "to " << start << endl;
901                 }
902                 //cerr << "start is " << start << "  loopstart: " << loop_start << "  loopend: " << loop_end << endl;
903         }
904
905         while (dur) {
906
907                 /* take any loop into account. we can't read past the end of the loop. */
908
909                 if (loc && (loop_end - start < dur)) {
910                         this_read = loop_end - start;
911                         //cerr << "reloop true: thisread: " << this_read << "  dur: " << dur << endl;
912                         reloop = true;
913                 } else {
914                         reloop = false;
915                         this_read = dur;
916                 }
917
918                 if (this_read == 0) {
919                         break;
920                 }
921
922                 this_read = min(dur,this_read);
923
924                 if (midi_playlist()->read (*_playback_buf, start, this_read) != this_read) {
925                         error << string_compose(
926                                         _("MidiDiskstream %1: cannot read %2 from playlist at frame %3"),
927                                         _id, this_read, start) << endmsg;
928                         return -1;
929                 }
930                 
931                 //cout << "MDS this read " << this_read << " start = " << start << endl;
932                 g_atomic_int_add(&_frames_written_to_ringbuffer, this_read);
933
934                 _read_data_count = _playlist->read_data_count();
935                 
936                 if (reversed) {
937
938                         // Swap note ons with note offs here.  etc?
939                         // Fully reversing MIDI requires look-ahead (well, behind) to find previous
940                         // CC values etc.  hard.
941
942                 } else {
943                         
944                         /* if we read to the end of the loop, go back to the beginning */
945                         
946                         if (reloop) {
947                                 // Synthesize LoopEvent here, because the next events
948                                 // written will have non-monotonic timestamps.
949                                 _playback_buf->write(loop_end - 1, LoopEventType, 0, 0);
950                                 //cout << "Pushing LoopEvent ts=" << loop_end-1 
951                                 //     << " start+this_read " << start+this_read << endl;
952
953                                 start = loop_start;
954                         } else {
955                                 start += this_read;
956                         }
957                 } 
958
959                 dur -= this_read;
960                 //offset += this_read;
961         }
962
963         return 0;
964 }
965
966 int
967 MidiDiskstream::do_refill_with_alloc ()
968 {
969         return do_refill();
970 }
971
972 int
973 MidiDiskstream::do_refill ()
974 {
975         int     ret         = 0;
976         size_t  write_space = _playback_buf->write_space();
977         bool    reversed    = (_visible_speed * _session.transport_speed()) < 0.0f;
978
979         if (write_space == 0) {
980                 return 0;
981         }
982         
983         if (reversed) {
984                 return 0;
985         }
986
987         /* at end: nothing to do */
988         if (file_frame == max_frames) {
989                 return 0;
990         }
991
992         // At this point we...
993         assert(_playback_buf->write_space() > 0); // ... have something to write to, and
994         assert(file_frame <= max_frames); // ... something to write
995
996         // now calculate how much time is in the ringbuffer.
997         // and lets write as much as we need to get this to be midi_readahead;
998         uint32_t frames_read = g_atomic_int_get(&_frames_read_from_ringbuffer);
999         uint32_t frames_written = g_atomic_int_get(&_frames_written_to_ringbuffer);
1000         if ((frames_written - frames_read) >= midi_readahead) {
1001                 //cout << "MDS Nothing to do. all fine" << endl;
1002                 return 0;
1003         }
1004
1005         nframes_t to_read = midi_readahead - (frames_written - frames_read);
1006
1007         //cout << "MDS read for midi_readahead " << to_read << "  rb_contains: "
1008         //      << frames_written - frames_read << endl;
1009
1010         to_read = min(to_read, (max_frames - file_frame));
1011         
1012         if (read (file_frame, to_read, reversed)) {
1013                 ret = -1;
1014         }
1015                 
1016         return ret;
1017 }
1018
1019 /** Flush pending data to disk.
1020  *
1021  * Important note: this function will write *AT MOST* disk_io_chunk_frames
1022  * of data to disk. it will never write more than that.  If it writes that
1023  * much and there is more than that waiting to be written, it will return 1,
1024  * otherwise 0 on success or -1 on failure.
1025  * 
1026  * If there is less than disk_io_chunk_frames to be written, no data will be
1027  * written at all unless @a force_flush is true.
1028  */
1029 int
1030 MidiDiskstream::do_flush (RunContext context, bool force_flush)
1031 {
1032         uint32_t to_write;
1033         int32_t ret = 0;
1034         nframes_t total;
1035
1036         _write_data_count = 0;
1037
1038         total = _session.transport_frame() - _last_flush_frame;
1039         
1040         if (_last_flush_frame > _session.transport_frame()
1041                         || _last_flush_frame < capture_start_frame) {
1042                 _last_flush_frame = _session.transport_frame();
1043         }
1044
1045         if (total == 0 || _capture_buf->read_space() == 0
1046                         || (!force_flush && (total < disk_io_chunk_frames && was_recording))) {
1047                 goto out;
1048         }
1049
1050         /* if there are 2+ chunks of disk i/o possible for
1051            this track, let the caller know so that it can arrange
1052            for us to be called again, ASAP.
1053
1054            if we are forcing a flush, then if there is* any* extra
1055            work, let the caller know.
1056
1057            if we are no longer recording and there is any extra work,
1058            let the caller know too.
1059            */
1060
1061         if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1062                 ret = 1;
1063         } 
1064
1065         to_write = disk_io_chunk_frames;
1066
1067         assert(!destructive());
1068
1069         if (record_enabled()
1070                         && (   (_session.transport_frame() - _last_flush_frame > disk_io_chunk_frames)
1071                                 || force_flush)) {
1072                 if ((!_write_source) || _write_source->midi_write (*_capture_buf, capture_start_frame, to_write) != to_write) {
1073                         error << string_compose(_("MidiDiskstream %1: cannot write to disk"), _id) << endmsg;
1074                         return -1;
1075                 } else {
1076                         _last_flush_frame = _session.transport_frame();
1077                 }
1078         }
1079
1080 out:
1081         return ret;
1082 }
1083
1084 void
1085 MidiDiskstream::transport_stopped (struct tm& when, time_t twhen, bool abort_capture)
1086 {
1087         uint32_t buffer_position;
1088         bool more_work = true;
1089         int err = 0;
1090         boost::shared_ptr<MidiRegion> region;
1091         nframes_t total_capture;
1092         MidiRegion::SourceList srcs;
1093         MidiRegion::SourceList::iterator src;
1094         vector<CaptureInfo*>::iterator ci;
1095         bool mark_write_completed = false;
1096
1097         finish_capture (true);
1098
1099         /* butler is already stopped, but there may be work to do 
1100            to flush remaining data to disk.
1101            */
1102
1103         while (more_work && !err) {
1104                 switch (do_flush (TransportContext, true)) {
1105                         case 0:
1106                                 more_work = false;
1107                                 break;
1108                         case 1:
1109                                 break;
1110                         case -1:
1111                                 error << string_compose(_("MidiDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1112                                 err++;
1113                 }
1114         }
1115
1116         /* XXX is there anything we can do if err != 0 ? */
1117         Glib::Mutex::Lock lm (capture_info_lock);
1118
1119         if (capture_info.empty()) {
1120                 return;
1121         }
1122
1123         if (abort_capture) {
1124
1125                 if (_write_source) {
1126
1127                         _write_source->mark_for_remove ();
1128                         _write_source->drop_references ();
1129                         _write_source.reset();
1130                 }
1131
1132                 /* new source set up in "out" below */
1133
1134         } else {
1135
1136                 assert(_write_source);
1137
1138                 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1139                         total_capture += (*ci)->frames;
1140                 }
1141
1142                 /* figure out the name for this take */
1143         
1144                 srcs.push_back (_write_source);
1145                 _write_source->set_timeline_position (capture_info.front()->start);
1146                 _write_source->set_captured_for (_name);
1147
1148                 string whole_file_region_name;
1149                 whole_file_region_name = region_name_from_path (_write_source->name(), true);
1150
1151                 /* Register a new region with the Session that
1152                    describes the entire source. Do this first
1153                    so that any sub-regions will obviously be
1154                    children of this one (later!)
1155                    */
1156
1157                 try {
1158                         boost::shared_ptr<Region> rx (RegionFactory::create (srcs, 0,
1159                                         total_capture, whole_file_region_name, 0,
1160                                         Region::Flag (Region::DefaultFlags|Region::Automatic|Region::WholeFile)));
1161
1162                         region = boost::dynamic_pointer_cast<MidiRegion> (rx);
1163                         region->special_set_position (capture_info.front()->start);
1164                 }
1165
1166
1167                 catch (failed_constructor& err) {
1168                         error << string_compose(_("%1: could not create region for complete midi file"), _name) << endmsg;
1169                         /* XXX what now? */
1170                 }
1171
1172                 _last_capture_regions.push_back (region);
1173
1174                 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1175
1176                 XMLNode &before = _playlist->get_state();
1177                 _playlist->freeze ();
1178
1179                 for (buffer_position = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1180
1181                         string region_name;
1182
1183                         _session.region_name (region_name, _write_source->name(), false);
1184
1185                         // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->frames << " add a region\n";
1186
1187                         try {
1188                                 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, buffer_position, (*ci)->frames, region_name));
1189                                 region = boost::dynamic_pointer_cast<MidiRegion> (rx);
1190                         }
1191
1192                         catch (failed_constructor& err) {
1193                                 error << _("MidiDiskstream: could not create region for captured midi!") << endmsg;
1194                                 continue; /* XXX is this OK? */
1195                         }
1196                         
1197                         region->GoingAway.connect (bind (mem_fun (*this, &Diskstream::remove_region_from_last_capture), boost::weak_ptr<Region>(region)));
1198
1199                         _last_capture_regions.push_back (region);
1200
1201                         // cerr << "add new region, buffer position = " << buffer_position << " @ " << (*ci)->start << endl;
1202
1203                         i_am_the_modifier++;
1204                         _playlist->add_region (region, (*ci)->start);
1205                         i_am_the_modifier--;
1206
1207                         buffer_position += (*ci)->frames;
1208                 }
1209
1210                 _playlist->thaw ();
1211                 XMLNode &after = _playlist->get_state();
1212                 _session.add_command (new MementoCommand<Playlist>(*_playlist, &before, &after));
1213
1214         }
1215
1216         mark_write_completed = true;
1217
1218         reset_write_sources (mark_write_completed);
1219
1220         for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1221                 delete *ci;
1222         }
1223
1224         capture_info.clear ();
1225         capture_start_frame = 0;
1226 }
1227
1228 void
1229 MidiDiskstream::transport_looped (nframes_t transport_frame)
1230 {
1231         if (was_recording) {
1232
1233                 // adjust the capture length knowing that the data will be recorded to disk
1234                 // only necessary after the first loop where we're recording
1235                 if (capture_info.size() == 0) {
1236                         capture_captured += _capture_offset;
1237
1238                         if (_alignment_style == ExistingMaterial) {
1239                                 capture_captured += _session.worst_output_latency();
1240                         } else {
1241                                 capture_captured += _roll_delay;
1242                         }
1243                 }
1244
1245                 finish_capture (true);
1246
1247                 // the next region will start recording via the normal mechanism
1248                 // we'll set the start position to the current transport pos
1249                 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1250                 capture_start_frame = transport_frame;
1251                 first_recordable_frame = transport_frame; // mild lie
1252                 last_recordable_frame = max_frames;
1253                 was_recording = true;
1254         }
1255 }
1256
1257 void
1258 MidiDiskstream::finish_capture (bool rec_monitors_input)
1259 {
1260         was_recording = false;
1261         
1262         if (capture_captured == 0) {
1263                 return;
1264         }
1265
1266         // Why must we destroy?
1267         assert(!destructive());
1268
1269         CaptureInfo* ci = new CaptureInfo;
1270         
1271         ci->start  = capture_start_frame;
1272         ci->frames = capture_captured;
1273         
1274         /* XXX theoretical race condition here. Need atomic exchange ? 
1275            However, the circumstances when this is called right 
1276            now (either on record-disable or transport_stopped)
1277            mean that no actual race exists. I think ...
1278            We now have a capture_info_lock, but it is only to be used
1279            to synchronize in the transport_stop and the capture info
1280            accessors, so that invalidation will not occur (both non-realtime).
1281         */
1282
1283         // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1284
1285         capture_info.push_back (ci);
1286         capture_captured = 0;
1287 }
1288
1289 void
1290 MidiDiskstream::set_record_enabled (bool yn)
1291 {
1292         if (!recordable() || !_session.record_enabling_legal()) {
1293                 return;
1294         }
1295
1296         assert(!destructive());
1297         
1298         if (yn && _source_port == 0) {
1299
1300                 /* pick up connections not initiated *from* the IO object
1301                    we're associated with.
1302                 */
1303
1304                 get_input_sources ();
1305         }
1306
1307         /* yes, i know that this not proof against race conditions, but its
1308            good enough. i think.
1309         */
1310
1311         if (record_enabled() != yn) {
1312                 if (yn) {
1313                         engage_record_enable ();
1314                 } else {
1315                         disengage_record_enable ();
1316                 }
1317         }
1318 }
1319
1320 void
1321 MidiDiskstream::engage_record_enable ()
1322 {
1323     bool rolling = _session.transport_speed() != 0.0f;
1324
1325         g_atomic_int_set (&_record_enabled, 1);
1326         
1327         if (_source_port && Config->get_monitoring_model() == HardwareMonitoring) {
1328                 _source_port->request_monitor_input (!(Config->get_auto_input() && rolling));
1329         }
1330
1331         // FIXME: Why is this necessary?  Isn't needed for AudioDiskstream...
1332         if (!_write_source)
1333                 use_new_write_source();
1334
1335         _write_source->mark_streaming_midi_write_started (_note_mode, _session.transport_frame());
1336
1337         RecordEnableChanged (); /* EMIT SIGNAL */
1338 }
1339
1340 void
1341 MidiDiskstream::disengage_record_enable ()
1342 {
1343         g_atomic_int_set (&_record_enabled, 0);
1344         if (_source_port && Config->get_monitoring_model() == HardwareMonitoring) {
1345                 if (_source_port) {
1346                         _source_port->request_monitor_input (false);
1347                 }
1348         }
1349
1350         RecordEnableChanged (); /* EMIT SIGNAL */
1351 }
1352
1353 XMLNode&
1354 MidiDiskstream::get_state ()
1355 {
1356         XMLNode* node = new XMLNode ("MidiDiskstream");
1357         char buf[64];
1358         LocaleGuard lg (X_("POSIX"));
1359
1360         snprintf (buf, sizeof(buf), "0x%x", _flags);
1361         node->add_property ("flags", buf);
1362
1363         node->add_property("channel-mode", enum_2_string(get_channel_mode()));
1364         
1365         snprintf (buf, sizeof(buf), "0x%x", get_channel_mask());
1366         node->add_property("channel-mask", buf);
1367         
1368         node->add_property ("playlist", _playlist->name());
1369         
1370         snprintf (buf, sizeof(buf), "%f", _visible_speed);
1371         node->add_property ("speed", buf);
1372
1373         node->add_property("name", _name);
1374         id().print(buf, sizeof(buf));
1375         node->add_property("id", buf);
1376
1377         if (_write_source && _session.get_record_enabled()) {
1378
1379                 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1380                 XMLNode* cs_grandchild;
1381
1382                 cs_grandchild = new XMLNode (X_("file"));
1383                 cs_grandchild->add_property (X_("path"), _write_source->path());
1384                 cs_child->add_child_nocopy (*cs_grandchild);
1385
1386                 /* store the location where capture will start */
1387
1388                 Location* pi;
1389
1390                 if (Config->get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1391                         snprintf (buf, sizeof (buf), "%" PRIu32, pi->start());
1392                 } else {
1393                         snprintf (buf, sizeof (buf), "%" PRIu32, _session.transport_frame());
1394                 }
1395
1396                 cs_child->add_property (X_("at"), buf);
1397                 node->add_child_nocopy (*cs_child);
1398         }
1399
1400         if (_extra_xml) {
1401                 node->add_child_copy (*_extra_xml);
1402         }
1403
1404         return* node;
1405 }
1406
1407 int
1408 MidiDiskstream::set_state (const XMLNode& node)
1409 {
1410         const XMLProperty* prop;
1411         XMLNodeList nlist = node.children();
1412         XMLNodeIterator niter;
1413         uint32_t nchans = 1;
1414         XMLNode* capture_pending_node = 0;
1415         LocaleGuard lg (X_("POSIX"));
1416
1417         in_set_state = true;
1418
1419         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1420                 /*if ((*niter)->name() == IO::state_node_name) {
1421                         deprecated_io_node = new XMLNode (**niter);
1422                 }*/
1423                 assert ((*niter)->name() != IO::state_node_name);
1424
1425                 if ((*niter)->name() == X_("CapturingSources")) {
1426                         capture_pending_node = *niter;
1427                 }
1428         }
1429
1430         /* prevent write sources from being created */
1431         
1432         in_set_state = true;
1433         
1434         if ((prop = node.property ("name")) != 0) {
1435                 _name = prop->value();
1436         } 
1437
1438         if ((prop = node.property ("id")) != 0) {
1439                 _id = prop->value ();
1440         }
1441
1442         if ((prop = node.property ("flags")) != 0) {
1443                 _flags = Flag (string_2_enum (prop->value(), _flags));
1444         }
1445
1446         ChannelMode channel_mode = AllChannels;
1447         if ((prop = node.property ("channel-mode")) != 0) {
1448                 channel_mode = ChannelMode (string_2_enum(prop->value(), channel_mode));
1449         }
1450         
1451         unsigned int channel_mask = 0xFFFF;
1452         if ((prop = node.property ("channel-mask")) != 0) {
1453                 sscanf (prop->value().c_str(), "0x%x", &channel_mask);
1454                 if (channel_mask & (~0xFFFF)) {
1455                         warning << _("MidiDiskstream: XML property channel-mask out of range") << endmsg;
1456                 }
1457         }
1458
1459         set_channel_mode(channel_mode, channel_mask);
1460         
1461         if ((prop = node.property ("channels")) != 0) {
1462                 nchans = atoi (prop->value().c_str());
1463         }
1464         
1465         if ((prop = node.property ("playlist")) == 0) {
1466                 return -1;
1467         }
1468
1469         {
1470                 bool had_playlist = (_playlist != 0);
1471         
1472                 if (find_and_use_playlist (prop->value())) {
1473                         return -1;
1474                 }
1475
1476                 if (!had_playlist) {
1477                         _playlist->set_orig_diskstream_id (_id);
1478                 }
1479                 
1480                 if (capture_pending_node) {
1481                         use_pending_capture_data (*capture_pending_node);
1482                 }
1483
1484         }
1485
1486         if ((prop = node.property ("speed")) != 0) {
1487                 double sp = atof (prop->value().c_str());
1488
1489                 if (realtime_set_speed (sp, false)) {
1490                         non_realtime_set_speed ();
1491                 }
1492         }
1493
1494         in_set_state = false;
1495
1496         /* make sure this is clear before we do anything else */
1497
1498         // FIXME?
1499         //_capturing_source = 0;
1500
1501         /* write sources are handled when we handle the input set 
1502            up of the IO that owns this DS (::non_realtime_input_change())
1503         */
1504                 
1505         in_set_state = false;
1506
1507         return 0;
1508 }
1509
1510 int
1511 MidiDiskstream::use_new_write_source (uint32_t n)
1512 {
1513         if (!recordable()) {
1514                 return 1;
1515         }
1516
1517         assert(n == 0);
1518
1519         if (_write_source) {
1520
1521                 if (_write_source->is_empty ()) {
1522                         _write_source->mark_for_remove ();
1523                         _write_source.reset();
1524                 } else {
1525                         _write_source.reset();
1526                 }
1527         }
1528
1529         try {
1530                 _write_source = boost::dynamic_pointer_cast<SMFSource>(_session.create_midi_source_for_session (*this));
1531                 if (!_write_source) {
1532                         throw failed_constructor();
1533                 }
1534         } 
1535
1536         catch (failed_constructor &err) {
1537                 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
1538                 _write_source.reset();
1539                 return -1;
1540         }
1541
1542         _write_source->set_allow_remove_if_empty (true);
1543
1544         return 0;
1545 }
1546
1547 void
1548 MidiDiskstream::reset_write_sources (bool mark_write_complete, bool force)
1549 {
1550         if (!recordable()) {
1551                 return;
1552         }
1553
1554         if (_write_source && mark_write_complete) {
1555                 _write_source->mark_streaming_write_completed ();
1556         }
1557
1558         use_new_write_source (0);
1559                         
1560         if (record_enabled()) {
1561                 //_capturing_sources.push_back (_write_source);
1562         }
1563 }
1564
1565 int
1566 MidiDiskstream::rename_write_sources ()
1567 {
1568         if (_write_source != 0) {
1569                 _write_source->set_source_name (_name, destructive());
1570                 /* XXX what to do if this fails ? */
1571         }
1572         return 0;
1573 }
1574
1575 void
1576 MidiDiskstream::set_block_size (nframes_t nframes)
1577 {
1578 }
1579
1580 void
1581 MidiDiskstream::allocate_temporary_buffers ()
1582 {
1583 }
1584
1585 void
1586 MidiDiskstream::monitor_input (bool yn)
1587 {
1588         if (_source_port)
1589                 _source_port->ensure_monitor_input (yn);
1590 }
1591
1592 void
1593 MidiDiskstream::set_align_style_from_io ()
1594 {
1595         bool have_physical = false;
1596
1597         if (_io == 0) {
1598                 return;
1599         }
1600
1601         get_input_sources ();
1602         
1603         if (_source_port && _source_port->flags() & JackPortIsPhysical) {
1604                 have_physical = true;
1605         }
1606
1607         if (have_physical) {
1608                 set_align_style (ExistingMaterial);
1609         } else {
1610                 set_align_style (CaptureTime);
1611         }
1612 }
1613
1614
1615 float
1616 MidiDiskstream::playback_buffer_load () const
1617 {
1618         return (float) ((double) _playback_buf->read_space()/
1619                         (double) _playback_buf->capacity());
1620 }
1621
1622 float
1623 MidiDiskstream::capture_buffer_load () const
1624 {
1625         return (float) ((double) _capture_buf->write_space()/
1626                         (double) _capture_buf->capacity());
1627 }
1628
1629 int
1630 MidiDiskstream::use_pending_capture_data (XMLNode& node)
1631 {
1632         return 0;
1633 }
1634
1635 /** Writes playback events in the given range to \a dst, translating time stamps
1636  * so that an event at \a start has time = 0
1637  */
1638 void
1639 MidiDiskstream::get_playback (MidiBuffer& dst, nframes_t start, nframes_t end)
1640 {
1641         dst.clear();
1642         assert(dst.size() == 0);
1643         
1644         // Reverse.  ... We just don't do reverse, ok?  Back off.
1645         if (end <= start) {
1646                 return;
1647         }
1648
1649         // Check only events added this offset cycle
1650         MidiBuffer::iterator this_cycle_start = dst.end();
1651         
1652         // Translates stamps to be relative to start
1653         #if 1
1654                 _playback_buf->read(dst, start, end);
1655         #else   
1656                 const size_t events_read = _playback_buf->read(dst, start, end);
1657                 cout << "MDS events read = " << events_read
1658                 << " start = " << start << " end = " << end
1659                 << " readspace " << _playback_buf->read_space()
1660                 << " writespace " << _playback_buf->write_space() << endl;
1661         #endif
1662         
1663         gint32 frames_read = end - start;
1664         g_atomic_int_add(&_frames_read_from_ringbuffer, frames_read);
1665         
1666         // Feed the data through the MidiStateTracker
1667         // If it detects a LoopEvent it will add necessary note offs
1668         if (_midi_state_tracker.track(this_cycle_start, dst.end())) {
1669                 _midi_state_tracker.resolve_notes(dst, end-start - 1);
1670         }
1671 }
1672