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