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