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