summaryrefslogtreecommitdiff
path: root/muse_qt4_evolution/muse/sync.cpp
blob: c4cb30fc31167e435f24239ba310c9269e0e226f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
//=============================================================================
//  MusE
//  Linux Music Editor
//  $Id:$
//
//  Copyright (C) 2002-2006 by Werner Schweer and others
//
//  This program is free software; you can redistribute it and/or modify
//  it under the terms of the GNU General Public License version 2.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program; if not, write to the Free Software
//  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//=============================================================================

#include "sync.h"
#include "song.h"
#include "widgets/utils.h"
#include "globals.h"
#include "audio.h"
#include "audiodev.h"
#include "gconfig.h"
#include "al/tempo.h"
#include "al/al.h"

int rxSyncPort = -1;         // receive from all ports
int txSyncPort = 1;

bool debugSync = false;
MTC mtcOffset;
bool extSyncFlag = false;
bool genMTCSync  = false;      // output MTC Sync
bool genMCSync   = false;      // output MidiClock Sync
bool genMMC      = false;      // output Midi Machine Control
bool acceptMTC   = false;
bool acceptMC    = true;
bool acceptMMC   = true;

static MTC mtcCurTime;
// static int mtcState;    // 0-7 next expected quarter message
// static bool mtcValid;
// static int mtcLost;
// static bool mtcSync;    // receive complete mtc frame?

//static bool mcStart = false;
//static int mcStartTick;

enum {
      MMC_STOP = 1,
      MMC_PLAY = 2,
      MMC_DEFERRED_PLAY = 3,
      MMC_FAST_FORWARD = 4,
      MMC_REWIND = 5,
      MMC_RECORD_STROBE = 6,  // Punch In
      MMC_RECORD_EXIT = 7,    // Punch Out
      MMC_PAUSE = 9,
      MMC_RESET = 13,
      MMC_GOTO = 0x44
      };

#if 0
//---------------------------------------------------------
//  mmcInput
//    Midi Machine Control Input received
//---------------------------------------------------------

void MidiSeq::mmcInput(int id, int cmd, const Pos& pos)
      {
#if 0
      int rxDeviceId = 127;

      if (!extSyncFlag || !acceptMMC || (id != 127 && id != rxDeviceId))
            return;

      if (debugMsg)
      	printf("mmcInput: id %d cmd %02x %02x\n", id, cmd, cmd);

      switch (cmd) {
            case MMC_STOP:
                  if (debugSync)
                        printf("  MMC: STOP\n");
                  if (audio->isPlaying())
            		audioDriver->stopTransport();
            	else
                  	// reset REC
				audio->sendMsgToGui(MSG_STOP);
                  break;
            case MMC_PLAY:
            case MMC_DEFERRED_PLAY:
            	audioDriver->startTransport();
                  break;
            case MMC_FAST_FORWARD:
                  printf("MMC: FF not implemented\n");
                  break;
            case MMC_REWIND:
                  printf("MMC: REWIND not implemented\n");
                  break;
            case MMC_RECORD_STROBE:
                  printf("MMC: REC STROBE not implemented\n");
                  break;
            case MMC_RECORD_EXIT:
                  printf("MMC: REC EXIT not implemented\n");
                  break;
            case MMC_PAUSE:
			audio->sendMsgToGui(MSG_RECORD);
            	break;
            case MMC_RESET:
                  printf("MMC: RESET not implemented\n");
                  break;

            case MMC_GOTO:
                  audioDriver->seekTransport(pos.frame());
                  break;

            default:
                  printf("MMC id %x cmd %x, unknown\n", id, cmd);
                  break;
            }
#endif
      }

//---------------------------------------------------------
//   mtcInputQuarter
//    process Quarter Frame Message
//---------------------------------------------------------

