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