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