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