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