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