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