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