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