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"
38 #include "pbd/stateful_diff_command.h"
40 #include "ardour/ardour.h"
41 #include "ardour/audioengine.h"
42 #include "ardour/butler.h"
43 #include "ardour/configuration.h"
44 #include "ardour/cycle_timer.h"
45 #include "ardour/debug.h"
46 #include "ardour/io.h"
47 #include "ardour/midi_diskstream.h"
48 #include "ardour/midi_playlist.h"
49 #include "ardour/midi_port.h"
50 #include "ardour/midi_region.h"
51 #include "ardour/playlist_factory.h"
52 #include "ardour/region_factory.h"
53 #include "ardour/send.h"
54 #include "ardour/session.h"
55 #include "ardour/smf_source.h"
56 #include "ardour/utils.h"
57 #include "ardour/session_playlists.h"
58 #include "ardour/route.h"
60 #include "midi++/types.h"
66 using namespace ARDOUR;
69 framecnt_t MidiDiskstream::midi_readahead = 4096;
71 MidiDiskstream::MidiDiskstream (Session &sess, const string &name, Diskstream::Flag flag)
72 : Diskstream(sess, name, flag)
76 , _last_flush_frame(0)
77 , _note_mode(Sustained)
78 , _frames_written_to_ringbuffer(0)
79 , _frames_read_from_ringbuffer(0)
81 /* prevent any write sources from being created */
87 use_new_write_source (0);
91 assert(!destructive());
94 MidiDiskstream::MidiDiskstream (Session& sess, const XMLNode& node)
95 : Diskstream(sess, node)
99 , _last_flush_frame(0)
100 , _note_mode(Sustained)
101 , _frames_written_to_ringbuffer(0)
102 , _frames_read_from_ringbuffer(0)
108 if (set_state (node, Stateful::loading_state_version)) {
109 in_set_state = false;
110 throw failed_constructor();
113 use_new_write_source (0);
115 in_set_state = false;
119 MidiDiskstream::init ()
121 /* there are no channels at this point, so these
122 two calls just get speed_buffer_size and wrap_buffer
123 size setup without duplicating their code.
126 set_block_size (_session.get_block_size());
127 allocate_temporary_buffers ();
129 const size_t size = _session.butler()->midi_diskstream_buffer_size();
130 _playback_buf = new MidiRingBuffer<framepos_t>(size);
131 _capture_buf = new MidiRingBuffer<framepos_t>(size);
133 _n_channels = ChanCount(DataType::MIDI, 1);
135 assert(recordable());
138 MidiDiskstream::~MidiDiskstream ()
140 Glib::Mutex::Lock lm (state_lock);
145 MidiDiskstream::non_realtime_locate (framepos_t position)
148 _write_source->set_timeline_position (position);
150 seek(position, false);
155 MidiDiskstream::non_realtime_input_change ()
158 Glib::Mutex::Lock lm (state_lock);
160 if (input_change_pending.type == IOChange::NoChange) {
164 if (input_change_pending.type & IOChange::ConfigurationChanged) {
165 if (_io->n_ports().n_midi() != _n_channels.n_midi()) {
166 error << string_compose (_("%1: I/O configuration change %4 requested to use %2, but channel setup is %3"),
169 _n_channels, input_change_pending.type)
174 if (input_change_pending.type & IOChange::ConnectionsChanged) {
175 get_input_sources ();
176 set_capture_offset ();
177 set_align_style_from_io ();
180 input_change_pending.type = IOChange::NoChange;
182 /* implicit unlock */
185 /* unlike with audio, there is never any need to reset write sources
186 based on input configuration changes because ... a MIDI track
187 has just 1 MIDI port as input, always.
190 /* now refill channel buffers */
192 if (speed() != 1.0f || speed() != -1.0f) {
193 seek ((framepos_t) (_session.transport_frame() * (double) speed()));
196 seek (_session.transport_frame());
199 _last_flush_frame = _session.transport_frame();
203 MidiDiskstream::get_input_sources ()
205 uint32_t ni = _io->n_ports().n_midi();
211 // This is all we do for now at least
214 _source_port = _io->midi(0);
220 MidiDiskstream::find_and_use_playlist (const string& name)
222 boost::shared_ptr<MidiPlaylist> playlist;
224 if ((playlist = boost::dynamic_pointer_cast<MidiPlaylist> (_session.playlists->by_name (name))) == 0) {
225 playlist = boost::dynamic_pointer_cast<MidiPlaylist> (PlaylistFactory::create (DataType::MIDI, _session, name));
229 error << string_compose(_("MidiDiskstream: Playlist \"%1\" isn't an midi playlist"), name) << endmsg;
233 return use_playlist (playlist);
237 MidiDiskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
239 assert(boost::dynamic_pointer_cast<MidiPlaylist>(playlist));
241 Diskstream::use_playlist(playlist);
247 MidiDiskstream::use_new_playlist ()
250 boost::shared_ptr<MidiPlaylist> playlist;
252 if (!in_set_state && destructive()) {
257 newname = Playlist::bump_name (_playlist->name(), _session);
259 newname = Playlist::bump_name (_name, _session);
262 if ((playlist = boost::dynamic_pointer_cast<MidiPlaylist> (PlaylistFactory::create (
263 DataType::MIDI, _session, newname, hidden()))) != 0) {
265 playlist->set_orig_diskstream_id (id());
266 return use_playlist (playlist);
274 MidiDiskstream::use_copy_playlist ()
276 assert(midi_playlist());
282 if (_playlist == 0) {
283 error << string_compose(_("MidiDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
288 boost::shared_ptr<MidiPlaylist> playlist;
290 newname = Playlist::bump_name (_playlist->name(), _session);
292 if ((playlist = boost::dynamic_pointer_cast<MidiPlaylist>(PlaylistFactory::create (midi_playlist(), newname))) != 0) {
293 playlist->set_orig_diskstream_id (id());
294 return use_playlist (playlist);
300 /** Overloaded from parent to die horribly
303 MidiDiskstream::set_destructive (bool yn)
305 assert( ! destructive());
311 MidiDiskstream::set_note_mode (NoteMode m)
314 midi_playlist()->set_note_mode(m);
315 if (_write_source && _write_source->model())
316 _write_source->model()->set_note_mode(m);
321 trace_midi (ostream& o, MIDI::byte *msg, size_t len)
323 using namespace MIDI;
325 const char trace_prefix = ':';
327 type = (eventType) (msg[0]&0xF0);
334 << " NoteOff NoteNum "
345 << " NoteOn NoteNum "
361 case MIDI::controller:
376 << " Program Change ProgNum "
385 << " Channel Pressure "
390 case MIDI::pitchbend:
395 << ((msg[2]<<7)|msg[1])
434 << "System Exclusive (1 byte : " << hex << (int) *msg << dec << ')'
440 << "System Exclusive (" << len << ") = [ " << hex;
441 for (unsigned int i = 0; i < len; ++i) {
442 o << (int) msg[i] << ' ';
444 o << dec << ']' << endl;
450 o << trace_prefix << "Song" << endl;
454 o << trace_prefix << "Tune" << endl;
458 o << trace_prefix << "End-of-System Exclusive" << endl;
462 o << trace_prefix << "Timing" << endl;
466 o << trace_prefix << "Start" << endl;
470 o << trace_prefix << "Stop" << endl;
474 o << trace_prefix << "Continue" << endl;
478 o << trace_prefix << "Active Sense" << endl;
482 o << trace_prefix << "Unrecognized MIDI message" << endl;
489 MidiDiskstream::process (framepos_t transport_frame, pframes_t nframes, bool can_record, bool rec_monitors_input, bool& need_butler)
492 framecnt_t rec_offset = 0;
493 framecnt_t rec_nframes = 0;
494 bool nominally_recording;
495 bool re = record_enabled ();
497 playback_distance = 0;
499 check_record_status (transport_frame, can_record);
501 nominally_recording = (can_record && re);
507 Glib::Mutex::Lock sm (state_lock, Glib::TRY_LOCK);
513 adjust_capture_position = 0;
515 if (nominally_recording || (re && was_recording && _session.get_record_enabled() && _session.config.get_punch_in())) {
516 OverlapType ot = coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
518 calculate_record_range(ot, transport_frame, nframes, rec_nframes, rec_offset);
520 if (rec_nframes && !was_recording) {
521 _write_source->mark_write_starting_now ();
522 capture_captured = 0;
523 was_recording = true;
528 if (can_record && !_last_capture_sources.empty()) {
529 _last_capture_sources.clear ();
532 if (nominally_recording || rec_nframes) {
534 // Pump entire port buffer into the ring buffer (FIXME: split cycles?)
535 MidiBuffer& buf = _source_port->get_midi_buffer(nframes);
536 for (MidiBuffer::iterator i = buf.begin(); i != buf.end(); ++i) {
537 const Evoral::MIDIEvent<MidiBuffer::TimeType> ev(*i, false);
539 _capture_buf->write(ev.time() + transport_frame, ev.type(), ev.size(), ev.buffer());
542 if (buf.size() != 0) {
543 /* Make a copy of this data and emit it for the GUI to see */
544 boost::shared_ptr<MidiBuffer> copy (new MidiBuffer (buf.capacity ()));
545 for (MidiBuffer::iterator i = buf.begin(); i != buf.end(); ++i) {
546 copy->push_back ((*i).time() + transport_frame, (*i).size(), (*i).buffer());
549 DataRecorded (copy, _write_source); /* EMIT SIGNAL */
555 finish_capture (rec_monitors_input);
562 /* data will be written to disk */
564 if (rec_nframes == nframes && rec_offset == 0) {
565 playback_distance = nframes;
568 adjust_capture_position = rec_nframes;
570 } else if (nominally_recording) {
572 /* XXXX do this for MIDI !!!
573 can't do actual capture yet - waiting for latency effects to finish before we start
576 playback_distance = nframes;
580 /* XXX: should be doing varispeed stuff here, similar to the code in AudioDiskstream::process */
582 playback_distance = nframes;
588 if (commit (nframes)) {
596 MidiDiskstream::commit (framecnt_t nframes)
598 bool need_butler = false;
600 if (_actual_speed < 0.0) {
601 playback_sample -= playback_distance;
603 playback_sample += playback_distance;
606 if (adjust_capture_position != 0) {
607 capture_captured += adjust_capture_position;
608 adjust_capture_position = 0;
611 uint32_t frames_read = g_atomic_int_get(&_frames_read_from_ringbuffer);
612 uint32_t frames_written = g_atomic_int_get(&_frames_written_to_ringbuffer);
613 if ((frames_written - frames_read) + nframes < midi_readahead) {
617 /*cerr << "MDS written: " << frames_written << " - read: " << frames_read <<
618 " = " << frames_written - frames_read
619 << " + " << nframes << " < " << midi_readahead << " = " << need_butler << ")" << endl;*/
625 MidiDiskstream::set_pending_overwrite (bool yn)
627 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
629 _pending_overwrite = yn;
630 overwrite_frame = playback_sample;
634 MidiDiskstream::overwrite_existing_buffers ()
636 /* This is safe as long as the butler thread is suspended, which it should be */
637 _playback_buf->reset ();
639 g_atomic_int_set (&_frames_read_from_ringbuffer, 0);
640 g_atomic_int_set (&_frames_written_to_ringbuffer, 0);
642 read (overwrite_frame, disk_io_chunk_frames, false);
643 file_frame = overwrite_frame; // it was adjusted by ::read()
644 overwrite_queued = false;
645 _pending_overwrite = false;
651 MidiDiskstream::seek (framepos_t frame, bool complete_refill)
653 Glib::Mutex::Lock lm (state_lock);
656 _playback_buf->reset();
657 _capture_buf->reset();
658 g_atomic_int_set(&_frames_read_from_ringbuffer, 0);
659 g_atomic_int_set(&_frames_written_to_ringbuffer, 0);
661 playback_sample = frame;
664 if (complete_refill) {
665 while ((ret = do_refill_with_alloc ()) > 0) ;
667 ret = do_refill_with_alloc ();
674 MidiDiskstream::can_internal_playback_seek (framecnt_t distance)
676 uint32_t frames_read = g_atomic_int_get(&_frames_read_from_ringbuffer);
677 uint32_t frames_written = g_atomic_int_get(&_frames_written_to_ringbuffer);
678 return ((frames_written - frames_read) < distance);
682 MidiDiskstream::internal_playback_seek (framecnt_t distance)
684 first_recordable_frame += distance;
685 playback_sample += distance;
690 /** @a start is set to the new frame position (TIME) read up to */
692 MidiDiskstream::read (framepos_t& start, framecnt_t dur, bool reversed)
694 framecnt_t this_read = 0;
696 framepos_t loop_end = 0;
697 framepos_t loop_start = 0;
702 framecnt_t loop_length = 0;
704 /* Make the use of a Location atomic for this read operation.
706 Note: Locations don't get deleted, so all we care about
707 when I say "atomic" is that we are always pointing to
708 the same one and using a start/length values obtained
712 if ((loc = loop_location) != 0) {
713 loop_start = loc->start();
714 loop_end = loc->end();
715 loop_length = loop_end - loop_start;
718 /* if we are looping, ensure that the first frame we read is at the correct
719 position within the loop.
722 if (loc && (start >= loop_end)) {
723 //cerr << "start adjusted from " << start;
724 start = loop_start + ((start - loop_start) % loop_length);
725 //cerr << "to " << start << endl;
727 //cerr << "start is " << start << " loopstart: " << loop_start << " loopend: " << loop_end << endl;
732 /* take any loop into account. we can't read past the end of the loop. */
734 if (loc && (loop_end - start < dur)) {
735 this_read = loop_end - start;
736 //cerr << "reloop true: thisread: " << this_read << " dur: " << dur << endl;
743 if (this_read == 0) {
747 this_read = min(dur,this_read);
749 if (midi_playlist()->read (*_playback_buf, start, this_read) != this_read) {
750 error << string_compose(
751 _("MidiDiskstream %1: cannot read %2 from playlist at frame %3"),
752 _id, this_read, start) << endmsg;
756 g_atomic_int_add(&_frames_written_to_ringbuffer, this_read);
758 _read_data_count = _playlist->read_data_count();
762 // Swap note ons with note offs here. etc?
763 // Fully reversing MIDI requires look-ahead (well, behind) to find previous
764 // CC values etc. hard.
768 /* if we read to the end of the loop, go back to the beginning */
771 // Synthesize LoopEvent here, because the next events
772 // written will have non-monotonic timestamps.
773 _playback_buf->write(loop_end - 1, LoopEventType, sizeof (framepos_t), (uint8_t *) &loop_start);
781 //offset += this_read;
788 MidiDiskstream::do_refill_with_alloc ()
794 MidiDiskstream::do_refill ()
797 size_t write_space = _playback_buf->write_space();
798 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
800 if (write_space == 0) {
808 /* at end: nothing to do */
809 if (file_frame == max_framepos) {
813 // At this point we...
814 assert(_playback_buf->write_space() > 0); // ... have something to write to, and
815 assert(file_frame <= max_framepos); // ... something to write
817 // now calculate how much time is in the ringbuffer.
818 // and lets write as much as we need to get this to be midi_readahead;
819 uint32_t frames_read = g_atomic_int_get(&_frames_read_from_ringbuffer);
820 uint32_t frames_written = g_atomic_int_get(&_frames_written_to_ringbuffer);
821 if ((frames_written - frames_read) >= midi_readahead) {
825 framecnt_t to_read = midi_readahead - (frames_written - frames_read);
827 //cout << "MDS read for midi_readahead " << to_read << " rb_contains: "
828 // << frames_written - frames_read << endl;
830 to_read = (framecnt_t) min ((framecnt_t) to_read, (framecnt_t) (max_framepos - file_frame));
832 if (read (file_frame, to_read, reversed)) {
839 /** Flush pending data to disk.
841 * Important note: this function will write *AT MOST* disk_io_chunk_frames
842 * of data to disk. it will never write more than that. If it writes that
843 * much and there is more than that waiting to be written, it will return 1,
844 * otherwise 0 on success or -1 on failure.
846 * If there is less than disk_io_chunk_frames to be written, no data will be
847 * written at all unless @a force_flush is true.
850 MidiDiskstream::do_flush (RunContext /*context*/, bool force_flush)
856 _write_data_count = 0;
858 total = _session.transport_frame() - _last_flush_frame;
860 if (_last_flush_frame > _session.transport_frame() || _last_flush_frame < capture_start_frame) {
861 _last_flush_frame = _session.transport_frame();
864 if (total == 0 || _capture_buf->read_space() == 0
865 || (!force_flush && (total < disk_io_chunk_frames && was_recording))) {
869 /* if there are 2+ chunks of disk i/o possible for
870 this track, let the caller know so that it can arrange
871 for us to be called again, ASAP.
873 if we are forcing a flush, then if there is* any* extra
874 work, let the caller know.
876 if we are no longer recording and there is any extra work,
877 let the caller know too.
880 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
884 to_write = disk_io_chunk_frames;
886 assert(!destructive());
888 if (record_enabled() &&
889 ((_session.transport_frame() - _last_flush_frame > disk_io_chunk_frames) ||
891 if ((!_write_source) || _write_source->midi_write (*_capture_buf, get_capture_start_frame (0), to_write) != to_write) {
892 error << string_compose(_("MidiDiskstream %1: cannot write to disk"), _id) << endmsg;
895 _last_flush_frame = _session.transport_frame();
904 MidiDiskstream::transport_stopped_wallclock (struct tm& /*when*/, time_t /*twhen*/, bool abort_capture)
906 bool more_work = true;
908 boost::shared_ptr<MidiRegion> region;
909 MidiRegion::SourceList srcs;
910 MidiRegion::SourceList::iterator src;
911 vector<CaptureInfo*>::iterator ci;
912 bool mark_write_completed = false;
914 finish_capture (true);
916 /* butler is already stopped, but there may be work to do
917 to flush remaining data to disk.
920 while (more_work && !err) {
921 switch (do_flush (TransportContext, true)) {
928 error << string_compose(_("MidiDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
933 /* XXX is there anything we can do if err != 0 ? */
934 Glib::Mutex::Lock lm (capture_info_lock);
936 if (capture_info.empty()) {
943 _write_source->mark_for_remove ();
944 _write_source->drop_references ();
945 _write_source.reset();
948 /* new source set up in "out" below */
952 assert(_write_source);
954 framecnt_t total_capture = 0;
955 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
956 total_capture += (*ci)->frames;
959 if (_write_source->length (capture_info.front()->start) != 0) {
961 /* phew, we have data */
963 /* figure out the name for this take */
965 srcs.push_back (_write_source);
967 _write_source->set_timeline_position (capture_info.front()->start);
968 _write_source->set_captured_for (_name);
970 /* flush to disk: this step differs from the audio path,
971 where all the data is already on disk.
974 _write_source->mark_streaming_write_completed ();
976 /* set length in beats to entire capture length */
978 BeatsFramesConverter converter (_session.tempo_map(), capture_info.front()->start);
979 const double total_capture_beats = converter.from(total_capture);
980 _write_source->set_length_beats(total_capture_beats);
982 /* we will want to be able to keep (over)writing the source
983 but we don't want it to be removable. this also differs
984 from the audio situation, where the source at this point
985 must be considered immutable. luckily, we can rely on
986 MidiSource::mark_streaming_write_completed() to have
987 already done the necessary work for that.
990 string whole_file_region_name;
991 whole_file_region_name = region_name_from_path (_write_source->name(), true);
993 /* Register a new region with the Session that
994 describes the entire source. Do this first
995 so that any sub-regions will obviously be
996 children of this one (later!)
1002 plist.add (Properties::name, whole_file_region_name);
1003 plist.add (Properties::whole_file, true);
1004 plist.add (Properties::automatic, true);
1005 plist.add (Properties::start, 0);
1006 plist.add (Properties::length, total_capture);
1007 plist.add (Properties::layer, 0);
1009 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1011 region = boost::dynamic_pointer_cast<MidiRegion> (rx);
1012 region->special_set_position (capture_info.front()->start);
1016 catch (failed_constructor& err) {
1017 error << string_compose(_("%1: could not create region for complete midi file"), _name) << endmsg;
1021 _last_capture_sources.insert (_last_capture_sources.end(), srcs.begin(), srcs.end());
1023 _playlist->clear_changes ();
1024 _playlist->freeze ();
1026 /* Session frame time of the initial capture in this pass, which is where the source starts */
1027 framepos_t initial_capture = 0;
1028 if (!capture_info.empty()) {
1029 initial_capture = capture_info.front()->start;
1032 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1036 RegionFactory::region_name (region_name, _write_source->name(), false);
1038 // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->frames << " add a region\n";
1043 /* start of this region is the offset between the start of its capture and the start of the whole pass */
1044 plist.add (Properties::start, (*ci)->start - initial_capture);
1045 plist.add (Properties::length, (*ci)->frames);
1046 plist.add (Properties::length_beats, converter.from((*ci)->frames));
1047 plist.add (Properties::name, region_name);
1049 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1050 region = boost::dynamic_pointer_cast<MidiRegion> (rx);
1053 catch (failed_constructor& err) {
1054 error << _("MidiDiskstream: could not create region for captured midi!") << endmsg;
1055 continue; /* XXX is this OK? */
1058 // cerr << "add new region, buffer position = " << buffer_position << " @ " << (*ci)->start << endl;
1060 i_am_the_modifier++;
1061 _playlist->add_region (region, (*ci)->start);
1062 i_am_the_modifier--;
1066 _session.add_command (new StatefulDiffCommand(_playlist));
1070 /* No data was recorded, so this capture will
1071 effectively be aborted; do the same as we
1072 do for an explicit abort.
1075 if (_write_source) {
1076 _write_source->mark_for_remove ();
1077 _write_source->drop_references ();
1078 _write_source.reset();
1083 mark_write_completed = true;
1086 use_new_write_source (0);
1088 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1093 midi_playlist()->clear_note_trackers ();
1096 capture_info.clear ();
1097 capture_start_frame = 0;
1101 MidiDiskstream::transport_looped (framepos_t transport_frame)
1103 if (was_recording) {
1105 // adjust the capture length knowing that the data will be recorded to disk
1106 // only necessary after the first loop where we're recording
1107 if (capture_info.size() == 0) {
1108 capture_captured += _capture_offset;
1110 if (_alignment_style == ExistingMaterial) {
1111 capture_captured += _session.worst_output_latency();
1113 capture_captured += _roll_delay;
1117 finish_capture (true);
1119 // the next region will start recording via the normal mechanism
1120 // we'll set the start position to the current transport pos
1121 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1122 capture_start_frame = transport_frame;
1123 first_recordable_frame = transport_frame; // mild lie
1124 last_recordable_frame = max_framepos;
1125 was_recording = true;
1130 MidiDiskstream::finish_capture (bool /*rec_monitors_input*/)
1132 was_recording = false;
1134 if (capture_captured == 0) {
1138 // Why must we destroy?
1139 assert(!destructive());
1141 CaptureInfo* ci = new CaptureInfo;
1143 ci->start = capture_start_frame;
1144 ci->frames = capture_captured;
1146 /* XXX theoretical race condition here. Need atomic exchange ?
1147 However, the circumstances when this is called right
1148 now (either on record-disable or transport_stopped)
1149 mean that no actual race exists. I think ...
1150 We now have a capture_info_lock, but it is only to be used
1151 to synchronize in the transport_stop and the capture info
1152 accessors, so that invalidation will not occur (both non-realtime).
1155 // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1157 capture_info.push_back (ci);
1158 capture_captured = 0;
1162 MidiDiskstream::set_record_enabled (bool yn)
1164 if (!recordable() || !_session.record_enabling_legal()) {
1168 assert(!destructive());
1170 /* yes, i know that this not proof against race conditions, but its
1171 good enough. i think.
1174 if (record_enabled() != yn) {
1176 engage_record_enable ();
1178 disengage_record_enable ();
1184 MidiDiskstream::engage_record_enable ()
1186 bool const rolling = _session.transport_speed() != 0.0f;
1188 g_atomic_int_set (&_record_enabled, 1);
1190 if (_source_port && Config->get_monitoring_model() == HardwareMonitoring) {
1191 _source_port->request_monitor_input (!(_session.config.get_auto_input() && rolling));
1194 RecordEnableChanged (); /* EMIT SIGNAL */
1198 MidiDiskstream::disengage_record_enable ()
1200 g_atomic_int_set (&_record_enabled, 0);
1201 RecordEnableChanged (); /* EMIT SIGNAL */
1205 MidiDiskstream::get_state ()
1207 XMLNode& node (Diskstream::get_state());
1209 LocaleGuard lg (X_("POSIX"));
1211 node.add_property("channel-mode", enum_2_string(get_channel_mode()));
1212 snprintf (buf, sizeof(buf), "0x%x", get_channel_mask());
1213 node.add_property("channel-mask", buf);
1215 if (_write_source && _session.get_record_enabled()) {
1217 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1218 XMLNode* cs_grandchild;
1220 cs_grandchild = new XMLNode (X_("file"));
1221 cs_grandchild->add_property (X_("path"), _write_source->path());
1222 cs_child->add_child_nocopy (*cs_grandchild);
1224 /* store the location where capture will start */
1228 if (_session.config.get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1229 snprintf (buf, sizeof (buf), "%" PRId64, pi->start());
1231 snprintf (buf, sizeof (buf), "%" PRId64, _session.transport_frame());
1234 cs_child->add_property (X_("at"), buf);
1235 node.add_child_nocopy (*cs_child);
1242 MidiDiskstream::set_state (const XMLNode& node, int version)
1244 const XMLProperty* prop;
1245 XMLNodeList nlist = node.children();
1246 XMLNodeIterator niter;
1247 XMLNode* capture_pending_node = 0;
1248 LocaleGuard lg (X_("POSIX"));
1250 /* prevent write sources from being created */
1252 in_set_state = true;
1254 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1255 assert ((*niter)->name() != IO::state_node_name);
1257 if ((*niter)->name() == X_("CapturingSources")) {
1258 capture_pending_node = *niter;
1262 if (Diskstream::set_state (node, version)) {
1266 ChannelMode channel_mode = AllChannels;
1267 if ((prop = node.property ("channel-mode")) != 0) {
1268 channel_mode = ChannelMode (string_2_enum(prop->value(), channel_mode));
1271 unsigned int channel_mask = 0xFFFF;
1272 if ((prop = node.property ("channel-mask")) != 0) {
1273 sscanf (prop->value().c_str(), "0x%x", &channel_mask);
1274 if (channel_mask & (~0xFFFF)) {
1275 warning << _("MidiDiskstream: XML property channel-mask out of range") << endmsg;
1280 if (capture_pending_node) {
1281 use_pending_capture_data (*capture_pending_node);
1284 set_channel_mode (channel_mode, channel_mask);
1286 in_set_state = false;
1292 MidiDiskstream::use_new_write_source (uint32_t n)
1294 if (!_session.writable() || !recordable()) {
1300 _write_source.reset();
1303 _write_source = boost::dynamic_pointer_cast<SMFSource>(
1304 _session.create_midi_source_for_session (0, name ()));
1306 if (!_write_source) {
1307 throw failed_constructor();
1311 catch (failed_constructor &err) {
1312 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
1313 _write_source.reset();
1320 list<boost::shared_ptr<Source> >
1321 MidiDiskstream::steal_write_sources()
1323 list<boost::shared_ptr<Source> > ret;
1325 /* put some data on the disk, even if its just a header for an empty file.
1326 XXX should we not have a more direct method for doing this? Maybe not
1327 since we don't want to mess around with the model/disk relationship
1328 that the Source has to pay attention to.
1331 boost::dynamic_pointer_cast<MidiSource>(_write_source)->session_saved ();
1333 /* never let it go away */
1334 _write_source->mark_nonremovable ();
1336 ret.push_back (_write_source);
1340 use_new_write_source (0);
1346 MidiDiskstream::reset_write_sources (bool mark_write_complete, bool /*force*/)
1348 if (!_session.writable() || !recordable()) {
1352 if (_write_source && mark_write_complete) {
1353 _write_source->mark_streaming_write_completed ();
1355 use_new_write_source (0);
1359 MidiDiskstream::set_block_size (pframes_t /*nframes*/)
1364 MidiDiskstream::allocate_temporary_buffers ()
1369 MidiDiskstream::monitor_input (bool yn)
1372 _source_port->ensure_monitor_input (yn);
1376 MidiDiskstream::set_align_style_from_io ()
1378 bool have_physical = false;
1380 if (_alignment_choice != Automatic) {
1388 get_input_sources ();
1390 if (_source_port && _source_port->flags() & JackPortIsPhysical) {
1391 have_physical = true;
1394 if (have_physical) {
1395 set_align_style (ExistingMaterial);
1397 set_align_style (CaptureTime);
1403 MidiDiskstream::playback_buffer_load () const
1405 return (float) ((double) _playback_buf->read_space()/
1406 (double) _playback_buf->capacity());
1410 MidiDiskstream::capture_buffer_load () const
1412 return (float) ((double) _capture_buf->write_space()/
1413 (double) _capture_buf->capacity());
1417 MidiDiskstream::use_pending_capture_data (XMLNode& /*node*/)
1422 /** Writes playback events in the given range to \a dst, translating time stamps
1423 * so that an event at \a start has time = 0
1426 MidiDiskstream::get_playback (MidiBuffer& dst, framepos_t start, framepos_t end)
1429 assert(dst.size() == 0);
1431 // Reverse. ... We just don't do reverse, ok? Back off.
1436 // Translates stamps to be relative to start
1440 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("%1 MDS pre-read read from %2 write to %3\n",
1442 _playback_buf->get_read_ptr(), _playback_buf->get_write_ptr()));
1443 // cerr << "================\n";
1444 // _playback_buf->dump (cerr);
1445 // cerr << "----------------\n";
1447 const size_t events_read = _playback_buf->read(dst, start, end);
1448 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("%1 MDS events read %2 range %3 .. %4 rspace %5 wspace %6 r@%7 w@%8\n", _name, events_read, start, end,
1449 _playback_buf->read_space(), _playback_buf->write_space(),
1450 _playback_buf->get_read_ptr(), _playback_buf->get_write_ptr()));
1452 _playback_buf->read(dst, start, end);
1455 gint32 frames_read = end - start;
1456 g_atomic_int_add(&_frames_read_from_ringbuffer, frames_read);