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