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