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