void MidiSeq::mtcInputQuarter(int, unsigned char c)
      {
#if 0
      static int hour, min, sec, frame;

      if (!extSyncFlag)
            return;

      int valL = c & 0xf;
      int valH = valL << 4;

      int _state = (c & 0x70) >> 4;
      if (mtcState != _state)
            mtcLost += _state - mtcState;
      mtcState = _state + 1;

      switch(_state) {
            case 7:
                  hour  = (hour  & 0x0f) | valH;
                  break;
            case 6:
                  hour  = (hour  & 0xf0) | valL;
                  break;
            case 5:
                  min   = (min   & 0x0f) | valH;
                  break;
            case 4:
                  min   = (min   & 0xf0) | valL;
                  break;
            case 3:
                  sec   = (sec   & 0x0f) | valH;
                  break;
            case 2:
                  sec   = (sec   & 0xf0) | valL;
                  break;
            case 1:
                  frame = (frame & 0x0f) | valH;
                  break;
            case 0:  frame = (frame & 0xf0) | valL;
                  break;
            }
      frame &= 0x1f;    // 0-29
      sec   &= 0x3f;    // 0-59
      min   &= 0x3f;    // 0-59
      hour  &= 0x1f;

      if (mtcState == 8) {
            mtcValid = (mtcLost == 0);
            mtcState = 0;
            mtcLost  = 0;
            if (mtcValid) {
                  mtcCurTime.set(hour, min, sec, frame);
                  mtcSyncMsg(mtcCurTime, !mtcSync);
                  mtcSync = true;
                  }
            }
      else if (mtcValid && (mtcLost == 0)) {
            mtcCurTime.incQuarter();
            mtcSyncMsg(mtcCurTime, false);
            }
#endif
      }

//---------------------------------------------------------
//   mtcInputFull
//    process Frame Message
//---------------------------------------------------------

void MidiSeq::mtcInputFull(const unsigned char* p, int n)
      {
#if 0
      if (debugSync)
            printf("mtcInputFull\n");
      if (!extSyncFlag)
            return;

      if (p[3] != 1) {
            if (p[3] != 2) {   // silently ignore user bits
                  printf("unknown mtc msg subtype 0x%02x\n", p[3]);
                  dump(p, n);
                  }
            return;
            }
      int hour  = p[4];
      int min   = p[5];
      int sec   = p[6];
      int frame = p[7];

      frame &= 0x1f;    // 0-29
      sec   &= 0x3f;    // 0-59
      min   &= 0x3f;    // 0-59
//      int type = (hour >> 5) & 3;
      hour &= 0x1f;

      mtcCurTime.set(hour, min, sec, frame);
      mtcState = 0;
      mtcValid = true;
      mtcLost  = 0;
#endif
      }

//---------------------------------------------------------
//   nonRealtimeSystemSysex
//---------------------------------------------------------

void MidiSeq::nonRealtimeSystemSysex(const unsigned char* p, int n)
      {
#if 0
//      int chan = p[2];
      switch(p[3]) {
            case 4:
                  printf("NRT Setup\n");
                  break;
            default:
                  printf("unknown NRT Msg 0x%02x\n", p[3]);
                  dump(p, n);
                  break;
           }
#endif
      }

//---------------------------------------------------------
//   setSongPosition
//    MidiBeat is a 14 Bit value. Each MidiBeat spans
//    6 MIDI Clocks. Inother words, each MIDI Beat is a
//    16th note (since there are 24 MIDI Clocks in a
//    quarter note).
//---------------------------------------------------------

void MidiSeq::setSongPosition(int port, int midiBeat)
      {
#if 0
      if (midiInputTrace)
            printf("set song position port:%d %d\n", port, midiBeat);
      if (!extSyncFlag)
            return;
      Pos pos((config.division * midiBeat) / 4, AL::TICKS);
      audioDriver->seekTransport(pos.frame());
      if (debugSync)
            printf("setSongPosition %d\n", pos.tick());
#endif
      }

//---------------------------------------------------------
//   realtimeSystemInput
//    real time message received
//---------------------------------------------------------

