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