d006097f09bbc7e6fe8f687521e065e6a03523f6
[ardour.git] / libs / ardour / session_midi.cc
1
2 /*
3   Copyright (C) 1999-2002 Paul Davis
4
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.
9
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.
14
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.
18
19 */
20
21 #include <string>
22 #include <cmath>
23 #include <cerrno>
24 #include <cassert>
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <poll.h>
28
29 #include <boost/shared_ptr.hpp>
30
31 #include <glibmm/main.h>
32
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"
38
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"
50
51 #include "i18n.h"
52
53 using namespace std;
54 using namespace ARDOUR;
55 using namespace PBD;
56 using namespace MIDI;
57 using namespace Glib;
58
59 MachineControl::CommandSignature MMC_CommandSignature;
60 MachineControl::ResponseSignature MMC_ResponseSignature;
61
62
63 void
64 Session::midi_panic()
65 {
66         {
67                 boost::shared_ptr<RouteList> r = routes.reader ();
68
69                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
70                         MidiTrack *track = dynamic_cast<MidiTrack*>((*i).get());
71                         if (track != 0) {
72                                 track->midi_panic();
73                         }
74                 }
75         }
76 }
77
78 int
79 Session::use_config_midi_ports ()
80 {
81         string port_name;
82
83         if (default_mmc_port) {
84                 set_mmc_port (default_mmc_port->name());
85         } else {
86                 set_mmc_port ("");
87         }
88
89         if (default_mtc_port) {
90                 set_mtc_port (default_mtc_port->name());
91         } else {
92                 set_mtc_port ("");
93         }
94
95         if (default_midi_port) {
96                 set_midi_port (default_midi_port->name());
97         } else {
98                 set_midi_port ("");
99         }
100
101         if (default_midi_clock_port) {
102                 set_midi_clock_port (default_midi_clock_port->name());
103         } else {
104                 set_midi_clock_port ("");
105         }
106
107         return 0;
108 }
109
110
111 /***********************************************************************
112  MTC, MMC, etc.
113 **********************************************************************/
114
115 int
116 Session::set_mtc_port (string port_tag)
117 {
118         MTC_Slave *ms;
119
120         if (port_tag.length() == 0) {
121
122                 if (_slave && ((ms = dynamic_cast<MTC_Slave*> (_slave)) != 0)) {
123                         error << _("Ardour is slaved to MTC - port cannot be reset") << endmsg;
124                         return -1;
125                 }
126
127                 if (_mtc_port == 0) {
128                         return 0;
129                 }
130
131                 _mtc_port = 0;
132                 goto out;
133         }
134
135         MIDI::Port* port;
136
137         if ((port = MIDI::Manager::instance()->port (port_tag)) == 0) {
138                 error << string_compose (_("unknown port %1 requested for MTC"), port_tag) << endl;
139                 return -1;
140         }
141
142         _mtc_port = port;
143
144         if (_slave && ((ms = dynamic_cast<MTC_Slave*> (_slave)) != 0)) {
145                 ms->rebind (*port);
146         }
147
148         Config->set_mtc_port_name (port_tag);
149
150   out:
151         MTC_PortChanged(); /* EMIT SIGNAL */
152         set_dirty();
153         return 0;
154 }
155
156 void
157 Session::set_mmc_receive_device_id (uint32_t device_id)
158 {
159         if (mmc) {
160                 mmc->set_receive_device_id (device_id);
161         }
162 }
163
164 void
165 Session::set_mmc_send_device_id (uint32_t device_id)
166 {
167         if (mmc) {
168                 mmc->set_send_device_id (device_id);
169         }
170 }
171
172 int
173 Session::set_mmc_port (string port_tag)
174 {
175         MIDI::byte old_recv_device_id = 0;
176         MIDI::byte old_send_device_id = 0;
177         bool reset_id = false;
178
179         if (port_tag.length() == 0) {
180                 if (_mmc_port == 0) {
181                         return 0;
182                 }
183                 _mmc_port = 0;
184                 goto out;
185         }
186
187         MIDI::Port* port;
188
189         if ((port = MIDI::Manager::instance()->port (port_tag)) == 0) {
190                 return -1;
191         }
192
193         _mmc_port = port;
194
195         if (mmc) {
196                 old_recv_device_id = mmc->receive_device_id();
197                 old_recv_device_id = mmc->send_device_id();
198                 reset_id = true;
199                 delete mmc;
200         }
201
202         mmc = new MIDI::MachineControl (*_mmc_port, 1.0,
203                                         MMC_CommandSignature,
204                                         MMC_ResponseSignature);
205
206         if (reset_id) {
207                 mmc->set_receive_device_id (old_recv_device_id);
208                 mmc->set_send_device_id (old_send_device_id);
209         }
210
211         mmc->Play.connect
212                 (sigc::mem_fun (*this, &Session::mmc_deferred_play));
213         mmc->DeferredPlay.connect
214                 (sigc::mem_fun (*this, &Session::mmc_deferred_play));
215         mmc->Stop.connect
216                 (sigc::mem_fun (*this, &Session::mmc_stop));
217         mmc->FastForward.connect
218                 (sigc::mem_fun (*this, &Session::mmc_fast_forward));
219         mmc->Rewind.connect
220                 (sigc::mem_fun (*this, &Session::mmc_rewind));
221         mmc->Pause.connect
222                 (sigc::mem_fun (*this, &Session::mmc_pause));
223         mmc->RecordPause.connect
224                 (sigc::mem_fun (*this, &Session::mmc_record_pause));
225         mmc->RecordStrobe.connect
226                 (sigc::mem_fun (*this, &Session::mmc_record_strobe));
227         mmc->RecordExit.connect
228                 (sigc::mem_fun (*this, &Session::mmc_record_exit));
229         mmc->Locate.connect
230                 (sigc::mem_fun (*this, &Session::mmc_locate));
231         mmc->Step.connect
232                 (sigc::mem_fun (*this, &Session::mmc_step));
233         mmc->Shuttle.connect
234                 (sigc::mem_fun (*this, &Session::mmc_shuttle));
235         mmc->TrackRecordStatusChange.connect
236                 (sigc::mem_fun (*this, &Session::mmc_record_enable));
237
238
239         /* also handle MIDI SPP because its so common */
240
241         _mmc_port->input()->start.connect (sigc::mem_fun (*this, &Session::spp_start));
242         _mmc_port->input()->contineu.connect (sigc::mem_fun (*this, &Session::spp_continue));
243         _mmc_port->input()->stop.connect (sigc::mem_fun (*this, &Session::spp_stop));
244
245         Config->set_mmc_port_name (port_tag);
246
247   out:
248         MMC_PortChanged(); /* EMIT SIGNAL */
249         set_dirty();
250         return 0;
251 }
252
253 int
254 Session::set_midi_port (string /*port_tag*/)
255 {
256 #if 0
257         if (port_tag.length() == 0) {
258                 if (_midi_port == 0) {
259                         return 0;
260                 }
261                 _midi_port = 0;
262                 goto out;
263         }
264
265         MIDI::Port* port;
266
267         if ((port = MIDI::Manager::instance()->port (port_tag)) == 0) {
268                 return -1;
269         }
270
271         _midi_port = port;
272
273         /* XXX need something to forward this to control protocols ? or just
274            use the signal below
275         */
276
277         Config->set_midi_port_name (port_tag);
278
279   out:
280 #endif
281         MIDI_PortChanged(); /* EMIT SIGNAL */
282         set_dirty();
283         return 0;
284 }
285
286 int
287 Session::set_midi_clock_port (string port_tag)
288 {
289         MIDIClock_Slave *ms;
290
291         if (port_tag.length() == 0) {
292
293                 if (_slave && ((ms = dynamic_cast<MIDIClock_Slave*> (_slave)) != 0)) {
294                         error << _("Ardour is slaved to MIDI Clock - port cannot be reset") << endmsg;
295                         return -1;
296                 }
297
298                 if (_midi_clock_port == 0) {
299                         return 0;
300                 }
301
302                 _midi_clock_port = 0;
303                 goto out;
304         }
305
306         MIDI::Port* port;
307
308         if ((port = MIDI::Manager::instance()->port (port_tag)) == 0) {
309                 error << string_compose (_("unknown port %1 requested for MIDI Clock"), port_tag) << endl;
310                 return -1;
311         }
312
313         _midi_clock_port = port;
314
315         if (_slave && ((ms = dynamic_cast<MIDIClock_Slave*> (_slave)) != 0)) {
316                 ms->rebind (*port);
317         }
318
319         Config->set_midi_clock_port_name (port_tag);
320
321   out:
322         MIDIClock_PortChanged(); /* EMIT SIGNAL */
323         set_dirty();
324         return 0;
325 }
326
327 void
328 Session::set_trace_midi_input (bool yn, MIDI::Port* port)
329 {
330         MIDI::Parser* input_parser;
331
332         cerr << "enabling tracing: " << yn << " for input port " << port->name() << endl;
333
334         if (port) {
335                 if ((input_parser = port->input()) != 0) {
336                         input_parser->trace (yn, &cout, "input: ");
337                 }
338         } else {
339
340                 if (_mmc_port) {
341                         if ((input_parser = _mmc_port->input()) != 0) {
342                                 input_parser->trace (yn, &cout, "input: ");
343                         }
344                 }
345
346                 if (_mtc_port && _mtc_port != _mmc_port) {
347                         if ((input_parser = _mtc_port->input()) != 0) {
348                                 input_parser->trace (yn, &cout, "input: ");
349                         }
350                 }
351
352                 if (_midi_port && _midi_port != _mmc_port && _midi_port != _mtc_port  ) {
353                         if ((input_parser = _midi_port->input()) != 0) {
354                                 input_parser->trace (yn, &cout, "input: ");
355                         }
356                 }
357
358                 if (_midi_clock_port
359                         && _midi_clock_port != _mmc_port
360                         && _midi_clock_port != _mtc_port
361                         && _midi_clock_port != _midi_port) {
362                         if ((input_parser = _midi_clock_port->input()) != 0) {
363                                 input_parser->trace (yn, &cout, "input: ");
364                         }
365                 }
366         }
367
368         Config->set_trace_midi_input (yn);
369 }
370
371 void
372 Session::set_trace_midi_output (bool yn, MIDI::Port* port)
373 {
374         MIDI::Parser* output_parser;
375
376         if (port) {
377                 if ((output_parser = port->output()) != 0) {
378                         output_parser->trace (yn, &cout, "output: ");
379                 }
380         } else {
381                 if (_mmc_port) {
382                         if ((output_parser = _mmc_port->output()) != 0) {
383                                 output_parser->trace (yn, &cout, "output: ");
384                         }
385                 }
386
387                 if (_mtc_port && _mtc_port != _mmc_port) {
388                         if ((output_parser = _mtc_port->output()) != 0) {
389                                 output_parser->trace (yn, &cout, "output: ");
390                         }
391                 }
392
393                 if (_midi_port && _midi_port != _mmc_port && _midi_port != _mtc_port  ) {
394                         if ((output_parser = _midi_port->output()) != 0) {
395                                 output_parser->trace (yn, &cout, "output: ");
396                         }
397                 }
398
399         }
400
401         Config->set_trace_midi_output (yn);
402 }
403
404 bool
405 Session::get_trace_midi_input(MIDI::Port *port)
406 {
407         MIDI::Parser* input_parser;
408         if (port) {
409                 if ((input_parser = port->input()) != 0) {
410                         return input_parser->tracing();
411                 }
412         }
413         else {
414                 if (_mmc_port) {
415                         if ((input_parser = _mmc_port->input()) != 0) {
416                                 return input_parser->tracing();
417                         }
418                 }
419
420                 if (_mtc_port) {
421                         if ((input_parser = _mtc_port->input()) != 0) {
422                                 return input_parser->tracing();
423                         }
424                 }
425
426                 if (_midi_port) {
427                         if ((input_parser = _midi_port->input()) != 0) {
428                                 return input_parser->tracing();
429                         }
430                 }
431         }
432
433         return false;
434 }
435
436 bool
437 Session::get_trace_midi_output(MIDI::Port *port)
438 {
439         MIDI::Parser* output_parser;
440         if (port) {
441                 if ((output_parser = port->output()) != 0) {
442                         return output_parser->tracing();
443                 }
444         }
445         else {
446                 if (_mmc_port) {
447                         if ((output_parser = _mmc_port->output()) != 0) {
448                                 return output_parser->tracing();
449                         }
450                 }
451
452                 if (_mtc_port) {
453                         if ((output_parser = _mtc_port->output()) != 0) {
454                                 return output_parser->tracing();
455                         }
456                 }
457
458                 if (_midi_port) {
459                         if ((output_parser = _midi_port->output()) != 0) {
460                                 return output_parser->tracing();
461                         }
462                 }
463         }
464
465         return false;
466
467 }
468
469 void
470 Session::setup_midi_control ()
471 {
472         outbound_mtc_timecode_frame = 0;
473         next_quarter_frame_to_send = 0;
474
475         /* setup the MMC buffer */
476
477         mmc_buffer[0] = 0xf0; // SysEx
478         mmc_buffer[1] = 0x7f; // Real Time SysEx ID for MMC
479         mmc_buffer[2] = (mmc ? mmc->send_device_id() : 0x7f);
480         mmc_buffer[3] = 0x6;  // MCC
481
482         /* Set up the qtr frame message */
483
484         mtc_msg[0] = 0xf1;
485         mtc_msg[2] = 0xf1;
486         mtc_msg[4] = 0xf1;
487         mtc_msg[6] = 0xf1;
488         mtc_msg[8] = 0xf1;
489         mtc_msg[10] = 0xf1;
490         mtc_msg[12] = 0xf1;
491         mtc_msg[14] = 0xf1;
492 }
493
494 void
495 Session::spp_start (Parser &, nframes_t /*timestamp*/)
496 {
497         if (Config->get_mmc_control() && (!config.get_external_sync() || config.get_sync_source() != JACK)) {
498                 request_transport_speed (1.0);
499         }
500 }
501
502 void
503 Session::spp_continue (Parser& ignored, nframes_t timestamp)
504 {
505         spp_start (ignored, timestamp);
506 }
507
508 void
509 Session::spp_stop (Parser&, nframes_t /*timestamp*/)
510 {
511         if (Config->get_mmc_control()) {
512                 request_stop ();
513         }
514 }
515
516 void
517 Session::mmc_deferred_play (MIDI::MachineControl &/*mmc*/)
518 {
519         if (Config->get_mmc_control() && (!config.get_external_sync() || (config.get_sync_source() != JACK))) {
520                 request_transport_speed (1.0);
521         }
522 }
523
524 void
525 Session::mmc_record_pause (MIDI::MachineControl &/*mmc*/)
526 {
527         if (Config->get_mmc_control()) {
528                 maybe_enable_record();
529         }
530 }
531
532 void
533 Session::mmc_record_strobe (MIDI::MachineControl &/*mmc*/)
534 {
535         if (!Config->get_mmc_control())
536                 return;
537
538         /* record strobe does an implicit "Play" command */
539
540         if (_transport_speed != 1.0) {
541
542                 /* start_transport() will move from Enabled->Recording, so we
543                    don't need to do anything here except enable recording.
544                    its not the same as maybe_enable_record() though, because
545                    that *can* switch to Recording, which we do not want.
546                 */
547
548                 save_state ("", true);
549                 g_atomic_int_set (&_record_status, Enabled);
550                 RecordStateChanged (); /* EMIT SIGNAL */
551
552                 request_transport_speed (1.0);
553
554         } else {
555
556                 enable_record ();
557         }
558 }
559
560 void
561 Session::mmc_record_exit (MIDI::MachineControl &/*mmc*/)
562 {
563         if (Config->get_mmc_control()) {
564                 disable_record (false);
565         }
566 }
567
568 void
569 Session::mmc_stop (MIDI::MachineControl &/*mmc*/)
570 {
571         if (Config->get_mmc_control()) {
572                 request_stop ();
573         }
574 }
575
576 void
577 Session::mmc_pause (MIDI::MachineControl &/*mmc*/)
578 {
579         if (Config->get_mmc_control()) {
580
581                 /* We support RECORD_PAUSE, so the spec says that
582                    we must interpret PAUSE like RECORD_PAUSE if
583                    recording.
584                 */
585
586                 if (actively_recording()) {
587                         maybe_enable_record ();
588                 } else {
589                         request_stop ();
590                 }
591         }
592 }
593
594 static bool step_queued = false;
595
596 void
597 Session::mmc_step (MIDI::MachineControl &/*mmc*/, int steps)
598 {
599         if (!Config->get_mmc_control()) {
600                 return;
601         }
602
603         struct timeval now;
604         struct timeval diff = { 0, 0 };
605
606         gettimeofday (&now, 0);
607
608         timersub (&now, &last_mmc_step, &diff);
609
610         gettimeofday (&now, 0);
611         timersub (&now, &last_mmc_step, &diff);
612
613         if (last_mmc_step.tv_sec != 0 && (diff.tv_usec + (diff.tv_sec * 1000000)) < _engine.usecs_per_cycle()) {
614                 return;
615         }
616
617         double diff_secs = diff.tv_sec + (diff.tv_usec / 1000000.0);
618         double cur_speed = (((steps * 0.5) * timecode_frames_per_second()) / diff_secs) / timecode_frames_per_second();
619
620         if (_transport_speed == 0 || cur_speed * _transport_speed < 0) {
621                 /* change direction */
622                 step_speed = cur_speed;
623         } else {
624                 step_speed = (0.6 * step_speed) + (0.4 * cur_speed);
625         }
626
627         step_speed *= 0.25;
628
629 #if 0
630         cerr << "delta = " << diff_secs
631              << " ct = " << _transport_speed
632              << " steps = " << steps
633              << " new speed = " << cur_speed
634              << " speed = " << step_speed
635              << endl;
636 #endif
637
638         request_transport_speed (step_speed);
639         last_mmc_step = now;
640
641         if (!step_queued) {
642                 if (midi_control_ui) {
643                         RefPtr<TimeoutSource> tsrc = TimeoutSource::create (100);
644                         tsrc->connect (sigc::mem_fun (*this, &Session::mmc_step_timeout));
645                         tsrc->attach (midi_control_ui->main_loop()->get_context());
646                         step_queued = true;
647                 }
648         }
649 }
650
651 void
652 Session::mmc_rewind (MIDI::MachineControl &/*mmc*/)
653 {
654         if (Config->get_mmc_control()) {
655                 request_transport_speed(-8.0f);
656         }
657 }
658
659 void
660 Session::mmc_fast_forward (MIDI::MachineControl &/*mmc*/)
661 {
662         if (Config->get_mmc_control()) {
663                 request_transport_speed(8.0f);
664         }
665 }
666
667 void
668 Session::mmc_locate (MIDI::MachineControl &/*mmc*/, const MIDI::byte* mmc_tc)
669 {
670         if (!Config->get_mmc_control()) {
671                 return;
672         }
673
674         nframes_t target_frame;
675         Timecode::Time timecode;
676
677         timecode.hours = mmc_tc[0] & 0xf;
678         timecode.minutes = mmc_tc[1];
679         timecode.seconds = mmc_tc[2];
680         timecode.frames = mmc_tc[3];
681         timecode.rate = timecode_frames_per_second();
682         timecode.drop = timecode_drop_frames();
683
684         // Also takes timecode offset into account:
685         timecode_to_sample( timecode, target_frame, true /* use_offset */, false /* use_subframes */ );
686
687         if (target_frame > max_frames) {
688                 target_frame = max_frames;
689         }
690
691         /* Some (all?) MTC/MMC devices do not send a full MTC frame
692            at the end of a locate, instead sending only an MMC
693            locate command. This causes the current position
694            of an MTC slave to become out of date. Catch this.
695         */
696
697         MTC_Slave* mtcs = dynamic_cast<MTC_Slave*> (_slave);
698
699         if (mtcs != 0) {
700                 // cerr << "Locate *with* MTC slave\n";
701                 mtcs->handle_locate (mmc_tc);
702         } else {
703                 // cerr << "Locate without MTC slave\n";
704                 request_locate (target_frame, false);
705         }
706 }
707
708 void
709 Session::mmc_shuttle (MIDI::MachineControl &/*mmc*/, float speed, bool forw)
710 {
711         if (!Config->get_mmc_control()) {
712                 return;
713         }
714
715         if (Config->get_shuttle_speed_threshold() >= 0 && speed > Config->get_shuttle_speed_threshold()) {
716                 speed *= Config->get_shuttle_speed_factor();
717         }
718
719         if (forw) {
720                 request_transport_speed (speed);
721         } else {
722                 request_transport_speed (-speed);
723         }
724 }
725
726 void
727 Session::mmc_record_enable (MIDI::MachineControl &mmc, size_t trk, bool enabled)
728 {
729         if (Config->get_mmc_control()) {
730
731                 RouteList::iterator i;
732                 boost::shared_ptr<RouteList> r = routes.reader();
733
734                 for (i = r->begin(); i != r->end(); ++i) {
735                         AudioTrack *at;
736
737                         if ((at = dynamic_cast<AudioTrack*>((*i).get())) != 0) {
738                                 if (trk == at->remote_control_id()) {
739                                         at->set_record_enable (enabled, &mmc);
740                                         break;
741                                 }
742                         }
743                 }
744         }
745 }
746
747 /** Send MTC Full Frame message (complete Timecode time) for the start of this cycle.
748  * This resets the MTC code, the next quarter frame message that is sent will be
749  * the first one with the beginning of this cycle as the new start point.
750  */
751 int
752 Session::send_full_time_code(nframes_t /*nframes*/)
753 {
754         /* This function could easily send at a given frame offset, but would
755          * that be useful?  Does ardour do sub-block accurate locating? [DR] */
756
757         MIDI::byte msg[10];
758         Timecode::Time timecode;
759
760         _send_timecode_update = false;
761
762         if (_mtc_port == 0 || !session_send_mtc) {
763                 return 0;
764         }
765
766         // Get timecode time for this transport frame
767         sample_to_timecode(_transport_frame, timecode, true /* use_offset */, false /* no subframes */);
768
769         transmitting_timecode_time = timecode;
770         outbound_mtc_timecode_frame = _transport_frame;
771
772         // I don't understand this bit yet.. [DR]
773         if (((mtc_timecode_bits >> 5) != MIDI::MTC_25_FPS) && (transmitting_timecode_time.frames % 2)) {
774                 // start MTC quarter frame transmission on an even frame
775                 Timecode::increment( transmitting_timecode_time, config.get_subframes_per_frame() );
776                 outbound_mtc_timecode_frame += (nframes_t) _frames_per_timecode_frame;
777         }
778
779         // Compensate for audio latency
780         outbound_mtc_timecode_frame += _worst_output_latency;
781
782         next_quarter_frame_to_send = 0;
783
784         // Sync slave to the same Timecode time as we are on
785         msg[0] = 0xf0;
786         msg[1] = 0x7f;
787         msg[2] = 0x7f;
788         msg[3] = 0x1;
789         msg[4] = 0x1;
790         msg[9] = 0xf7;
791
792         msg[5] = mtc_timecode_bits | timecode.hours;
793         msg[6] = timecode.minutes;
794         msg[7] = timecode.seconds;
795         msg[8] = timecode.frames;
796
797         cerr << "MTC: Sending full time code at " << outbound_mtc_timecode_frame << endl;
798
799         // Send message at offset 0, sent time is for the start of this cycle
800         if (_mtc_port->midimsg (msg, sizeof (msg), 0)) {
801                 error << _("Session: could not send full MIDI time code") << endmsg;
802                 return -1;
803         }
804
805         return 0;
806 }
807
808 /** Send MTC (quarter-frame) messages for this cycle.
809  * Must be called exactly once per cycle from the audio thread.  Realtime safe.
810  * This function assumes the state of full Timecode is sane, eg. the slave is
811  * expecting quarter frame messages and has the right frame of reference (any
812  * full MTC Timecode time messages that needed to be sent should have been sent
813  * earlier already this cycle by send_full_time_code)
814  */
815 int
816 Session::send_midi_time_code_for_cycle(nframes_t nframes)
817 {
818         assert (next_quarter_frame_to_send >= 0);
819         assert (next_quarter_frame_to_send <= 7);
820
821         if (_mtc_port == 0 || !session_send_mtc || transmitting_timecode_time.negative
822             /*|| (next_quarter_frame_to_send < 0)*/ ) {
823                 // cerr << "(MTC) Not sending MTC\n";
824                 return 0;
825         }
826
827         /* Duration of one quarter frame */
828         nframes_t quarter_frame_duration = ((long) _frames_per_timecode_frame) >> 2;
829
830         DEBUG_TRACE (DEBUG::MTC, string_compose ("TF %1 SF %2 NQ %3 FD %\4n",  _transport_frame, outbound_mtc_timecode_frame,
831                                                  next_quarter_frame_to_send, quarter_frame_duration));
832
833         // FIXME: this should always be true
834         //assert((outbound_mtc_timecode_frame + (next_quarter_frame_to_send * quarter_frame_duration))
835         //              > _transport_frame);
836
837
838         // Send quarter frames for this cycle
839         while (_transport_frame + nframes > (outbound_mtc_timecode_frame +
840                                 (next_quarter_frame_to_send * quarter_frame_duration))) {
841
842                 DEBUG_TRACE (DEBUG::MTC, string_compose ("next frame to send: %1\n", next_quarter_frame_to_send));
843
844                 switch (next_quarter_frame_to_send) {
845                         case 0:
846                                 mtc_msg[1] =  0x00 | (transmitting_timecode_time.frames & 0xf);
847                                 break;
848                         case 1:
849                                 mtc_msg[1] =  0x10 | ((transmitting_timecode_time.frames & 0xf0) >> 4);
850                                 break;
851                         case 2:
852                                 mtc_msg[1] =  0x20 | (transmitting_timecode_time.seconds & 0xf);
853                                 break;
854                         case 3:
855                                 mtc_msg[1] =  0x30 | ((transmitting_timecode_time.seconds & 0xf0) >> 4);
856                                 break;
857                         case 4:
858                                 mtc_msg[1] =  0x40 | (transmitting_timecode_time.minutes & 0xf);
859                                 break;
860                         case 5:
861                                 mtc_msg[1] = 0x50 | ((transmitting_timecode_time.minutes & 0xf0) >> 4);
862                                 break;
863                         case 6:
864                                 mtc_msg[1] = 0x60 | ((mtc_timecode_bits|transmitting_timecode_time.hours) & 0xf);
865                                 break;
866                         case 7:
867                                 mtc_msg[1] = 0x70 | (((mtc_timecode_bits|transmitting_timecode_time.hours) & 0xf0) >> 4);
868                                 break;
869                 }
870
871                 const nframes_t msg_time = (outbound_mtc_timecode_frame
872                         + (quarter_frame_duration * next_quarter_frame_to_send));
873
874                 // This message must fall within this block or something is broken
875                 assert(msg_time >= _transport_frame);
876                 assert(msg_time < _transport_frame + nframes);
877
878                 nframes_t out_stamp = msg_time - _transport_frame;
879                 assert(out_stamp < nframes);
880
881                 if (_mtc_port->midimsg (mtc_msg, 2, out_stamp)) {
882                         error << string_compose(_("Session: cannot send quarter-frame MTC message (%1)"), strerror (errno))
883                               << endmsg;
884                         return -1;
885                 }
886
887 #ifndef NDEBUG
888                 DEBUG_STR_SET(foo,"sending ");
889                 DEBUG_STR(foo) << transmitting_timecode_time;
890                 DEBUG_TRACE (DEBUG::MTC, string_compose ("%1 qfm = %2, stamp = %3\n", DEBUG_STR(foo).str(), next_quarter_frame_to_send,
891                                                          out_stamp));
892 #endif
893
894                 // Increment quarter frame counter
895                 next_quarter_frame_to_send++;
896
897                 if (next_quarter_frame_to_send >= 8) {
898                         // Wrap quarter frame counter
899                         next_quarter_frame_to_send = 0;
900                         // Increment timecode time twice
901                         Timecode::increment( transmitting_timecode_time, config.get_subframes_per_frame() );
902                         Timecode::increment( transmitting_timecode_time, config.get_subframes_per_frame() );
903                         // Re-calculate timing of first quarter frame
904                         //timecode_to_sample( transmitting_timecode_time, outbound_mtc_timecode_frame, true /* use_offset */, false );
905                         outbound_mtc_timecode_frame += 8 * quarter_frame_duration;
906                         // Compensate for audio latency
907                         outbound_mtc_timecode_frame += _worst_output_latency;
908                 }
909         }
910
911         return 0;
912 }
913
914 /***********************************************************************
915  OUTBOUND MMC STUFF
916 **********************************************************************/
917
918 void
919 Session::deliver_mmc (MIDI::MachineControl::Command cmd, nframes_t where)
920 {
921         using namespace MIDI;
922         int nbytes = 4;
923         Timecode::Time timecode;
924
925         if (_mmc_port == 0 || !session_send_mmc) {
926                 // cerr << "Not delivering MMC " << _mmc_port << " - " << session_send_mmc << endl;
927                 return;
928         }
929
930         mmc_buffer[nbytes++] = cmd;
931
932         // cerr << "delivering MMC, cmd = " << hex << (int) cmd << dec << endl;
933
934         switch (cmd) {
935         case MachineControl::cmdLocate:
936                 timecode_time_subframes (where, timecode);
937
938                 mmc_buffer[nbytes++] = 0x6; // byte count
939                 mmc_buffer[nbytes++] = 0x1; // "TARGET" subcommand
940                 mmc_buffer[nbytes++] = timecode.hours;
941                 mmc_buffer[nbytes++] = timecode.minutes;
942                 mmc_buffer[nbytes++] = timecode.seconds;
943                 mmc_buffer[nbytes++] = timecode.frames;
944                 mmc_buffer[nbytes++] = timecode.subframes;
945                 break;
946
947         case MachineControl::cmdStop:
948                 break;
949
950         case MachineControl::cmdPlay:
951                 /* always convert Play into Deferred Play */
952                 /* Why? [DR] */
953                 mmc_buffer[4] = MachineControl::cmdDeferredPlay;
954                 break;
955
956         case MachineControl::cmdDeferredPlay:
957                 break;
958
959         case MachineControl::cmdRecordStrobe:
960                 break;
961
962         case MachineControl::cmdRecordExit:
963                 break;
964
965         case MachineControl::cmdRecordPause:
966                 break;
967
968         default:
969                 nbytes = 0;
970         };
971
972         if (nbytes) {
973
974                 mmc_buffer[nbytes++] = 0xf7; // terminate SysEx/MMC message
975
976                 if (_mmc_port->midimsg (mmc_buffer, nbytes, 0)) {
977                         error << string_compose(_("MMC: cannot send command %1%2%3"), &hex, cmd, &dec) << endmsg;
978                 }
979         }
980 }
981
982 bool
983 Session::mmc_step_timeout ()
984 {
985         struct timeval now;
986         struct timeval diff;
987         double diff_usecs;
988         gettimeofday (&now, 0);
989
990         timersub (&now, &last_mmc_step, &diff);
991         diff_usecs = diff.tv_sec * 1000000 + diff.tv_usec;
992
993         if (diff_usecs > 1000000.0 || fabs (_transport_speed) < 0.0000001) {
994                 /* too long or too slow, stop transport */
995                 request_transport_speed (0.0);
996                 step_queued = false;
997                 return false;
998         }
999
1000         if (diff_usecs < 250000.0) {
1001                 /* too short, just keep going */
1002                 return true;
1003         }
1004
1005         /* slow it down */
1006
1007         request_transport_speed (_transport_speed * 0.75);
1008         return true;
1009 }
1010
1011 /*---------------------------------------------------------------------------
1012   MIDI THREAD
1013   ---------------------------------------------------------------------------*/
1014
1015 int
1016 Session::start_midi_thread ()
1017 {
1018         midi_control_ui = new MidiControlUI (*this);
1019         midi_control_ui->run ();
1020         return 0;
1021 }
1022
1023 void
1024 Session::terminate_midi_thread ()
1025 {
1026         if (midi_control_ui) {
1027                 midi_control_ui->quit ();
1028         }
1029 }
1030
1031