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