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