90% done with external sync design changes (GUI now has toggle switch for ext/int...
[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 "midi++/mmc.h"
32 #include "midi++/port.h"
33 #include "midi++/manager.h"
34 #include "pbd/error.h"
35 #include <glibmm/thread.h>
36 #include "pbd/pthread_utils.h"
37
38 #include "ardour/configuration.h"
39 #include "ardour/audioengine.h"
40 #include "ardour/session.h"
41 #include "ardour/audio_track.h"
42 #include "ardour/midi_track.h"
43 #include "ardour/audio_diskstream.h"
44 #include "ardour/slave.h"
45 #include "ardour/cycles.h"
46 #include "ardour/timecode.h"
47
48 #include "i18n.h"
49
50 using namespace std;
51 using namespace ARDOUR;
52 using namespace PBD;
53 using namespace MIDI;
54
55 MachineControl::CommandSignature MMC_CommandSignature;
56 MachineControl::ResponseSignature MMC_ResponseSignature;
57
58
59 void
60 Session::midi_panic()
61 {
62         {
63                 boost::shared_ptr<RouteList> r = routes.reader ();
64
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();
69                         }
70                 }
71         }
72 }
73
74 int
75 Session::use_config_midi_ports ()
76 {
77         string port_name;
78
79         if (default_mmc_port) {
80                 set_mmc_port (default_mmc_port->name());
81         } else {
82                 set_mmc_port ("");
83         }
84
85         if (default_mtc_port) {
86                 set_mtc_port (default_mtc_port->name());
87         } else {
88                 set_mtc_port ("");
89         }
90
91         if (default_midi_port) {
92                 set_midi_port (default_midi_port->name());
93         } else {
94                 set_midi_port ("");
95         }
96
97         if (default_midi_clock_port) {
98                 set_midi_clock_port (default_midi_clock_port->name());
99         } else {
100                 set_midi_clock_port ("");
101         }
102
103         return 0;
104 }
105
106
107 /***********************************************************************
108  MTC, MMC, etc.
109 **********************************************************************/
110
111 int
112 Session::set_mtc_port (string port_tag)
113 {
114         MTC_Slave *ms;
115
116         if (port_tag.length() == 0) {
117
118                 if (_slave && ((ms = dynamic_cast<MTC_Slave*> (_slave)) != 0)) {
119                         error << _("Ardour is slaved to MTC - port cannot be reset") << endmsg;
120                         return -1;
121                 }
122
123                 if (_mtc_port == 0) {
124                         return 0;
125                 }
126
127                 _mtc_port = 0;
128                 goto out;
129         }
130
131         MIDI::Port* port;
132
133         if ((port = MIDI::Manager::instance()->port (port_tag)) == 0) {
134                 error << string_compose (_("unknown port %1 requested for MTC"), port_tag) << endl;
135                 return -1;
136         }
137
138         _mtc_port = port;
139
140         if (_slave && ((ms = dynamic_cast<MTC_Slave*> (_slave)) != 0)) {
141                 ms->rebind (*port);
142         }
143
144         cerr << "!!SPT to " << port_tag << endl;
145
146         Config->set_mtc_port_name (port_tag);
147
148   out:
149         MTC_PortChanged(); /* EMIT SIGNAL */
150         change_midi_ports ();
151         set_dirty();
152         return 0;
153 }
154
155 void
156 Session::set_mmc_receive_device_id (uint32_t device_id)
157 {
158         if (mmc) {
159                 mmc->set_receive_device_id (device_id);
160         }
161 }
162
163 void
164 Session::set_mmc_send_device_id (uint32_t device_id)
165 {
166         if (mmc) {
167                 mmc->set_send_device_id (device_id);
168         }
169 }
170
171 int
172 Session::set_mmc_port (string port_tag)
173 {
174         MIDI::byte old_recv_device_id = 0;
175         MIDI::byte old_send_device_id = 0;
176         bool reset_id = false;
177
178         if (port_tag.length() == 0) {
179                 if (_mmc_port == 0) {
180                         return 0;
181                 }
182                 _mmc_port = 0;
183                 goto out;
184         }
185
186         MIDI::Port* port;
187
188         if ((port = MIDI::Manager::instance()->port (port_tag)) == 0) {
189                 return -1;
190         }
191
192         _mmc_port = port;
193
194         if (mmc) {
195                 old_recv_device_id = mmc->receive_device_id();
196                 old_recv_device_id = mmc->send_device_id();
197                 reset_id = true;
198                 delete mmc;
199         }
200
201         mmc = new MIDI::MachineControl (*_mmc_port, 1.0,
202                                         MMC_CommandSignature,
203                                         MMC_ResponseSignature);
204
205         if (reset_id) {
206                 mmc->set_receive_device_id (old_recv_device_id);
207                 mmc->set_send_device_id (old_send_device_id);
208         }
209
210         mmc->Play.connect
211                 (mem_fun (*this, &Session::mmc_deferred_play));
212         mmc->DeferredPlay.connect
213                 (mem_fun (*this, &Session::mmc_deferred_play));
214         mmc->Stop.connect
215                 (mem_fun (*this, &Session::mmc_stop));
216         mmc->FastForward.connect
217                 (mem_fun (*this, &Session::mmc_fast_forward));
218         mmc->Rewind.connect
219                 (mem_fun (*this, &Session::mmc_rewind));
220         mmc->Pause.connect
221                 (mem_fun (*this, &Session::mmc_pause));
222         mmc->RecordPause.connect
223                 (mem_fun (*this, &Session::mmc_record_pause));
224         mmc->RecordStrobe.connect
225                 (mem_fun (*this, &Session::mmc_record_strobe));
226         mmc->RecordExit.connect
227                 (mem_fun (*this, &Session::mmc_record_exit));
228         mmc->Locate.connect
229                 (mem_fun (*this, &Session::mmc_locate));
230         mmc->Step.connect
231                 (mem_fun (*this, &Session::mmc_step));
232         mmc->Shuttle.connect
233                 (mem_fun (*this, &Session::mmc_shuttle));
234         mmc->TrackRecordStatusChange.connect
235                 (mem_fun (*this, &Session::mmc_record_enable));
236
237
238         /* also handle MIDI SPP because its so common */
239
240         _mmc_port->input()->start.connect (mem_fun (*this, &Session::spp_start));
241         _mmc_port->input()->contineu.connect (mem_fun (*this, &Session::spp_continue));
242         _mmc_port->input()->stop.connect (mem_fun (*this, &Session::spp_stop));
243
244         Config->set_mmc_port_name (port_tag);
245
246   out:
247         MMC_PortChanged(); /* EMIT SIGNAL */
248         change_midi_ports ();
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         change_midi_ports ();
283         set_dirty();
284         return 0;
285 }
286
287 int
288 Session::set_midi_clock_port (string port_tag)
289 {
290         MIDIClock_Slave *ms;
291
292         if (port_tag.length() == 0) {
293
294                 if (_slave && ((ms = dynamic_cast<MIDIClock_Slave*> (_slave)) != 0)) {
295                         error << _("Ardour is slaved to MIDI Clock - port cannot be reset") << endmsg;
296                         return -1;
297                 }
298
299                 if (_midi_clock_port == 0) {
300                         return 0;
301                 }
302
303                 _midi_clock_port = 0;
304                 goto out;
305         }
306
307         MIDI::Port* port;
308
309         if ((port = MIDI::Manager::instance()->port (port_tag)) == 0) {
310                 error << string_compose (_("unknown port %1 requested for MIDI Clock"), port_tag) << endl;
311                 return -1;
312         }
313
314         _midi_clock_port = port;
315
316         if (_slave && ((ms = dynamic_cast<MIDIClock_Slave*> (_slave)) != 0)) {
317                 ms->rebind (*port);
318         }
319
320         Config->set_midi_clock_port_name (port_tag);
321
322   out:
323         MIDIClock_PortChanged(); /* EMIT SIGNAL */
324         change_midi_ports ();
325         set_dirty();
326         return 0;
327 }
328
329 void
330 Session::set_trace_midi_input (bool yn, MIDI::Port* port)
331 {
332         MIDI::Parser* input_parser;
333
334         cerr << "enabling tracing: " << yn << " for input port " << port->name() << endl;
335
336         if (port) {
337                 if ((input_parser = port->input()) != 0) {
338                         input_parser->trace (yn, &cout, "input: ");
339                 }
340         } else {
341
342                 if (_mmc_port) {
343                         if ((input_parser = _mmc_port->input()) != 0) {
344                                 input_parser->trace (yn, &cout, "input: ");
345                         }
346                 }
347
348                 if (_mtc_port && _mtc_port != _mmc_port) {
349                         if ((input_parser = _mtc_port->input()) != 0) {
350                                 input_parser->trace (yn, &cout, "input: ");
351                         }
352                 }
353
354                 if (_midi_port && _midi_port != _mmc_port && _midi_port != _mtc_port  ) {
355                         if ((input_parser = _midi_port->input()) != 0) {
356                                 input_parser->trace (yn, &cout, "input: ");
357                         }
358                 }
359
360                 if (_midi_clock_port
361                         && _midi_clock_port != _mmc_port
362                         && _midi_clock_port != _mtc_port
363                         && _midi_clock_port != _midi_port) {
364                         if ((input_parser = _midi_clock_port->input()) != 0) {
365                                 input_parser->trace (yn, &cout, "input: ");
366                         }
367                 }
368         }
369
370         Config->set_trace_midi_input (yn);
371 }
372
373 void
374 Session::set_trace_midi_output (bool yn, MIDI::Port* port)
375 {
376         MIDI::Parser* output_parser;
377
378         if (port) {
379                 if ((output_parser = port->output()) != 0) {
380                         output_parser->trace (yn, &cout, "output: ");
381                 }
382         } else {
383                 if (_mmc_port) {
384                         if ((output_parser = _mmc_port->output()) != 0) {
385                                 output_parser->trace (yn, &cout, "output: ");
386                         }
387                 }
388
389                 if (_mtc_port && _mtc_port != _mmc_port) {
390                         if ((output_parser = _mtc_port->output()) != 0) {
391                                 output_parser->trace (yn, &cout, "output: ");
392                         }
393                 }
394
395                 if (_midi_port && _midi_port != _mmc_port && _midi_port != _mtc_port  ) {
396                         if ((output_parser = _midi_port->output()) != 0) {
397                                 output_parser->trace (yn, &cout, "output: ");
398                         }
399                 }
400
401         }
402
403         Config->set_trace_midi_output (yn);
404 }
405
406 bool
407 Session::get_trace_midi_input(MIDI::Port *port)
408 {
409         MIDI::Parser* input_parser;
410         if (port) {
411                 if ((input_parser = port->input()) != 0) {
412                         return input_parser->tracing();
413                 }
414         }
415         else {
416                 if (_mmc_port) {
417                         if ((input_parser = _mmc_port->input()) != 0) {
418                                 return input_parser->tracing();
419                         }
420                 }
421
422                 if (_mtc_port) {
423                         if ((input_parser = _mtc_port->input()) != 0) {
424                                 return input_parser->tracing();
425                         }
426                 }
427
428                 if (_midi_port) {
429                         if ((input_parser = _midi_port->input()) != 0) {
430                                 return input_parser->tracing();
431                         }
432                 }
433         }
434
435         return false;
436 }
437
438 bool
439 Session::get_trace_midi_output(MIDI::Port *port)
440 {
441         MIDI::Parser* output_parser;
442         if (port) {
443                 if ((output_parser = port->output()) != 0) {
444                         return output_parser->tracing();
445                 }
446         }
447         else {
448                 if (_mmc_port) {
449                         if ((output_parser = _mmc_port->output()) != 0) {
450                                 return output_parser->tracing();
451                         }
452                 }
453
454                 if (_mtc_port) {
455                         if ((output_parser = _mtc_port->output()) != 0) {
456                                 return output_parser->tracing();
457                         }
458                 }
459
460                 if (_midi_port) {
461                         if ((output_parser = _midi_port->output()) != 0) {
462                                 return output_parser->tracing();
463                         }
464                 }
465         }
466
467         return false;
468
469 }
470
471 void
472 Session::setup_midi_control ()
473 {
474         outbound_mtc_timecode_frame = 0;
475         next_quarter_frame_to_send = 0;
476
477         /* setup the MMC buffer */
478
479         mmc_buffer[0] = 0xf0; // SysEx
480         mmc_buffer[1] = 0x7f; // Real Time SysEx ID for MMC
481         mmc_buffer[2] = (mmc ? mmc->send_device_id() : 0x7f);
482         mmc_buffer[3] = 0x6;  // MCC
483
484         /* Set up the qtr frame message */
485
486         mtc_msg[0] = 0xf1;
487         mtc_msg[2] = 0xf1;
488         mtc_msg[4] = 0xf1;
489         mtc_msg[6] = 0xf1;
490         mtc_msg[8] = 0xf1;
491         mtc_msg[10] = 0xf1;
492         mtc_msg[12] = 0xf1;
493         mtc_msg[14] = 0xf1;
494 }
495
496 void
497 Session::spp_start (Parser &, nframes_t /*timestamp*/)
498 {
499         if (Config->get_mmc_control() && (config.get_external_sync() && config.get_sync_source() != MTC)) {
500                 request_transport_speed (1.0);
501         }
502 }
503
504 void
505 Session::spp_continue (Parser& ignored, nframes_t timestamp)
506 {
507         spp_start (ignored, timestamp);
508 }
509
510 void
511 Session::spp_stop (Parser&, nframes_t /*timestamp*/)
512 {
513         if (Config->get_mmc_control()) {
514                 request_stop ();
515         }
516 }
517 /*
518 void
519 Session::midi_clock_start (Parser& ignored, nframes_t timestamp)
520 {
521         if (config.get_external_sync() && (config.get_sync_source() == MIDIClock)) {
522                 request_transport_speed (1.0);
523         }
524 }
525
526 void
527 Session::midi_clock_continue (Parser& parser, nframes_t timestamp)
528 {
529         midi_clock_start (parser, 0);
530 }
531
532 void
533 Session::midi_clock_stop (Parser& ignored, nframes_t timestamp)
534 {
535         if (config.get_external_sync() && (config.get_slave_source() == MIDIClock)) {
536                 request_stop ();
537         }
538 }
539 */
540
541 void
542 Session::mmc_deferred_play (MIDI::MachineControl &/*mmc*/)
543 {
544         if (Config->get_mmc_control() && (config.get_external_sync() && (config.get_sync_source() != MTC))) {
545                 request_transport_speed (1.0);
546         }
547 }
548
549 void
550 Session::mmc_record_pause (MIDI::MachineControl &/*mmc*/)
551 {
552         if (Config->get_mmc_control()) {
553                 maybe_enable_record();
554         }
555 }
556
557 void
558 Session::mmc_record_strobe (MIDI::MachineControl &/*mmc*/)
559 {
560         if (!Config->get_mmc_control())
561                 return;
562
563         /* record strobe does an implicit "Play" command */
564
565         if (_transport_speed != 1.0) {
566
567                 /* start_transport() will move from Enabled->Recording, so we
568                    don't need to do anything here except enable recording.
569                    its not the same as maybe_enable_record() though, because
570                    that *can* switch to Recording, which we do not want.
571                 */
572
573                 save_state ("", true);
574                 g_atomic_int_set (&_record_status, Enabled);
575                 RecordStateChanged (); /* EMIT SIGNAL */
576
577                 request_transport_speed (1.0);
578
579         } else {
580
581                 enable_record ();
582         }
583 }
584
585 void
586 Session::mmc_record_exit (MIDI::MachineControl &/*mmc*/)
587 {
588         if (Config->get_mmc_control()) {
589                 disable_record (false);
590         }
591 }
592
593 void
594 Session::mmc_stop (MIDI::MachineControl &/*mmc*/)
595 {
596         if (Config->get_mmc_control()) {
597                 request_stop ();
598         }
599 }
600
601 void
602 Session::mmc_pause (MIDI::MachineControl &/*mmc*/)
603 {
604         if (Config->get_mmc_control()) {
605
606                 /* We support RECORD_PAUSE, so the spec says that
607                    we must interpret PAUSE like RECORD_PAUSE if
608                    recording.
609                 */
610
611                 if (actively_recording()) {
612                         maybe_enable_record ();
613                 } else {
614                         request_stop ();
615                 }
616         }
617 }
618
619 static bool step_queued = false;
620
621 void
622 Session::mmc_step (MIDI::MachineControl &/*mmc*/, int steps)
623 {
624         if (!Config->get_mmc_control()) {
625                 return;
626         }
627
628         struct timeval now;
629         struct timeval diff = { 0, 0 };
630
631         gettimeofday (&now, 0);
632
633         timersub (&now, &last_mmc_step, &diff);
634
635         gettimeofday (&now, 0);
636         timersub (&now, &last_mmc_step, &diff);
637
638         if (last_mmc_step.tv_sec != 0 && (diff.tv_usec + (diff.tv_sec * 1000000)) < _engine.usecs_per_cycle()) {
639                 return;
640         }
641
642         double diff_secs = diff.tv_sec + (diff.tv_usec / 1000000.0);
643         double cur_speed = (((steps * 0.5) * timecode_frames_per_second()) / diff_secs) / timecode_frames_per_second();
644
645         if (_transport_speed == 0 || cur_speed * _transport_speed < 0) {
646                 /* change direction */
647                 step_speed = cur_speed;
648         } else {
649                 step_speed = (0.6 * step_speed) + (0.4 * cur_speed);
650         }
651
652         step_speed *= 0.25;
653
654 #if 0
655         cerr << "delta = " << diff_secs
656              << " ct = " << _transport_speed
657              << " steps = " << steps
658              << " new speed = " << cur_speed
659              << " speed = " << step_speed
660              << endl;
661 #endif
662
663         request_transport_speed (step_speed);
664         last_mmc_step = now;
665
666         if (!step_queued) {
667                 midi_timeouts.push_back (mem_fun (*this, &Session::mmc_step_timeout));
668                 step_queued = true;
669         }
670 }
671
672 void
673 Session::mmc_rewind (MIDI::MachineControl &/*mmc*/)
674 {
675         if (Config->get_mmc_control()) {
676                 request_transport_speed(-8.0f);
677         }
678 }
679
680 void
681 Session::mmc_fast_forward (MIDI::MachineControl &/*mmc*/)
682 {
683         if (Config->get_mmc_control()) {
684                 request_transport_speed(8.0f);
685         }
686 }
687
688 void
689 Session::mmc_locate (MIDI::MachineControl &/*mmc*/, const MIDI::byte* mmc_tc)
690 {
691         if (!Config->get_mmc_control()) {
692                 return;
693         }
694
695         nframes_t target_frame;
696         Timecode::Time timecode;
697
698         timecode.hours = mmc_tc[0] & 0xf;
699         timecode.minutes = mmc_tc[1];
700         timecode.seconds = mmc_tc[2];
701         timecode.frames = mmc_tc[3];
702         timecode.rate = timecode_frames_per_second();
703         timecode.drop = timecode_drop_frames();
704
705         // Also takes timecode offset into account:
706         timecode_to_sample( timecode, target_frame, true /* use_offset */, false /* use_subframes */ );
707
708         if (target_frame > max_frames) {
709                 target_frame = max_frames;
710         }
711
712         /* Some (all?) MTC/MMC devices do not send a full MTC frame
713            at the end of a locate, instead sending only an MMC
714            locate command. This causes the current position
715            of an MTC slave to become out of date. Catch this.
716         */
717
718         MTC_Slave* mtcs = dynamic_cast<MTC_Slave*> (_slave);
719
720         if (mtcs != 0) {
721                 // cerr << "Locate *with* MTC slave\n";
722                 mtcs->handle_locate (mmc_tc);
723         } else {
724                 // cerr << "Locate without MTC slave\n";
725                 request_locate (target_frame, false);
726         }
727 }
728
729 void
730 Session::mmc_shuttle (MIDI::MachineControl &/*mmc*/, float speed, bool forw)
731 {
732         if (!Config->get_mmc_control()) {
733                 return;
734         }
735
736         if (Config->get_shuttle_speed_threshold() >= 0 && speed > Config->get_shuttle_speed_threshold()) {
737                 speed *= Config->get_shuttle_speed_factor();
738         }
739
740         if (forw) {
741                 request_transport_speed (speed);
742         } else {
743                 request_transport_speed (-speed);
744         }
745 }
746
747 void
748 Session::mmc_record_enable (MIDI::MachineControl &mmc, size_t trk, bool enabled)
749 {
750         if (Config->get_mmc_control()) {
751
752                 RouteList::iterator i;
753                 boost::shared_ptr<RouteList> r = routes.reader();
754
755                 for (i = r->begin(); i != r->end(); ++i) {
756                         AudioTrack *at;
757
758                         if ((at = dynamic_cast<AudioTrack*>((*i).get())) != 0) {
759                                 if (trk == at->remote_control_id()) {
760                                         at->set_record_enable (enabled, &mmc);
761                                         break;
762                                 }
763                         }
764                 }
765         }
766 }
767
768 void
769 Session::change_midi_ports ()
770 {
771         MIDIRequest* request = new MIDIRequest;
772
773         request->type = MIDIRequest::PortChange;
774         midi_requests.write (&request, 1);
775         poke_midi_thread ();
776 }
777
778 /** Send MTC Full Frame message (complete Timecode time) for the start of this cycle.
779  * This resets the MTC code, the next quarter frame message that is sent will be
780  * the first one with the beginning of this cycle as the new start point.
781  */
782 int
783 Session::send_full_time_code(nframes_t /*nframes*/)
784 {
785         /* This function could easily send at a given frame offset, but would
786          * that be useful?  Does ardour do sub-block accurate locating? [DR] */
787
788         MIDI::byte msg[10];
789         Timecode::Time timecode;
790
791         _send_timecode_update = false;
792
793         if (_mtc_port == 0 || !session_send_mtc) {
794                 return 0;
795         }
796
797         // Get timecode time for this transport frame
798         sample_to_timecode(_transport_frame, timecode, true /* use_offset */, false /* no subframes */);
799
800         transmitting_timecode_time = timecode;
801         outbound_mtc_timecode_frame = _transport_frame;
802
803         // I don't understand this bit yet.. [DR]
804         if (((mtc_timecode_bits >> 5) != MIDI::MTC_25_FPS) && (transmitting_timecode_time.frames % 2)) {
805                 // start MTC quarter frame transmission on an even frame
806                 Timecode::increment( transmitting_timecode_time, config.get_subframes_per_frame() );
807                 outbound_mtc_timecode_frame += (nframes_t) _frames_per_timecode_frame;
808         }
809
810         // Compensate for audio latency
811         outbound_mtc_timecode_frame += _worst_output_latency;
812
813         next_quarter_frame_to_send = 0;
814
815         // Sync slave to the same Timecode time as we are on
816         msg[0] = 0xf0;
817         msg[1] = 0x7f;
818         msg[2] = 0x7f;
819         msg[3] = 0x1;
820         msg[4] = 0x1;
821         msg[9] = 0xf7;
822
823         msg[5] = mtc_timecode_bits | timecode.hours;
824         msg[6] = timecode.minutes;
825         msg[7] = timecode.seconds;
826         msg[8] = timecode.frames;
827
828         cerr << "MTC: Sending full time code at " << outbound_mtc_timecode_frame << endl;
829
830         // Send message at offset 0, sent time is for the start of this cycle
831         if (_mtc_port->midimsg (msg, sizeof (msg), 0)) {
832                 error << _("Session: could not send full MIDI time code") << endmsg;
833                 return -1;
834         }
835
836         return 0;
837 }
838
839 /** Send MTC (quarter-frame) messages for this cycle.
840  * Must be called exactly once per cycle from the audio thread.  Realtime safe.
841  * This function assumes the state of full Timecode is sane, eg. the slave is
842  * expecting quarter frame messages and has the right frame of reference (any
843  * full MTC Timecode time messages that needed to be sent should have been sent
844  * earlier already this cycle by send_full_time_code)
845  */
846 int
847 Session::send_midi_time_code_for_cycle(nframes_t nframes)
848 {
849         assert (next_quarter_frame_to_send >= 0);
850         assert (next_quarter_frame_to_send <= 7);
851
852         if (_mtc_port == 0 || !session_send_mtc || transmitting_timecode_time.negative
853             /*|| (next_quarter_frame_to_send < 0)*/ ) {
854                 // cerr << "(MTC) Not sending MTC\n";
855                 return 0;
856         }
857
858         /* Duration of one quarter frame */
859         nframes_t quarter_frame_duration = ((long) _frames_per_timecode_frame) >> 2;
860
861         // cerr << "(MTC) TR: " << _transport_frame << " - SF: " << outbound_mtc_timecode_frame
862         // << " - NQ: " << next_quarter_frame_to_send << " - FD" << quarter_frame_duration << endl;
863
864         // FIXME: this should always be true
865         //assert((outbound_mtc_timecode_frame + (next_quarter_frame_to_send * quarter_frame_duration))
866         //              > _transport_frame);
867
868
869         // Send quarter frames for this cycle
870         while (_transport_frame + nframes > (outbound_mtc_timecode_frame +
871                                 (next_quarter_frame_to_send * quarter_frame_duration))) {
872
873                 // cerr << "(MTC) Next frame to send: " << next_quarter_frame_to_send << endl;
874
875                 switch (next_quarter_frame_to_send) {
876                         case 0:
877                                 mtc_msg[1] =  0x00 | (transmitting_timecode_time.frames & 0xf);
878                                 break;
879                         case 1:
880                                 mtc_msg[1] =  0x10 | ((transmitting_timecode_time.frames & 0xf0) >> 4);
881                                 break;
882                         case 2:
883                                 mtc_msg[1] =  0x20 | (transmitting_timecode_time.seconds & 0xf);
884                                 break;
885                         case 3:
886                                 mtc_msg[1] =  0x30 | ((transmitting_timecode_time.seconds & 0xf0) >> 4);
887                                 break;
888                         case 4:
889                                 mtc_msg[1] =  0x40 | (transmitting_timecode_time.minutes & 0xf);
890                                 break;
891                         case 5:
892                                 mtc_msg[1] = 0x50 | ((transmitting_timecode_time.minutes & 0xf0) >> 4);
893                                 break;
894                         case 6:
895                                 mtc_msg[1] = 0x60 | ((mtc_timecode_bits|transmitting_timecode_time.hours) & 0xf);
896                                 break;
897                         case 7:
898                                 mtc_msg[1] = 0x70 | (((mtc_timecode_bits|transmitting_timecode_time.hours) & 0xf0) >> 4);
899                                 break;
900                 }
901
902                 const nframes_t msg_time = (outbound_mtc_timecode_frame
903                         + (quarter_frame_duration * next_quarter_frame_to_send));
904
905                 // This message must fall within this block or something is broken
906                 assert(msg_time >= _transport_frame);
907                 assert(msg_time < _transport_frame + nframes);
908
909                 nframes_t out_stamp = msg_time - _transport_frame;
910                 assert(out_stamp < nframes);
911
912                 if (_mtc_port->midimsg (mtc_msg, 2, out_stamp)) {
913                         error << string_compose(_("Session: cannot send quarter-frame MTC message (%1)"), strerror (errno))
914                               << endmsg;
915                         return -1;
916                 }
917
918                 /*cerr << "(MTC) Timecode: " << transmitting_timecode_time.hours
919                         << ":" << transmitting_timecode_time.minutes
920                         << ":" << transmitting_timecode_time.seconds
921                         << ":" << transmitting_timecode_time.frames
922                         << ", qfm = " << next_quarter_frame_to_send
923                         << ", stamp = " << out_stamp
924                         << ", delta = " << _transport_frame + out_stamp - last_time << endl;*/
925
926                 // Increment quarter frame counter
927                 next_quarter_frame_to_send++;
928
929                 if (next_quarter_frame_to_send >= 8) {
930                         // Wrap quarter frame counter
931                         next_quarter_frame_to_send = 0;
932                         // Increment timecode time twice
933                         Timecode::increment( transmitting_timecode_time, config.get_subframes_per_frame() );
934                         Timecode::increment( transmitting_timecode_time, config.get_subframes_per_frame() );
935                         // Re-calculate timing of first quarter frame
936                         //timecode_to_sample( transmitting_timecode_time, outbound_mtc_timecode_frame, true /* use_offset */, false );
937                         outbound_mtc_timecode_frame += 8 * quarter_frame_duration;
938                         // Compensate for audio latency
939                         outbound_mtc_timecode_frame += _worst_output_latency;
940                 }
941         }
942
943         return 0;
944 }
945
946 /***********************************************************************
947  OUTBOUND MMC STUFF
948 **********************************************************************/
949
950 void
951 Session::deliver_mmc (MIDI::MachineControl::Command cmd, nframes_t where)
952 {
953         using namespace MIDI;
954         int nbytes = 4;
955         Timecode::Time timecode;
956
957         if (_mmc_port == 0 || !session_send_mmc) {
958                 // cerr << "Not delivering MMC " << _mmc_port << " - " << session_send_mmc << endl;
959                 return;
960         }
961
962         mmc_buffer[nbytes++] = cmd;
963
964         // cerr << "delivering MMC, cmd = " << hex << (int) cmd << dec << endl;
965
966         switch (cmd) {
967         case MachineControl::cmdLocate:
968                 timecode_time_subframes (where, timecode);
969
970                 mmc_buffer[nbytes++] = 0x6; // byte count
971                 mmc_buffer[nbytes++] = 0x1; // "TARGET" subcommand
972                 mmc_buffer[nbytes++] = timecode.hours;
973                 mmc_buffer[nbytes++] = timecode.minutes;
974                 mmc_buffer[nbytes++] = timecode.seconds;
975                 mmc_buffer[nbytes++] = timecode.frames;
976                 mmc_buffer[nbytes++] = timecode.subframes;
977                 break;
978
979         case MachineControl::cmdStop:
980                 break;
981
982         case MachineControl::cmdPlay:
983                 /* always convert Play into Deferred Play */
984                 /* Why? [DR] */
985                 mmc_buffer[4] = MachineControl::cmdDeferredPlay;
986                 break;
987
988         case MachineControl::cmdDeferredPlay:
989                 break;
990
991         case MachineControl::cmdRecordStrobe:
992                 break;
993
994         case MachineControl::cmdRecordExit:
995                 break;
996
997         case MachineControl::cmdRecordPause:
998                 break;
999
1000         default:
1001                 nbytes = 0;
1002         };
1003
1004         if (nbytes) {
1005
1006                 mmc_buffer[nbytes++] = 0xf7; // terminate SysEx/MMC message
1007
1008                 if (_mmc_port->midimsg (mmc_buffer, nbytes, 0)) {
1009                         error << string_compose(_("MMC: cannot send command %1%2%3"), &hex, cmd, &dec) << endmsg;
1010                 }
1011         }
1012 }
1013
1014 bool
1015 Session::mmc_step_timeout ()
1016 {
1017         struct timeval now;
1018         struct timeval diff;
1019         double diff_usecs;
1020         gettimeofday (&now, 0);
1021
1022         timersub (&now, &last_mmc_step, &diff);
1023         diff_usecs = diff.tv_sec * 1000000 + diff.tv_usec;
1024
1025         if (diff_usecs > 1000000.0 || fabs (_transport_speed) < 0.0000001) {
1026                 /* too long or too slow, stop transport */
1027                 request_transport_speed (0.0);
1028                 step_queued = false;
1029                 return false;
1030         }
1031
1032         if (diff_usecs < 250000.0) {
1033                 /* too short, just keep going */
1034                 return true;
1035         }
1036
1037         /* slow it down */
1038
1039         request_transport_speed (_transport_speed * 0.75);
1040         return true;
1041 }
1042
1043 /*---------------------------------------------------------------------------
1044   MIDI THREAD
1045   ---------------------------------------------------------------------------*/
1046
1047 int
1048 Session::start_midi_thread ()
1049 {
1050         if (pipe (midi_request_pipe)) {
1051                 error << string_compose(_("Cannot create transport request signal pipe (%1)"), strerror (errno)) << endmsg;
1052                 return -1;
1053         }
1054
1055         if (fcntl (midi_request_pipe[0], F_SETFL, O_NONBLOCK)) {
1056                 error << string_compose(_("UI: cannot set O_NONBLOCK on "    "signal read pipe (%1)"), strerror (errno)) << endmsg;
1057                 return -1;
1058         }
1059
1060         if (fcntl (midi_request_pipe[1], F_SETFL, O_NONBLOCK)) {
1061                 error << string_compose(_("UI: cannot set O_NONBLOCK on "    "signal write pipe (%1)"), strerror (errno)) << endmsg;
1062                 return -1;
1063         }
1064
1065         if (pthread_create_and_store ("transport", &midi_thread, 0, _midi_thread_work, this)) {
1066                 error << _("Session: could not create transport thread") << endmsg;
1067                 return -1;
1068         }
1069
1070         return 0;
1071 }
1072
1073 void
1074 Session::terminate_midi_thread ()
1075 {
1076         if (midi_thread) {
1077
1078                 MIDIRequest* request = new MIDIRequest;
1079                 void* status;
1080
1081                 request->type = MIDIRequest::Quit;
1082
1083                 midi_requests.write (&request, 1);
1084                 poke_midi_thread ();
1085
1086                 pthread_join (midi_thread, &status);
1087         }
1088 }
1089
1090 void
1091 Session::poke_midi_thread ()
1092 {
1093         static char c = 0;
1094
1095         if (write (midi_request_pipe[1], &c, 1) != 1) {
1096                 error << string_compose(_("cannot send signal to midi thread! (%1)"), strerror (errno)) << endmsg;
1097         }
1098 }
1099
1100 void *
1101 Session::_midi_thread_work (void* arg)
1102 {
1103         pthread_setcancelstate (PTHREAD_CANCEL_ENABLE, 0);
1104         pthread_setcanceltype (PTHREAD_CANCEL_ASYNCHRONOUS, 0);
1105
1106         ((Session *) arg)->midi_thread_work ();
1107         return 0;
1108 }
1109
1110 void
1111 Session::midi_thread_work ()
1112 {
1113         MIDIRequest* request;
1114         struct pollfd pfd[4];
1115         int nfds = 0;
1116         int timeout;
1117         int fds_ready;
1118         struct sched_param rtparam;
1119         int x;
1120         bool restart;
1121         vector<MIDI::Port*> ports;
1122
1123         PBD::notify_gui_about_thread_creation (pthread_self(), X_("MIDI"), 2048);
1124
1125         memset (&rtparam, 0, sizeof (rtparam));
1126         rtparam.sched_priority = 9; /* XXX should be relative to audio (JACK) thread */
1127
1128         if ((x = pthread_setschedparam (pthread_self(), SCHED_FIFO, &rtparam)) != 0) {
1129                 // do we care? not particularly.
1130         }
1131
1132         /* set up the port vector; 5 is the largest possible size for now */
1133
1134         ports.assign (5, (MIDI::Port*) 0);
1135
1136         while (1) {
1137
1138                 nfds = 0;
1139
1140                 pfd[nfds].fd = midi_request_pipe[0];
1141                 pfd[nfds].events = POLLIN|POLLHUP|POLLERR;
1142                 nfds++;
1143
1144                 if (Config->get_mmc_control() && _mmc_port && _mmc_port->selectable() >= 0) {
1145                         pfd[nfds].fd = _mmc_port->selectable();
1146                         pfd[nfds].events = POLLIN|POLLHUP|POLLERR;
1147                         ports[nfds] = _mmc_port;
1148                         //cerr << "MIDI port " << nfds << " = MMC @ " << _mmc_port << endl;
1149                         nfds++;
1150                 }
1151
1152                 /* if MTC is being handled on a different port from MMC
1153                    or we are not handling MMC at all, poll
1154                    the relevant port.
1155                 */
1156
1157                 if (_mtc_port && (_mtc_port != _mmc_port || !Config->get_mmc_control()) && _mtc_port->selectable() >= 0) {
1158                         pfd[nfds].fd = _mtc_port->selectable();
1159                         pfd[nfds].events = POLLIN|POLLHUP|POLLERR;
1160                         ports[nfds] = _mtc_port;
1161                         //cerr << "MIDI port " << nfds << " = MTC @ " << _mtc_port << endl;
1162                         nfds++;
1163                 }
1164
1165                 if (_midi_clock_port && (_midi_clock_port != _mmc_port || !Config->get_mmc_control()) && _midi_clock_port->selectable() >= 0) {
1166                         pfd[nfds].fd = _midi_clock_port->selectable();
1167                         pfd[nfds].events = POLLIN|POLLHUP|POLLERR;
1168                         ports[nfds] = _midi_clock_port;
1169                         nfds++;
1170                 }
1171
1172                 /* if we are using MMC control, we obviously have to listen
1173                    the relevant port.
1174                 */
1175
1176                 if (_midi_port && (_midi_port != _mmc_port || !Config->get_mmc_control()) && (_midi_port != _mtc_port) && _midi_port->selectable() >= 0) {
1177                         pfd[nfds].fd = _midi_port->selectable();
1178                         pfd[nfds].events = POLLIN|POLLHUP|POLLERR;
1179                         ports[nfds] = _midi_port;
1180                         // cerr << "MIDI port " << nfds << " = MIDI @ " << _midi_port << endl;
1181                         nfds++;
1182                 }
1183
1184                 if (!midi_timeouts.empty()) {
1185                         timeout = 100; /* 10msecs */
1186                 } else {
1187                         timeout = -1; /* if there is no data, we don't care */
1188                 }
1189
1190           again:
1191                 // cerr << "MIDI poll on " << nfds << " for " << timeout << endl;
1192                 if (poll (pfd, nfds, timeout) < 0) {
1193                         if (errno == EINTR) {
1194                                 /* gdb at work, perhaps */
1195                                 goto again;
1196                         }
1197
1198                         error << string_compose(_("MIDI thread poll failed (%1)"), strerror (errno)) << endmsg;
1199
1200                         break;
1201                 }
1202                 // cerr << "MIDI thread wakes at " << get_cycles () << endl;
1203
1204                 fds_ready = 0;
1205
1206                 /* check the transport request pipe */
1207
1208                 if (pfd[0].revents & ~POLLIN) {
1209                         error << _("Error on transport thread request pipe") << endmsg;
1210                         break;
1211                 }
1212
1213                 if (pfd[0].revents & POLLIN) {
1214
1215                         char foo[16];
1216
1217                         // cerr << "MIDI request FIFO ready\n";
1218                         fds_ready++;
1219
1220                         /* empty the pipe of all current requests */
1221
1222                         while (1) {
1223                                 size_t nread = read (midi_request_pipe[0], &foo, sizeof (foo));
1224
1225                                 if (nread > 0) {
1226                                         if ((size_t) nread < sizeof (foo)) {
1227                                                 break;
1228                                         } else {
1229                                                 continue;
1230                                         }
1231                                 } else if (nread == 0) {
1232                                         break;
1233                                 } else if (errno == EAGAIN) {
1234                                         break;
1235                                 } else {
1236                                         fatal << _("Error reading from transport request pipe") << endmsg;
1237                                         /*NOTREACHED*/
1238                                 }
1239                         }
1240
1241                         while (midi_requests.read (&request, 1) == 1) {
1242
1243                                 switch (request->type) {
1244                                 case MIDIRequest::PortChange:
1245                                         /* restart poll with new ports */
1246                                         // cerr << "rebind\n";
1247                                         restart = true;
1248                                         break;
1249
1250                                 case MIDIRequest::Quit:
1251                                         delete request;
1252                                         pthread_exit_pbd (0);
1253                                         /*NOTREACHED*/
1254                                         break;
1255
1256                                 default:
1257                                         break;
1258                                 }
1259
1260
1261                                 delete request;
1262                         }
1263
1264                 }
1265
1266                 if (restart) {
1267                         continue;
1268                 }
1269
1270                 /* now read the rest of the ports */
1271
1272                 for (int p = 1; p < nfds; ++p) {
1273                         if ((pfd[p].revents & ~POLLIN)) {
1274                                 // error << string_compose(_("Transport: error polling MIDI port %1 (revents =%2%3%4"), p, &hex, pfd[p].revents, &dec) << endmsg;
1275                                 break;
1276                         }
1277
1278                         if (pfd[p].revents & POLLIN) {
1279                                 fds_ready++;
1280                                 ports[p]->parse ();
1281                         }
1282                 }
1283
1284                 /* timeout driven */
1285
1286                 if (fds_ready < 2 && timeout != -1) {
1287
1288                         for (MidiTimeoutList::iterator i = midi_timeouts.begin(); i != midi_timeouts.end(); ) {
1289
1290                                 MidiTimeoutList::iterator tmp;
1291                                 tmp = i;
1292                                 ++tmp;
1293
1294                                 if (!(*i)()) {
1295                                         midi_timeouts.erase (i);
1296                                 }
1297
1298                                 i = tmp;
1299                         }
1300                 }
1301         }
1302 }
1303