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