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 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
|
/*
Standard MIDI File component
Copyright (C) 2006-2024, Pedro Lopez-Cabanillas <plcl@users.sf.net>
Based on midifile.c by Tim Thompson, M.Czeiszperger and Greg Lee
This library is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This library 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, see <http://www.gnu.org/licenses/>.
*/
#include <QDataStream>
#include <QFile>
#include <QList>
#include <QTextCodec>
#include <cmath>
#include <drumstick/qsmf.h>
#include <limits>
DISABLE_WARNING_PUSH
DISABLE_WARNING_DEPRECATED_DECLARATIONS
/**
* @file qsmf.cpp
* Implementation of a class managing Standard MIDI Files input/output
*/
namespace drumstick {
namespace File {
/**
* @addtogroup SMF
* @{
*
* QSmf provides a mechanism to parse and encode Standard MIDI Files, without
* the burden of a policy forcing to use some internal sequence representation.
*
* This class is not related or based on the ALSA library.
*
* @}
*/
class QSmf::QSmfPrivate {
public:
QSmfPrivate():
m_Interactive(false),
m_CurrTime(0),
m_RealTime(0),
m_DblRealTime(0),
m_DblOldRealtime(0),
m_Division(96),
m_CurrTempo(500000),
m_OldCurrTempo(500000),
m_OldRealTime(0),
m_OldCurrTime(0),
m_RevisedTime(0),
m_TempoChangeTime(0),
m_ToBeRead(0),
m_NumBytesWritten(0),
m_Tracks(0),
m_fileFormat(0),
m_LastStatus(0),
m_codec(nullptr),
m_IOStream(nullptr)
{ }
bool m_Interactive; /**< file and track headers are not required */
quint64 m_CurrTime; /**< current time in delta-time units */
quint64 m_RealTime; /**< current time in 1/16 centisecond-time units */
double m_DblRealTime; /**< as above, floating */
double m_DblOldRealtime;
int m_Division; /**< ticks per beat. Default = 96 */
quint64 m_CurrTempo; /**< microseconds per quarter note */
quint64 m_OldCurrTempo;
quint64 m_OldRealTime;
quint64 m_OldCurrTime;
quint64 m_RevisedTime;
quint64 m_TempoChangeTime;
quint64 m_ToBeRead;
quint64 m_NumBytesWritten;
int m_Tracks;
int m_fileFormat;
int m_LastStatus;
QTextCodec *m_codec;
QDataStream *m_IOStream;
QByteArray m_MsgBuff;
QList<QSmfRecTempo> m_TempoList;
};
/**
* Constructor
* @param parent Optional parent object
*/
QSmf::QSmf(QObject * parent) :
QObject(parent),
d(new QSmfPrivate)
{ }
/**
* Destructor
*/
QSmf::~QSmf()
{
d->m_TempoList.clear();
}
/**
* Check if the SMF stream is positioned at the end.
* @return True if the SMF stream is at the end
*/
bool QSmf::endOfSmf()
{
return d->m_IOStream->atEnd();
}
/**
* Gets a single byte from the SMF stream
* @return A Single byte
*/
quint8 QSmf::getByte()
{
quint8 b = 0;
if (!endOfSmf())
{
*d->m_IOStream >> b;
d->m_ToBeRead--;
}
return b;
}
/**
* Puts a single byte to the SMF stream
* @param value A Single byte
*/
void QSmf::putByte(quint8 value)
{
*d->m_IOStream << value;
d->m_NumBytesWritten++;
}
/**
* Adds a tempo change to the internal tempo list
* @param tempo Tempo in microseconds per quarter
* @param time Location in ticks
*/
void QSmf::addTempo(quint64 tempo, quint64 time)
{
QSmfRecTempo tempoRec;
tempoRec.tempo = tempo;
tempoRec.time = time;
d->m_TempoList.append(tempoRec);
}
/**
* Reads a SMF header
*/
void QSmf::readHeader()
{
d->m_CurrTime = 0;
d->m_RealTime = 0;
d->m_Division = 96;
d->m_CurrTempo = 500000;
d->m_OldCurrTempo = 500000;
addTempo(d->m_CurrTempo, 0);
if (d->m_Interactive)
{
d->m_fileFormat= 0;
d->m_Tracks = 1;
d->m_Division = 96;
}
else
{
readExpected("MThd");
d->m_ToBeRead = read32bit();
d->m_fileFormat = read16bit();
d->m_Tracks = read16bit();
d->m_Division = read16bit();
}
Q_EMIT signalSMFHeader(d->m_fileFormat, d->m_Tracks, d->m_Division);
/* flush any extra stuff, in case the length of header is not */
while ((d->m_ToBeRead > 0) && !endOfSmf())
{
getByte();
}
if (d->m_ToBeRead > 0)
{
SMFError("Unexpected end of input");
}
}
/**
* Reads a track chunk
*/
void QSmf::readTrack()
{
/* This array is indexed by the high half of a status byte. It's
value is either the number of bytes needed (1 or 2) for a channel
message, or 0 (meaning it's not a channel message). */
static const quint8 chantype[16] =
{ 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 1, 1, 2, 0 };
quint64 lookfor;
quint8 c, c1, type;
bool sysexcontinue; // true if last message was an unfinished SysEx
bool running; // true when running status is used
quint8 status; // status value (e.g. 0x90==note-on)
int needed;
double delta_secs;
quint64 delta_ticks, save_time, save_tempo;
sysexcontinue = false;
status = 0;
if (d->m_Interactive)
{
d->m_ToBeRead = std::numeric_limits<unsigned long long>::max();
}
else
{
readExpected("MTrk");
d->m_ToBeRead = read32bit();
}
d->m_CurrTime = 0;
d->m_RealTime = 0;
d->m_DblRealTime = 0;
d->m_DblOldRealtime = 0;
d->m_OldCurrTime = 0;
d->m_OldRealTime = 0;
d->m_CurrTempo = findTempo();
Q_EMIT signalSMFTrackStart();
while (!endOfSmf() && (d->m_Interactive || d->m_ToBeRead > 0))
{
lookfor = 0;
if (d->m_Interactive)
{
d->m_CurrTime++;
}
else
{
delta_ticks = unsigned(readVarLen());
d->m_RevisedTime = d->m_CurrTime;
d->m_CurrTime += delta_ticks;
while (d->m_RevisedTime < d->m_CurrTime)
{
save_time = d->m_RevisedTime;
save_tempo = d->m_CurrTempo;
d->m_CurrTempo = findTempo();
if (d->m_CurrTempo != d->m_OldCurrTempo)
{
d->m_OldCurrTempo = d->m_CurrTempo;
d->m_OldRealTime = d->m_RealTime;
if (d->m_RevisedTime != d->m_TempoChangeTime)
{
d->m_DblOldRealtime = d->m_DblRealTime;
d->m_OldCurrTime = save_time;
}
delta_secs = ticksToSecs(d->m_RevisedTime - d->m_OldCurrTime,
quint16(d->m_Division), save_tempo);
d->m_DblRealTime = d->m_DblOldRealtime + delta_secs * 1600.0;
d->m_RealTime = llround(d->m_DblRealTime);
if (d->m_RevisedTime == d->m_TempoChangeTime)
{
d->m_OldCurrTime = d->m_RevisedTime;
d->m_DblOldRealtime = d->m_DblRealTime;
}
}
else
{
delta_secs = ticksToSecs(d->m_RevisedTime - d->m_OldCurrTime,
quint16(d->m_Division), d->m_CurrTempo);
d->m_DblRealTime = d->m_DblOldRealtime + delta_secs * 1600.0;
d->m_RealTime = llround(d->m_DblRealTime);
}
}
}
c = getByte();
if (sysexcontinue && (c != end_of_sysex))
{
SMFError("didn't find expected continuation of a SysEx");
}
if (c < 0xf8)
{
if ((c & 0x80) == 0)
{
if (status == 0)
{
SMFError("unexpected running status");
}
running = true;
}
else
{
status = c;
running = false;
}
needed = chantype[status >> 4 & 0x0f];
if (needed != 0)
{
if (running)
{
c1 = c;
}
else
{
c1 = getByte();
}
if (needed > 1)
{
channelMessage(status, c1, getByte());
}
else
{
channelMessage(status, c1, 0);
}
continue;
}
}
switch (c)
{
case meta_event:
type = getByte();
lookfor = quint64(readVarLen());
lookfor = d->m_ToBeRead - lookfor;
msgInit();
while ((d->m_ToBeRead > lookfor) && !endOfSmf())
{
msgAdd(getByte());
}
metaEvent(type);
break;
case system_exclusive:
lookfor = quint64(readVarLen());
lookfor = d->m_ToBeRead - lookfor;
msgInit();
msgAdd(system_exclusive);
while ((d->m_ToBeRead > lookfor) && !endOfSmf())
{
c = getByte();
msgAdd(c);
}
if (c == end_of_sysex)
{
sysEx();
}
else
{
sysexcontinue = true;
}
break;
case end_of_sysex:
lookfor = readVarLen();
lookfor = d->m_ToBeRead - lookfor;
if (!sysexcontinue)
{
msgInit();
}
while ((d->m_ToBeRead > lookfor) && !endOfSmf())
{
c = getByte();
msgAdd(c);
}
if (sysexcontinue)
{
if (c == end_of_sysex)
{
sysEx();
sysexcontinue = false;
}
}
break;
default:
badByte(c, d->m_IOStream->device()->pos() - 1);
break;
}
if ((d->m_ToBeRead > lookfor) && endOfSmf()) {
SMFError("Unexpected end of input");
}
}
if (d->m_ToBeRead > 0) {
SMFError(QStringLiteral("Track ended before reading last %1 bytes").arg(d->m_ToBeRead));
}
Q_EMIT signalSMFTrackEnd();
}
/**
* Reads a SMF stream.
*/
void QSmf::SMFRead()
{
int i;
readHeader();
for ( i = d->m_Tracks; (i > 0) && !endOfSmf(); i--)
{
readTrack();
}
if (i > 0) {
SMFError(
QStringLiteral("%1 tracks out of a total of %2 are missing").arg(i).arg(d->m_Tracks));
}
}
/**
* Writes a SMF stream.
*
* Every MIDI file starts with a header.
* In format 1 files, the first track is a tempo map.
* The rest of the file is a series of tracks
*/
void QSmf::SMFWrite()
{
int i;
d->m_LastStatus = 0;
writeHeaderChunk(d->m_fileFormat, d->m_Tracks, d->m_Division);
d->m_LastStatus = 0;
if (d->m_fileFormat == 1)
{
Q_EMIT signalSMFWriteTempoTrack();
}
for (i = 0; i < d->m_Tracks; ++i)
{
writeTrackChunk(i);
}
}
/**
* Reads a SMF stream.
* @param stream Pointer to an existing and opened stream
*/
void QSmf::readFromStream(QDataStream *stream)
{
d->m_IOStream = stream;
SMFRead();
}
/**
* Reads a SMF stream from a disk file.
* @param fileName Name of an existing file.
*/
void QSmf::readFromFile(const QString& fileName)
{
QFile file(fileName);
file.open(QIODevice::ReadOnly);
QDataStream ds(&file);
readFromStream(&ds);
file.close();
}
/**
* Writes a SMF stream
* @param stream Pointer to an existing and opened stream
*/
void QSmf::writeToStream(QDataStream *stream)
{
d->m_IOStream = stream;
SMFWrite();
}
/**
* Writes a SMF stream to a disk file
* @param fileName File name
*/
void QSmf::writeToFile(const QString& fileName)
{
QFile file(fileName);
file.open(QIODevice::WriteOnly);
QDataStream ds(&file);
writeToStream(&ds);
file.close();
}
/**
* Writes a SMF header chuck
* @param format SMF Format (0/1/2)
* @param ntracks Number of tracks
* @param division Resolution in ticks per quarter note
*/
void QSmf::writeHeaderChunk(int format, int ntracks, int division)
{
write32bit(MThd);
write32bit(6);
write16bit(quint16(format));
write16bit(quint16(ntracks));
write16bit(quint16(division));
}
/**
* Writes a track chuck
* @param track Number of the track
*/
void QSmf::writeTrackChunk(int track)
{
quint32 trkhdr;
quint32 trklength;
qint64 offset;
qint64 place_marker;
d->m_LastStatus = 0;
trkhdr = MTrk;
trklength = 0;
offset = d->m_IOStream->device()->pos();
write32bit(trkhdr);
write32bit(trklength);
d->m_NumBytesWritten = 0;
Q_EMIT signalSMFWriteTrack(track);
place_marker = d->m_IOStream->device()->pos();
d->m_IOStream->device()->seek(offset);
trklength = d->m_NumBytesWritten;
write32bit(trkhdr);
write32bit(trklength);
d->m_IOStream->device()->seek(place_marker);
}
/**
* Writes a variable length Meta Event
* @param deltaTime Time offset in ticks
* @param type Meta event type
* @param data Message data
*/
void QSmf::writeMetaEvent(long deltaTime, int type, const QByteArray& data)
{
writeVarLen(deltaTime);
d->m_LastStatus = meta_event;
putByte(d->m_LastStatus);
putByte(type);
writeVarLen(data.size());
foreach(char byte, data)
putByte(byte);
}
/**
* Writes a Text Meta Event
* @param deltaTime Time offset in ticks
* @param type Meta event type
* @param data Message text
*/
void QSmf::writeMetaEvent(long deltaTime, int type, const QString& data)
{
writeVarLen(deltaTime);
putByte(d->m_LastStatus = meta_event);
putByte(type);
QByteArray lcldata;
if (d->m_codec == nullptr)
lcldata = data.toLatin1();
else
lcldata = d->m_codec->fromUnicode(data);
writeVarLen(lcldata.length());
foreach(char byte, lcldata)
putByte(byte);
}
/**
* Writes a simple Meta event
* @param deltaTime Time offset in ticks
* @param type Meta event type
* @param data Meta event data
* @since 0.2.0
*/
void QSmf::writeMetaEvent(long deltaTime, int type, int data)
{
writeVarLen(deltaTime);
putByte(d->m_LastStatus = meta_event);
putByte(type);
putByte(1);
putByte(data);
}
/**
* Writes a simple Meta event
* @param deltaTime Time offset in ticks
* @param type Meta event type
*/
void QSmf::writeMetaEvent(long deltaTime, int type)
{
writeVarLen(deltaTime);
putByte(d->m_LastStatus = meta_event);
putByte(type);
putByte(0);
}
/**
* Writes a variable length MIDI message
* @param deltaTime Time offset in ticks
* @param type MIDI event type
* @param chan MIDI Channel
* @param data Message data
*/
void QSmf::writeMidiEvent(long deltaTime, int type, int chan,
const QByteArray& data)
{
unsigned int i, j, size;
quint8 c;
writeVarLen(quint64(deltaTime));
if ((type == system_exclusive) || (type == end_of_sysex))
{
c = type;
d->m_LastStatus = 0;
}
else
{
if (chan > 15)
{
SMFError("error: MIDI channel greater than 16");
}
c = type | chan;
}
if (d->m_LastStatus != c)
{
d->m_LastStatus = c;
putByte(c);
}
c = quint8(data[0]);
if (type == system_exclusive || type == end_of_sysex)
{
size = data.size();
if (type == c)
--size;
writeVarLen(size);
}
j = (c == type ? 1 : 0);
for (i = j; i < unsigned(data.size()); ++i)
{
putByte(quint8(data[i]));
}
}
/**
* Writes a MIDI message with a single parameter
* @param deltaTime Time offset in ticks
* @param type MIDI event type
* @param chan MIDI Channel
* @param b1 Message parameter
*/
void QSmf::writeMidiEvent(long deltaTime, int type, int chan, int b1)
{
quint8 c;
writeVarLen(deltaTime);
if ((type == system_exclusive) || (type == end_of_sysex))
{
SMFError("error: Wrong method for a system exclusive event");
}
if (chan > 15)
{
SMFError("error: MIDI channel greater than 16");
}
c = type | chan;
if (d->m_LastStatus != c)
{
d->m_LastStatus = c;
putByte(c);
}
putByte(b1);
}
/**
* Writes a MIDI message with two parameters
* @param deltaTime Time offset in ticks
* @param type MIDI event type
* @param chan MIDI Channel
* @param b1 Message parameter 1
* @param b2 Message parameter 2
*/
void QSmf::writeMidiEvent(long deltaTime, int type, int chan, int b1, int b2)
{
quint8 c;
writeVarLen(deltaTime);
if ((type == system_exclusive) || (type == end_of_sysex))
{
SMFError("error: Wrong method for a system exclusive event");
}
if (chan > 15)
{
SMFError("error: MIDI channel greater than 16");
}
c = type | chan;
if (d->m_LastStatus != c)
{
d->m_LastStatus = c;
putByte(c);
}
putByte(b1);
putByte(b2);
}
/**
* Writes a variable length MIDI message
* @param deltaTime Time offset in ticks
* @param type MIDI event type
* @param len Message length
* @param data Message data
*/
void QSmf::writeMidiEvent(long deltaTime, int type, long len, char* data)
{
unsigned int i, j, size;
quint8 c;
writeVarLen(quint64(deltaTime));
if ((type != system_exclusive) && (type != end_of_sysex))
{
SMFError("error: type should be system exclusive");
}
d->m_LastStatus = 0;
c = quint8(type);
putByte(c);
size = unsigned(len);
c = quint8(data[0]);
if (c == type)
--size;
writeVarLen(size);
j = (c == type ? 1 : 0);
for (i = j; i < unsigned(len); ++i)
{
putByte(quint8(data[i]));
}
}
/**
* Writes a MIDI Sequence number
* @param deltaTime Time offset in ticks
* @param seqnum Sequence number
*/
void QSmf::writeSequenceNumber(long deltaTime, int seqnum)
{
writeVarLen(deltaTime);
d->m_LastStatus = meta_event;
putByte(d->m_LastStatus);
putByte(sequence_number);
putByte(2);
putByte((seqnum >> 8) & 0xff);
putByte(seqnum & 0xff);
}
/**
* Writes a Tempo change message
* @param deltaTime Time offset in ticks
* @param tempo Tempo in microseconds per quarter note
*/
void QSmf::writeTempo(long deltaTime, long tempo)
{
writeVarLen(deltaTime);
putByte(d->m_LastStatus = meta_event);
putByte(set_tempo);
putByte(3);
putByte((tempo >> 16) & 0xff);
putByte((tempo >> 8) & 0xff);
putByte(tempo & 0xff);
}
/**
* Writes a Tempo change message
* @param deltaTime Time offset in ticks
* @param tempo Tempo expressed in quarter notes per minute
*/
void QSmf::writeBpmTempo(long deltaTime, int tempo)
{
long us_tempo = 60000000l / tempo;
writeTempo(deltaTime, us_tempo);
}
/**
* Writes a Time Signature message
* @param deltaTime Time offset in ticks
* @param num Numerator
* @param den Denominator (exponent for a power of two)
* @param cc Number of MIDI clocks in a metronome click
* @param bb Number of notated 32nd notes in 24 MIDI clocks
*/
void QSmf::writeTimeSignature(long deltaTime, int num, int den, int cc, int bb)
{
writeVarLen(deltaTime);
putByte(d->m_LastStatus = meta_event);
putByte(time_signature);
putByte(4);
putByte(num & 0xff);
putByte(den & 0xff);
putByte(cc & 0xff);
putByte(bb & 0xff);
}
/**
* Writes a key Signature message
* @param deltaTime Time offset in ticks
* @param tone Number of alterations (positive=sharps, negative=flats)
* @param mode Scale mode (0=major, 1=minor)
*/
void QSmf::writeKeySignature(long deltaTime, int tone, int mode)
{
writeVarLen(quint64(deltaTime));
putByte(d->m_LastStatus = meta_event);
putByte(key_signature);
putByte(2);
putByte(quint8(tone));
putByte(mode & 0x01);
}
/**
* Writes multi-length bytes
* @param value Integer value
*/
void QSmf::writeVarLen(quint64 value)
{
quint64 buffer;
buffer = value & 0x7f;
while ((value >>= 7) > 0)
{
buffer <<= 8;
buffer |= 0x80;
buffer += (value & 0x7f);
}
while (true)
{
putByte(buffer & 0xff);
if (buffer & 0x80)
buffer >>= 8;
else
break;
}
}
/* These routines are used to make sure that the byte order of
the various data types remains constant between machines. */
void QSmf::write32bit(quint32 data)
{
putByte((data >> 24) & 0xff);
putByte((data >> 16) & 0xff);
putByte((data >> 8) & 0xff);
putByte(data & 0xff);
}
void QSmf::write16bit(quint16 data)
{
putByte((data >> 8) & 0xff);
putByte(data & 0xff);
}
quint16 QSmf::to16bit(quint8 c1, quint8 c2)
{
quint16 value;
value = quint16(c1 << 8);
value += c2;
return value;
}
quint32 QSmf::to32bit(quint8 c1, quint8 c2, quint8 c3, quint8 c4)
{
quint32 value;
value = unsigned(c1 << 24);
value += unsigned(c2 << 16);
value += unsigned(c3 << 8);
value += c4;
return value;
}
quint16 QSmf::read16bit()
{
quint8 c1, c2;
c1 = getByte();
c2 = getByte();
return to16bit(c1, c2);
}
quint32 QSmf::read32bit()
{
quint8 c1, c2, c3, c4;
c1 = getByte();
c2 = getByte();
c3 = getByte();
c4 = getByte();
return to32bit(c1, c2, c3, c4);
}
long QSmf::readVarLen()
{
quint64 value;
quint8 c;
c = getByte();
value = c;
if ((c & 0x80) != 0)
{
value &= 0x7f;
do
{
c = getByte();
value = (value << 7) + (c & 0x7f);
} while ((c & 0x80) != 0);
}
return long(value);
}
void QSmf::readExpected(const QString& s)
{
int j;
quint8 b;
for (j = 0; j < s.length(); ++j)
{
b = getByte();
if (QChar(b) != s[j])
{
SMFError(QString("Invalid (%1) SMF format at %2").arg(b, 0, 16).arg(d->m_IOStream->device()->pos()));
break;
}
}
}
quint64 QSmf::findTempo()
{
quint64 result, old_tempo, new_tempo;
QSmfRecTempo rec = d->m_TempoList.last();
old_tempo = d->m_CurrTempo;
new_tempo = d->m_CurrTempo;
QList<QSmfRecTempo>::Iterator it;
for( it = d->m_TempoList.begin(); it != d->m_TempoList.end(); ++it )
{
rec = (*it);
if (rec.time <= d->m_CurrTime)
{
old_tempo = rec.tempo;
}
new_tempo = rec.tempo;
if (rec.time > d->m_RevisedTime)
{
break;
}
}
if ((rec.time <= d->m_RevisedTime) || (rec.time > d->m_CurrTime))
{
d->m_RevisedTime = d->m_CurrTime;
result = old_tempo;
}
else
{
d->m_RevisedTime = rec.time;
d->m_TempoChangeTime = d->m_RevisedTime;
result = new_tempo;
}
return result;
}
/* This routine converts delta times in ticks into seconds. The
else statement is needed because the formula is different for tracks
based on notes and tracks based on SMPTE times. */
double QSmf::ticksToSecs(quint64 ticks, quint16 division, quint64 tempo)
{
double result;
double smpte_format;
double smpte_resolution;
if (division > 0)
{
result = double(ticks * tempo)/(division * 1000000.0);
}
else
{
smpte_format = upperByte(division);
smpte_resolution = lowerByte(division);
result = double(ticks)/(smpte_format * smpte_resolution
* 1000000.0);
}
return result;
}
void QSmf::SMFError(const QString& s)
{
Q_EMIT signalSMFError(s);
}
void QSmf::channelMessage(quint8 status, quint8 c1, quint8 c2)
{
quint8 chan;
int k;
chan = status & midi_channel_mask;
if (c1 > 127)
{
SMFError(QString("ChannelMessage with bad c1 = %1").arg(c1));
//c1 &= 127;
}
if (c2 > 127)
{
SMFError(QString("ChannelMessage with bad c2 = %1").arg(c2));
//c2 &= 127;
}
switch (status & midi_command_mask)
{
case note_off:
Q_EMIT signalSMFNoteOff(chan, c1, c2);
break;
case note_on:
Q_EMIT signalSMFNoteOn(chan, c1, c2);
break;
case poly_aftertouch:
Q_EMIT signalSMFKeyPress(chan, c1, c2);
break;
case control_change:
Q_EMIT signalSMFCtlChange(chan, c1, c2);
break;
case program_chng:
Q_EMIT signalSMFProgram(chan, c1);
break;
case channel_aftertouch:
Q_EMIT signalSMFChanPress(chan, c1);
break;
case pitch_wheel:
k = c1 + (c2 << 7) - 8192;
Q_EMIT signalSMFPitchBend(chan, k);
break;
default:
SMFError(QString("Invalid MIDI status %1. Unhandled event").arg(status));
break;
}
}
void QSmf::metaEvent(quint8 b)
{
QSmfRecTempo rec;
QByteArray m(d->m_MsgBuff);
switch (b)
{
case sequence_number:
Q_EMIT signalSMFSequenceNum(to16bit(m[0], m[1]));
break;
case text_event:
case copyright_notice:
case sequence_name:
case instrument_name:
case lyric:
case marker:
case cue_point: {
QString s;
if (d->m_codec == nullptr) {
Q_EMIT signalSMFText2(b, m);
} else {
s = d->m_codec->toUnicode(m);
Q_EMIT signalSMFText(b, s);
}
}
break;
case forced_channel:
Q_EMIT signalSMFforcedChannel(m[0]);
break;
case forced_port:
Q_EMIT signalSMFforcedPort(m[0]);
break;
case end_of_track:
Q_EMIT signalSMFendOfTrack();
break;
case set_tempo:
d->m_CurrTempo = to32bit(0, m[0], m[1], m[2]);
Q_EMIT signalSMFTempo(d->m_CurrTempo);
rec = d->m_TempoList.last();
if (rec.tempo == d->m_CurrTempo)
{
return;
}
if (rec.time > d->m_CurrTime)
{
return;
}
addTempo(d->m_CurrTempo, d->m_CurrTime);
break;
case smpte_offset:
Q_EMIT signalSMFSmpte(m[0], m[1], m[2], m[3], m[4]);
break;
case time_signature:
Q_EMIT signalSMFTimeSig(m[0], m[1], m[2], m[3]);
break;
case key_signature:
Q_EMIT signalSMFKeySig(m[0], m[1]);
break;
case sequencer_specific:
Q_EMIT signalSMFSeqSpecific(m);
break;
default:
Q_EMIT signalSMFMetaUnregistered(b, m);
break;
}
Q_EMIT signalSMFMetaMisc(b, m);
}
void QSmf::sysEx()
{
QByteArray varr(d->m_MsgBuff);
Q_EMIT signalSMFSysex(varr);
}
void QSmf::badByte(quint8 b, int p)
{
SMFError(QString("Unexpected byte (%1) at %2").arg(b, 2, 16).arg(p));
}
quint8 QSmf::lowerByte(quint16 x)
{
return (x & 0xff);
}
quint8 QSmf::upperByte(quint16 x)
{
return ((x >> 8) & 0xff);
}
void QSmf::msgInit()
{
d->m_MsgBuff.truncate(0);
}
void QSmf::msgAdd(quint8 b)
{
int s = d->m_MsgBuff.size();
d->m_MsgBuff.resize(s + 1);
d->m_MsgBuff[s] = b;
}
/* public properties (accessors) */
/**
* Gets the current time in ticks
* @return Time in ticks
*/
long QSmf::getCurrentTime()
{
return d->m_CurrTime;
}
/**
* Gets the current tempo
* @return Tempo in us per quarter
*/
long QSmf::getCurrentTempo()
{
return d->m_CurrTempo;
}
/**
* Gets the real time in seconds
* @return Time in seconds
*/
long QSmf::getRealTime()
{
return d->m_RealTime;
}
/**
* Gets the resolution
* @return Resolution in ticks per quarter note
*/
int QSmf::getDivision()
{
return d->m_Division;
}
/**
* Sets the resolution
* @param division Resolution in ticks per quarter note
*/
void QSmf::setDivision(int division)
{
d->m_Division = division;
}
/**
* Gets the number of tracks
* @return Number of tracks
*/
int QSmf::getTracks()
{
return d->m_Tracks;
}
/**
* Sets the number of tracks
* @param tracks Number of tracks
*/
void QSmf::setTracks(int tracks)
{
d->m_Tracks = tracks;
}
/**
* Gets the SMF file format
* @return File format (0, 1, or 2)
*/
int QSmf::getFileFormat()
{
return d->m_fileFormat;
}
/**
* Sets the SMF file format
* @param fileFormat File format (0, 1, or 2)
*/
void QSmf::setFileFormat(int fileFormat)
{
d->m_fileFormat = fileFormat;
}
/**
* Gets the position in the SMF stream
* @return Position offset in the stream
*/
long QSmf::getFilePos()
{
return long(d->m_IOStream->device()->pos());
}
/**
* Gets the text codec used for text meta-events I/O
* @return QTextCodec pointer
* @since 0.2.0
* @deprecated because the class QTextCodec was removed from QtCore since Qt6.
*/
QTextCodec* QSmf::getTextCodec()
{
return d->m_codec;
}
/**
* Sets the text codec for text meta-events.
* The engine doesn't take ownership of the codec instance.
*
* @param codec QTextCodec pointer
* @since 0.2.0
* @deprecated because the class QTextCodec was removed from QtCore since Qt6.
*/
void QSmf::setTextCodec(QTextCodec *codec)
{
d->m_codec = codec;
}
/**
* @brief drumstickLibraryVersion provides the Drumstick version as an edited QString
* @return Drumstick library version
*/
QString drumstickLibraryVersion()
{
return QStringLiteral(QT_STRINGIFY(VERSION));
}
} // namespace File
} // namespace drumstick
DISABLE_WARNING_POP
|