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