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