fix assumption that Session::_mmc != 0
[ardour2.git] / libs / ardour / session_midi.cc
blob425c12db6cc2c69399d4862ede5decfea7e7b578
2 /*
3 Copyright (C) 1999-2002 Paul Davis
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 #include <string>
22 #include <cmath>
23 #include <cerrno>
24 #include <cassert>
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <poll.h>
29 #include <boost/shared_ptr.hpp>
31 #include <glibmm/main.h>
33 #include "midi++/mmc.h"
34 #include "midi++/port.h"
35 #include "midi++/manager.h"
36 #include "pbd/error.h"
37 #include "pbd/pthread_utils.h"
39 #include "ardour/configuration.h"
40 #include "ardour/debug.h"
41 #include "ardour/audioengine.h"
42 #include "ardour/session.h"
43 #include "ardour/audio_track.h"
44 #include "ardour/midi_track.h"
45 #include "ardour/midi_ui.h"
46 #include "ardour/audio_diskstream.h"
47 #include "ardour/slave.h"
48 #include "ardour/cycles.h"
49 #include "ardour/timecode.h"
51 #include "i18n.h"
53 using namespace std;
54 using namespace ARDOUR;
55 using namespace PBD;
56 using namespace MIDI;
57 using namespace Glib;
59 void
60 Session::midi_panic()
63 boost::shared_ptr<RouteList> r = routes.reader ();
65 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
66 MidiTrack *track = dynamic_cast<MidiTrack*>((*i).get());
67 if (track != 0) {
68 track->midi_panic();
74 int
75 Session::use_config_midi_ports ()
77 string port_name;
79 if (default_mtc_port) {
80 set_mtc_port (default_mtc_port->name());
81 } else {
82 set_mtc_port ("");
85 if (default_midi_port) {
86 set_midi_port (default_midi_port->name());
87 } else {
88 set_midi_port ("");
91 if (default_midi_clock_port) {
92 set_midi_clock_port (default_midi_clock_port->name());
93 } else {
94 set_midi_clock_port ("");
97 return 0;
101 /***********************************************************************
102 MTC, MMC, etc.
103 **********************************************************************/
106 Session::set_mtc_port (string port_tag)
108 MTC_Slave *ms;
110 if (port_tag.length() == 0) {
112 if (_slave && ((ms = dynamic_cast<MTC_Slave*> (_slave)) != 0)) {
113 error << string_compose (_("%1 is slaved to MTC - port cannot be reset"), PROGRAM_NAME) << endmsg;
114 return -1;
117 if (_mtc_port == 0) {
118 return 0;
121 _mtc_port = 0;
122 goto out;
125 MIDI::Port* port;
127 if ((port = MIDI::Manager::instance()->port (port_tag)) == 0) {
128 error << string_compose (_("unknown port %1 requested for MTC"), port_tag) << endl;
129 return -1;
132 _mtc_port = port;
134 if (_slave && ((ms = dynamic_cast<MTC_Slave*> (_slave)) != 0)) {
135 ms->rebind (*port);
138 Config->set_mtc_port_name (port_tag);
140 out:
141 MTC_PortChanged(); /* EMIT SIGNAL */
142 set_dirty();
143 return 0;
147 Session::set_midi_port (string /*port_tag*/)
149 #if 0
150 if (port_tag.length() == 0) {
151 if (_midi_port == 0) {
152 return 0;
154 _midi_port = 0;
155 goto out;
158 MIDI::Port* port;
160 if ((port = MIDI::Manager::instance()->port (port_tag)) == 0) {
161 return -1;
164 _midi_port = port;
166 /* XXX need something to forward this to control protocols ? or just
167 use the signal below
170 Config->set_midi_port_name (port_tag);
172 out:
173 #endif
174 MIDI_PortChanged(); /* EMIT SIGNAL */
175 set_dirty();
176 return 0;
180 Session::set_midi_clock_port (string port_tag)
182 MIDIClock_Slave *ms;
184 if (port_tag.length() == 0) {
186 if (_slave && ((ms = dynamic_cast<MIDIClock_Slave*> (_slave)) != 0)) {
187 error << string_compose (_("%1 is slaved to MIDI Clock - port cannot be reset"), PROGRAM_NAME) << endmsg;
188 return -1;
191 if (_midi_clock_port == 0) {
192 return 0;
195 _midi_clock_port = 0;
196 goto out;
199 MIDI::Port* port;
201 if ((port = MIDI::Manager::instance()->port (port_tag)) == 0) {
202 error << string_compose (_("unknown port %1 requested for MIDI Clock"), port_tag) << endl;
203 return -1;
206 _midi_clock_port = port;
208 if (_slave && ((ms = dynamic_cast<MIDIClock_Slave*> (_slave)) != 0)) {
209 ms->rebind (*port);
212 Config->set_midi_clock_port_name (port_tag);
214 out:
215 MIDIClock_PortChanged(); /* EMIT SIGNAL */
216 set_dirty();
217 return 0;
220 void
221 Session::set_trace_midi_input (bool yn, MIDI::Port* port)
223 MIDI::Parser* input_parser;
225 cerr << "enabling tracing: " << yn << " for input port " << port->name() << endl;
227 if (port) {
228 if ((input_parser = port->input()) != 0) {
229 input_parser->trace (yn, &cout, "input: ");
231 } else {
233 if (_mmc && _mmc->port()) {
234 if ((input_parser = _mmc->port()->input()) != 0) {
235 input_parser->trace (yn, &cout, "input: ");
239 if (_mtc_port && (!_mmc || (_mtc_port != _mmc->port()))) {
240 if ((input_parser = _mtc_port->input()) != 0) {
241 input_parser->trace (yn, &cout, "input: ");
245 if (_midi_port && (!_mmc || (_midi_port != _mmc->port())) && _midi_port != _mtc_port ) {
246 if ((input_parser = _midi_port->input()) != 0) {
247 input_parser->trace (yn, &cout, "input: ");
251 if (_midi_clock_port
252 && (!_mmc || (_midi_clock_port != _mmc->port()))
253 && _midi_clock_port != _mtc_port
254 && _midi_clock_port != _midi_port) {
255 if ((input_parser = _midi_clock_port->input()) != 0) {
256 input_parser->trace (yn, &cout, "input: ");
261 Config->set_trace_midi_input (yn);
264 void
265 Session::set_trace_midi_output (bool yn, MIDI::Port* port)
267 MIDI::Parser* output_parser;
269 if (port) {
270 if ((output_parser = port->output()) != 0) {
271 output_parser->trace (yn, &cout, "output: ");
273 } else {
274 if (_mmc && _mmc->port()) {
275 if ((output_parser = _mmc->port()->output()) != 0) {
276 output_parser->trace (yn, &cout, "output: ");
280 if (_mtc_port && _mtc_port != _mmc->port()) {
281 if ((output_parser = _mtc_port->output()) != 0) {
282 output_parser->trace (yn, &cout, "output: ");
286 if (_midi_port && (!_mmc || (_midi_port != _mmc->port())) && _midi_port != _mtc_port ) {
287 if ((output_parser = _midi_port->output()) != 0) {
288 output_parser->trace (yn, &cout, "output: ");
294 Config->set_trace_midi_output (yn);
297 bool
298 Session::get_trace_midi_input(MIDI::Port *port)
300 MIDI::Parser* input_parser;
301 if (port) {
302 if ((input_parser = port->input()) != 0) {
303 return input_parser->tracing();
306 else {
307 if (_mmc && _mmc->port()) {
308 if ((input_parser = _mmc->port()->input()) != 0) {
309 return input_parser->tracing();
313 if (_mtc_port) {
314 if ((input_parser = _mtc_port->input()) != 0) {
315 return input_parser->tracing();
319 if (_midi_port) {
320 if ((input_parser = _midi_port->input()) != 0) {
321 return input_parser->tracing();
326 return false;
329 bool
330 Session::get_trace_midi_output(MIDI::Port *port)
332 MIDI::Parser* output_parser;
333 if (port) {
334 if ((output_parser = port->output()) != 0) {
335 return output_parser->tracing();
338 else {
339 if (_mmc && _mmc->port()) {
340 if ((output_parser = _mmc->port()->output()) != 0) {
341 return output_parser->tracing();
345 if (_mtc_port) {
346 if ((output_parser = _mtc_port->output()) != 0) {
347 return output_parser->tracing();
351 if (_midi_port) {
352 if ((output_parser = _midi_port->output()) != 0) {
353 return output_parser->tracing();
358 return false;
362 void
363 Session::setup_midi_control ()
365 outbound_mtc_timecode_frame = 0;
366 next_quarter_frame_to_send = 0;
368 /* Set up the qtr frame message */
370 mtc_msg[0] = 0xf1;
371 mtc_msg[2] = 0xf1;
372 mtc_msg[4] = 0xf1;
373 mtc_msg[6] = 0xf1;
374 mtc_msg[8] = 0xf1;
375 mtc_msg[10] = 0xf1;
376 mtc_msg[12] = 0xf1;
377 mtc_msg[14] = 0xf1;
380 void
381 Session::spp_start (Parser &, nframes_t /*timestamp*/)
383 if (Config->get_mmc_control() && (!config.get_external_sync() || config.get_sync_source() != JACK)) {
384 request_transport_speed (1.0);
388 void
389 Session::spp_continue (Parser& ignored, nframes_t timestamp)
391 spp_start (ignored, timestamp);
394 void
395 Session::spp_stop (Parser&, nframes_t /*timestamp*/)
397 if (Config->get_mmc_control()) {
398 request_stop ();
402 void
403 Session::mmc_deferred_play (MIDI::MachineControl &/*mmc*/)
405 if (Config->get_mmc_control() && (!config.get_external_sync() || (config.get_sync_source() != JACK))) {
406 request_transport_speed (1.0);
410 void
411 Session::mmc_record_pause (MIDI::MachineControl &/*mmc*/)
413 if (Config->get_mmc_control()) {
414 maybe_enable_record();
418 void
419 Session::mmc_record_strobe (MIDI::MachineControl &/*mmc*/)
421 if (!Config->get_mmc_control())
422 return;
424 /* record strobe does an implicit "Play" command */
426 if (_transport_speed != 1.0) {
428 /* start_transport() will move from Enabled->Recording, so we
429 don't need to do anything here except enable recording.
430 its not the same as maybe_enable_record() though, because
431 that *can* switch to Recording, which we do not want.
434 save_state ("", true);
435 g_atomic_int_set (&_record_status, Enabled);
436 RecordStateChanged (); /* EMIT SIGNAL */
438 request_transport_speed (1.0);
440 } else {
442 enable_record ();
446 void
447 Session::mmc_record_exit (MIDI::MachineControl &/*mmc*/)
449 if (Config->get_mmc_control()) {
450 disable_record (false);
454 void
455 Session::mmc_stop (MIDI::MachineControl &/*mmc*/)
457 if (Config->get_mmc_control()) {
458 request_stop ();
462 void
463 Session::mmc_pause (MIDI::MachineControl &/*mmc*/)
465 if (Config->get_mmc_control()) {
467 /* We support RECORD_PAUSE, so the spec says that
468 we must interpret PAUSE like RECORD_PAUSE if
469 recording.
472 if (actively_recording()) {
473 maybe_enable_record ();
474 } else {
475 request_stop ();
480 static bool step_queued = false;
482 void
483 Session::mmc_step (MIDI::MachineControl &/*mmc*/, int steps)
485 if (!Config->get_mmc_control()) {
486 return;
489 struct timeval now;
490 struct timeval diff = { 0, 0 };
492 gettimeofday (&now, 0);
494 timersub (&now, &last_mmc_step, &diff);
496 gettimeofday (&now, 0);
497 timersub (&now, &last_mmc_step, &diff);
499 if (last_mmc_step.tv_sec != 0 && (diff.tv_usec + (diff.tv_sec * 1000000)) < _engine.usecs_per_cycle()) {
500 return;
503 double diff_secs = diff.tv_sec + (diff.tv_usec / 1000000.0);
504 double cur_speed = (((steps * 0.5) * timecode_frames_per_second()) / diff_secs) / timecode_frames_per_second();
506 if (_transport_speed == 0 || cur_speed * _transport_speed < 0) {
507 /* change direction */
508 step_speed = cur_speed;
509 } else {
510 step_speed = (0.6 * step_speed) + (0.4 * cur_speed);
513 step_speed *= 0.25;
515 #if 0
516 cerr << "delta = " << diff_secs
517 << " ct = " << _transport_speed
518 << " steps = " << steps
519 << " new speed = " << cur_speed
520 << " speed = " << step_speed
521 << endl;
522 #endif
524 request_transport_speed (step_speed);
525 last_mmc_step = now;
527 if (!step_queued) {
528 if (midi_control_ui) {
529 RefPtr<TimeoutSource> tsrc = TimeoutSource::create (100);
530 tsrc->connect (sigc::mem_fun (*this, &Session::mmc_step_timeout));
531 tsrc->attach (midi_control_ui->main_loop()->get_context());
532 step_queued = true;
537 void
538 Session::mmc_rewind (MIDI::MachineControl &/*mmc*/)
540 if (Config->get_mmc_control()) {
541 request_transport_speed(-8.0f);
545 void
546 Session::mmc_fast_forward (MIDI::MachineControl &/*mmc*/)
548 if (Config->get_mmc_control()) {
549 request_transport_speed(8.0f);
553 void
554 Session::mmc_locate (MIDI::MachineControl &/*mmc*/, const MIDI::byte* mmc_tc)
556 if (!Config->get_mmc_control()) {
557 return;
560 nframes_t target_frame;
561 Timecode::Time timecode;
563 timecode.hours = mmc_tc[0] & 0xf;
564 timecode.minutes = mmc_tc[1];
565 timecode.seconds = mmc_tc[2];
566 timecode.frames = mmc_tc[3];
567 timecode.rate = timecode_frames_per_second();
568 timecode.drop = timecode_drop_frames();
570 // Also takes timecode offset into account:
571 timecode_to_sample( timecode, target_frame, true /* use_offset */, false /* use_subframes */ );
573 if (target_frame > max_frames) {
574 target_frame = max_frames;
577 /* Some (all?) MTC/MMC devices do not send a full MTC frame
578 at the end of a locate, instead sending only an MMC
579 locate command. This causes the current position
580 of an MTC slave to become out of date. Catch this.
583 MTC_Slave* mtcs = dynamic_cast<MTC_Slave*> (_slave);
585 if (mtcs != 0) {
586 // cerr << "Locate *with* MTC slave\n";
587 mtcs->handle_locate (mmc_tc);
588 } else {
589 // cerr << "Locate without MTC slave\n";
590 request_locate (target_frame, false);
594 void
595 Session::mmc_shuttle (MIDI::MachineControl &/*mmc*/, float speed, bool forw)
597 if (!Config->get_mmc_control()) {
598 return;
601 if (Config->get_shuttle_speed_threshold() >= 0 && speed > Config->get_shuttle_speed_threshold()) {
602 speed *= Config->get_shuttle_speed_factor();
605 if (forw) {
606 request_transport_speed (speed);
607 } else {
608 request_transport_speed (-speed);
612 void
613 Session::mmc_record_enable (MIDI::MachineControl &mmc, size_t trk, bool enabled)
615 if (Config->get_mmc_control()) {
617 RouteList::iterator i;
618 boost::shared_ptr<RouteList> r = routes.reader();
620 for (i = r->begin(); i != r->end(); ++i) {
621 AudioTrack *at;
623 if ((at = dynamic_cast<AudioTrack*>((*i).get())) != 0) {
624 if (trk == at->remote_control_id()) {
625 at->set_record_enable (enabled, &mmc);
626 break;
633 /** Send MTC Full Frame message (complete Timecode time) for the start of this cycle.
634 * This resets the MTC code, the next quarter frame message that is sent will be
635 * the first one with the beginning of this cycle as the new start point.
638 Session::send_full_time_code(nframes_t /*nframes*/)
640 /* This function could easily send at a given frame offset, but would
641 * that be useful? Does ardour do sub-block accurate locating? [DR] */
643 MIDI::byte msg[10];
644 Timecode::Time timecode;
646 _send_timecode_update = false;
648 if (_mtc_port == 0 || !session_send_mtc || _slave) {
649 return 0;
652 // Get timecode time for this transport frame
653 sample_to_timecode(_transport_frame, timecode, true /* use_offset */, false /* no subframes */);
655 transmitting_timecode_time = timecode;
656 outbound_mtc_timecode_frame = _transport_frame;
658 // I don't understand this bit yet.. [DR]
659 if (((mtc_timecode_bits >> 5) != MIDI::MTC_25_FPS) && (transmitting_timecode_time.frames % 2)) {
660 // start MTC quarter frame transmission on an even frame
661 Timecode::increment (transmitting_timecode_time, config.get_subframes_per_frame());
662 outbound_mtc_timecode_frame += (nframes_t) _frames_per_timecode_frame;
665 // Compensate for audio latency
666 outbound_mtc_timecode_frame += _worst_output_latency;
667 next_quarter_frame_to_send = 0;
669 // Sync slave to the same Timecode time as we are on
670 msg[0] = 0xf0;
671 msg[1] = 0x7f;
672 msg[2] = 0x7f;
673 msg[3] = 0x1;
674 msg[4] = 0x1;
675 msg[9] = 0xf7;
677 msg[5] = mtc_timecode_bits | timecode.hours;
678 msg[6] = timecode.minutes;
679 msg[7] = timecode.seconds;
680 msg[8] = timecode.frames;
682 // Send message at offset 0, sent time is for the start of this cycle
683 if (_mtc_port->midimsg (msg, sizeof (msg), 0)) {
684 error << _("Session: could not send full MIDI time code") << endmsg;
685 return -1;
688 return 0;
691 /** Send MTC (quarter-frame) messages for this cycle.
692 * Must be called exactly once per cycle from the audio thread. Realtime safe.
693 * This function assumes the state of full Timecode is sane, eg. the slave is
694 * expecting quarter frame messages and has the right frame of reference (any
695 * full MTC Timecode time messages that needed to be sent should have been sent
696 * earlier already this cycle by send_full_time_code)
699 Session::send_midi_time_code_for_cycle(nframes_t nframes)
701 if (_mtc_port == 0 || _slave || !session_send_mtc || transmitting_timecode_time.negative || (next_quarter_frame_to_send < 0)) {
702 // cerr << "(MTC) Not sending MTC\n";
703 return 0;
706 assert (next_quarter_frame_to_send >= 0);
707 assert (next_quarter_frame_to_send <= 7);
709 /* Duration of one quarter frame */
710 nframes_t quarter_frame_duration = ((long) _frames_per_timecode_frame) >> 2;
712 DEBUG_TRACE (DEBUG::MTC, string_compose ("TF %1 SF %2 NQ %3 FD %4\n", _transport_frame, outbound_mtc_timecode_frame,
713 next_quarter_frame_to_send, quarter_frame_duration));
715 assert((outbound_mtc_timecode_frame + (next_quarter_frame_to_send * quarter_frame_duration))
716 >= _transport_frame);
719 // Send quarter frames for this cycle
720 while (_transport_frame + nframes > (outbound_mtc_timecode_frame +
721 (next_quarter_frame_to_send * quarter_frame_duration))) {
723 DEBUG_TRACE (DEBUG::MTC, string_compose ("next frame to send: %1\n", next_quarter_frame_to_send));
725 switch (next_quarter_frame_to_send) {
726 case 0:
727 mtc_msg[1] = 0x00 | (transmitting_timecode_time.frames & 0xf);
728 break;
729 case 1:
730 mtc_msg[1] = 0x10 | ((transmitting_timecode_time.frames & 0xf0) >> 4);
731 break;
732 case 2:
733 mtc_msg[1] = 0x20 | (transmitting_timecode_time.seconds & 0xf);
734 break;
735 case 3:
736 mtc_msg[1] = 0x30 | ((transmitting_timecode_time.seconds & 0xf0) >> 4);
737 break;
738 case 4:
739 mtc_msg[1] = 0x40 | (transmitting_timecode_time.minutes & 0xf);
740 break;
741 case 5:
742 mtc_msg[1] = 0x50 | ((transmitting_timecode_time.minutes & 0xf0) >> 4);
743 break;
744 case 6:
745 mtc_msg[1] = 0x60 | ((mtc_timecode_bits|transmitting_timecode_time.hours) & 0xf);
746 break;
747 case 7:
748 mtc_msg[1] = 0x70 | (((mtc_timecode_bits|transmitting_timecode_time.hours) & 0xf0) >> 4);
749 break;
752 const nframes_t msg_time = (outbound_mtc_timecode_frame
753 + (quarter_frame_duration * next_quarter_frame_to_send));
755 // This message must fall within this block or something is broken
756 assert(msg_time >= _transport_frame);
757 assert(msg_time < _transport_frame + nframes);
759 nframes_t out_stamp = msg_time - _transport_frame;
760 assert(out_stamp < nframes);
762 if (_mtc_port->midimsg (mtc_msg, 2, out_stamp)) {
763 error << string_compose(_("Session: cannot send quarter-frame MTC message (%1)"), strerror (errno))
764 << endmsg;
765 return -1;
768 #ifndef NDEBUG
769 DEBUG_STR_DECL(foo)
770 DEBUG_STR_APPEND(foo,"sending ");
771 DEBUG_STR_APPEND(foo, transmitting_timecode_time);
772 DEBUG_TRACE (DEBUG::MTC, string_compose ("%1 qfm = %2, stamp = %3\n", DEBUG_STR(foo).str(), next_quarter_frame_to_send,
773 out_stamp));
774 #endif
776 // Increment quarter frame counter
777 next_quarter_frame_to_send++;
779 if (next_quarter_frame_to_send >= 8) {
780 // Wrap quarter frame counter
781 next_quarter_frame_to_send = 0;
782 // Increment timecode time twice
783 Timecode::increment( transmitting_timecode_time, config.get_subframes_per_frame() );
784 Timecode::increment( transmitting_timecode_time, config.get_subframes_per_frame() );
785 // Re-calculate timing of first quarter frame
786 //timecode_to_sample( transmitting_timecode_time, outbound_mtc_timecode_frame, true /* use_offset */, false );
787 outbound_mtc_timecode_frame += 8 * quarter_frame_duration;
791 return 0;
794 /***********************************************************************
795 OUTBOUND MMC STUFF
796 **********************************************************************/
799 bool
800 Session::mmc_step_timeout ()
802 struct timeval now;
803 struct timeval diff;
804 double diff_usecs;
805 gettimeofday (&now, 0);
807 timersub (&now, &last_mmc_step, &diff);
808 diff_usecs = diff.tv_sec * 1000000 + diff.tv_usec;
810 if (diff_usecs > 1000000.0 || fabs (_transport_speed) < 0.0000001) {
811 /* too long or too slow, stop transport */
812 request_transport_speed (0.0);
813 step_queued = false;
814 return false;
817 if (diff_usecs < 250000.0) {
818 /* too short, just keep going */
819 return true;
822 /* slow it down */
824 request_transport_speed (_transport_speed * 0.75);
825 return true;
828 /*---------------------------------------------------------------------------
829 MIDI THREAD
830 ---------------------------------------------------------------------------*/
833 Session::start_midi_thread ()
835 midi_control_ui = new MidiControlUI (*this);
836 midi_control_ui->run ();
837 return 0;
840 void
841 Session::terminate_midi_thread ()
843 if (midi_control_ui) {
844 midi_control_ui->quit ();