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