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