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