Remove non-portable and unnused header includes
[ardour.git] / libs / ardour / session_midi.cc
1 /*
2   Copyright (C) 1999-2002 Paul Davis
3
4   This program is free software; you can redistribute it and/or modify
5   it under the terms of the GNU General Public License as published by
6   the Free Software Foundation; either version 2 of the License, or
7   (at your option) any later version.
8
9   This program is distributed in the hope that it will be useful,
10   but WITHOUT ANY WARRANTY; without even the implied warranty of
11   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12   GNU General Public License for more details.
13
14   You should have received a copy of the GNU General Public License
15   along with this program; if not, write to the Free Software
16   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include <string>
21 #include <cmath>
22 #include <cerrno>
23 #include <cassert>
24 #include <unistd.h>
25
26 #include <boost/shared_ptr.hpp>
27
28 #include <glibmm/main.h>
29
30 #include "midi++/mmc.h"
31 #include "midi++/port.h"
32 #include "midi++/manager.h"
33
34 #include "pbd/error.h"
35 #include "pbd/pthread_utils.h"
36
37 #include "timecode/time.h"
38
39 #include "ardour/audio_track.h"
40 #include "ardour/audioengine.h"
41 #include "ardour/debug.h"
42 #include "ardour/midi_track.h"
43 #include "ardour/midi_ui.h"
44 #include "ardour/session.h"
45 #include "ardour/slave.h"
46
47 #include "i18n.h"
48
49 using namespace std;
50 using namespace ARDOUR;
51 using namespace PBD;
52 using namespace MIDI;
53 using namespace Glib;
54
55 void
56 Session::midi_panic()
57 {
58         {
59                 boost::shared_ptr<RouteList> r = routes.reader ();
60
61                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
62                         MidiTrack *track = dynamic_cast<MidiTrack*>((*i).get());
63                         if (track != 0) {
64                                 track->midi_panic();
65                         }
66                 }
67         }
68 }
69
70 void
71 Session::setup_midi_control ()
72 {
73         outbound_mtc_timecode_frame = 0;
74         next_quarter_frame_to_send = 0;
75
76         /* Set up the qtr frame message */
77
78         mtc_msg[0] = 0xf1;
79         mtc_msg[2] = 0xf1;
80         mtc_msg[4] = 0xf1;
81         mtc_msg[6] = 0xf1;
82         mtc_msg[8] = 0xf1;
83         mtc_msg[10] = 0xf1;
84         mtc_msg[12] = 0xf1;
85         mtc_msg[14] = 0xf1;
86 }
87
88 void
89 Session::spp_start ()
90 {
91         if (Config->get_mmc_control ()) {
92                 request_transport_speed (1.0);
93         }
94 }
95
96 void
97 Session::spp_continue ()
98 {
99         spp_start ();
100 }
101
102 void
103 Session::spp_stop ()
104 {
105         if (Config->get_mmc_control ()) {
106                 request_stop ();
107         }
108 }
109
110 void
111 Session::mmc_deferred_play (MIDI::MachineControl &/*mmc*/)
112 {
113         if (Config->get_mmc_control ()) {
114                 request_transport_speed (1.0);
115         }
116 }
117
118 void
119 Session::mmc_record_pause (MIDI::MachineControl &/*mmc*/)
120 {
121         if (Config->get_mmc_control ()) {
122                 maybe_enable_record();
123         }
124 }
125
126 void
127 Session::mmc_record_strobe (MIDI::MachineControl &/*mmc*/)
128 {
129         if (!Config->get_mmc_control() || (_step_editors > 0)) {
130                 return;
131         }
132
133         /* record strobe does an implicit "Play" command */
134
135         if (_transport_speed != 1.0) {
136
137                 /* start_transport() will move from Enabled->Recording, so we
138                    don't need to do anything here except enable recording.
139                    its not the same as maybe_enable_record() though, because
140                    that *can* switch to Recording, which we do not want.
141                 */
142
143                 save_state ("", true);
144                 g_atomic_int_set (&_record_status, Enabled);
145                 RecordStateChanged (); /* EMIT SIGNAL */
146
147                 request_transport_speed (1.0);
148
149         } else {
150
151                 enable_record ();
152         }
153 }
154
155 void
156 Session::mmc_record_exit (MIDI::MachineControl &/*mmc*/)
157 {
158         if (Config->get_mmc_control ()) {
159                 disable_record (false);
160         }
161 }
162
163 void
164 Session::mmc_stop (MIDI::MachineControl &/*mmc*/)
165 {
166         if (Config->get_mmc_control ()) {
167                 request_stop ();
168         }
169 }
170
171 void
172 Session::mmc_pause (MIDI::MachineControl &/*mmc*/)
173 {
174         if (Config->get_mmc_control ()) {
175
176                 /* We support RECORD_PAUSE, so the spec says that
177                    we must interpret PAUSE like RECORD_PAUSE if
178                    recording.
179                 */
180
181                 if (actively_recording()) {
182                         maybe_enable_record ();
183                 } else {
184                         request_stop ();
185                 }
186         }
187 }
188
189 static bool step_queued = false;
190
191 void
192 Session::mmc_step (MIDI::MachineControl &/*mmc*/, int steps)
193 {
194         if (!Config->get_mmc_control ()) {
195                 return;
196         }
197
198         struct timeval now;
199         struct timeval diff = { 0, 0 };
200
201         gettimeofday (&now, 0);
202
203         timersub (&now, &last_mmc_step, &diff);
204
205         gettimeofday (&now, 0);
206         timersub (&now, &last_mmc_step, &diff);
207
208         if (last_mmc_step.tv_sec != 0 && (diff.tv_usec + (diff.tv_sec * 1000000)) < _engine.usecs_per_cycle()) {
209                 return;
210         }
211
212         double diff_secs = diff.tv_sec + (diff.tv_usec / 1000000.0);
213         double cur_speed = (((steps * 0.5) * timecode_frames_per_second()) / diff_secs) / timecode_frames_per_second();
214
215         if (_transport_speed == 0 || cur_speed * _transport_speed < 0) {
216                 /* change direction */
217                 step_speed = cur_speed;
218         } else {
219                 step_speed = (0.6 * step_speed) + (0.4 * cur_speed);
220         }
221
222         step_speed *= 0.25;
223
224 #if 0
225         cerr << "delta = " << diff_secs
226              << " ct = " << _transport_speed
227              << " steps = " << steps
228              << " new speed = " << cur_speed
229              << " speed = " << step_speed
230              << endl;
231 #endif
232
233         request_transport_speed_nonzero (step_speed);
234         last_mmc_step = now;
235
236         if (!step_queued) {
237                 if (midi_control_ui) {
238                         RefPtr<TimeoutSource> tsrc = TimeoutSource::create (100);
239                         tsrc->connect (sigc::mem_fun (*this, &Session::mmc_step_timeout));
240                         tsrc->attach (midi_control_ui->main_loop()->get_context());
241                         step_queued = true;
242                 }
243         }
244 }
245
246 void
247 Session::mmc_rewind (MIDI::MachineControl &/*mmc*/)
248 {
249         if (Config->get_mmc_control ()) {
250                 request_transport_speed(-8.0f);
251         }
252 }
253
254 void
255 Session::mmc_fast_forward (MIDI::MachineControl &/*mmc*/)
256 {
257         if (Config->get_mmc_control ()) {
258                 request_transport_speed(8.0f);
259         }
260 }
261
262 void
263 Session::mmc_locate (MIDI::MachineControl &/*mmc*/, const MIDI::byte* mmc_tc)
264 {
265         if (!Config->get_mmc_control ()) {
266                 return;
267         }
268
269         framepos_t target_frame;
270         Timecode::Time timecode;
271
272         timecode.hours = mmc_tc[0] & 0xf;
273         timecode.minutes = mmc_tc[1];
274         timecode.seconds = mmc_tc[2];
275         timecode.frames = mmc_tc[3];
276         timecode.rate = timecode_frames_per_second();
277         timecode.drop = timecode_drop_frames();
278
279         // Also takes timecode offset into account:
280         timecode_to_sample( timecode, target_frame, true /* use_offset */, false /* use_subframes */ );
281
282         if (target_frame > max_framepos) {
283                 target_frame = max_framepos;
284         }
285
286         /* Some (all?) MTC/MMC devices do not send a full MTC frame
287            at the end of a locate, instead sending only an MMC
288            locate command. This causes the current position
289            of an MTC slave to become out of date. Catch this.
290         */
291
292         MTC_Slave* mtcs = dynamic_cast<MTC_Slave*> (_slave);
293
294         if (mtcs != 0) {
295                 // cerr << "Locate *with* MTC slave\n";
296                 mtcs->handle_locate (mmc_tc);
297         } else {
298                 // cerr << "Locate without MTC slave\n";
299                 request_locate (target_frame, false);
300         }
301 }
302
303 void
304 Session::mmc_shuttle (MIDI::MachineControl &/*mmc*/, float speed, bool forw)
305 {
306         if (!Config->get_mmc_control ()) {
307                 return;
308         }
309
310         if (Config->get_shuttle_speed_threshold() >= 0 && speed > Config->get_shuttle_speed_threshold()) {
311                 speed *= Config->get_shuttle_speed_factor();
312         }
313
314         if (forw) {
315                 request_transport_speed_nonzero (speed);
316         } else {
317                 request_transport_speed_nonzero (-speed);
318         }
319 }
320
321 void
322 Session::mmc_record_enable (MIDI::MachineControl &mmc, size_t trk, bool enabled)
323 {
324         if (!Config->get_mmc_control ()) {
325                 return;
326         }
327
328         RouteList::iterator i;
329         boost::shared_ptr<RouteList> r = routes.reader();
330
331         for (i = r->begin(); i != r->end(); ++i) {
332                 AudioTrack *at;
333
334                 if ((at = dynamic_cast<AudioTrack*>((*i).get())) != 0) {
335                         if (trk == at->remote_control_id()) {
336                                 at->set_record_enabled (enabled, &mmc);
337                                 break;
338                         }
339                 }
340         }
341 }
342
343 /** Send MTC Full Frame message (complete Timecode time) for the start of this cycle.
344  * This resets the MTC code, the next quarter frame message that is sent will be
345  * the first one with the beginning of this cycle as the new start point.
346  * @param t time to send.
347  */
348 int
349 Session::send_full_time_code (framepos_t const t)
350 {
351         /* This function could easily send at a given frame offset, but would
352          * that be useful?  Does ardour do sub-block accurate locating? [DR] */
353
354         MIDI::byte msg[10];
355         Timecode::Time timecode;
356
357         _send_timecode_update = false;
358
359         if (_engine.freewheeling() || !Config->get_send_mtc()) {
360                 return 0;
361         }
362         if (_slave && !_slave->locked()) {
363                 return 0;
364         }
365
366         // Get timecode time for the given time
367         sample_to_timecode (t, timecode, true /* use_offset */, false /* no subframes */);
368
369         // sample-align outbound to rounded (no subframes) timecode
370         framepos_t mtc_tc;
371         timecode_to_sample(timecode, mtc_tc, true, false);
372         outbound_mtc_timecode_frame = mtc_tc;
373
374         transmitting_timecode_time = timecode;
375
376         double const quarter_frame_duration = ((framecnt_t) _frames_per_timecode_frame) / 4.0;
377         if (ceil((t - mtc_tc) / quarter_frame_duration) > 0) {
378                 Timecode::increment (transmitting_timecode_time, config.get_subframes_per_frame());
379                 outbound_mtc_timecode_frame += _frames_per_timecode_frame;
380         }
381
382         DEBUG_TRACE (DEBUG::MTC, string_compose ("Full MTC TC %1\n", outbound_mtc_timecode_frame));
383
384         // I don't understand this bit yet.. [DR]
385         // I do [rg]:
386         // according to MTC spec 24, 30 drop and 30 non-drop TC, the frame-number represented by 8 quarter frames must be even.
387         if (((mtc_timecode_bits >> 5) != MIDI::MTC_25_FPS) && (transmitting_timecode_time.frames % 2)) {
388                 // start MTC quarter frame transmission on an even frame
389                 Timecode::increment (transmitting_timecode_time, config.get_subframes_per_frame());
390                 outbound_mtc_timecode_frame += _frames_per_timecode_frame;
391         }
392
393 #if 0 // compensate for audio latency  -- disabled [rg]
394         /* this needs more thought and work.
395          * the proper solution will be to just offset MTC by the MIDI port's latency.
396          *
397          * using worst_playback_latency() is wrong when the generated MTC is used to sync
398          * clients which send audio to Ardour for recording.
399          * worst_capture_latency() vs. worst_playback_latency()
400          *
401          * NB. similarly to session_ltc, the offset should be subtracted from the timecode to send,
402          * instead of being added to timestamp when to send the timecode.
403          * Otherwise the timestamp may not fall into the jack-cycle of the current _transport frame.
404          * and no MTC QF will be sent.
405          */
406         outbound_mtc_timecode_frame += worst_playback_latency();
407 #endif
408         next_quarter_frame_to_send = 0;
409
410         // Sync slave to the same Timecode time as we are on
411         msg[0] = 0xf0;
412         msg[1] = 0x7f;
413         msg[2] = 0x7f;
414         msg[3] = 0x1;
415         msg[4] = 0x1;
416         msg[9] = 0xf7;
417
418         msg[5] = mtc_timecode_bits | timecode.hours;
419         msg[6] = timecode.minutes;
420         msg[7] = timecode.seconds;
421         msg[8] = timecode.frames;
422
423         // Send message at offset 0, sent time is for the start of this cycle
424         if (MIDI::Manager::instance()->mtc_output_port()->midimsg (msg, sizeof (msg), 0)) {
425                 error << _("Session: could not send full MIDI time code") << endmsg;
426                 return -1;
427         }
428
429         _pframes_since_last_mtc = 0;
430         return 0;
431 }
432
433 /** Send MTC (quarter-frame) messages for this cycle.
434  * Must be called exactly once per cycle from the process thread.  Realtime safe.
435  * This function assumes the state of full Timecode is sane, eg. the slave is
436  * expecting quarter frame messages and has the right frame of reference (any
437  * full MTC Timecode time messages that needed to be sent should have been sent
438  * earlier already this cycle by send_full_time_code)
439  */
440 int
441 Session::send_midi_time_code_for_cycle (framepos_t start_frame, framepos_t end_frame, pframes_t nframes)
442 {
443         if (_engine.freewheeling() || !_send_qf_mtc || transmitting_timecode_time.negative || (next_quarter_frame_to_send < 0)) {
444                 // cerr << "(MTC) Not sending MTC\n";
445                 return 0;
446         }
447         if (_slave && !_slave->locked()) {
448                 return 0;
449         }
450
451         /* MTC is max. 30 fps - assert() below will fail
452          * TODO actually limit it to 24,25,29df,30fps
453          * talk to oofus, first.
454          */
455         if (Timecode::timecode_to_frames_per_second(config.get_timecode_format()) > 30) {
456                 return 0;
457         }
458
459         assert (next_quarter_frame_to_send >= 0);
460         assert (next_quarter_frame_to_send <= 7);
461
462         /* Duration of one quarter frame */
463         double const quarter_frame_duration = _frames_per_timecode_frame / 4.0;
464
465         DEBUG_TRACE (DEBUG::MTC, string_compose ("TF %1 SF %2 MT %3 QF %4 QD %5\n",
466                                 _transport_frame, start_frame, outbound_mtc_timecode_frame,
467                                 next_quarter_frame_to_send, quarter_frame_duration));
468
469         if (rint(outbound_mtc_timecode_frame + (next_quarter_frame_to_send * quarter_frame_duration)) < _transport_frame) {
470                 send_full_time_code (_transport_frame);
471                 return 0;
472         }
473
474         /* Send quarter frames for this cycle */
475         while (end_frame > rint(outbound_mtc_timecode_frame + (next_quarter_frame_to_send * quarter_frame_duration))) {
476
477                 DEBUG_TRACE (DEBUG::MTC, string_compose ("next frame to send: %1\n", next_quarter_frame_to_send));
478
479                 switch (next_quarter_frame_to_send) {
480                         case 0:
481                                 mtc_msg[1] = 0x00 | (transmitting_timecode_time.frames & 0xf);
482                                 break;
483                         case 1:
484                                 mtc_msg[1] = 0x10 | ((transmitting_timecode_time.frames & 0xf0) >> 4);
485                                 break;
486                         case 2:
487                                 mtc_msg[1] = 0x20 | (transmitting_timecode_time.seconds & 0xf);
488                                 break;
489                         case 3:
490                                 mtc_msg[1] = 0x30 | ((transmitting_timecode_time.seconds & 0xf0) >> 4);
491                                 break;
492                         case 4:
493                                 mtc_msg[1] = 0x40 | (transmitting_timecode_time.minutes & 0xf);
494                                 break;
495                         case 5:
496                                 mtc_msg[1] = 0x50 | ((transmitting_timecode_time.minutes & 0xf0) >> 4);
497                                 break;
498                         case 6:
499                                 mtc_msg[1] = 0x60 | ((mtc_timecode_bits | transmitting_timecode_time.hours) & 0xf);
500                                 break;
501                         case 7:
502                                 mtc_msg[1] = 0x70 | (((mtc_timecode_bits | transmitting_timecode_time.hours) & 0xf0) >> 4);
503                                 break;
504                 }
505
506                 const framepos_t msg_time = rint(outbound_mtc_timecode_frame    + (quarter_frame_duration * next_quarter_frame_to_send));
507
508                 // This message must fall within this block or something is broken
509                 assert (msg_time >= start_frame);
510                 assert (msg_time < end_frame);
511
512                 /* convert from session frames back to JACK frames using the transport speed */
513                 pframes_t const out_stamp = (msg_time - start_frame) / _transport_speed;
514                 assert (out_stamp < nframes);
515
516                 if (MIDI::Manager::instance()->mtc_output_port()->midimsg (mtc_msg, 2, out_stamp)) {
517                         error << string_compose(_("Session: cannot send quarter-frame MTC message (%1)"), strerror (errno))
518                                                 << endmsg;
519                         return -1;
520                 }
521
522 #ifndef NDEBUG
523                 DEBUG_STR_DECL(foo)
524                 DEBUG_STR_APPEND(foo,"sending ");
525                 DEBUG_STR_APPEND(foo, transmitting_timecode_time);
526                 DEBUG_TRACE (DEBUG::MTC, string_compose ("%1 qfm = %2, stamp = %3\n", DEBUG_STR(foo).str(), next_quarter_frame_to_send,
527                                                          out_stamp));
528 #endif
529
530                 // Increment quarter frame counter
531                 next_quarter_frame_to_send++;
532
533                 if (next_quarter_frame_to_send >= 8) {
534                         // Wrap quarter frame counter
535                         next_quarter_frame_to_send = 0;
536                         // Increment timecode time twice
537                         Timecode::increment (transmitting_timecode_time, config.get_subframes_per_frame());
538                         Timecode::increment (transmitting_timecode_time, config.get_subframes_per_frame());
539                         // Re-calculate timing of first quarter frame
540                         //timecode_to_sample( transmitting_timecode_time, outbound_mtc_timecode_frame, true /* use_offset */, false );
541                         outbound_mtc_timecode_frame += 2.0 * _frames_per_timecode_frame;
542                 }
543         }
544
545         return 0;
546 }
547
548 /***********************************************************************
549  OUTBOUND MMC STUFF
550 **********************************************************************/
551
552
553 bool
554 Session::mmc_step_timeout ()
555 {
556         struct timeval now;
557         struct timeval diff;
558         double diff_usecs;
559         gettimeofday (&now, 0);
560
561         timersub (&now, &last_mmc_step, &diff);
562         diff_usecs = diff.tv_sec * 1000000 + diff.tv_usec;
563
564         if (diff_usecs > 1000000.0 || fabs (_transport_speed) < 0.0000001) {
565                 /* too long or too slow, stop transport */
566                 request_transport_speed (0.0);
567                 step_queued = false;
568                 return false;
569         }
570
571         if (diff_usecs < 250000.0) {
572                 /* too short, just keep going */
573                 return true;
574         }
575
576         /* slow it down */
577
578         request_transport_speed_nonzero (_transport_speed * 0.75);
579         return true;
580 }
581
582 int
583 Session::start_midi_thread ()
584 {
585         midi_control_ui = new MidiControlUI (*this);
586         midi_control_ui->run ();
587         return 0;
588 }
589