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