void MidiSeq::realtimeSystemInput(int port, int c)
      {
#if 0
      if (midiInputTrace)
            printf("realtimeSystemInput port:%d 0x%x\n", port+1, c);

      if (midiInputTrace && (rxSyncPort != port) && rxSyncPort != -1) {
            if (debugSync)
                  printf("rxSyncPort configured as %d; received sync from port %d\n",
                     rxSyncPort, port);
            return;
            }
      if (!extSyncFlag)
            return;
      switch(c) {
            case 0xf8:  // midi clock (24 ticks / quarter note)
                  {
                  double mclock0 = curTime();
                  // Difference in time last 2 rounds:
                  double tdiff0   = mclock0 - mclock1;
                  double tdiff1   = mclock1 - mclock2;
                  double averagetimediff = 0.0;

                  if (mclock1 != 0.0) {
                        if (storedtimediffs < 24)
                        {
                           timediff[storedtimediffs] = mclock0 - mclock1;
                           storedtimediffs++;
                        }
                        else {
                              for (int i=0; i<23; i++) {
                                    timediff[i] = timediff[i+1];
                                    }
                              timediff[23] = mclock0 - mclock1;
                        }
                        // Calculate average timediff:
                        for (int i=0; i < storedtimediffs; i++) {
                              averagetimediff += timediff[i]/storedtimediffs;
                              }
                        }
                  processMidiClock();

                  // Compare w audio if playing:
                  if (audio->isPlaying() /*state == PLAY*/) {
                        //BEGIN standard setup:
                        recTick  += config.division / 24; // The one we're syncing to
                        int tempo = AL::tempomap.tempo(0);
                        unsigned curFrame = audio->pos().frame();
                        double songtick = (double(curFrame)/double(AL::sampleRate)) * config.division * 1000000.0 / double(tempo);
                        double scale = tdiff0/averagetimediff;
                        double tickdiff = songtick - ((double) recTick - 24 + scale*24.0);

                        //END standard setup
                        if (debugSync) {
                              //
                              // Create debug values for printing out which beat we're at, etc etc... yaddayadda...
                              //
                              int m, b, t;
                              audio->pos().mbt(&m, &b, &t);

                              int song_beat = b + m*4; // if the time-signature is different than 4/4, this will be wrong.
                              int sync_beat = recTick/config.division;
                              printf("pT=%.3f rT=%d diff=%.3f songB=%d syncB=%d scale=%.3f", songtick, recTick, tickdiff, song_beat, sync_beat, scale);
                              }
                        //if ((mclock2 !=0.0) && (tdiff1 > 0.0) && tickdiff != 0.0 && lastTempo != 0) {
                        if ((mclock2 !=0.0) && (tdiff1 > 0.0) && fabs(tickdiff) > 2.0 && lastTempo != 0) {
                              // Interpolate:
                              double tickdiff1 = songtick1 - recTick1;
                              double tickdiff2 = songtick2 - recTick2;
                              //double newtickdiff = tickdiff/3.0 + tickdiff1/5.0 + tickdiff2/7.0; //2 min 15 sec, 120BPM, -p 512 jackd
                              //double newtickdiff = tickdiff/4.0 + tickdiff1/4.0 + tickdiff2/4.0; // Not long... :-P
                              //double newtickdiff = tickdiff/5.0 + tickdiff1/8.0 + tickdiff2/12.0; //3,5 mins on 120BPM, -p 512 jackd
                              //double newtickdiff = tickdiff/7.0 + tickdiff1/8.0 + tickdiff2/9.0; //2 min 15 sec, 120BPM, -p 512 jackd
                              //double newtickdiff = tickdiff/5.0 + tickdiff1/8.0 + tickdiff2/16.0; //3,5 mins on 120BPM, -p 512 jackd
                              double newtickdiff = tickdiff/5.0 + tickdiff1/16.0 + tickdiff2/24.0; //5 mins 30 secs on 116BPM, -p 512 jackd
                              //double newtickdiff = tickdiff/5.0 + tickdiff1/23.0 + tickdiff2/31.0; //5 mins on 116BPM, -p 512 jackd
                              //double newtickdiff = tickdiff + tickdiff1/8.0 + tickdiff2/16.0; // Not long...

                              if (newtickdiff != 0.0) {
                                    int newTempo = AL::tempomap.tempo(0);
                                    //newTempo += int(24.0 * newtickdiff * scale);
                                    newTempo += int(24.0 * newtickdiff);
                                    if (debugSync)
                                          printf(" tdiff=%f ntd=%f lt=%d tmpo=%.3f", tdiff0, newtickdiff, lastTempo, (float)((1000000.0 * 60.0)/newTempo));
                                    AL::tempomap.setTempo(0,newTempo);
                                    }
                              if (debugSync)
                                    printf("\n");
                              }
                        else if (debugSync)
                              printf("\n");

                        //BEGIN post calc
                        lastTempo = tempo;
                        recTick2 = recTick1;
                        recTick1 = recTick;
                        mclock2 = mclock1;
                        mclock1 = mclock0;
                        songtick2 = songtick1;
                        songtick1 = songtick;
                        //END post calc
                        break;
                        } // END state play
                  //
                  // Pre-sync (when audio is not running)
                  // Calculate tempo depending on time per pulse
                  //
                  if (mclock1 == 0.0) {
//TODO3                        midiPorts[port].device()->discardInput();
                        if (debugSync)
                           printf("Discarding input from port %d\n", port);
                        }
                  if ((mclock2 != 0.0) && (tdiff0 > 0.0)) {
                        int tempo0 = int(24000000.0 * tdiff0 + .5);
                        int tempo1 = int(24000000.0 * tdiff1 + .5);
                        int tempo = AL::tempomap.tempo(0);

                        int diff0 = tempo0 - tempo;
                        int diff1 = tempo1 - tempo0;
                        if (diff0) {
                              int newTempo = tempo + diff0/8 + diff1/16;
                              if (debugSync)
                                 printf("setting new tempo %d = %f\n", newTempo, (float)((1000000.0 * 60.0)/newTempo));
                              AL::tempomap.setTempo(0, newTempo);
                              }
                        }
                  mclock2 = mclock1;
                  mclock1 = mclock0;
                  }
                  break;
            case 0xf9:  // midi tick  (every 10 msec)
                  if (mcStart) {
                        song->setPos(0, mcStartTick);
                        mcStart = false;
                        return;
                        }
                  break;
            case 0xfa:  // start
                  if (debugSync)
                        printf("   start\n");
                  if (!audio->isPlaying() /*state == IDLE*/) {
                        //seek(0);
                        audioDriver->seekTransport(0);
                        unsigned curFrame = audioDriver->framePos();
                        recTick = recTick1 = recTick2 = 0;
                        mclock1 = 0.0; mclock2 = 0.0;
                        songtick1 = songtick2 = 0;
                        if (debugSync)
                              printf("   curFrame: %d curTick: %d tempo: %d\n", curFrame, recTick, AL::tempomap.tempo(0));

                        //startPlay();
                        storedtimediffs = 0;
                        for (int i=0; i<24; i++)
                              timediff[i] = 0.0;
                        audio->msgPlay(true);
                        }
                  break;
            case 0xfb:  // continue
                  if (debugSync)
                        printf("   continue\n");
                  if (!audio->isPlaying() /*state == IDLE */) {
                        unsigned curFrame = audioDriver->framePos();
                        recTick = AL::tempomap.frame2tick(curFrame); // don't think this will work... (ml)
                        audio->msgPlay(true);
                        }
                  break;
            case 0xfc:  // stop
                  if (debugSync)
                        printf("   stop\n");
                  if (audio->isPlaying() /*state == PLAY*/)
                        audio->msgPlay(false);
                  break;
            case 0xfd:  // unknown
            case 0xfe:  // active sensing
            case 0xff:  // system reset
                  break;
            }
#endif

      }

//---------------------------------------------------------
//   mtcSyncMsg
//    process received mtc Sync
//    seekFlag - first complete mtc frame received after
//                start
//---------------------------------------------------------

void MidiSeq::mtcSyncMsg(const MTC& /*mtc*/, bool /*seekFlag*/)
      {
#if 0
      double time = mtc.time();
      if (debugSync)
            printf("mtcSyncMsg: time %f\n", time);

      if (seekFlag && state == START_PLAY) {
//            int tick = tempomap.time2tick(time);
            state = PLAY;
            sendMsgToGui(MSG_PLAY);
            return;
            }
      // double curT = curTime();

      if (tempoSN != tempomap.tempoSN()) {
            double cpos    = tempomap.tick2time(_midiTick, 0);
            samplePosStart = samplePos - lrint(cpos * sampleRate);
            rtcTickStart   = rtcTick - lrint(cpos * realRtcTicks);
            tempoSN        = tempomap.tempoSN();
            }

      //
      // diff is the time in sec MusE is out of sync
      //
      double diff = time - (double(samplePosStart)/double(sampleRate));
      if (debugSync)
            printf("   state %d diff %f\n", mtcState, diff);
#endif
      }
#endif