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