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