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