Large nasty commit in the form of a 5000 line patch chock-full of completely
[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 PBD;
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 Session::mmc_step (MIDI::MachineControl &mmc, int steps)
664 {
665         if (!mmc_control) {
666                 return;
667         }
668
669         struct timeval now;
670         struct timeval diff = { 0, 0 };
671
672         gettimeofday (&now, 0);
673         
674         timersub (&now, &last_mmc_step, &diff);
675
676         gettimeofday (&now, 0);
677         timersub (&now, &last_mmc_step, &diff);
678
679         if (last_mmc_step.tv_sec != 0 && (diff.tv_usec + (diff.tv_sec * 1000000)) < _engine.usecs_per_cycle()) {
680                 return;
681         }
682         
683         double diff_secs = diff.tv_sec + (diff.tv_usec / 1000000.0);
684         double cur_speed = (((steps * 0.5) * smpte_frames_per_second) / diff_secs) / smpte_frames_per_second;
685         
686         if (_transport_speed == 0 || cur_speed * _transport_speed < 0) {
687                 /* change direction */
688                 step_speed = cur_speed;
689         } else {
690                 step_speed = (0.6 * step_speed) + (0.4 * cur_speed);
691         }
692
693         step_speed *= 0.25;
694
695 #if 0
696         cerr << "delta = " << diff_secs 
697              << " ct = " << _transport_speed
698              << " steps = " << steps
699              << " new speed = " << cur_speed 
700              << " speed = " << step_speed
701              << endl;
702 #endif  
703
704         request_transport_speed (step_speed);
705         last_mmc_step = now;
706
707         if (!step_queued) {
708                 midi_timeouts.push_back (mem_fun (*this, &Session::mmc_step_timeout));
709                 step_queued = true;
710         }
711 }
712
713 void
714 Session::mmc_rewind (MIDI::MachineControl &mmc)
715 {
716         if (mmc_control) {
717                 request_transport_speed(-8.0f);
718         }
719 }
720
721 void
722 Session::mmc_fast_forward (MIDI::MachineControl &mmc)
723 {
724         if (mmc_control) {
725                 request_transport_speed(8.0f);
726         }
727 }
728
729 void
730 Session::mmc_locate (MIDI::MachineControl &mmc, const MIDI::byte* mmc_tc)
731 {
732         if (!mmc_control) {
733                 return;
734         }
735
736         jack_nframes_t target_frame;
737         SMPTE::Time smpte;
738
739         smpte.hours = mmc_tc[0] & 0xf;
740         smpte.minutes = mmc_tc[1];
741         smpte.seconds = mmc_tc[2];
742         smpte.frames = mmc_tc[3];
743   
744         // Also takes smpte offset into account:
745         smpte_to_sample( smpte, target_frame, true /* use_offset */, false /* use_subframes */ );
746         
747         if (target_frame > max_frames) {
748                 target_frame = max_frames;
749         }
750
751         /* Some (all?) MTC/MMC devices do not send a full MTC frame
752            at the end of a locate, instead sending only an MMC
753            locate command. This causes the current position
754            of an MTC slave to become out of date. Catch this.
755         */
756
757         MTC_Slave* mtcs = dynamic_cast<MTC_Slave*> (_slave);
758
759         if (mtcs != 0) {
760                 // cerr << "Locate *with* MTC slave\n";
761                 mtcs->handle_locate (mmc_tc);
762         } else {
763                 // cerr << "Locate without MTC slave\n";
764                 request_locate (target_frame, false);
765         }
766 }
767
768 void
769 Session::mmc_shuttle (MIDI::MachineControl &mmc, float speed, bool forw)
770 {
771         cerr << "MMC shuttle, speed = " << speed << endl;
772
773         if (!mmc_control) {
774                 return;
775         }
776
777         if (shuttle_speed_threshold >= 0 && speed > shuttle_speed_threshold) {
778                 speed *= shuttle_speed_factor;
779         }
780
781         cerr << "requested MMC control speed = " << speed << endl;
782         
783         if (forw) {
784                 request_transport_speed (speed);
785         } else {
786                 request_transport_speed (-speed);
787         }
788 }
789
790 void
791 Session::mmc_record_enable (MIDI::MachineControl &mmc, size_t trk, bool enabled)
792 {
793         if (mmc_control) {
794
795                 RouteList::iterator i;
796                 Glib::RWLock::ReaderLock guard (route_lock);
797                 
798                 for (i = routes.begin(); i != routes.end(); ++i) {
799                         AudioTrack *at;
800
801                         if ((at = dynamic_cast<AudioTrack*>(*i)) != 0) {
802                                 if (trk == at->remote_control_id()) {
803                                         at->set_record_enable (enabled, &mmc);
804                                         break;
805                                 }
806                         }
807                 }
808         }
809 }
810
811
812 void
813 Session::change_midi_ports ()
814 {
815 /*
816         MIDIRequest* request = new MIDIRequest;
817
818         request->type = MIDIRequest::PortChange;
819         midi_requests.write (&request, 1);
820         poke_midi_thread ();
821 */
822 }
823
824 /** Send MTC Full Frame message (complete SMPTE time) for the start of this cycle.
825  * This resets the MTC code, the next quarter frame message that is sent will be
826  * the first one with the beginning of this cycle as the new start point.
827  *
828  * Audio thread only, realtime safe.  MIDI::Manager::cycle_start must
829  * have been called with the appropriate nframes parameter this cycle.
830  */
831 int
832 Session::send_full_time_code(jack_nframes_t nframes)
833 {
834         /* This function could easily send at a given frame offset, but would
835          * that be useful?  Does ardour do sub-block accurate locating? [DR] */
836
837         MIDI::byte msg[10];
838         SMPTE::Time smpte;
839
840         _send_smpte_update = false;
841
842         if (_mtc_port == 0 || !send_mtc) {
843                 return 0;
844         }
845         
846         // Get smpte time for this transport frame
847         sample_to_smpte(_transport_frame, smpte, true /* use_offset */, false /* no subframes */);
848
849         transmitting_smpte_time = smpte;
850         outbound_mtc_smpte_frame = _transport_frame;
851
852         // I don't understand this bit yet.. [DR]
853         if (((mtc_smpte_bits >> 5) != MIDI::MTC_25_FPS) && (transmitting_smpte_time.frames % 2)) {
854                 // start MTC quarter frame transmission on an even frame
855                 SMPTE::increment( transmitting_smpte_time );
856                 outbound_mtc_smpte_frame += (jack_nframes_t) _frames_per_smpte_frame;
857         }
858
859         // Compensate for audio latency
860         outbound_mtc_smpte_frame += _worst_output_latency;
861
862         next_quarter_frame_to_send = 0;
863
864         // Sync slave to the same SMPTE time as we are on
865         msg[0] = 0xf0;
866         msg[1] = 0x7f;
867         msg[2] = 0x7f;
868         msg[3] = 0x1;
869         msg[4] = 0x1;
870         msg[9] = 0xf7;
871
872         msg[5] = mtc_smpte_bits | smpte.hours;
873         msg[6] = smpte.minutes;
874         msg[7] = smpte.seconds;
875         msg[8] = smpte.frames;
876
877         cerr << "MTC: Sending full time code at " << outbound_mtc_smpte_frame << endl;
878
879         // Send message at offset 0, sent time is for the start of this cycle
880         if (!_mtc_port->midimsg (msg, sizeof (msg), 0)) {
881                 error << _("Session: could not send full MIDI time code") << endmsg;
882                 return -1;
883         }
884
885         return 0;
886 }
887
888
889 /** Sends MTC (quarter-frame) messages for this cycle.
890  * Must be called exactly once per cycle from the audio thread.  Realtime safe.
891  * This function assumes the state of full SMPTE is sane, eg. the slave is
892  * expecting quarter frame messages and has the right frame of reference (any
893  * full MTC SMPTE time messages that needed to be sent should have been sent
894  * earlier already this cycle by send_full_time_code)
895  */
896 int
897 Session::send_midi_time_code_for_cycle(jack_nframes_t nframes)
898 {       
899         assert (next_quarter_frame_to_send >= 0);
900         assert (next_quarter_frame_to_send <= 7);
901         
902         if (next_quarter_frame_to_send < 0)
903         {
904                 printf("Negative????\n");
905         }
906
907         if (_mtc_port == 0 || !send_mtc || transmitting_smpte_time.negative
908                         /*|| (next_quarter_frame_to_send < 0)*/ ) {
909                 //printf("(MTC) Not sending MTC\n");
910                 return 0;
911         }
912         
913         /* Duration of one quarter frame */
914         jack_nframes_t quarter_frame_duration = ((long) _frames_per_smpte_frame) >> 2;
915         
916         //cerr << "(MTC) TR: " << _transport_frame << " - SF: " << outbound_mtc_smpte_frame
917         //<< " - NQ: " << next_quarter_frame_to_send << " - FD" << quarter_frame_duration << endl;
918                 
919         // FIXME: this should always be true
920         //assert((outbound_mtc_smpte_frame + (next_quarter_frame_to_send * quarter_frame_duration))
921         //              > _transport_frame);
922
923         
924         // Send quarter frames for this cycle
925         while (_transport_frame + nframes > (outbound_mtc_smpte_frame +
926                                 (next_quarter_frame_to_send * quarter_frame_duration))) {
927
928                 //cerr << "(MTC) Next frame to send: " << next_quarter_frame_to_send << endl;
929
930                 switch (next_quarter_frame_to_send) {
931                         case 0:
932                                 mtc_msg[1] =  0x00 | (transmitting_smpte_time.frames & 0xf);
933                                 break;
934                         case 1:
935                                 mtc_msg[1] =  0x10 | ((transmitting_smpte_time.frames & 0xf0) >> 4);
936                                 break;
937                         case 2:
938                                 mtc_msg[1] =  0x20 | (transmitting_smpte_time.seconds & 0xf);
939                                 break;
940                         case 3:
941                                 mtc_msg[1] =  0x30 | ((transmitting_smpte_time.seconds & 0xf0) >> 4);
942                                 break;
943                         case 4:
944                                 mtc_msg[1] =  0x40 | (transmitting_smpte_time.minutes & 0xf);
945                                 break;
946                         case 5:
947                                 mtc_msg[1] = 0x50 | ((transmitting_smpte_time.minutes & 0xf0) >> 4);
948                                 break;
949                         case 6:
950                                 mtc_msg[1] = 0x60 | ((mtc_smpte_bits|transmitting_smpte_time.hours) & 0xf);
951                                 break;
952                         case 7:
953                                 mtc_msg[1] = 0x70 | (((mtc_smpte_bits|transmitting_smpte_time.hours) & 0xf0) >> 4);
954                                 break;
955                 }                       
956                 
957                 const jack_nframes_t msg_time = (outbound_mtc_smpte_frame
958                         + (quarter_frame_duration * next_quarter_frame_to_send));
959         
960                 // This message must fall within this block or something is broken
961                 assert(msg_time >= _transport_frame);
962                 assert(msg_time < _transport_frame + nframes);
963
964                 jack_nframes_t out_stamp = msg_time - _transport_frame;
965                 assert(out_stamp < nframes);
966
967                 if (!_mtc_port->midimsg (mtc_msg, 2, out_stamp)) {
968                         error << string_compose(_("Session: cannot send quarter-frame MTC message (%1)"), strerror (errno)) 
969                                 << endmsg;
970                         return -1;
971                 }
972
973                 /*cerr << "(MTC) SMPTE: " << transmitting_smpte_time.hours
974                         << ":" << transmitting_smpte_time.minutes
975                         << ":" << transmitting_smpte_time.seconds
976                         << ":" << transmitting_smpte_time.frames
977                         << ", qfm = " << next_quarter_frame_to_send
978                         << ", stamp = " << out_stamp
979                         << ", delta = " << _transport_frame + out_stamp - last_time << endl;*/
980                 
981                 // Increment quarter frame counter
982                 next_quarter_frame_to_send++;
983
984                 if (next_quarter_frame_to_send >= 8) {
985                         // Wrap quarter frame counter
986                         next_quarter_frame_to_send = 0;
987                         // Increment smpte time twice
988                         SMPTE::increment( transmitting_smpte_time );
989                         SMPTE::increment( transmitting_smpte_time );        
990                         // Re-calculate timing of first quarter frame
991                         //smpte_to_sample( transmitting_smpte_time, outbound_mtc_smpte_frame, true /* use_offset */, false );
992                         outbound_mtc_smpte_frame += 8 * quarter_frame_duration;
993                         // Compensate for audio latency
994                         outbound_mtc_smpte_frame += _worst_output_latency;
995                 }
996         }
997
998         return 0;
999 }
1000
1001 /***********************************************************************
1002  OUTBOUND MMC STUFF
1003 **********************************************************************/
1004 /*
1005 void
1006 Session::send_mmc_in_another_thread (MIDI::MachineControl::Command cmd, jack_nframes_t target_frame)
1007 {
1008         MIDIRequest* request;
1009
1010         if (_mtc_port == 0 || !send_mmc) {
1011                 return;
1012         }
1013
1014         request = new MIDIRequest;
1015         request->type = MIDIRequest::SendMMC;
1016         request->mmc_cmd = cmd;
1017         request->locate_frame = target_frame;
1018
1019         midi_requests.write (&request, 1);
1020         poke_midi_thread ();
1021 }
1022 */
1023
1024 /** Send an MMC command at the given absolute timestamp (@a where).
1025  *
1026  * This must be called in the process thread, and @a where must fall within
1027  * this process cycle or horrible things will happen.
1028  */
1029 void
1030 Session::deliver_mmc (MIDI::MachineControl::Command cmd, jack_nframes_t where)
1031 {
1032         using namespace MIDI;
1033         int nbytes = 4;
1034         SMPTE::Time smpte;
1035
1036         if (_mmc_port == 0 || !send_mmc) {
1037                 //cerr << "Not delivering MMC " << _mmc_port << " - " << send_mmc << endl;
1038                 return;
1039         }
1040
1041         mmc_buffer[nbytes++] = cmd;
1042
1043         //cerr << "delivering MMC, cmd = " << hex << (int) cmd << dec << endl;
1044         
1045         switch (cmd) {
1046         case MachineControl::cmdLocate:
1047                 smpte_time_subframes (where, smpte);
1048
1049                 mmc_buffer[nbytes++] = 0x6; // byte count
1050                 mmc_buffer[nbytes++] = 0x1; // "TARGET" subcommand
1051                 mmc_buffer[nbytes++] = smpte.hours;
1052                 mmc_buffer[nbytes++] = smpte.minutes;
1053                 mmc_buffer[nbytes++] = smpte.seconds;
1054                 mmc_buffer[nbytes++] = smpte.frames;
1055                 mmc_buffer[nbytes++] = smpte.subframes;
1056                 break;
1057
1058         case MachineControl::cmdStop:
1059                 break;
1060
1061         case MachineControl::cmdPlay:
1062                 /* always convert Play into Deferred Play */
1063                 /* Why? [DR] */
1064                 mmc_buffer[4] = MachineControl::cmdDeferredPlay;
1065                 break;
1066
1067         case MachineControl::cmdDeferredPlay:
1068                 break;
1069
1070         case MachineControl::cmdRecordStrobe:
1071                 break;
1072
1073         case MachineControl::cmdRecordExit:
1074                 break;
1075
1076         case MachineControl::cmdRecordPause:
1077                 break;
1078
1079         default:
1080                 nbytes = 0;
1081         };
1082
1083         if (nbytes) {
1084
1085                 mmc_buffer[nbytes++] = 0xf7; // terminate SysEx/MMC message
1086
1087                 assert(where >= _transport_frame);
1088
1089                 // FIXME: timestamp correct? [DR]
1090                 if (!_mmc_port->midimsg (mmc_buffer, sizeof (mmc_buffer), where - _transport_frame)) {
1091                         error << string_compose(_("MMC: cannot send command %1%2%3"), &hex, cmd, &dec) << endmsg;
1092                 } /*else {
1093                         cerr << "Sending MMC\n";
1094                 }*/
1095         }
1096 }
1097
1098 bool
1099 Session::mmc_step_timeout ()
1100 {
1101         struct timeval now;
1102         struct timeval diff;
1103         double diff_usecs;
1104         gettimeofday (&now, 0);
1105
1106         timersub (&now, &last_mmc_step, &diff);
1107         diff_usecs = diff.tv_sec * 1000000 + diff.tv_usec;
1108
1109         if (diff_usecs > 1000000.0 || fabs (_transport_speed) < 0.0000001) {
1110                 /* too long or too slow, stop transport */
1111                 request_transport_speed (0.0);
1112                 step_queued = false;
1113                 return false;
1114         }
1115
1116         if (diff_usecs < 250000.0) {
1117                 /* too short, just keep going */
1118                 return true;
1119         }
1120
1121         /* slow it down */
1122
1123         request_transport_speed (_transport_speed * 0.75);
1124         return true;
1125 }
1126
1127
1128 void
1129 Session::send_midi_message (MIDI::Port * port, MIDI::eventType ev, MIDI::channel_t ch, MIDI::EventTwoBytes data)
1130 {
1131         // in another thread, really
1132         /*
1133         MIDIRequest* request = new MIDIRequest;
1134
1135         request->type = MIDIRequest::SendMessage;
1136         request->port = port;
1137         request->ev = ev;
1138         request->chan = ch;
1139         request->data = data;
1140         
1141         midi_requests.write (&request, 1);
1142         poke_midi_thread ();
1143         */
1144 }
1145
1146 void
1147 Session::deliver_midi (MIDI::Port * port, MIDI::byte* buf, int32_t bufsize)
1148 {
1149         // in another thread, really
1150         /*
1151         MIDIRequest* request = new MIDIRequest;
1152
1153         request->type = MIDIRequest::Deliver;
1154         request->port = port;
1155         request->buf = buf;
1156         request->size = bufsize;
1157         
1158         midi_requests.write (&request, 1);
1159         poke_midi_thread ();
1160         */
1161 }
1162
1163 #if 0
1164
1165 This is aaalll gone. 
1166
1167
1168 void
1169 Session::deliver_midi_message (MIDI::Port * port, MIDI::eventType ev, MIDI::channel_t ch, MIDI::EventTwoBytes data)
1170 {
1171         if (port == 0 || ev == MIDI::none) {
1172                 return;
1173         }
1174
1175         midi_msg[0] = (ev & 0xF0) | (ch & 0xF); 
1176         midi_msg[1] = data.controller_number;
1177         midi_msg[2] = data.value;
1178
1179         port->write (midi_msg, 3);
1180 }
1181
1182 void
1183 Session::deliver_data (MIDI::Port * port, MIDI::byte* buf, int32_t size)
1184 {
1185         if (port) {
1186                 port->write (buf, size);
1187         }
1188
1189         /* this is part of the semantics of the Deliver request */
1190
1191         delete [] buf;
1192 }
1193 #endif
1194
1195
1196 /*---------------------------------------------------------------------------
1197   MIDI THREAD 
1198   ---------------------------------------------------------------------------*/
1199
1200 #if 0
1201 int
1202 Session::start_midi_thread ()
1203 {
1204         if (pipe (midi_request_pipe)) {
1205                 error << string_compose(_("Cannot create transport request signal pipe (%1)"), strerror (errno)) << endmsg;
1206                 return -1;
1207         }
1208
1209         if (fcntl (midi_request_pipe[0], F_SETFL, O_NONBLOCK)) {
1210                 error << string_compose(_("UI: cannot set O_NONBLOCK on "    "signal read pipe (%1)"), strerror (errno)) << endmsg;
1211                 return -1;
1212         }
1213
1214         if (fcntl (midi_request_pipe[1], F_SETFL, O_NONBLOCK)) {
1215                 error << string_compose(_("UI: cannot set O_NONBLOCK on "    "signal write pipe (%1)"), strerror (errno)) << endmsg;
1216                 return -1;
1217         }
1218
1219         if (pthread_create_and_store ("transport", &midi_thread, 0, _midi_thread_work, this)) {
1220                 error << _("Session: could not create transport thread") << endmsg;
1221                 return -1;
1222         }
1223
1224         // pthread_detach (midi_thread);
1225
1226         return 0;
1227 }
1228
1229 void
1230 Session::terminate_midi_thread ()
1231 {
1232         MIDIRequest* request = new MIDIRequest;
1233         void* status;
1234
1235         request->type = MIDIRequest::Quit;
1236
1237         midi_requests.write (&request, 1);
1238         poke_midi_thread ();
1239
1240         pthread_join (midi_thread, &status);
1241 }
1242
1243 void
1244 Session::poke_midi_thread ()
1245 {
1246         char c;
1247
1248         if (write (midi_request_pipe[1], &c, 1) != 1) {
1249                 error << string_compose(_("cannot send signal to midi thread! (%1)"), strerror (errno)) << endmsg;
1250         }
1251 }
1252
1253 void *
1254 Session::_midi_thread_work (void* arg)
1255 {
1256         pthread_setcancelstate (PTHREAD_CANCEL_ENABLE, 0);
1257         pthread_setcanceltype (PTHREAD_CANCEL_ASYNCHRONOUS, 0);
1258
1259         ((Session *) arg)->midi_thread_work ();
1260         return 0;
1261 }
1262
1263 void
1264 Session::midi_thread_work ()
1265 {
1266         MIDIRequest* request;
1267         struct pollfd pfd[4];
1268         int nfds = 0;
1269         int timeout;
1270         int fds_ready;
1271         struct sched_param rtparam;
1272         int x;
1273         bool restart;
1274         vector<MIDI::Port*> ports;
1275
1276         PBD::ThreadCreatedWithRequestSize (pthread_self(), X_("MIDI"), 2048);
1277
1278         memset (&rtparam, 0, sizeof (rtparam));
1279         rtparam.sched_priority = 9; /* XXX should be relative to audio (JACK) thread */
1280         
1281         if ((x = pthread_setschedparam (pthread_self(), SCHED_FIFO, &rtparam)) != 0) {
1282                 // do we care? not particularly.
1283         } 
1284
1285         /* set up the port vector; 4 is the largest possible size for now */
1286
1287         ports.push_back (0);
1288         ports.push_back (0);
1289         ports.push_back (0);
1290         ports.push_back (0);
1291
1292         while (1) {
1293
1294                 nfds = 0;
1295
1296                 pfd[nfds].fd = midi_request_pipe[0];
1297                 pfd[nfds].events = POLLIN|POLLHUP|POLLERR;
1298                 nfds++;
1299
1300                 /* if we are using MMC control, we obviously have to listen
1301                    on the appropriate port.
1302                 */
1303
1304                 if (mmc_control && _mmc_port && _mmc_port->selectable() >= 0) {
1305                         pfd[nfds].fd = _mmc_port->selectable();
1306                         pfd[nfds].events = POLLIN|POLLHUP|POLLERR;
1307                         ports[nfds] = _mmc_port;
1308                         nfds++;
1309                 }
1310
1311                 /* if MTC is being handled on a different port from MMC
1312                    or we are not handling MMC at all, poll
1313                    the relevant port.
1314                 */
1315
1316                 if (_mtc_port && (_mtc_port != _mmc_port || !mmc_control) && _mtc_port->selectable() >= 0) {
1317                         pfd[nfds].fd = _mtc_port->selectable();
1318                         pfd[nfds].events = POLLIN|POLLHUP|POLLERR;
1319                         ports[nfds] = _mtc_port;
1320                         nfds++;
1321                 }
1322
1323                 if (_midi_port && (_midi_port != _mmc_port || !mmc_control) && (_midi_port != _mtc_port) && _midi_port->selectable() >= 0) {
1324                         pfd[nfds].fd = _midi_port->selectable();
1325                         pfd[nfds].events = POLLIN|POLLHUP|POLLERR;
1326                         ports[nfds] = _midi_port;
1327                         nfds++;
1328                 }
1329                 
1330                 if (!midi_timeouts.empty()) {
1331                         timeout = 100; /* 10msecs */
1332                 } else {
1333                         timeout = -1; /* if there is no data, we don't care */
1334                 }
1335
1336           again:
1337                 // cerr << "MIDI poll on " << nfds << " for " << timeout << endl;
1338                 if (poll (pfd, nfds, timeout) < 0) {
1339                         if (errno == EINTR) {
1340                                 /* gdb at work, perhaps */
1341                                 goto again;
1342                         }
1343
1344                         error << string_compose(_("MIDI thread poll failed (%1)"), strerror (errno)) << endmsg;
1345
1346                         break;
1347                 }
1348                 // cerr << "MIDI thread wakes at " << get_cycles () << endl;
1349
1350                 fds_ready = 0;
1351                 restart = false;
1352
1353                 /* check the transport request pipe */
1354
1355                 if (pfd[0].revents & ~POLLIN) {
1356                         error << _("Error on transport thread request pipe") << endmsg;
1357                         break;
1358                 }
1359
1360                 if (pfd[0].revents & POLLIN) {
1361
1362                         char foo[16];
1363                         
1364                         // cerr << "MIDI request FIFO ready\n";
1365                         fds_ready++;
1366
1367                         /* empty the pipe of all current requests */
1368
1369                         while (1) {
1370                                 size_t nread = read (midi_request_pipe[0], &foo, sizeof (foo));
1371
1372                                 if (nread > 0) {
1373                                         if ((size_t) nread < sizeof (foo)) {
1374                                                 break;
1375                                         } else {
1376                                                 continue;
1377                                         }
1378                                 } else if (nread == 0) {
1379                                         break;
1380                                 } else if (errno == EAGAIN) {
1381                                         break;
1382                                 } else {
1383                                         fatal << _("Error reading from transport request pipe") << endmsg;
1384                                         /*NOTREACHED*/
1385                                 }
1386                         }
1387
1388                         while (midi_requests.read (&request, 1) == 1) {
1389
1390                                 switch (request->type) {
1391                                         
1392                                 case MIDIRequest::SendFullMTC:
1393                                         // cerr << "send full MTC\n";
1394                                         send_full_time_code ();
1395                                         // cerr << "... done\n";
1396                                         break;
1397                                         
1398                                 case MIDIRequest::SendMTC:
1399                                         // cerr << "send qtr MTC\n";
1400                                         send_midi_time_code ();
1401                                         // cerr << "... done\n";
1402                                         break;
1403                                         
1404                                 case MIDIRequest::SendMMC:
1405                                         // cerr << "send MMC\n";
1406                                         deliver_mmc (request->mmc_cmd, request->locate_frame);
1407                                         // cerr << "... done\n";
1408                                         break;
1409
1410                                 case MIDIRequest::SendMessage:
1411                                         // cerr << "send Message\n";
1412                                         deliver_midi_message (request->port, request->ev, request->chan, request->data);
1413                                         // cerr << "... done\n";
1414                                         break;
1415                                         
1416                                 case MIDIRequest::Deliver:
1417                                         // cerr << "deliver\n";
1418                                         deliver_data (_midi_port, request->buf, request->size);
1419                                         // cerr << "... done\n";
1420                                         break;
1421                                                 
1422                                 case MIDIRequest::PortChange:
1423                                         /* restart poll with new ports */
1424                                         // cerr << "rebind\n";
1425                                         restart = true;
1426                                         break;
1427                                                 
1428                                 case MIDIRequest::Quit:
1429                                         delete request;
1430                                         pthread_exit_pbd (0);
1431                                         /*NOTREACHED*/
1432                                         break;
1433                                         
1434                                 default:
1435                                         break;
1436                                 }
1437
1438
1439                                 delete request;
1440                         }
1441
1442                 } 
1443
1444                 if (restart) {
1445                         continue;
1446                 }
1447
1448                 /* now read the rest of the ports */
1449
1450                 for (int p = 1; p < nfds; ++p) {
1451                         if ((pfd[p].revents & ~POLLIN)) {
1452                                 // error << string_compose(_("Transport: error polling MIDI port %1 (revents =%2%3%4"), p, &hex, pfd[p].revents, &dec) << endmsg;
1453                                 break;
1454                         }
1455                         
1456                         if (pfd[p].revents & POLLIN) {
1457                                 fds_ready++;
1458                                 midi_read (ports[p]);
1459                         }
1460                 }
1461
1462                 /* timeout driven */
1463                 
1464                 if (fds_ready < 2 && timeout != -1) {
1465
1466                         for (MidiTimeoutList::iterator i = midi_timeouts.begin(); i != midi_timeouts.end(); ) {
1467                                 
1468                                 MidiTimeoutList::iterator tmp;
1469                                 tmp = i;
1470                                 ++tmp;
1471                                 
1472                                 if (!(*i)()) {
1473                                         midi_timeouts.erase (i);
1474                                 }
1475                                 
1476                                 i = tmp;
1477                         }
1478                 }
1479         }
1480 }
1481 #endif
1482
1483 bool
1484 Session::get_mmc_control () const
1485 {
1486         return mmc_control;
1487 }
1488
1489 bool
1490 Session::get_midi_control () const
1491 {
1492         return midi_control;
1493 }