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