2 Copyright (C) 2000-2003 Paul Davis
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.
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.
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.
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"
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"
55 #include "midi++/types.h"
61 using namespace ARDOUR;
64 nframes_t MidiDiskstream::midi_readahead = 4096;
66 MidiDiskstream::MidiDiskstream (Session &sess, const string &name, Diskstream::Flag flag)
67 : Diskstream(sess, name, flag)
71 , _last_flush_frame(0)
72 , _note_mode(Sustained)
73 , _frames_written_to_ringbuffer(0)
74 , _frames_read_from_ringbuffer(0)
76 /* prevent any write sources from being created */
85 assert(!destructive());
88 MidiDiskstream::MidiDiskstream (Session& sess, const XMLNode& node)
89 : Diskstream(sess, node)
93 , _last_flush_frame(0)
94 , _note_mode(Sustained)
95 , _frames_written_to_ringbuffer(0)
96 , _frames_read_from_ringbuffer(0)
101 if (set_state (node)) {
102 in_set_state = false;
103 throw failed_constructor();
106 in_set_state = false;
109 use_destructive_playlist ();
114 MidiDiskstream::init (Diskstream::Flag f)
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.
123 set_block_size (_session.get_block_size());
124 allocate_temporary_buffers ();
126 const size_t size = _session.midi_diskstream_buffer_size();
127 _playback_buf = new MidiRingBuffer<nframes_t>(size);
128 _capture_buf = new MidiRingBuffer<nframes_t>(size);
130 _n_channels = ChanCount(DataType::MIDI, 1);
132 assert(recordable());
135 MidiDiskstream::~MidiDiskstream ()
137 Glib::Mutex::Lock lm (state_lock);
142 MidiDiskstream::non_realtime_locate (nframes_t position)
145 _write_source->set_timeline_position (position);
147 seek(position, false);
152 MidiDiskstream::non_realtime_input_change ()
155 Glib::Mutex::Lock lm (state_lock);
157 if (input_change_pending == NoChange) {
161 if (input_change_pending & ConfigurationChanged) {
162 if (_io->n_ports().n_midi() != _n_channels.n_midi()) {
163 error << "Can not feed IO " << _io->n_ports()
164 << " with diskstream " << _n_channels << endl;
168 get_input_sources ();
169 set_capture_offset ();
171 if (first_input_change) {
172 set_align_style (_persistent_alignment_style);
173 first_input_change = false;
175 set_align_style_from_io ();
178 input_change_pending = NoChange;
180 /* implicit unlock */
183 /* reset capture files */
185 reset_write_sources (false);
187 /* now refill channel buffers */
189 if (speed() != 1.0f || speed() != -1.0f) {
190 seek ((nframes_t) (_session.transport_frame() * (double) speed()));
193 seek (_session.transport_frame());
196 _last_flush_frame = _session.transport_frame();
200 MidiDiskstream::get_input_sources ()
202 uint32_t ni = _io->n_ports().n_midi();
208 // This is all we do for now at least
211 _source_port = _io->midi(0);
217 MidiDiskstream::find_and_use_playlist (const string& name)
219 boost::shared_ptr<MidiPlaylist> playlist;
221 if ((playlist = boost::dynamic_pointer_cast<MidiPlaylist> (_session.playlist_by_name (name))) == 0) {
222 playlist = boost::dynamic_pointer_cast<MidiPlaylist> (PlaylistFactory::create (DataType::MIDI, _session, name));
226 error << string_compose(_("MidiDiskstream: Playlist \"%1\" isn't an midi playlist"), name) << endmsg;
230 return use_playlist (playlist);
234 MidiDiskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
236 assert(boost::dynamic_pointer_cast<MidiPlaylist>(playlist));
238 Diskstream::use_playlist(playlist);
244 MidiDiskstream::use_new_playlist ()
247 boost::shared_ptr<MidiPlaylist> playlist;
249 if (!in_set_state && destructive()) {
254 newname = Playlist::bump_name (_playlist->name(), _session);
256 newname = Playlist::bump_name (_name, _session);
259 if ((playlist = boost::dynamic_pointer_cast<MidiPlaylist> (PlaylistFactory::create (
260 DataType::MIDI, _session, newname, hidden()))) != 0) {
262 playlist->set_orig_diskstream_id (id());
263 return use_playlist (playlist);
271 MidiDiskstream::use_copy_playlist ()
273 assert(midi_playlist());
279 if (_playlist == 0) {
280 error << string_compose(_("MidiDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
285 boost::shared_ptr<MidiPlaylist> playlist;
287 newname = Playlist::bump_name (_playlist->name(), _session);
289 if ((playlist = boost::dynamic_pointer_cast<MidiPlaylist>(PlaylistFactory::create (midi_playlist(), newname))) != 0) {
290 playlist->set_orig_diskstream_id (id());
291 return use_playlist (playlist);
297 /** Overloaded from parent to die horribly
300 MidiDiskstream::set_destructive (bool yn)
302 assert( ! destructive());
308 MidiDiskstream::set_note_mode (NoteMode m)
311 midi_playlist()->set_note_mode(m);
312 if (_write_source && _write_source->model())
313 _write_source->model()->set_note_mode(m);
317 MidiDiskstream::check_record_status (nframes_t transport_frame, nframes_t nframes, bool can_record)
319 // FIXME: waaay too much code to duplicate (AudioDiskstream)
321 int possibly_recording;
324 const int transport_rolling = 0x4;
325 const int track_rec_enabled = 0x2;
326 const int global_rec_enabled = 0x1;
328 /* merge together the 3 factors that affect record status, and compute
332 rolling = _session.transport_speed() != 0.0f;
333 possibly_recording = (rolling << 2) | (record_enabled() << 1) | can_record;
334 change = possibly_recording ^ last_possibly_recording;
336 if (possibly_recording == last_possibly_recording) {
342 /* if per-track or global rec-enable turned on while the other was already on, we've started recording */
344 if (((change & track_rec_enabled) && record_enabled() && (!(change & global_rec_enabled) && can_record)) ||
345 ((change & global_rec_enabled) && can_record && (!(change & track_rec_enabled) && record_enabled()))) {
347 /* starting to record: compute first+last frames */
349 first_recordable_frame = transport_frame + _capture_offset;
350 last_recordable_frame = max_frames;
351 capture_start_frame = transport_frame;
353 if (!(last_possibly_recording & transport_rolling) && (possibly_recording & transport_rolling)) {
355 /* was stopped, now rolling (and recording) */
357 if (_alignment_style == ExistingMaterial) {
358 first_recordable_frame += _session.worst_output_latency();
360 first_recordable_frame += _roll_delay;
365 /* was rolling, but record state changed */
367 if (_alignment_style == ExistingMaterial) {
370 if (!_session.config.get_punch_in()) {
372 /* manual punch in happens at the correct transport frame
373 because the user hit a button. but to get alignment correct
374 we have to back up the position of the new region to the
375 appropriate spot given the roll delay.
378 capture_start_frame -= _roll_delay;
380 /* XXX paul notes (august 2005): i don't know why
384 first_recordable_frame += _capture_offset;
388 /* autopunch toggles recording at the precise
389 transport frame, and then the DS waits
390 to start recording for a time that depends
391 on the output latency.
394 first_recordable_frame += _session.worst_output_latency();
399 if (_session.config.get_punch_in()) {
400 first_recordable_frame += _roll_delay;
402 capture_start_frame -= _roll_delay;
408 } else if (!record_enabled() || !can_record) {
412 last_recordable_frame = transport_frame + _capture_offset;
414 if (_alignment_style == ExistingMaterial) {
415 last_recordable_frame += _session.worst_output_latency();
417 last_recordable_frame += _roll_delay;
421 last_possibly_recording = possibly_recording;
426 trace_midi (ostream& o, MIDI::byte *msg, size_t len)
428 using namespace MIDI;
430 const char trace_prefix = ':';
432 type = (eventType) (msg[0]&0xF0);
439 << " NoteOff NoteNum "
450 << " NoteOn NoteNum "
466 case MIDI::controller:
481 << " Program Change ProgNum "
490 << " Channel Pressure "
495 case MIDI::pitchbend:
500 << ((msg[2]<<7)|msg[1])
539 << "System Exclusive (1 byte : " << hex << (int) *msg << dec << ')'
545 << "System Exclusive (" << len << ") = [ " << hex;
546 for (unsigned int i = 0; i < len; ++i) {
547 o << (int) msg[i] << ' ';
549 o << dec << ']' << endl;
555 o << trace_prefix << "Song" << endl;
559 o << trace_prefix << "Tune" << endl;
563 o << trace_prefix << "End-of-System Exclusive" << endl;
567 o << trace_prefix << "Timing" << endl;
571 o << trace_prefix << "Start" << endl;
575 o << trace_prefix << "Stop" << endl;
579 o << trace_prefix << "Continue" << endl;
583 o << trace_prefix << "Active Sense" << endl;
587 o << trace_prefix << "Unrecognized MIDI message" << endl;
594 MidiDiskstream::process (nframes_t transport_frame, nframes_t nframes, bool can_record, bool rec_monitors_input)
596 // FIXME: waay too much code to duplicate (AudioDiskstream::process)
598 nframes_t rec_offset = 0;
599 nframes_t rec_nframes = 0;
600 bool nominally_recording;
601 bool re = record_enabled ();
602 bool collect_playback = true;
604 /* if we've already processed the frames corresponding to this call,
605 just return. this allows multiple routes that are taking input
606 from this diskstream to call our ::process() method, but have
607 this stuff only happen once. more commonly, it allows both
608 the AudioTrack that is using this AudioDiskstream *and* the Session
609 to call process() without problems.
616 commit_should_unlock = false;
618 check_record_status (transport_frame, nframes, can_record);
620 nominally_recording = (can_record && re);
627 /* This lock is held until the end of ::commit, so these two functions
628 must always be called as a pair. The only exception is if this function
629 returns a non-zero value, in which case, ::commit should not be called.
632 // If we can't take the state lock return.
633 if (!state_lock.trylock()) {
636 commit_should_unlock = true;
637 adjust_capture_position = 0;
639 if (nominally_recording || (_session.get_record_enabled() && _session.config.get_punch_in())) {
642 ot = coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
649 case OverlapInternal:
650 /* ---------- recrange
653 rec_nframes = nframes;
658 /* |--------| recrange
661 rec_nframes = transport_frame + nframes - first_recordable_frame;
663 rec_offset = first_recordable_frame - transport_frame;
668 /* |--------| recrange
671 rec_nframes = last_recordable_frame - transport_frame;
675 case OverlapExternal:
676 /* |--------| recrange
677 -------------- transrange
679 rec_nframes = last_recordable_frame - last_recordable_frame;
680 rec_offset = first_recordable_frame - transport_frame;
684 if (rec_nframes && !was_recording) {
685 capture_captured = 0;
686 was_recording = true;
691 if (can_record && !_last_capture_regions.empty()) {
692 _last_capture_regions.clear ();
695 if (nominally_recording || rec_nframes) {
697 // Pump entire port buffer into the ring buffer (FIXME: split cycles?)
698 MidiBuffer& buf = _source_port->get_midi_buffer(nframes);
699 for (MidiBuffer::iterator i = buf.begin(); i != buf.end(); ++i) {
700 const Evoral::MIDIEvent<MidiBuffer::TimeType> ev(*i, false);
702 _capture_buf->write(ev.time() + transport_frame, ev.type(), ev.size(), ev.buffer());
708 finish_capture (rec_monitors_input);
715 /* data will be written to disk */
717 if (rec_nframes == nframes && rec_offset == 0) {
718 playback_distance = nframes;
721 adjust_capture_position = rec_nframes;
723 } else if (nominally_recording) {
725 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
727 playback_distance = nframes;
728 collect_playback = false;
732 if (collect_playback) {
734 /* we're doing playback */
736 nframes_t necessary_samples;
738 /* no varispeed playback if we're recording, because the output .... TBD */
740 if (rec_nframes == 0 && _actual_speed != 1.0f) {
741 necessary_samples = (nframes_t) floor ((nframes * fabs (_actual_speed))) + 1;
743 necessary_samples = nframes;
746 // Pump entire port buffer into playback buffer (FIXME: split cycles?)
747 MidiBuffer& buf = _source_port->get_midi_buffer(nframes);
748 for (MidiBuffer::iterator i = buf.begin(); i != buf.end(); ++i) {
749 const Evoral::MIDIEvent<MidiBuffer::TimeType> ev(*i, false);
751 _playback_buf->write(ev.time() + transport_frame, ev.type(), ev.size(), ev.buffer());
761 /* we're exiting with failure, so ::commit will not
762 be called. unlock the state lock.
765 commit_should_unlock = false;
773 MidiDiskstream::commit (nframes_t nframes)
775 bool need_butler = false;
777 if (_actual_speed < 0.0) {
778 playback_sample -= playback_distance;
780 playback_sample += playback_distance;
783 if (adjust_capture_position != 0) {
784 capture_captured += adjust_capture_position;
785 adjust_capture_position = 0;
788 uint32_t frames_read = g_atomic_int_get(&_frames_read_from_ringbuffer);
789 uint32_t frames_written = g_atomic_int_get(&_frames_written_to_ringbuffer);
790 if ((frames_written - frames_read) + nframes < midi_readahead) {
794 /*cerr << "MDS written: " << frames_written << " - read: " << frames_read <<
795 " = " << frames_written - frames_read
796 << " + " << nframes << " < " << midi_readahead << " = " << need_butler << ")" << endl;*/
798 if (commit_should_unlock) {
808 MidiDiskstream::set_pending_overwrite (bool yn)
810 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
812 pending_overwrite = yn;
814 overwrite_frame = playback_sample;
818 MidiDiskstream::overwrite_existing_buffers ()
820 //read(overwrite_frame, disk_io_chunk_frames, false);
821 overwrite_queued = false;
822 pending_overwrite = false;
828 MidiDiskstream::seek (nframes_t frame, bool complete_refill)
830 Glib::Mutex::Lock lm (state_lock);
833 _playback_buf->reset();
834 _capture_buf->reset();
835 g_atomic_int_set(&_frames_read_from_ringbuffer, 0);
836 g_atomic_int_set(&_frames_written_to_ringbuffer, 0);
838 playback_sample = frame;
841 if (complete_refill) {
842 while ((ret = do_refill_with_alloc ()) > 0) ;
844 ret = do_refill_with_alloc ();
851 MidiDiskstream::can_internal_playback_seek (nframes_t distance)
853 uint32_t frames_read = g_atomic_int_get(&_frames_read_from_ringbuffer);
854 uint32_t frames_written = g_atomic_int_get(&_frames_written_to_ringbuffer);
855 return ((frames_written - frames_read) < distance);
859 MidiDiskstream::internal_playback_seek (nframes_t distance)
861 cerr << "MDS: internal_playback_seek " << distance << endl;
863 first_recordable_frame += distance;
864 playback_sample += distance;
869 /** @a start is set to the new frame position (TIME) read up to */
871 MidiDiskstream::read (nframes_t& start, nframes_t dur, bool reversed)
873 nframes_t this_read = 0;
875 nframes_t loop_end = 0;
876 nframes_t loop_start = 0;
877 nframes_t loop_length = 0;
881 /* Make the use of a Location atomic for this read operation.
883 Note: Locations don't get deleted, so all we care about
884 when I say "atomic" is that we are always pointing to
885 the same one and using a start/length values obtained
889 if ((loc = loop_location) != 0) {
890 loop_start = loc->start();
891 loop_end = loc->end();
892 loop_length = loop_end - loop_start;
895 /* if we are looping, ensure that the first frame we read is at the correct
896 position within the loop.
899 if (loc && (start >= loop_end)) {
900 //cerr << "start adjusted from " << start;
901 start = loop_start + ((start - loop_start) % loop_length);
902 //cerr << "to " << start << endl;
904 //cerr << "start is " << start << " loopstart: " << loop_start << " loopend: " << loop_end << endl;
909 /* take any loop into account. we can't read past the end of the loop. */
911 if (loc && (loop_end - start < dur)) {
912 this_read = loop_end - start;
913 //cerr << "reloop true: thisread: " << this_read << " dur: " << dur << endl;
920 if (this_read == 0) {
924 this_read = min(dur,this_read);
926 if (midi_playlist()->read (*_playback_buf, start, this_read) != this_read) {
927 error << string_compose(
928 _("MidiDiskstream %1: cannot read %2 from playlist at frame %3"),
929 _id, this_read, start) << endmsg;
933 //cout << "MDS this read " << this_read << " start = " << start << endl;
934 g_atomic_int_add(&_frames_written_to_ringbuffer, this_read);
936 _read_data_count = _playlist->read_data_count();
940 // Swap note ons with note offs here. etc?
941 // Fully reversing MIDI requires look-ahead (well, behind) to find previous
942 // CC values etc. hard.
946 /* if we read to the end of the loop, go back to the beginning */
949 // Synthesize LoopEvent here, because the next events
950 // written will have non-monotonic timestamps.
951 _playback_buf->write(loop_end - 1, LoopEventType, 0, 0);
952 //cout << "Pushing LoopEvent ts=" << loop_end-1
953 // << " start+this_read " << start+this_read << endl;
962 //offset += this_read;
969 MidiDiskstream::do_refill_with_alloc ()
975 MidiDiskstream::do_refill ()
978 size_t write_space = _playback_buf->write_space();
979 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
981 if (write_space == 0) {
989 /* at end: nothing to do */
990 if (file_frame == max_frames) {
994 // At this point we...
995 assert(_playback_buf->write_space() > 0); // ... have something to write to, and
996 assert(file_frame <= max_frames); // ... something to write
998 // now calculate how much time is in the ringbuffer.
999 // and lets write as much as we need to get this to be midi_readahead;
1000 uint32_t frames_read = g_atomic_int_get(&_frames_read_from_ringbuffer);
1001 uint32_t frames_written = g_atomic_int_get(&_frames_written_to_ringbuffer);
1002 if ((frames_written - frames_read) >= midi_readahead) {
1003 //cout << "MDS Nothing to do. all fine" << endl;
1007 nframes_t to_read = midi_readahead - (frames_written - frames_read);
1009 //cout << "MDS read for midi_readahead " << to_read << " rb_contains: "
1010 // << frames_written - frames_read << endl;
1012 to_read = min(to_read, (max_frames - file_frame));
1014 if (read (file_frame, to_read, reversed)) {
1021 /** Flush pending data to disk.
1023 * Important note: this function will write *AT MOST* disk_io_chunk_frames
1024 * of data to disk. it will never write more than that. If it writes that
1025 * much and there is more than that waiting to be written, it will return 1,
1026 * otherwise 0 on success or -1 on failure.
1028 * If there is less than disk_io_chunk_frames to be written, no data will be
1029 * written at all unless @a force_flush is true.
1032 MidiDiskstream::do_flush (RunContext context, bool force_flush)
1038 _write_data_count = 0;
1040 total = _session.transport_frame() - _last_flush_frame;
1042 if (_last_flush_frame > _session.transport_frame()
1043 || _last_flush_frame < capture_start_frame) {
1044 _last_flush_frame = _session.transport_frame();
1047 if (total == 0 || _capture_buf->read_space() == 0
1048 || (!force_flush && (total < disk_io_chunk_frames && was_recording))) {
1052 /* if there are 2+ chunks of disk i/o possible for
1053 this track, let the caller know so that it can arrange
1054 for us to be called again, ASAP.
1056 if we are forcing a flush, then if there is* any* extra
1057 work, let the caller know.
1059 if we are no longer recording and there is any extra work,
1060 let the caller know too.
1063 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
1067 to_write = disk_io_chunk_frames;
1069 assert(!destructive());
1071 if (record_enabled()
1072 && ( (_session.transport_frame() - _last_flush_frame > disk_io_chunk_frames)
1074 if ((!_write_source) || _write_source->midi_write (*_capture_buf, capture_start_frame, to_write) != to_write) {
1075 error << string_compose(_("MidiDiskstream %1: cannot write to disk"), _id) << endmsg;
1078 _last_flush_frame = _session.transport_frame();
1087 MidiDiskstream::transport_stopped (struct tm& when, time_t twhen, bool abort_capture)
1089 uint32_t buffer_position;
1090 bool more_work = true;
1092 boost::shared_ptr<MidiRegion> region;
1093 nframes_t total_capture;
1094 MidiRegion::SourceList srcs;
1095 MidiRegion::SourceList::iterator src;
1096 vector<CaptureInfo*>::iterator ci;
1097 bool mark_write_completed = false;
1099 finish_capture (true);
1101 /* butler is already stopped, but there may be work to do
1102 to flush remaining data to disk.
1105 while (more_work && !err) {
1106 switch (do_flush (TransportContext, true)) {
1113 error << string_compose(_("MidiDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1118 /* XXX is there anything we can do if err != 0 ? */
1119 Glib::Mutex::Lock lm (capture_info_lock);
1121 if (capture_info.empty()) {
1125 if (abort_capture) {
1127 if (_write_source) {
1129 _write_source->mark_for_remove ();
1130 _write_source->drop_references ();
1131 _write_source.reset();
1134 /* new source set up in "out" below */
1138 assert(_write_source);
1140 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1141 total_capture += (*ci)->frames;
1144 /* figure out the name for this take */
1146 srcs.push_back (_write_source);
1147 _write_source->set_timeline_position (capture_info.front()->start);
1148 _write_source->set_captured_for (_name);
1150 string whole_file_region_name;
1151 whole_file_region_name = region_name_from_path (_write_source->name(), true);
1153 /* Register a new region with the Session that
1154 describes the entire source. Do this first
1155 so that any sub-regions will obviously be
1156 children of this one (later!)
1160 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, 0,
1161 total_capture, whole_file_region_name, 0,
1162 Region::Flag (Region::DefaultFlags|Region::Automatic|Region::WholeFile)));
1164 region = boost::dynamic_pointer_cast<MidiRegion> (rx);
1165 region->special_set_position (capture_info.front()->start);
1169 catch (failed_constructor& err) {
1170 error << string_compose(_("%1: could not create region for complete midi file"), _name) << endmsg;
1174 _last_capture_regions.push_back (region);
1176 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1178 XMLNode &before = _playlist->get_state();
1179 _playlist->freeze ();
1181 for (buffer_position = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1185 _session.region_name (region_name, _write_source->name(), false);
1187 // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->frames << " add a region\n";
1190 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, buffer_position, (*ci)->frames, region_name));
1191 region = boost::dynamic_pointer_cast<MidiRegion> (rx);
1194 catch (failed_constructor& err) {
1195 error << _("MidiDiskstream: could not create region for captured midi!") << endmsg;
1196 continue; /* XXX is this OK? */
1199 region->GoingAway.connect (bind (mem_fun (*this, &Diskstream::remove_region_from_last_capture), boost::weak_ptr<Region>(region)));
1201 _last_capture_regions.push_back (region);
1203 // cerr << "add new region, buffer position = " << buffer_position << " @ " << (*ci)->start << endl;
1205 i_am_the_modifier++;
1206 _playlist->add_region (region, (*ci)->start);
1207 i_am_the_modifier--;
1209 buffer_position += (*ci)->frames;
1213 XMLNode &after = _playlist->get_state();
1214 _session.add_command (new MementoCommand<Playlist>(*_playlist, &before, &after));
1218 mark_write_completed = true;
1220 reset_write_sources (mark_write_completed);
1222 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1226 capture_info.clear ();
1227 capture_start_frame = 0;
1231 MidiDiskstream::transport_looped (nframes_t transport_frame)
1233 if (was_recording) {
1235 // adjust the capture length knowing that the data will be recorded to disk
1236 // only necessary after the first loop where we're recording
1237 if (capture_info.size() == 0) {
1238 capture_captured += _capture_offset;
1240 if (_alignment_style == ExistingMaterial) {
1241 capture_captured += _session.worst_output_latency();
1243 capture_captured += _roll_delay;
1247 finish_capture (true);
1249 // the next region will start recording via the normal mechanism
1250 // we'll set the start position to the current transport pos
1251 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1252 capture_start_frame = transport_frame;
1253 first_recordable_frame = transport_frame; // mild lie
1254 last_recordable_frame = max_frames;
1255 was_recording = true;
1260 MidiDiskstream::finish_capture (bool rec_monitors_input)
1262 was_recording = false;
1264 if (capture_captured == 0) {
1268 // Why must we destroy?
1269 assert(!destructive());
1271 CaptureInfo* ci = new CaptureInfo;
1273 ci->start = capture_start_frame;
1274 ci->frames = capture_captured;
1276 /* XXX theoretical race condition here. Need atomic exchange ?
1277 However, the circumstances when this is called right
1278 now (either on record-disable or transport_stopped)
1279 mean that no actual race exists. I think ...
1280 We now have a capture_info_lock, but it is only to be used
1281 to synchronize in the transport_stop and the capture info
1282 accessors, so that invalidation will not occur (both non-realtime).
1285 // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1287 capture_info.push_back (ci);
1288 capture_captured = 0;
1292 MidiDiskstream::set_record_enabled (bool yn)
1294 if (!recordable() || !_session.record_enabling_legal()) {
1298 assert(!destructive());
1300 if (yn && _source_port == 0) {
1302 /* pick up connections not initiated *from* the IO object
1303 we're associated with.
1306 get_input_sources ();
1309 /* yes, i know that this not proof against race conditions, but its
1310 good enough. i think.
1313 if (record_enabled() != yn) {
1315 engage_record_enable ();
1317 disengage_record_enable ();
1323 MidiDiskstream::engage_record_enable ()
1325 bool rolling = _session.transport_speed() != 0.0f;
1327 g_atomic_int_set (&_record_enabled, 1);
1329 if (_source_port && Config->get_monitoring_model() == HardwareMonitoring) {
1330 _source_port->request_monitor_input (!(_session.config.get_auto_input() && rolling));
1333 // FIXME: Why is this necessary? Isn't needed for AudioDiskstream...
1335 use_new_write_source();
1337 _write_source->mark_streaming_midi_write_started (_note_mode, _session.transport_frame());
1339 RecordEnableChanged (); /* EMIT SIGNAL */
1343 MidiDiskstream::disengage_record_enable ()
1345 g_atomic_int_set (&_record_enabled, 0);
1346 if (_source_port && Config->get_monitoring_model() == HardwareMonitoring) {
1348 _source_port->request_monitor_input (false);
1352 RecordEnableChanged (); /* EMIT SIGNAL */
1356 MidiDiskstream::get_state ()
1358 XMLNode* node = new XMLNode ("MidiDiskstream");
1360 LocaleGuard lg (X_("POSIX"));
1362 snprintf (buf, sizeof(buf), "0x%x", _flags);
1363 node->add_property ("flags", buf);
1365 node->add_property("channel-mode", enum_2_string(get_channel_mode()));
1367 snprintf (buf, sizeof(buf), "0x%x", get_channel_mask());
1368 node->add_property("channel-mask", buf);
1370 node->add_property ("playlist", _playlist->name());
1372 snprintf (buf, sizeof(buf), "%f", _visible_speed);
1373 node->add_property ("speed", buf);
1375 node->add_property("name", _name);
1376 id().print(buf, sizeof(buf));
1377 node->add_property("id", buf);
1379 if (_write_source && _session.get_record_enabled()) {
1381 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1382 XMLNode* cs_grandchild;
1384 cs_grandchild = new XMLNode (X_("file"));
1385 cs_grandchild->add_property (X_("path"), _write_source->path());
1386 cs_child->add_child_nocopy (*cs_grandchild);
1388 /* store the location where capture will start */
1392 if (_session.config.get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1393 snprintf (buf, sizeof (buf), "%" PRIu32, pi->start());
1395 snprintf (buf, sizeof (buf), "%" PRIu32, _session.transport_frame());
1398 cs_child->add_property (X_("at"), buf);
1399 node->add_child_nocopy (*cs_child);
1403 node->add_child_copy (*_extra_xml);
1410 MidiDiskstream::set_state (const XMLNode& node)
1412 const XMLProperty* prop;
1413 XMLNodeList nlist = node.children();
1414 XMLNodeIterator niter;
1415 uint32_t nchans = 1;
1416 XMLNode* capture_pending_node = 0;
1417 LocaleGuard lg (X_("POSIX"));
1419 in_set_state = true;
1421 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1422 /*if ((*niter)->name() == IO::state_node_name) {
1423 deprecated_io_node = new XMLNode (**niter);
1425 assert ((*niter)->name() != IO::state_node_name);
1427 if ((*niter)->name() == X_("CapturingSources")) {
1428 capture_pending_node = *niter;
1432 /* prevent write sources from being created */
1434 in_set_state = true;
1436 if ((prop = node.property ("name")) != 0) {
1437 _name = prop->value();
1440 if ((prop = node.property ("id")) != 0) {
1441 _id = prop->value ();
1444 if ((prop = node.property ("flags")) != 0) {
1445 _flags = Flag (string_2_enum (prop->value(), _flags));
1448 ChannelMode channel_mode = AllChannels;
1449 if ((prop = node.property ("channel-mode")) != 0) {
1450 channel_mode = ChannelMode (string_2_enum(prop->value(), channel_mode));
1453 unsigned int channel_mask = 0xFFFF;
1454 if ((prop = node.property ("channel-mask")) != 0) {
1455 sscanf (prop->value().c_str(), "0x%x", &channel_mask);
1456 if (channel_mask & (~0xFFFF)) {
1457 warning << _("MidiDiskstream: XML property channel-mask out of range") << endmsg;
1461 set_channel_mode(channel_mode, channel_mask);
1463 if ((prop = node.property ("channels")) != 0) {
1464 nchans = atoi (prop->value().c_str());
1467 if ((prop = node.property ("playlist")) == 0) {
1472 bool had_playlist = (_playlist != 0);
1474 if (find_and_use_playlist (prop->value())) {
1478 if (!had_playlist) {
1479 _playlist->set_orig_diskstream_id (_id);
1482 if (capture_pending_node) {
1483 use_pending_capture_data (*capture_pending_node);
1488 if ((prop = node.property ("speed")) != 0) {
1489 double sp = atof (prop->value().c_str());
1491 if (realtime_set_speed (sp, false)) {
1492 non_realtime_set_speed ();
1496 in_set_state = false;
1498 /* make sure this is clear before we do anything else */
1501 //_capturing_source = 0;
1503 /* write sources are handled when we handle the input set
1504 up of the IO that owns this DS (::non_realtime_input_change())
1507 in_set_state = false;
1513 MidiDiskstream::use_new_write_source (uint32_t n)
1515 if (!recordable()) {
1521 if (_write_source) {
1523 if (_write_source->is_empty ()) {
1524 _write_source->mark_for_remove ();
1525 _write_source.reset();
1527 _write_source.reset();
1532 _write_source = boost::dynamic_pointer_cast<SMFSource>(_session.create_midi_source_for_session (*this));
1533 if (!_write_source) {
1534 throw failed_constructor();
1538 catch (failed_constructor &err) {
1539 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
1540 _write_source.reset();
1544 _write_source->set_allow_remove_if_empty (true);
1550 MidiDiskstream::reset_write_sources (bool mark_write_complete, bool force)
1552 if (!recordable()) {
1556 if (_write_source && mark_write_complete) {
1557 _write_source->mark_streaming_write_completed ();
1560 use_new_write_source (0);
1562 if (record_enabled()) {
1563 //_capturing_sources.push_back (_write_source);
1568 MidiDiskstream::rename_write_sources ()
1570 if (_write_source != 0) {
1571 _write_source->set_source_name (_name, destructive());
1572 /* XXX what to do if this fails ? */
1578 MidiDiskstream::set_block_size (nframes_t nframes)
1583 MidiDiskstream::allocate_temporary_buffers ()
1588 MidiDiskstream::monitor_input (bool yn)
1591 _source_port->ensure_monitor_input (yn);
1595 MidiDiskstream::set_align_style_from_io ()
1597 bool have_physical = false;
1603 get_input_sources ();
1605 if (_source_port && _source_port->flags() & JackPortIsPhysical) {
1606 have_physical = true;
1609 if (have_physical) {
1610 set_align_style (ExistingMaterial);
1612 set_align_style (CaptureTime);
1618 MidiDiskstream::playback_buffer_load () const
1620 return (float) ((double) _playback_buf->read_space()/
1621 (double) _playback_buf->capacity());
1625 MidiDiskstream::capture_buffer_load () const
1627 return (float) ((double) _capture_buf->write_space()/
1628 (double) _capture_buf->capacity());
1632 MidiDiskstream::use_pending_capture_data (XMLNode& node)
1637 /** Writes playback events in the given range to \a dst, translating time stamps
1638 * so that an event at \a start has time = 0
1641 MidiDiskstream::get_playback (MidiBuffer& dst, nframes_t start, nframes_t end)
1644 assert(dst.size() == 0);
1646 // Reverse. ... We just don't do reverse, ok? Back off.
1651 // Check only events added this offset cycle
1652 MidiBuffer::iterator this_cycle_start = dst.end();
1654 // Translates stamps to be relative to start
1656 _playback_buf->read(dst, start, end);
1658 const size_t events_read = _playback_buf->read(dst, start, end);
1659 cout << "MDS events read = " << events_read
1660 << " start = " << start << " end = " << end
1661 << " readspace " << _playback_buf->read_space()
1662 << " writespace " << _playback_buf->write_space() << endl;
1665 gint32 frames_read = end - start;
1666 g_atomic_int_add(&_frames_read_from_ringbuffer, frames_read);
1668 // Feed the data through the MidiStateTracker
1669 // If it detects a LoopEvent it will add necessary note offs
1670 if (_midi_state_tracker.track(this_cycle_start, dst.end())) {
1671 _midi_state_tracker.resolve_notes(dst, end-start - 1);