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