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