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