File: midifile.cpp

package info (click to toggle)
musescore2 2.3.2%2Bdfsg3-11~bpo9%2B1
  • links: PTS, VCS
  • area: main
  • in suites: stretch-backports-sloppy
  • size: 192,432 kB
  • sloc: cpp: 262,278; xml: 176,707; sh: 3,376; ansic: 1,384; python: 356; makefile: 229; perl: 82; pascal: 78
file content (531 lines) | stat: -rw-r--r-- 15,632 bytes parent folder | download | duplicates (9)
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
//=============================================================================
//  MuseScore
//  Music Composition & Notation
//
//  Copyright (C) 2007-2011 Werner Schweer
//
//  This program is free software; you can redistribute it and/or modify
//  it under the terms of the GNU General Public License version 2
//  as published by the Free Software Foundation and appearing in
//  the file LICENCE.GPL
//=============================================================================

#include <QFile>
#include "midifile.h"

//---------------------------------------------------------
//   MidiFile
//---------------------------------------------------------

MidiFile::MidiFile()
      {
      fp               = 0;
      _format          = 1;
      _division        = 480;
      }

//---------------------------------------------------------
//   readMidi
//    return false on error
//---------------------------------------------------------

bool MidiFile::read(const QString& path)
      {
      QFile f(path);
      if (!f.open(QIODevice::ReadOnly))
            return false;
      return read(&f);
      }

bool MidiFile::read(QIODevice* f)
      {
      fp = f;
      _tracks.clear();
      curPos    = 0;

      char tmp[4];

      read(tmp, 4);
      int len = readLong();
      if (memcmp(tmp, "MThd", 4) || len < 6)
            throw(QString("bad midifile: MThd expected"));

      _format     = readShort();
      int ntracks = readShort();
      _division   = readShort();

      if (_division < 0)
            _division = (-(_division/256)) * (_division & 0xff);
      if (len > 6)
            skip(len-6); // skip the excess

      switch (_format) {
            case 0:
                  if (readTrack())
                        return false;
                  break;
            case 1:
                  for (int i = 0; i < ntracks; i++) {
                        if (readTrack())
                              return false;
                        }
                  break;
            default:
                  throw(QString("midi file format %1 not implemented").arg(_format));
            }
      return true;
      }

//---------------------------------------------------------
//   readTrack
//    return true on error
//---------------------------------------------------------

bool MidiFile::readTrack()
      {
      char tmp[4];
      read(tmp, 4);
      if (memcmp(tmp, "MTrk", 4))
            throw(QString("bad midifile: MTrk expected"));
      int len       = readLong();       // len
      qint64 endPos = curPos + len;
      status        = -1;
      sstatus       = -1;  // running status, will not be reset on meta or sysex
      click         =  0;
      MidiTrack* track  = new MidiTrack(this);
      _tracks.push_back(track);

      for (;;) {
            MidiEvent event;
            int rv = readEvent(&event);
            if (rv == 0)
                  track->events().insert(std::pair<int, MidiEvent>(click, event));
            else if (rv == 2)
                  break;
            }
      if (curPos != endPos) {
            qWarning("bad track len: %lld != %lld, %lld bytes too much\n", endPos, curPos, endPos - curPos);
            if (curPos < endPos) {
                  qWarning("  skip %lld\n", endPos-curPos);
                  skip(endPos - curPos);
                  }
            }
      return false;
      }

/*---------------------------------------------------------
 *    read
 *    return false on error
 *---------------------------------------------------------*/

void MidiFile::read(void* p, qint64 len)
      {
      curPos += len;
      qint64 rv = fp->read((char*)p, len);
      if (rv != len)
            throw(QString("bad midifile: unexpected EOF"));
      }

//---------------------------------------------------------
//   readShort
//---------------------------------------------------------

int MidiFile::readShort()
      {
      char c;
      int val = 0;
      for (int i = 0; i < 2; ++i) {
            fp->getChar(&c);
            val <<= 8;
            val += (c & 0xff);
            }
      return val;
      }

//---------------------------------------------------------
//   readLong
//   writeLong
//---------------------------------------------------------

int MidiFile::readLong()
      {
      char c;
      int val = 0;
      for (int i = 0; i < 4; ++i) {
            fp->getChar(&c);
            val <<= 8;
            val += (c & 0xff);
            }
      return val;
      }

/*---------------------------------------------------------
 *    skip
 *    This is meant for skipping a few bytes in a
 *    file or fifo.
 *---------------------------------------------------------*/

void MidiFile::skip(qint64 len)
      {
      if (len <= 0)
            return;
      char tmp[len];
      read(tmp, len);
      }

/*---------------------------------------------------------
 *    getvl
 *    Read variable-length number (7 bits per byte, MSB first)
 *---------------------------------------------------------*/

