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