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/midi_diskstream.h>
42 #include <ardour/utils.h>
43 #include <ardour/configuration.h>
44 #include <ardour/smf_source.h>
45 #include <ardour/send.h>
46 #include <ardour/region_factory.h>
47 #include <ardour/midi_playlist.h>
48 #include <ardour/playlist_factory.h>
49 #include <ardour/cycle_timer.h>
50 #include <ardour/midi_region.h>
51 #include <ardour/midi_port.h>
57 using namespace ARDOUR;
60 MidiDiskstream::MidiDiskstream (Session &sess, const string &name, Diskstream::Flag flag)
61 : Diskstream(sess, name, flag)
64 //, _current_playback_buffer(0)
65 //, _current_capture_buffer(0)
66 //, _playback_wrap_buffer(0)
67 //, _capture_wrap_buffer(0)
69 , _capture_transition_buf(0)
70 , _last_flush_frame(0)
72 /* prevent any write sources from being created */
81 assert(!destructive());
84 MidiDiskstream::MidiDiskstream (Session& sess, const XMLNode& node)
85 : Diskstream(sess, node)
88 //, _current_playback_buffer(0)
89 //, _current_capture_buffer(0)
90 //, _playback_wrap_buffer(0)
91 //, _capture_wrap_buffer(0)
93 , _capture_transition_buf(0)
94 , _last_flush_frame(0)
99 if (set_state (node)) {
100 in_set_state = false;
101 throw failed_constructor();
104 in_set_state = false;
107 use_destructive_playlist ();
112 MidiDiskstream::init (Diskstream::Flag f)
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.
121 set_block_size (_session.get_block_size());
122 allocate_temporary_buffers ();
124 _playback_buf = new MidiRingBuffer (_session.diskstream_buffer_size());
125 _capture_buf = new MidiRingBuffer (_session.diskstream_buffer_size());
126 _capture_transition_buf = new RingBufferNPT<CaptureTransition> (128);
128 _n_channels = ChanCount(DataType::MIDI, 1);
130 assert(recordable());
133 MidiDiskstream::~MidiDiskstream ()
135 Glib::Mutex::Lock lm (state_lock);
139 MidiDiskstream::non_realtime_input_change ()
142 Glib::Mutex::Lock lm (state_lock);
144 if (input_change_pending == NoChange) {
148 if (input_change_pending & ConfigurationChanged) {
149 assert(_io->n_inputs() == _n_channels);
152 get_input_sources ();
153 set_capture_offset ();
155 if (first_input_change) {
156 set_align_style (_persistent_alignment_style);
157 first_input_change = false;
159 set_align_style_from_io ();
162 input_change_pending = NoChange;
164 /* implicit unlock */
167 /* reset capture files */
169 reset_write_sources (false);
171 /* now refill channel buffers */
173 if (speed() != 1.0f || speed() != -1.0f) {
174 seek ((nframes_t) (_session.transport_frame() * (double) speed()));
177 seek (_session.transport_frame());
180 _last_flush_frame = _session.transport_frame();
184 MidiDiskstream::get_input_sources ()
186 uint32_t ni = _io->n_inputs().n_midi();
192 // This is all we do for now at least
195 _source_port = _io->midi_input(0);
197 /* I don't get it....
198 const char **connections = _io->input(0)->get_connections ();
200 if (connections == 0 || connections[0] == 0) {
203 // _source_port->disable_metering ();
209 _source_port = dynamic_cast<MidiPort*>(
210 _session.engine().get_port_by_name (connections[0]) );
219 MidiDiskstream::find_and_use_playlist (const string& name)
221 boost::shared_ptr<MidiPlaylist> playlist;
223 if ((playlist = boost::dynamic_pointer_cast<MidiPlaylist> (_session.playlist_by_name (name))) == 0) {
224 playlist = boost::dynamic_pointer_cast<MidiPlaylist> (PlaylistFactory::create (DataType::MIDI, _session, name));
228 error << string_compose(_("MidiDiskstream: Playlist \"%1\" isn't an midi playlist"), name) << endmsg;
232 return use_playlist (playlist);
236 MidiDiskstream::use_playlist (boost::shared_ptr<Playlist> playlist)
238 assert(boost::dynamic_pointer_cast<MidiPlaylist>(playlist));
240 Diskstream::use_playlist(playlist);
246 MidiDiskstream::use_new_playlist ()
249 boost::shared_ptr<MidiPlaylist> playlist;
251 if (!in_set_state && destructive()) {
256 newname = Playlist::bump_name (_playlist->name(), _session);
258 newname = Playlist::bump_name (_name, _session);
261 if ((playlist = boost::dynamic_pointer_cast<MidiPlaylist> (PlaylistFactory::create (
262 DataType::MIDI, _session, newname, hidden()))) != 0) {
264 playlist->set_orig_diskstream_id (id());
265 return use_playlist (playlist);
273 MidiDiskstream::use_copy_playlist ()
275 assert(midi_playlist());
281 if (_playlist == 0) {
282 error << string_compose(_("MidiDiskstream %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
287 boost::shared_ptr<MidiPlaylist> playlist;
289 newname = Playlist::bump_name (_playlist->name(), _session);
291 if ((playlist = boost::dynamic_pointer_cast<MidiPlaylist>(PlaylistFactory::create (midi_playlist(), newname))) != 0) {
292 playlist->set_orig_diskstream_id (id());
293 return use_playlist (playlist);
299 /** Overloaded from parent to die horribly
302 MidiDiskstream::set_destructive (bool yn)
304 assert( ! destructive());
310 MidiDiskstream::check_record_status (nframes_t transport_frame, nframes_t nframes, bool can_record)
312 // FIXME: waaay too much code to duplicate (AudioDiskstream)
314 int possibly_recording;
317 const int transport_rolling = 0x4;
318 const int track_rec_enabled = 0x2;
319 const int global_rec_enabled = 0x1;
321 /* merge together the 3 factors that affect record status, and compute
325 rolling = _session.transport_speed() != 0.0f;
326 possibly_recording = (rolling << 2) | (record_enabled() << 1) | can_record;
327 change = possibly_recording ^ last_possibly_recording;
329 if (possibly_recording == last_possibly_recording) {
335 /* if per-track or global rec-enable turned on while the other was already on, we've started recording */
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()))) {
340 /* starting to record: compute first+last frames */
342 first_recordable_frame = transport_frame + _capture_offset;
343 last_recordable_frame = max_frames;
344 capture_start_frame = transport_frame;
346 if (!(last_possibly_recording & transport_rolling) && (possibly_recording & transport_rolling)) {
348 /* was stopped, now rolling (and recording) */
350 if (_alignment_style == ExistingMaterial) {
351 first_recordable_frame += _session.worst_output_latency();
353 first_recordable_frame += _roll_delay;
358 /* was rolling, but record state changed */
360 if (_alignment_style == ExistingMaterial) {
363 if (!Config->get_punch_in()) {
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.
371 capture_start_frame -= _roll_delay;
373 /* XXX paul notes (august 2005): i don't know why
377 first_recordable_frame += _capture_offset;
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.
387 first_recordable_frame += _session.worst_output_latency();
392 if (Config->get_punch_in()) {
393 first_recordable_frame += _roll_delay;
395 capture_start_frame -= _roll_delay;
401 if (_flags & Recordable) {
402 RingBufferNPT<CaptureTransition>::rw_vector transvec;
403 _capture_transition_buf->get_write_vector(&transvec);
405 if (transvec.len[0] > 0) {
406 transvec.buf[0]->type = CaptureStart;
407 transvec.buf[0]->capture_val = capture_start_frame;
408 _capture_transition_buf->increment_write_ptr(1);
411 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
416 } else if (!record_enabled() || !can_record) {
420 last_recordable_frame = transport_frame + _capture_offset;
422 if (_alignment_style == ExistingMaterial) {
423 last_recordable_frame += _session.worst_output_latency();
425 last_recordable_frame += _roll_delay;
429 last_possibly_recording = possibly_recording;
433 MidiDiskstream::process (nframes_t transport_frame, nframes_t nframes, nframes_t offset, bool can_record, bool rec_monitors_input)
435 // FIXME: waay too much code to duplicate (AudioDiskstream::process)
437 nframes_t rec_offset = 0;
438 nframes_t rec_nframes = 0;
439 bool nominally_recording;
440 bool re = record_enabled ();
441 bool collect_playback = false;
443 /* if we've already processed the frames corresponding to this call,
444 just return. this allows multiple routes that are taking input
445 from this diskstream to call our ::process() method, but have
446 this stuff only happen once. more commonly, it allows both
447 the AudioTrack that is using this AudioDiskstream *and* the Session
448 to call process() without problems.
455 commit_should_unlock = false;
457 check_record_status (transport_frame, nframes, can_record);
459 nominally_recording = (can_record && re);
466 /* This lock is held until the end of AudioDiskstream::commit, so these two functions
467 must always be called as a pair. The only exception is if this function
468 returns a non-zero value, in which case, ::commit should not be called.
471 // If we can't take the state lock return.
472 if (!state_lock.trylock()) {
475 commit_should_unlock = true;
476 adjust_capture_position = 0;
478 if (nominally_recording || (_session.get_record_enabled() && Config->get_punch_in())) {
481 ot = coverage (first_recordable_frame, last_recordable_frame, transport_frame, transport_frame + nframes);
488 case OverlapInternal:
489 /* ---------- recrange
492 rec_nframes = nframes;
497 /* |--------| recrange
500 rec_nframes = transport_frame + nframes - first_recordable_frame;
502 rec_offset = first_recordable_frame - transport_frame;
507 /* |--------| recrange
510 rec_nframes = last_recordable_frame - transport_frame;
514 case OverlapExternal:
515 /* |--------| recrange
516 -------------- transrange
518 rec_nframes = last_recordable_frame - last_recordable_frame;
519 rec_offset = first_recordable_frame - transport_frame;
523 if (rec_nframes && !was_recording) {
524 capture_captured = 0;
525 was_recording = true;
530 if (can_record && !_last_capture_regions.empty()) {
531 _last_capture_regions.clear ();
534 if (nominally_recording || rec_nframes) {
536 assert(_source_port);
538 // Pump entire port buffer into the ring buffer (FIXME: split cycles?)
539 //_capture_buf->write(_source_port->get_midi_buffer(), transport_frame);
540 size_t num_events = _source_port->get_midi_buffer().size();
541 size_t to_write = std::min(_capture_buf->write_space(), num_events);
543 for (size_t i=0; i < to_write; ++i) {
544 MidiEvent& ev = _source_port->get_midi_buffer()[i];
545 _capture_buf->write(ev.time + transport_frame, ev.size, ev.buffer);
551 finish_capture (rec_monitors_input);
558 /* XXX XXX XXX XXX XXX XXX XXX XXX */
560 /* data will be written to disk */
562 if (rec_nframes == nframes && rec_offset == 0) {
564 playback_distance = nframes;
567 collect_playback = true;
570 adjust_capture_position = rec_nframes;
572 } else if (nominally_recording) {
574 /* can't do actual capture yet - waiting for latency effects to finish before we start*/
576 playback_distance = nframes;
580 collect_playback = true;
583 if (collect_playback) {
585 /* we're doing playback */
587 nframes_t necessary_samples;
589 /* no varispeed playback if we're recording, because the output .... TBD */
591 if (rec_nframes == 0 && _actual_speed != 1.0f) {
592 necessary_samples = (nframes_t) floor ((nframes * fabs (_actual_speed))) + 1;
594 necessary_samples = nframes;
597 // XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX
598 // Write into playback buffer here, and whatnot?
599 //cerr << "MDS FIXME: collect playback" << endl;
609 /* we're exiting with failure, so ::commit will not
610 be called. unlock the state lock.
613 commit_should_unlock = false;
621 MidiDiskstream::commit (nframes_t nframes)
623 bool need_butler = false;
625 if (_actual_speed < 0.0) {
626 playback_sample -= playback_distance;
628 playback_sample += playback_distance;
631 if (adjust_capture_position != 0) {
632 capture_captured += adjust_capture_position;
633 adjust_capture_position = 0;
637 need_butler = _playback_buf->write_space() >= _playback_buf->capacity() / 2;
639 need_butler = _playback_buf->write_space() >= disk_io_chunk_frames
640 || _capture_buf->read_space() >= disk_io_chunk_frames;
643 if (commit_should_unlock) {
653 MidiDiskstream::set_pending_overwrite (bool yn)
655 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
657 pending_overwrite = yn;
659 overwrite_frame = playback_sample;
660 //overwrite_offset = channels.front().playback_buf->get_read_ptr();
664 MidiDiskstream::overwrite_existing_buffers ()
670 MidiDiskstream::seek (nframes_t frame, bool complete_refill)
672 Glib::Mutex::Lock lm (state_lock);
675 _playback_buf->reset();
676 _capture_buf->reset();
678 playback_sample = frame;
681 if (complete_refill) {
682 while ((ret = do_refill_with_alloc ()) > 0) ;
684 ret = do_refill_with_alloc ();
691 MidiDiskstream::can_internal_playback_seek (nframes_t distance)
693 if (_playback_buf->read_space() < distance) {
701 MidiDiskstream::internal_playback_seek (nframes_t distance)
703 first_recordable_frame += distance;
704 playback_sample += distance;
709 /** @a start is set to the new frame position (TIME) read up to */
711 MidiDiskstream::read (nframes_t& start, nframes_t dur, bool reversed)
713 nframes_t this_read = 0;
715 nframes_t loop_end = 0;
716 nframes_t loop_start = 0;
717 nframes_t loop_length = 0;
721 /* Make the use of a Location atomic for this read operation.
723 Note: Locations don't get deleted, so all we care about
724 when I say "atomic" is that we are always pointing to
725 the same one and using a start/length values obtained
729 if ((loc = loop_location) != 0) {
730 loop_start = loc->start();
731 loop_end = loc->end();
732 loop_length = loop_end - loop_start;
735 /* if we are looping, ensure that the first frame we read is at the correct
736 position within the loop.
739 if (loc && start >= loop_end) {
740 //cerr << "start adjusted from " << start;
741 start = loop_start + ((start - loop_start) % loop_length);
742 //cerr << "to " << start << endl;
744 //cerr << "start is " << start << " loopstart: " << loop_start << " loopend: " << loop_end << endl;
749 /* take any loop into account. we can't read past the end of the loop. */
751 if (loc && (loop_end - start < dur)) {
752 this_read = loop_end - start;
753 //cerr << "reloop true: thisread: " << this_read << " dur: " << dur << endl;
760 if (this_read == 0) {
764 this_read = min(dur,this_read);
766 if (midi_playlist()->read (*_playback_buf, start, this_read) != this_read) {
767 error << string_compose(_("MidiDiskstream %1: cannot read %2 from playlist at frame %3"), _id, this_read,
772 _read_data_count = _playlist->read_data_count();
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.
782 /* if we read to the end of the loop, go back to the beginning */
792 //offset += this_read;
799 MidiDiskstream::do_refill_with_alloc ()
805 MidiDiskstream::do_refill ()
808 size_t write_space = _playback_buf->write_space();
810 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
812 if (write_space == 0) {
816 /* if there are 2+ chunks of disk i/o possible for
817 this track, let the caller know so that it can arrange
818 for us to be called again, ASAP.
821 // FIXME: using disk_io_chunk_frames as an event count, not good
822 // count vs duration semantic differences are nonexistant for audio,
823 // which makes translating for MIDI code confusing...
824 if (_playback_buf->write_space() >= (_slaved?3:2) * disk_io_chunk_frames) {
828 /* if we're running close to normal speed and there isn't enough
829 space to do disk_io_chunk_frames of I/O, then don't bother.
831 at higher speeds, just do it because the sync between butler
832 and audio thread may not be good enough.
835 if ((write_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
836 cerr << "No refill 1\n";
840 /* when slaved, don't try to get too close to the read pointer. this
841 leaves space for the buffer reversal to have something useful to
845 if (_slaved && write_space < (_playback_buf->capacity() / 2)) {
846 cerr << "No refill 2\n";
851 cerr << "No refill 3 (reverse)\n";
855 if (file_frame == max_frames) {
856 //cerr << "No refill 4 (EOF)\n";
858 /* at end: nothing to do */
865 if (file_frame > max_frames - total_space) {
867 /* to close to the end: read what we can, and zero fill the rest */
869 zero_fill = total_space - (max_frames - file_frame);
870 total_space = max_frames - file_frame;
878 assert(_playback_buf->write_space() > 0); // ... have something to write to, and
879 assert(file_frame <= max_frames); // ... something to write
881 // So (read it, then) write it:
883 nframes_t file_frame_tmp = file_frame;
884 nframes_t to_read = min(disk_io_chunk_frames, (max_frames - file_frame));
886 // FIXME: read count?
887 if (read (file_frame_tmp, to_read, reversed)) {
892 file_frame = file_frame_tmp;
899 /** Flush pending data to disk.
901 * Important note: this function will write *AT MOST* disk_io_chunk_frames
902 * of data to disk. it will never write more than that. If it writes that
903 * much and there is more than that waiting to be written, it will return 1,
904 * otherwise 0 on success or -1 on failure.
906 * If there is less than disk_io_chunk_frames to be written, no data will be
907 * written at all unless @a force_flush is true.
910 MidiDiskstream::do_flush (Session::RunContext context, bool force_flush)
914 // FIXME: I'd be lying if I said I knew what this thing was
915 //RingBufferNPT<CaptureTransition>::rw_vector transvec;
918 _write_data_count = 0;
920 if (_last_flush_frame > _session.transport_frame()
921 || _last_flush_frame < capture_start_frame) {
922 _last_flush_frame = _session.transport_frame();
925 total = _session.transport_frame() - _last_flush_frame;
927 if (total == 0 || _capture_buf->read_space() == 0 && _session.transport_speed() == 0 || (total < disk_io_chunk_frames && !force_flush && was_recording)) {
931 /* if there are 2+ chunks of disk i/o possible for
932 this track, let the caller know so that it can arrange
933 for us to be called again, ASAP.
935 if we are forcing a flush, then if there is* any* extra
936 work, let the caller know.
938 if we are no longer recording and there is any extra work,
939 let the caller know too.
942 if (total >= 2 * disk_io_chunk_frames || ((force_flush || !was_recording) && total > disk_io_chunk_frames)) {
946 //to_write = min (disk_io_chunk_frames, (nframes_t) vector.len[0]);
947 to_write = disk_io_chunk_frames;
949 assert(!destructive());
951 if (record_enabled() && _session.transport_frame() - _last_flush_frame > disk_io_chunk_frames) {
952 if ((!_write_source) || _write_source->write (*_capture_buf, to_write) != to_write) {
953 error << string_compose(_("MidiDiskstream %1: cannot write to disk"), _id) << endmsg;
956 _last_flush_frame = _session.transport_frame();
962 return 0; // FIXME: everything's fine! always! honest!
966 MidiDiskstream::transport_stopped (struct tm& when, time_t twhen, bool abort_capture)
968 uint32_t buffer_position;
969 bool more_work = true;
971 boost::shared_ptr<MidiRegion> region;
972 nframes_t total_capture;
973 MidiRegion::SourceList srcs;
974 MidiRegion::SourceList::iterator src;
975 vector<CaptureInfo*>::iterator ci;
976 bool mark_write_completed = false;
978 finish_capture (true);
980 /* butler is already stopped, but there may be work to do
981 to flush remaining data to disk.
984 while (more_work && !err) {
985 switch (do_flush (Session::TransportContext, true)) {
992 error << string_compose(_("MidiDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
997 /* XXX is there anything we can do if err != 0 ? */
998 Glib::Mutex::Lock lm (capture_info_lock);
1000 if (capture_info.empty()) {
1004 if (abort_capture) {
1006 if (_write_source) {
1008 _write_source->mark_for_remove ();
1009 _write_source->drop_references ();
1010 _write_source.reset();
1013 /* new source set up in "out" below */
1017 assert(_write_source);
1019 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1020 total_capture += (*ci)->frames;
1023 /* figure out the name for this take */
1025 srcs.push_back (_write_source);
1026 _write_source->update_header (capture_info.front()->start, when, twhen);
1027 _write_source->set_captured_for (_name);
1029 string whole_file_region_name;
1030 whole_file_region_name = region_name_from_path (_write_source->name(), true);
1032 /* Register a new region with the Session that
1033 describes the entire source. Do this first
1034 so that any sub-regions will obviously be
1035 children of this one (later!)
1039 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, _write_source->last_capture_start_frame(), total_capture,
1040 whole_file_region_name,
1041 0, Region::Flag (Region::DefaultFlags|Region::Automatic|Region::WholeFile)));
1043 region = boost::dynamic_pointer_cast<MidiRegion> (rx);
1044 region->special_set_position (capture_info.front()->start);
1048 catch (failed_constructor& err) {
1049 error << string_compose(_("%1: could not create region for complete midi file"), _name) << endmsg;
1053 _last_capture_regions.push_back (region);
1055 // cerr << _name << ": there are " << capture_info.size() << " capture_info records\n";
1057 XMLNode &before = _playlist->get_state();
1058 _playlist->freeze ();
1060 for (buffer_position = _write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1064 _session.region_name (region_name, _write_source->name(), false);
1066 // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->frames << " add a region\n";
1069 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, buffer_position, (*ci)->frames, region_name));
1070 region = boost::dynamic_pointer_cast<MidiRegion> (rx);
1073 catch (failed_constructor& err) {
1074 error << _("MidiDiskstream: could not create region for captured midi!") << endmsg;
1075 continue; /* XXX is this OK? */
1078 region->GoingAway.connect (bind (mem_fun (*this, &Diskstream::remove_region_from_last_capture), boost::weak_ptr<Region>(region)));
1080 _last_capture_regions.push_back (region);
1082 // cerr << "add new region, buffer position = " << buffer_position << " @ " << (*ci)->start << endl;
1084 i_am_the_modifier++;
1085 _playlist->add_region (region, (*ci)->start);
1086 i_am_the_modifier--;
1088 buffer_position += (*ci)->frames;
1092 XMLNode &after = _playlist->get_state();
1093 _session.add_command (new MementoCommand<Playlist>(*_playlist, &before, &after));
1097 mark_write_completed = true;
1099 reset_write_sources (mark_write_completed);
1101 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1105 capture_info.clear ();
1106 capture_start_frame = 0;
1110 MidiDiskstream::transport_looped (nframes_t transport_frame)
1112 if (was_recording) {
1114 // adjust the capture length knowing that the data will be recorded to disk
1115 // only necessary after the first loop where we're recording
1116 if (capture_info.size() == 0) {
1117 capture_captured += _capture_offset;
1119 if (_alignment_style == ExistingMaterial) {
1120 capture_captured += _session.worst_output_latency();
1122 capture_captured += _roll_delay;
1126 finish_capture (true);
1128 // the next region will start recording via the normal mechanism
1129 // we'll set the start position to the current transport pos
1130 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1131 capture_start_frame = transport_frame;
1132 first_recordable_frame = transport_frame; // mild lie
1133 last_recordable_frame = max_frames;
1134 was_recording = true;
1139 MidiDiskstream::finish_capture (bool rec_monitors_input)
1141 was_recording = false;
1143 if (capture_captured == 0) {
1147 // Why must we destroy?
1148 assert(!destructive());
1150 CaptureInfo* ci = new CaptureInfo;
1152 ci->start = capture_start_frame;
1153 ci->frames = capture_captured;
1155 /* XXX theoretical race condition here. Need atomic exchange ?
1156 However, the circumstances when this is called right
1157 now (either on record-disable or transport_stopped)
1158 mean that no actual race exists. I think ...
1159 We now have a capture_info_lock, but it is only to be used
1160 to synchronize in the transport_stop and the capture info
1161 accessors, so that invalidation will not occur (both non-realtime).
1164 // cerr << "Finish capture, add new CI, " << ci->start << '+' << ci->frames << endl;
1166 capture_info.push_back (ci);
1167 capture_captured = 0;
1171 MidiDiskstream::set_record_enabled (bool yn)
1173 if (!recordable() || !_session.record_enabling_legal()) {
1177 assert(!destructive());
1179 if (yn && _source_port == 0) {
1181 /* pick up connections not initiated *from* the IO object
1182 we're associated with.
1185 get_input_sources ();
1188 /* yes, i know that this not proof against race conditions, but its
1189 good enough. i think.
1192 if (record_enabled() != yn) {
1194 engage_record_enable ();
1196 disengage_record_enable ();
1202 MidiDiskstream::engage_record_enable ()
1204 bool rolling = _session.transport_speed() != 0.0f;
1206 g_atomic_int_set (&_record_enabled, 1);
1208 if (_source_port && Config->get_monitoring_model() == HardwareMonitoring) {
1209 _source_port->request_monitor_input (!(Config->get_auto_input() && rolling));
1212 RecordEnableChanged (); /* EMIT SIGNAL */
1216 MidiDiskstream::disengage_record_enable ()
1218 g_atomic_int_set (&_record_enabled, 0);
1219 if (_source_port && Config->get_monitoring_model() == HardwareMonitoring) {
1221 _source_port->request_monitor_input (false);
1225 RecordEnableChanged (); /* EMIT SIGNAL */
1229 MidiDiskstream::get_state ()
1231 XMLNode* node = new XMLNode ("MidiDiskstream");
1233 LocaleGuard lg (X_("POSIX"));
1235 snprintf (buf, sizeof(buf), "0x%x", _flags);
1236 node->add_property ("flags", buf);
1238 node->add_property ("playlist", _playlist->name());
1240 snprintf (buf, sizeof(buf), "%f", _visible_speed);
1241 node->add_property ("speed", buf);
1243 node->add_property("name", _name);
1244 id().print(buf, sizeof(buf));
1245 node->add_property("id", buf);
1247 if (_write_source && _session.get_record_enabled()) {
1249 XMLNode* cs_child = new XMLNode (X_("CapturingSources"));
1250 XMLNode* cs_grandchild;
1252 cs_grandchild = new XMLNode (X_("file"));
1253 cs_grandchild->add_property (X_("path"), _write_source->path());
1254 cs_child->add_child_nocopy (*cs_grandchild);
1256 /* store the location where capture will start */
1260 if (Config->get_punch_in() && ((pi = _session.locations()->auto_punch_location()) != 0)) {
1261 snprintf (buf, sizeof (buf), "%" PRIu32, pi->start());
1263 snprintf (buf, sizeof (buf), "%" PRIu32, _session.transport_frame());
1266 cs_child->add_property (X_("at"), buf);
1267 node->add_child_nocopy (*cs_child);
1271 node->add_child_copy (*_extra_xml);
1278 MidiDiskstream::set_state (const XMLNode& node)
1280 const XMLProperty* prop;
1281 XMLNodeList nlist = node.children();
1282 XMLNodeIterator niter;
1283 uint32_t nchans = 1;
1284 XMLNode* capture_pending_node = 0;
1285 LocaleGuard lg (X_("POSIX"));
1287 in_set_state = true;
1289 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1290 /*if ((*niter)->name() == IO::state_node_name) {
1291 deprecated_io_node = new XMLNode (**niter);
1293 assert ((*niter)->name() != IO::state_node_name);
1295 if ((*niter)->name() == X_("CapturingSources")) {
1296 capture_pending_node = *niter;
1300 /* prevent write sources from being created */
1302 in_set_state = true;
1304 if ((prop = node.property ("name")) != 0) {
1305 _name = prop->value();
1308 if ((prop = node.property ("id")) != 0) {
1309 _id = prop->value ();
1312 if ((prop = node.property ("flags")) != 0) {
1313 _flags = Flag (string_2_enum (prop->value(), _flags));
1316 if ((prop = node.property ("channels")) != 0) {
1317 nchans = atoi (prop->value().c_str());
1320 if ((prop = node.property ("playlist")) == 0) {
1325 bool had_playlist = (_playlist != 0);
1327 if (find_and_use_playlist (prop->value())) {
1331 if (!had_playlist) {
1332 _playlist->set_orig_diskstream_id (_id);
1335 if (capture_pending_node) {
1336 use_pending_capture_data (*capture_pending_node);
1341 if ((prop = node.property ("speed")) != 0) {
1342 double sp = atof (prop->value().c_str());
1344 if (realtime_set_speed (sp, false)) {
1345 non_realtime_set_speed ();
1349 in_set_state = false;
1351 /* make sure this is clear before we do anything else */
1354 //_capturing_source = 0;
1356 /* write sources are handled when we handle the input set
1357 up of the IO that owns this DS (::non_realtime_input_change())
1360 in_set_state = false;
1366 MidiDiskstream::use_new_write_source (uint32_t n)
1368 if (!recordable()) {
1374 if (_write_source) {
1376 if (SMFSource::is_empty (_write_source->path())) {
1377 _write_source->mark_for_remove ();
1378 _write_source.reset();
1380 _write_source.reset();
1385 _write_source = boost::dynamic_pointer_cast<SMFSource>(_session.create_midi_source_for_session (*this));
1386 if (!_write_source) {
1387 throw failed_constructor();
1391 catch (failed_constructor &err) {
1392 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
1393 _write_source.reset();
1397 _write_source->set_allow_remove_if_empty (true);
1403 MidiDiskstream::reset_write_sources (bool mark_write_complete, bool force)
1405 if (!recordable()) {
1409 if (_write_source && mark_write_complete) {
1410 _write_source->mark_streaming_write_completed ();
1412 use_new_write_source (0);
1414 if (record_enabled()) {
1415 //_capturing_sources.push_back (_write_source);
1420 MidiDiskstream::rename_write_sources ()
1422 if (_write_source != 0) {
1423 _write_source->set_source_name (_name, destructive());
1424 /* XXX what to do if this fails ? */
1430 MidiDiskstream::set_block_size (nframes_t nframes)
1435 MidiDiskstream::allocate_temporary_buffers ()
1440 MidiDiskstream::monitor_input (bool yn)
1443 _source_port->request_monitor_input (yn);
1445 cerr << "MidiDiskstream NO SOURCE PORT TO MONITOR\n";
1449 MidiDiskstream::set_align_style_from_io ()
1451 bool have_physical = false;
1457 get_input_sources ();
1459 if (_source_port && _source_port->flags() & JackPortIsPhysical) {
1460 have_physical = true;
1463 if (have_physical) {
1464 set_align_style (ExistingMaterial);
1466 set_align_style (CaptureTime);
1472 MidiDiskstream::playback_buffer_load () const
1474 return (float) ((double) _playback_buf->read_space()/
1475 (double) _playback_buf->capacity());
1479 MidiDiskstream::capture_buffer_load () const
1481 return (float) ((double) _capture_buf->write_space()/
1482 (double) _capture_buf->capacity());
1487 MidiDiskstream::use_pending_capture_data (XMLNode& node)
1492 /** Writes playback events in the given range to \a dst, translating time stamps
1493 * so that an event at \a start has time = 0
1496 MidiDiskstream::get_playback(MidiBuffer& dst, nframes_t start, nframes_t end)
1499 assert(dst.size() == 0);
1501 // Reverse. ... We just don't do reverse, ok? Back off.
1506 // Translates stamps to be relative to start
1507 _playback_buf->read(dst, start, end);