int MidiFile::getvl()
      {
      int l = 0;
      for (int i = 0; i < 16; i++) {
            uchar c;
            read(&c, 1);
            l += (c & 0x7f);
            if (!(c & 0x80)) {
                  return l;
                  }
            l <<= 7;
            }
      return -1;
      }

//---------------------------------------------------------
//   MidiTrack
//---------------------------------------------------------

MidiTrack::MidiTrack(MidiFile* f)
      {
      mf          = f;
//      _outChannel = -1;
//      _outPort    = -1;
//      _drumTrack  = false;
//      _hasKey     = false;
//      _staffIdx   = -1;
      }

//---------------------------------------------------------
//   readEvent
//    return 0 - valid event
//           1 - skip event
//           2 - EOT
//---------------------------------------------------------

int MidiFile::readEvent(MidiEvent* event)
      {
      uchar me, a, b;

      int nclick = getvl();
      if (nclick == -1)
            throw(QString("readEvent: error 1(getvl)"));
      click += nclick;
      for (;;) {
            read(&me, 1);
            if (me >= 0xf1 && me <= 0xfe && me != 0xf7)
                  qDebug("Midi: Unknown Message 0x%02x", me & 0xff);
            else
                  break;
            }

      uchar* data;
      int dataLen;

      if (me == 0xf0 || me == 0xf7) {
            status  = -1;                  // no running status
            int len = getvl();
            if (len == -1)
                  throw(QString("readEvent: error 3"));
            data    = new unsigned char[len+1];
            dataLen = len;
            read(data, len);
            data[dataLen] = 0;    // always terminate with zero
            if (data[len-1] != 0xf7) {
                  qDebug("SYSEX does not end with 0xf7!");
                  // more to come?
                  }
            else
                  dataLen--;      // don't count 0xf7
            delete[] data;
#if 0
            event->setType(MidiEventType::SYSEX);
            event->setData(data);
            event->setLen(dataLen);
            event->setOntime(click);
#endif
            return 1;
            }

      if (me == 0xff) { // MidiEventType::META) {
            status = -1;                  // no running status
            uchar type;
            read(&type, 1);
            dataLen = getvl();                // read len
            if (dataLen == -1)
                  throw(QString("readEvent: error 6"));
            data = new unsigned char[dataLen + 1];
            if (dataLen)
                  read(data, dataLen);
            data[dataLen] = 0;      // always terminate with zero so we get valid C++ strings
            if (type == META_TEMPO) {
                  unsigned tempo = data[2] + (data[1] << 8) + (data[0] << 16);
                  double t = 1000000.0 / double(tempo);
                  _tempoMap.insert(std::pair<const int, qreal>(click, t));
                  }
            // else
            //      printf("META %02x\n", type);
            delete[] data;
            if (type == META_EOT)
                  return 2;
            return 1;
            }

      if (me & 0x80) {                     // status byte
            status   = me;
            sstatus  = status;
            read(&a, 1);
            }
      else {
            if (status == -1) {
                  qDebug("readEvent: no running status, read 0x%02x", me);
                  qDebug("sstatus ist 0x%02x", sstatus);
                  if (sstatus == -1)
                        return 0;
                  status = sstatus;
                  }
            a = me;
            }
      int channel = status & 0x0f;
      b           = 0;
      MidiEventType t = MidiEventType(status & 0xf0);
      switch (t) {
            case MidiEventType::NOTEOFF:
            case MidiEventType::NOTEON:
            case MidiEventType::POLYAFTER:
            case MidiEventType::CONTROLLER:        // controller
            case MidiEventType::PITCHBEND:        // pitch bend
                  read(&b, 1);
            default:
                  break;
            }
      switch (t) {
            case MidiEventType::NOTEOFF:
            case MidiEventType::NOTEON:
            case MidiEventType::CONTROLLER:
            case MidiEventType::PITCHBEND:
            case MidiEventType::POLYAFTER:
                  event->set(t, channel, a, b);
                  break;
            case MidiEventType::PROGRAM:
            case MidiEventType::AFTERTOUCH:
                  event->set(t, channel, a, 0);
                  break;
            default:          // f1 f2 f3 f4 f5 f6 f7 f8 f9
                  throw(QString("BAD STATUS")); // 0x%02x, me 0x%02x", status, me);
            }

      if ((a & 0x80) || (b & 0x80)) {
            qDebug("8't bit in data set(%02x %02x): tick %d read 0x%02x  status:0x%02x",
              a & 0xff, b & 0xff, click, me, status);
            qDebug("readEvent: error 16");
            if (b & 0x80) {
                  // Try to fix: interpret as channel byte
                  status   = b;
                  sstatus  = status;
                  return 0;
                  }
            throw(QString("readEvent: error 16"));
            }
      return 0;
      }

