switch to using boost::signals2 instead of sigc++, at least for libardour. not finish...
[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 <glibmm/main.h>
32
33 #include "midi++/mmc.h"
34 #include "midi++/port.h"
35 #include "midi++/manager.h"
36 #include "pbd/error.h"
37 #include "pbd/pthread_utils.h"
38
39 #include "ardour/configuration.h"
40 #include "ardour/debug.h"
41 #include "ardour/audioengine.h"
42 #include "ardour/session.h"
43 #include "ardour/audio_track.h"
44 #include "ardour/midi_track.h"
45 #include "ardour/midi_ui.h"
46 #include "ardour/audio_diskstream.h"
47 #include "ardour/slave.h"
48 #include "ardour/cycles.h"
49 #include "ardour/timecode.h"
50
51 #include "i18n.h"
52
53 using namespace std;
54 using namespace ARDOUR;
55 using namespace PBD;
56 using namespace MIDI;
57 using namespace Glib;
58
59 MachineControl::CommandSignature MMC_CommandSignature;
60 MachineControl::ResponseSignature MMC_ResponseSignature;
61
62
63 void
64 Session::midi_panic()
65 {
66         {
67                 boost::shared_ptr<RouteList> r = routes.reader ();
68
69                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
70                         MidiTrack *track = dynamic_cast<MidiTrack*>((*i).get());
71                         if (track != 0) {
72                                 track->midi_panic();
73                         }
74                 }
75         }
76 }
77
78 int
79 Session::use_config_midi_ports ()
80 {
81         string port_name;
82
83         if (default_mmc_port) {
84                 set_mmc_port (default_mmc_port->name());
85         } else {
86                 set_mmc_port ("");
87         }
88
89         if (default_mtc_port) {
90                 set_mtc_port (default_mtc_port->name());
91         } else {
92                 set_mtc_port ("");
93         }
94
95         if (default_midi_port) {
96                 set_midi_port (default_midi_port->name());
97         } else {
98                 set_midi_port ("");
99         }
100
101         if (default_midi_clock_port) {
102                 set_midi_clock_port (default_midi_clock_port->name());
103         } else {
104                 set_midi_clock_port ("");
105         }
106
107         return 0;
108 }
109
110
111 /***********************************************************************
112  MTC, MMC, etc.
113 **********************************************************************/
114
115 int
116 Session::set_mtc_port (string port_tag)
117 {
118         MTC_Slave *ms;
119
120         if (port_tag.length() == 0) {
121
122                 if (_slave && ((ms = dynamic_cast<MTC_Slave*> (_slave)) != 0)) {
123                         error << _("Ardour is slaved to MTC - port cannot be reset") << endmsg;
124                         return -1;
125                 }
126
127                 if (_mtc_port == 0) {
128                         return 0;
129                 }
130
131                 _mtc_port = 0;
132                 goto out;
133         }
134
135         MIDI::Port* port;
136
137         if ((port = MIDI::Manager::instance()->port (port_tag)) == 0) {
138                 error << string_compose (_("unknown port %1 requested for MTC"), port_tag) << endl;
139                 return -1;
140         }
141
142         _mtc_port = port;
143
144         if (_slave && ((ms = dynamic_cast<MTC_Slave*> (_slave)) != 0)) {
145                 ms->rebind (*port);
146         }
147
148         Config->set_mtc_port_name (port_tag);
149
150   out:
151         MTC_PortChanged(); /* EMIT SIGNAL */
152         set_dirty();
153         return 0;
154 }
155
156 void
157 Session::set_mmc_receive_device_id (uint32_t device_id)
158 {
159         if (mmc) {
160                 mmc->set_receive_device_id (device_id);
161         }
162 }
163
164 void
165 Session::set_mmc_send_device_id (uint32_t device_id)
166 {
167         if (mmc) {
168                 mmc->set_send_device_id (device_id);
169         }
170 }
171
172 int
173 Session::set_mmc_port (string port_tag)
174 {
175         MIDI::byte old_recv_device_id = 0;
176         MIDI::byte old_send_device_id = 0;
177         bool reset_id = false;
178
179         if (port_tag.length() == 0) {
180                 if (_mmc_port == 0) {
181                         return 0;
182                 }
183                 _mmc_port = 0;
184                 goto out;
185         }
186
187         MIDI::Port* port;
188
189         if ((port = MIDI::Manager::instance()->port (port_tag)) == 0) {
190                 return -1;
191         }
192
193         _mmc_port = port;
194
195         if (mmc) {
196                 old_recv_device_id = mmc->receive_device_id();
197                 old_recv_device_id = mmc->send_device_id();
198                 reset_id = true;
199                 delete mmc;
200         }
201
202         mmc = new MIDI::MachineControl (*_mmc_port, 1.0,
203                                         MMC_CommandSignature,
204                                         MMC_ResponseSignature);
205
206         if (reset_id) {
207                 mmc->set_receive_device_id (old_recv_device_id);
208                 mmc->set_send_device_id (old_send_device_id);
209         }
210
211         scoped_connect (mmc->Play, boost::bind (&Session::mmc_deferred_play, this, _1));
212         scoped_connect (mmc->DeferredPlay, boost::bind (&Session::mmc_deferred_play, this, _1));
213         scoped_connect (mmc->Stop, boost::bind (&Session::mmc_stop, this, _1));
214         scoped_connect (mmc->FastForward, boost::bind (&Session::mmc_fast_forward, this, _1));
215         scoped_connect (mmc->Rewind, boost::bind (&Session::mmc_rewind, this, _1));
216         scoped_connect (mmc->Pause, boost::bind (&Session::mmc_pause, this, _1));
217         scoped_connect (mmc->RecordPause, boost::bind (&Session::mmc_record_pause, this, _1));
218         scoped_connect (mmc->RecordStrobe, boost::bind (&Session::mmc_record_strobe, this, _1));
219         scoped_connect (mmc->RecordExit, boost::bind (&Session::mmc_record_exit, this, _1));
220         scoped_connect (mmc->Locate, boost::bind (&Session::mmc_locate, this, _1, _2));
221         scoped_connect (mmc->Step, boost::bind (&Session::mmc_step, this, _1, _2));
222         scoped_connect (mmc->Shuttle, boost::bind (&Session::mmc_shuttle, this, _1, _2, _3));
223         scoped_connect (mmc->TrackRecordStatusChange, boost::bind (&Session::mmc_record_enable, this, _1, _2, _3));
224
225
226         /* also handle MIDI SPP because its so common */
227
228         scoped_connect (_mmc_port->input()->start, boost::bind (&Session::spp_start, this, _1, _2));
229         scoped_connect (_mmc_port->input()->contineu, boost::bind (&Session::spp_continue, this, _1, _2));
230         scoped_connect (_mmc_port->input()->stop, boost::bind (&Session::spp_stop, this, _1, _2));
231
232         Config->set_mmc_port_name (port_tag);
233
234   out:
235         MMC_PortChanged(); /* EMIT SIGNAL */
236         set_dirty();
237         return 0;
238 }
239
240 int
241 Session::set_midi_port (string /*port_tag*/)
242 {
243 #if 0
244         if (port_tag.length() == 0) {
245                 if (_midi_port == 0) {
246                         return 0;
247                 }
248                 _midi_port = 0;
249                 goto out;
250         }
251
252         MIDI::Port* port;
253
254         if ((port = MIDI::Manager::instance()->port (port_tag)) == 0) {
255                 return -1;
256         }
257
258         _midi_port = port;
259
260         /* XXX need something to forward this to control protocols ? or just
261            use the signal below
262         */
263
264         Config->set_midi_port_name (port_tag);
265
266   out:
267 #endif
268         MIDI_PortChanged(); /* EMIT SIGNAL */
269         set_dirty();
270         return 0;
271 }
272
273 int
274 Session::set_midi_clock_port (string port_tag)
275 {
276         MIDIClock_Slave *ms;
277
278         if (port_tag.length() == 0) {
279
280                 if (_slave && ((ms = dynamic_cast<MIDIClock_Slave*> (_slave)) != 0)) {
281                         error << _("Ardour is slaved to MIDI Clock - port cannot be reset") << endmsg;
282                         return -1;
283                 }
284
285                 if (_midi_clock_port == 0) {
286                         return 0;
287                 }
288
289                 _midi_clock_port = 0;
290                 goto out;
291         }
292
293         MIDI::Port* port;
294
295         if ((port = MIDI::Manager::instance()->port (port_tag)) == 0) {
296                 error << string_compose (_("unknown port %1 requested for MIDI Clock"), port_tag) << endl;
297                 return -1;
298         }
299
300         _midi_clock_port = port;
301
302         if (_slave && ((ms = dynamic_cast<MIDIClock_Slave*> (_slave)) != 0)) {
303                 ms->rebind (*port);
304         }
305
306         Config->set_midi_clock_port_name (port_tag);
307
308   out:
309         MIDIClock_PortChanged(); /* EMIT SIGNAL */
310         set_dirty();
311         return 0;
312 }
313
314 void
315 Session::set_trace_midi_input (bool yn, MIDI::Port* port)
316 {
317         MIDI::Parser* input_parser;
318
319         cerr << "enabling tracing: " << yn << " for input port " << port->name() << endl;
320
321         if (port) {
322                 if ((input_parser = port->input()) != 0) {
323                         input_parser->trace (yn, &cout, "input: ");
324                 }
325         } else {
326
327                 if (_mmc_port) {
328                         if ((input_parser = _mmc_port->input()) != 0) {
329                                 input_parser->trace (yn, &cout, "input: ");
330                         }
331                 }
332
333                 if (_mtc_port && _mtc_port != _mmc_port) {
334                         if ((input_parser = _mtc_port->input()) != 0) {
335                                 input_parser->trace (yn, &cout, "input: ");
336                         }
337                 }
338
339                 if (_midi_port && _midi_port != _mmc_port && _midi_port != _mtc_port  ) {
340                         if ((input_parser = _midi_port->input()) != 0) {
341                                 input_parser->trace (yn, &cout, "input: ");
342                         }
343                 }
344
345                 if (_midi_clock_port
346                         && _midi_clock_port != _mmc_port
347                         && _midi_clock_port != _mtc_port
348                         && _midi_clock_port != _midi_port) {
349                         if ((input_parser = _midi_clock_port->input()) != 0) {
350                                 input_parser->trace (yn, &cout, "input: ");
351                         }
352                 }
353         }
354
355         Config->set_trace_midi_input (yn);
356 }
357
358 void
359 Session::set_trace_midi_output (bool yn, MIDI::Port* port)
360 {
361         MIDI::Parser* output_parser;
362
363         if (port) {
364                 if ((output_parser = port->output()) != 0) {
365                         output_parser->trace (yn, &cout, "output: ");
366                 }
367         } else {
368                 if (_mmc_port) {
369                         if ((output_parser = _mmc_port->output()) != 0) {
370                                 output_parser->trace (yn, &cout, "output: ");
371                         }
372                 }
373
374                 if (_mtc_port && _mtc_port != _mmc_port) {
375                         if ((output_parser = _mtc_port->output()) != 0) {
376                                 output_parser->trace (yn, &cout, "output: ");
377                         }
378                 }
379
380                 if (_midi_port && _midi_port != _mmc_port && _midi_port != _mtc_port  ) {
381                         if ((output_parser = _midi_port->output()) != 0) {
382                                 output_parser->trace (yn, &cout, "output: ");
383                         }
384                 }
385
386         }
387
388         Config->set_trace_midi_output (yn);
389 }
390
391 bool
392 Session::get_trace_midi_input(MIDI::Port *port)
393 {
394         MIDI::Parser* input_parser;
395         if (port) {
396                 if ((input_parser = port->input()) != 0) {
397                         return input_parser->tracing();
398                 }
399         }
400         else {
401                 if (_mmc_port) {
402                         if ((input_parser = _mmc_port->input()) != 0) {
403                                 return input_parser->tracing();
404                         }
405                 }
406
407                 if (_mtc_port) {
408                         if ((input_parser = _mtc_port->input()) != 0) {
409                                 return input_parser->tracing();
410                         }
411                 }
412
413                 if (_midi_port) {
414                         if ((input_parser = _midi_port->input()) != 0) {
415                                 return input_parser->tracing();
416                         }
417                 }
418         }
419
420         return false;
421 }
422
423 bool
424 Session::get_trace_midi_output(MIDI::Port *port)
425 {
426         MIDI::Parser* output_parser;
427         if (port) {
428                 if ((output_parser = port->output()) != 0) {
429                         return output_parser->tracing();
430                 }
431         }
432         else {
433                 if (_mmc_port) {
434                         if ((output_parser = _mmc_port->output()) != 0) {
435                                 return output_parser->tracing();
436                         }
437                 }
438
439                 if (_mtc_port) {
440                         if ((output_parser = _mtc_port->output()) != 0) {
441                                 return output_parser->tracing();
442                         }
443                 }
444
445                 if (_midi_port) {
446                         if ((output_parser = _midi_port->output()) != 0) {
447                                 return output_parser->tracing();
448                         }
449                 }
450         }
451
452         return false;
453
454 }
455
456 void
457 Session::setup_midi_control ()
458 {
459         outbound_mtc_timecode_frame = 0;
460         next_quarter_frame_to_send = 0;
461
462         /* setup the MMC buffer */
463
464         mmc_buffer[0] = 0xf0; // SysEx
465         mmc_buffer[1] = 0x7f; // Real Time SysEx ID for MMC
466         mmc_buffer[2] = (mmc ? mmc->send_device_id() : 0x7f);
467         mmc_buffer[3] = 0x6;  // MCC
468
469         /* Set up the qtr frame message */
470
471         mtc_msg[0] = 0xf1;
472         mtc_msg[2] = 0xf1;
473         mtc_msg[4] = 0xf1;
474         mtc_msg[6] = 0xf1;
475         mtc_msg[8] = 0xf1;
476         mtc_msg[10] = 0xf1;
477         mtc_msg[12] = 0xf1;
478         mtc_msg[14] = 0xf1;
479 }
480
481 void
482 Session::spp_start (Parser &, nframes_t /*timestamp*/)
483 {
484         if (Config->get_mmc_control() && (!config.get_external_sync() || config.get_sync_source() != JACK)) {
485                 request_transport_speed (1.0);
486         }
487 }
488
489 void
490 Session::spp_continue (Parser& ignored, nframes_t timestamp)
491 {
492         spp_start (ignored, timestamp);
493 }
494
495 void
496 Session::spp_stop (Parser&, nframes_t /*timestamp*/)
497 {
498         if (Config->get_mmc_control()) {
499                 request_stop ();
500         }
501 }
502
503 void
504 Session::mmc_deferred_play (MIDI::MachineControl &/*mmc*/)
505 {
506         if (Config->get_mmc_control() && (!config.get_external_sync() || (config.get_sync_source() != JACK))) {
507                 request_transport_speed (1.0);
508         }
509 }
510
511 void
512 Session::mmc_record_pause (MIDI::MachineControl &/*mmc*/)
513 {
514         if (Config->get_mmc_control()) {
515                 maybe_enable_record();
516         }
517 }
518
519 void
520 Session::mmc_record_strobe (MIDI::MachineControl &/*mmc*/)
521 {
522         if (!Config->get_mmc_control())
523                 return;
524
525         /* record strobe does an implicit "Play" command */
526
527         if (_transport_speed != 1.0) {
528
529                 /* start_transport() will move from Enabled->Recording, so we
530                    don't need to do anything here except enable recording.
531                    its not the same as maybe_enable_record() though, because
532                    that *can* switch to Recording, which we do not want.
533                 */
534
535                 save_state ("", true);
536                 g_atomic_int_set (&_record_status, Enabled);
537                 RecordStateChanged (); /* EMIT SIGNAL */
538
539                 request_transport_speed (1.0);
540
541         } else {
542
543                 enable_record ();
544         }
545 }
546
547 void
548 Session::mmc_record_exit (MIDI::MachineControl &/*mmc*/)
549 {
550         if (Config->get_mmc_control()) {
551                 disable_record (false);
552         }
553 }
554
555 void
556 Session::mmc_stop (MIDI::MachineControl &/*mmc*/)
557 {
558         if (Config->get_mmc_control()) {
559                 request_stop ();
560         }
561 }
562
563 void
564 Session::mmc_pause (MIDI::MachineControl &/*mmc*/)
565 {
566         if (Config->get_mmc_control()) {
567
568                 /* We support RECORD_PAUSE, so the spec says that
569                    we must interpret PAUSE like RECORD_PAUSE if
570                    recording.
571                 */
572
573                 if (actively_recording()) {
574                         maybe_enable_record ();
575                 } else {
576                         request_stop ();
577                 }
578         }
579 }
580
581 static bool step_queued = false;
582
583 void
584 Session::mmc_step (MIDI::MachineControl &/*mmc*/, int steps)
585 {
586         if (!Config->get_mmc_control()) {
587                 return;
588         }
589
590         struct timeval now;
591         struct timeval diff = { 0, 0 };
592
593         gettimeofday (&now, 0);
594
595         timersub (&now, &last_mmc_step, &diff);
596
597         gettimeofday (&now, 0);
598         timersub (&now, &last_mmc_step, &diff);
599
600         if (last_mmc_step.tv_sec != 0 && (diff.tv_usec + (diff.tv_sec * 1000000)) < _engine.usecs_per_cycle()) {
601                 return;
602         }
603
604         double diff_secs = diff.tv_sec + (diff.tv_usec / 1000000.0);
605         double cur_speed = (((steps * 0.5) * timecode_frames_per_second()) / diff_secs) / timecode_frames_per_second();
606
607         if (_transport_speed == 0 || cur_speed * _transport_speed < 0) {
608                 /* change direction */
609                 step_speed = cur_speed;
610         } else {
611                 step_speed = (0.6 * step_speed) + (0.4 * cur_speed);
612         }
613
614         step_speed *= 0.25;
615
616 #if 0
617         cerr << "delta = " << diff_secs
618              << " ct = " << _transport_speed
619              << " steps = " << steps
620              << " new speed = " << cur_speed
621              << " speed = " << step_speed
622              << endl;
623 #endif
624
625         request_transport_speed (step_speed);
626         last_mmc_step = now;
627
628         if (!step_queued) {
629                 if (midi_control_ui) {
630                         RefPtr<TimeoutSource> tsrc = TimeoutSource::create (100);
631                         tsrc->connect (sigc::mem_fun (*this, &Session::mmc_step_timeout));
632                         tsrc->attach (midi_control_ui->main_loop()->get_context());
633                         step_queued = true;
634                 }
635         }
636 }
637
638 void
639 Session::mmc_rewind (MIDI::MachineControl &/*mmc*/)
640 {
641         if (Config->get_mmc_control()) {
642                 request_transport_speed(-8.0f);
643         }
644 }
645
646 void
647 Session::mmc_fast_forward (MIDI::MachineControl &/*mmc*/)
648 {
649         if (Config->get_mmc_control()) {
650                 request_transport_speed(8.0f);
651         }
652 }
653
654 void
655 Session::mmc_locate (MIDI::MachineControl &/*mmc*/, const MIDI::byte* mmc_tc)
656 {
657         if (!Config->get_mmc_control()) {
658                 return;
659         }
660
661         nframes_t target_frame;
662         Timecode::Time timecode;
663
664         timecode.hours = mmc_tc[0] & 0xf;
665         timecode.minutes = mmc_tc[1];
666         timecode.seconds = mmc_tc[2];
667         timecode.frames = mmc_tc[3];
668         timecode.rate = timecode_frames_per_second();
669         timecode.drop = timecode_drop_frames();
670
671         // Also takes timecode offset into account:
672         timecode_to_sample( timecode, target_frame, true /* use_offset */, false /* use_subframes */ );
673
674         if (target_frame > max_frames) {
675                 target_frame = max_frames;
676         }
677
678         /* Some (all?) MTC/MMC devices do not send a full MTC frame
679            at the end of a locate, instead sending only an MMC
680            locate command. This causes the current position
681            of an MTC slave to become out of date. Catch this.
682         */
683
684         MTC_Slave* mtcs = dynamic_cast<MTC_Slave*> (_slave);
685
686         if (mtcs != 0) {
687                 // cerr << "Locate *with* MTC slave\n";
688                 mtcs->handle_locate (mmc_tc);
689         } else {
690                 // cerr << "Locate without MTC slave\n";
691                 request_locate (target_frame, false);
692         }
693 }
694
695 void
696 Session::mmc_shuttle (MIDI::MachineControl &/*mmc*/, float speed, bool forw)
697 {
698         if (!Config->get_mmc_control()) {
699                 return;
700         }
701
702         if (Config->get_shuttle_speed_threshold() >= 0 && speed > Config->get_shuttle_speed_threshold()) {
703                 speed *= Config->get_shuttle_speed_factor();
704         }
705
706         if (forw) {
707                 request_transport_speed (speed);
708         } else {
709                 request_transport_speed (-speed);
710         }
711 }
712
713 void
714 Session::mmc_record_enable (MIDI::MachineControl &mmc, size_t trk, bool enabled)
715 {
716         if (Config->get_mmc_control()) {
717
718                 RouteList::iterator i;
719                 boost::shared_ptr<RouteList> r = routes.reader();
720
721                 for (i = r->begin(); i != r->end(); ++i) {
722                         AudioTrack *at;
723
724                         if ((at = dynamic_cast<AudioTrack*>((*i).get())) != 0) {
725                                 if (trk == at->remote_control_id()) {
726                                         at->set_record_enable (enabled, &mmc);
727                                         break;
728                                 }
729                         }
730                 }
731         }
732 }
733
734 /** Send MTC Full Frame message (complete Timecode time) for the start of this cycle.
735  * This resets the MTC code, the next quarter frame message that is sent will be
736  * the first one with the beginning of this cycle as the new start point.
737  */
738 int
739 Session::send_full_time_code(nframes_t /*nframes*/)
740 {
741         /* This function could easily send at a given frame offset, but would
742          * that be useful?  Does ardour do sub-block accurate locating? [DR] */
743
744         MIDI::byte msg[10];
745         Timecode::Time timecode;
746
747         _send_timecode_update = false;
748
749         if (_mtc_port == 0 || !session_send_mtc) {
750                 return 0;
751         }
752
753         // Get timecode time for this transport frame
754         sample_to_timecode(_transport_frame, timecode, true /* use_offset */, false /* no subframes */);
755
756         transmitting_timecode_time = timecode;
757         outbound_mtc_timecode_frame = _transport_frame;
758
759         // I don't understand this bit yet.. [DR]
760         if (((mtc_timecode_bits >> 5) != MIDI::MTC_25_FPS) && (transmitting_timecode_time.frames % 2)) {
761                 // start MTC quarter frame transmission on an even frame
762                 Timecode::increment( transmitting_timecode_time, config.get_subframes_per_frame() );
763                 outbound_mtc_timecode_frame += (nframes_t) _frames_per_timecode_frame;
764         }
765
766         // Compensate for audio latency
767         outbound_mtc_timecode_frame += _worst_output_latency;
768
769         next_quarter_frame_to_send = 0;
770
771         // Sync slave to the same Timecode time as we are on
772         msg[0] = 0xf0;
773         msg[1] = 0x7f;
774         msg[2] = 0x7f;
775         msg[3] = 0x1;
776         msg[4] = 0x1;
777         msg[9] = 0xf7;
778
779         msg[5] = mtc_timecode_bits | timecode.hours;
780         msg[6] = timecode.minutes;
781         msg[7] = timecode.seconds;
782         msg[8] = timecode.frames;
783
784         cerr << "MTC: Sending full time code at " << outbound_mtc_timecode_frame << endl;
785
786         // Send message at offset 0, sent time is for the start of this cycle
787         if (_mtc_port->midimsg (msg, sizeof (msg), 0)) {
788                 error << _("Session: could not send full MIDI time code") << endmsg;
789                 return -1;
790         }
791
792         return 0;
793 }
794
795 /** Send MTC (quarter-frame) messages for this cycle.
796  * Must be called exactly once per cycle from the audio thread.  Realtime safe.
797  * This function assumes the state of full Timecode is sane, eg. the slave is
798  * expecting quarter frame messages and has the right frame of reference (any
799  * full MTC Timecode time messages that needed to be sent should have been sent
800  * earlier already this cycle by send_full_time_code)
801  */
802 int
803 Session::send_midi_time_code_for_cycle(nframes_t nframes)
804 {
805         assert (next_quarter_frame_to_send >= 0);
806         assert (next_quarter_frame_to_send <= 7);
807
808         if (_mtc_port == 0 || !session_send_mtc || transmitting_timecode_time.negative
809             /*|| (next_quarter_frame_to_send < 0)*/ ) {
810                 // cerr << "(MTC) Not sending MTC\n";
811                 return 0;
812         }
813
814         /* Duration of one quarter frame */
815         nframes_t quarter_frame_duration = ((long) _frames_per_timecode_frame) >> 2;
816
817         DEBUG_TRACE (DEBUG::MTC, string_compose ("TF %1 SF %2 NQ %3 FD %\4n",  _transport_frame, outbound_mtc_timecode_frame,
818                                                  next_quarter_frame_to_send, quarter_frame_duration));
819
820         // FIXME: this should always be true
821         //assert((outbound_mtc_timecode_frame + (next_quarter_frame_to_send * quarter_frame_duration))
822         //              > _transport_frame);
823
824
825         // Send quarter frames for this cycle
826         while (_transport_frame + nframes > (outbound_mtc_timecode_frame +
827                                 (next_quarter_frame_to_send * quarter_frame_duration))) {
828
829                 DEBUG_TRACE (DEBUG::MTC, string_compose ("next frame to send: %1\n", next_quarter_frame_to_send));
830
831                 switch (next_quarter_frame_to_send) {
832                         case 0:
833                                 mtc_msg[1] =  0x00 | (transmitting_timecode_time.frames & 0xf);
834                                 break;
835                         case 1:
836                                 mtc_msg[1] =  0x10 | ((transmitting_timecode_time.frames & 0xf0) >> 4);
837                                 break;
838                         case 2:
839                                 mtc_msg[1] =  0x20 | (transmitting_timecode_time.seconds & 0xf);
840                                 break;
841                         case 3:
842                                 mtc_msg[1] =  0x30 | ((transmitting_timecode_time.seconds & 0xf0) >> 4);
843                                 break;
844                         case 4:
845                                 mtc_msg[1] =  0x40 | (transmitting_timecode_time.minutes & 0xf);
846                                 break;
847                         case 5:
848                                 mtc_msg[1] = 0x50 | ((transmitting_timecode_time.minutes & 0xf0) >> 4);
849                                 break;
850                         case 6:
851                                 mtc_msg[1] = 0x60 | ((mtc_timecode_bits|transmitting_timecode_time.hours) & 0xf);
852                                 break;
853                         case 7:
854                                 mtc_msg[1] = 0x70 | (((mtc_timecode_bits|transmitting_timecode_time.hours) & 0xf0) >> 4);
855                                 break;
856                 }
857
858                 const nframes_t msg_time = (outbound_mtc_timecode_frame
859                         + (quarter_frame_duration * next_quarter_frame_to_send));
860
861                 // This message must fall within this block or something is broken
862                 assert(msg_time >= _transport_frame);
863                 assert(msg_time < _transport_frame + nframes);
864
865                 nframes_t out_stamp = msg_time - _transport_frame;
866                 assert(out_stamp < nframes);
867
868                 if (_mtc_port->midimsg (mtc_msg, 2, out_stamp)) {
869                         error << string_compose(_("Session: cannot send quarter-frame MTC message (%1)"), strerror (errno))
870                               << endmsg;
871                         return -1;
872                 }
873
874 #ifndef NDEBUG
875                 DEBUG_STR_SET(foo,"sending ");
876                 DEBUG_STR(foo) << transmitting_timecode_time;
877                 DEBUG_TRACE (DEBUG::MTC, string_compose ("%1 qfm = %2, stamp = %3\n", DEBUG_STR(foo).str(), next_quarter_frame_to_send,
878                                                          out_stamp));
879 #endif
880
881                 // Increment quarter frame counter
882                 next_quarter_frame_to_send++;
883
884                 if (next_quarter_frame_to_send >= 8) {
885                         // Wrap quarter frame counter
886                         next_quarter_frame_to_send = 0;
887                         // Increment timecode time twice
888                         Timecode::increment( transmitting_timecode_time, config.get_subframes_per_frame() );
889                         Timecode::increment( transmitting_timecode_time, config.get_subframes_per_frame() );
890                         // Re-calculate timing of first quarter frame
891                         //timecode_to_sample( transmitting_timecode_time, outbound_mtc_timecode_frame, true /* use_offset */, false );
892                         outbound_mtc_timecode_frame += 8 * quarter_frame_duration;
893                         // Compensate for audio latency
894                         outbound_mtc_timecode_frame += _worst_output_latency;
895                 }
896         }
897
898         return 0;
899 }
900
901 /***********************************************************************
902  OUTBOUND MMC STUFF
903 **********************************************************************/
904
905 void
906 Session::deliver_mmc (MIDI::MachineControl::Command cmd, nframes_t where)
907 {
908         using namespace MIDI;
909         int nbytes = 4;
910         Timecode::Time timecode;
911
912         if (_mmc_port == 0 || !session_send_mmc) {
913                 // cerr << "Not delivering MMC " << _mmc_port << " - " << session_send_mmc << endl;
914                 return;
915         }
916
917         mmc_buffer[nbytes++] = cmd;
918
919         // cerr << "delivering MMC, cmd = " << hex << (int) cmd << dec << endl;
920
921         switch (cmd) {
922         case MachineControl::cmdLocate:
923                 timecode_time_subframes (where, timecode);
924
925                 mmc_buffer[nbytes++] = 0x6; // byte count
926                 mmc_buffer[nbytes++] = 0x1; // "TARGET" subcommand
927                 mmc_buffer[nbytes++] = timecode.hours;
928                 mmc_buffer[nbytes++] = timecode.minutes;
929                 mmc_buffer[nbytes++] = timecode.seconds;
930                 mmc_buffer[nbytes++] = timecode.frames;
931                 mmc_buffer[nbytes++] = timecode.subframes;
932                 break;
933
934         case MachineControl::cmdStop:
935                 break;
936
937         case MachineControl::cmdPlay:
938                 /* always convert Play into Deferred Play */
939                 /* Why? [DR] */
940                 mmc_buffer[4] = MachineControl::cmdDeferredPlay;
941                 break;
942
943         case MachineControl::cmdDeferredPlay:
944                 break;
945
946         case MachineControl::cmdRecordStrobe:
947                 break;
948
949         case MachineControl::cmdRecordExit:
950                 break;
951
952         case MachineControl::cmdRecordPause:
953                 break;
954
955         default:
956                 nbytes = 0;
957         };
958
959         if (nbytes) {
960
961                 mmc_buffer[nbytes++] = 0xf7; // terminate SysEx/MMC message
962
963                 if (_mmc_port->midimsg (mmc_buffer, nbytes, 0)) {
964                         error << string_compose(_("MMC: cannot send command %1%2%3"), &hex, cmd, &dec) << endmsg;
965                 }
966         }
967 }
968
969 bool
970 Session::mmc_step_timeout ()
971 {
972         struct timeval now;
973         struct timeval diff;
974         double diff_usecs;
975         gettimeofday (&now, 0);
976
977         timersub (&now, &last_mmc_step, &diff);
978         diff_usecs = diff.tv_sec * 1000000 + diff.tv_usec;
979
980         if (diff_usecs > 1000000.0 || fabs (_transport_speed) < 0.0000001) {
981                 /* too long or too slow, stop transport */
982                 request_transport_speed (0.0);
983                 step_queued = false;
984                 return false;
985         }
986
987         if (diff_usecs < 250000.0) {
988                 /* too short, just keep going */
989                 return true;
990         }
991
992         /* slow it down */
993
994         request_transport_speed (_transport_speed * 0.75);
995         return true;
996 }
997
998 /*---------------------------------------------------------------------------
999   MIDI THREAD
1000   ---------------------------------------------------------------------------*/
1001
1002 int
1003 Session::start_midi_thread ()
1004 {
1005         midi_control_ui = new MidiControlUI (*this);
1006         midi_control_ui->run ();
1007         return 0;
1008 }
1009
1010 void
1011 Session::terminate_midi_thread ()
1012 {
1013         if (midi_control_ui) {
1014                 midi_control_ui->quit ();
1015         }
1016 }
1017
1018