//---------------------------------------------------------
//   write
//---------------------------------------------------------

bool MidiFile::write(const QString& path)
      {
      QFile f(path);
      if (!f.open(QIODevice::WriteOnly))
            return false;
      return write(&f);
      }

bool MidiFile::write(QIODevice* f)
      {
      fp = f;
      write("MThd", 4);
      writeLong(6);                 // header len
      writeShort(_format);          // format
      writeShort(_tracks.size());
      writeShort(_division);
      foreach (const MidiTrack* t, _tracks) {
            if (writeTrack(t))
                  return true;
            }
      return false;
      }

//---------------------------------------------------------
//   write
//---------------------------------------------------------

void MidiFile::writeEvent(const MidiEvent& event)
      {
      switch (event.type()) {
            case MidiEventType::NOTEON:
                  writeStatus(event.type(), event.channel());
                  put(event.dataA() & 0x7f);
                  put(event.dataB() & 0x7f);
                  break;

            case MidiEventType::NOTEOFF:
                  writeStatus(event.type(), event.channel());
                  put(event.dataA() & 0x7f);
                  put(event.dataB() & 0x7f);
                  break;

            case MidiEventType::CONTROLLER:
                  writeStatus(event.type(), event.channel());
                  put(event.dataA() & 0x7f);
                  put(event.dataB() & 0x7f);
                  break;

            case MidiEventType::PROGRAM:
                  writeStatus(event.type(), event.channel());
                  put(event.dataA() & 0x7f);
                  break;
#if 0
            case MidieEventType::META:
                  put(MidiEventType::META);
                  put(event.metaType());
                  putvl(event.len());
                  write(event.edata(), event.len());
                  resetRunningStatus();     // really ?!
                  break;

            case MidiEventType::SYSEX:
                  put(MidiEventType::SYSEX);
                  putvl(event.len() + 1);  // including 0xf7
                  write(event.edata(), event.len());
                  put(MidiEventTppe::ENDSYSEX);
                  resetRunningStatus();
                  break;
#endif
            default:
                  printf("unsupported\n");
                  break;
            }
      }

//---------------------------------------------------------
//   writeTrack
//---------------------------------------------------------

bool MidiFile::writeTrack(const MidiTrack* t)
      {
      write("MTrk", 4);
      qint64 lenpos = fp->pos();
      writeLong(0);                 // dummy len

      status   = -1;
      int tick = 0;
      for (auto i : t->events()) {
            int ntick = i.first;
            putvl(ntick - tick);    // write tick delta
            writeEvent(i.second);
            tick = ntick;
            }

      //---------------------------------------------------
      //    write "End Of Track" Meta
      //    write Track Len
      //

      putvl(1);
      put(0xff);        // Meta
      put(0x2f);        // EOT
      putvl(0);         // len 0
      qint64 endpos = fp->pos();
      fp->seek(lenpos);
      writeLong(endpos-lenpos-4);   // tracklen
      fp->seek(endpos);
      return false;
      }

//---------------------------------------------------------
//   writeStatus
//---------------------------------------------------------

void MidiFile::writeStatus(MidiEventType st, int c)
      {
      uchar nstat = uchar(st) | (c & 0xf);
      //
      //  running status; except for Sysex- and Meta Events
      //
      if ((((nstat & 0xf0) != 0xf0) && (nstat != status))) {
            status = nstat;
            put(nstat);
            }
      }

//---------------------------------------------------------
//   write
//---------------------------------------------------------

bool MidiFile::write(const void* p, qint64 len)
      {
      qint64 rv = fp->write((char*)p, len);
      if (rv == len)
            return false;
      qDebug("write midifile failed: %s", fp->errorString().toLatin1().data());
      return true;
      }

//---------------------------------------------------------
//   writeShort
//---------------------------------------------------------

void MidiFile::writeShort(int i)
      {
      fp->putChar(i >> 8);
      fp->putChar(i);
      }

//---------------------------------------------------------
//   writeLong
//---------------------------------------------------------

void MidiFile::writeLong(int i)
      {
      fp->putChar(i >> 24);
      fp->putChar(i >> 16);
      fp->putChar(i >> 8);
      fp->putChar(i);
      }

/*---------------------------------------------------------
 *    putvl
 *    Write variable-length number (7 bits per byte, MSB first)
 *---------------------------------------------------------*/

void MidiFile::putvl(unsigned val)
      {
      unsigned long buf = val & 0x7f;
      while ((val >>= 7) > 0) {
            buf <<= 8;
            buf |= 0x80;
            buf += (val & 0x7f);
            }
      for (;;) {
            put(buf);
            if (buf & 0x80)
                  buf >>= 8;
            else
                  break;
            }
      }