libcm is a C development framework with an emphasis on audio signal processing applications.
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

cmMidiFile.c 37KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536
  1. #include "cmPrefix.h"
  2. #include "cmGlobal.h"
  3. #include "cmRpt.h"
  4. #include "cmErr.h"
  5. #include "cmCtx.h"
  6. #include "cmFile.h"
  7. #include "cmMem.h"
  8. #include "cmMallocDebug.h"
  9. #include "cmLinkedHeap.h"
  10. #include "cmTime.h"
  11. #include "cmMidi.h"
  12. #include "cmMidiFile.h"
  13. #ifdef cmBIG_ENDIAN
  14. #define mfSwap16(v) (v)
  15. #define mfSwap32(v) (v)
  16. #else
  17. #define mfSwap16(v) cmSwap16(v)
  18. #define mfSwap32(v) cmSwap32(v)
  19. #endif
  20. typedef struct
  21. {
  22. unsigned cnt; // count of track records
  23. cmMidiTrackMsg_t* base; // pointer to first track recd
  24. cmMidiTrackMsg_t* last; // pointer to last track recd
  25. } _cmMidiTrack_t;
  26. typedef struct
  27. {
  28. cmErr_t err; // this objects error object
  29. cmLHeapH_t lhH; // linked heap used for all dynamically alloc'd data space
  30. cmFileH_t fh; // cmFile handle (only used in fmMidiFileOpen() and cmMidiFileWrite())
  31. unsigned short fmtId; // midi file type id: 0,1,2
  32. unsigned short ticksPerQN; // ticks per quarter note or 0 if smpteFmtId is valid
  33. cmMidiByte_t smpteFmtId; // smpte format or 0 if ticksPerQN is valid
  34. cmMidiByte_t smpteTicksPerFrame; // smpte ticks per frame or 0 if ticksPerQN is valid
  35. unsigned short trkN; // track count
  36. _cmMidiTrack_t* trkV; // track vector
  37. char* fn; // file name or NULL if this object did not originate from a file
  38. unsigned msgN; // count of msg's in msgV[]
  39. cmMidiTrackMsg_t** msgV; // sorted msg list
  40. unsigned nextUid; // next available msg uid
  41. } _cmMidiFile_t;
  42. cmMidiFileH_t cmMidiFileNullHandle = cmSTATIC_NULL_HANDLE;
  43. _cmMidiFile_t* _cmMidiFileHandleToPtr( cmMidiFileH_t h )
  44. {
  45. _cmMidiFile_t* p = (_cmMidiFile_t*)h.h;
  46. assert( p != NULL );
  47. return p;
  48. }
  49. void* _cmMidiFileMalloc( _cmMidiFile_t* mfp, unsigned byteN )
  50. { return cmLHeapAllocZ(mfp->lhH,byteN); }
  51. cmMfRC_t _cmMidiFileRead8( _cmMidiFile_t* mfp, cmMidiByte_t* p )
  52. {
  53. if( cmFileReadUChar(mfp->fh,p,1) != kOkFileRC )
  54. return cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI byte read failed.");
  55. return kOkMfRC;
  56. }
  57. cmMfRC_t _cmMidiFileRead16( _cmMidiFile_t* mfp, unsigned short* p )
  58. {
  59. if( cmFileReadUShort(mfp->fh,p,1) != kOkFileRC )
  60. return cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI short read failed.");
  61. *p = mfSwap16(*p);
  62. return kOkMfRC;
  63. }
  64. cmMfRC_t _cmMidiFileRead24( _cmMidiFile_t* mfp, unsigned* p )
  65. {
  66. *p = 0;
  67. int i = 0;
  68. for(; i<3; ++i)
  69. {
  70. unsigned char c;
  71. if( cmFileReadUChar(mfp->fh,&c,1) != kOkFileRC )
  72. return cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI 24 bit integer read failed.");
  73. *p = (*p << 8) + c;
  74. }
  75. //*p =mfSwap32(*p);
  76. return kOkMfRC;
  77. }
  78. cmMfRC_t _cmMidiFileRead32( _cmMidiFile_t* mfp, unsigned* p )
  79. {
  80. if( cmFileReadUInt(mfp->fh,p,1) != kOkFileRC )
  81. return cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI integer read failed.");
  82. *p = mfSwap32(*p);
  83. return kOkMfRC;
  84. }
  85. cmMfRC_t _cmMidiFileReadText( _cmMidiFile_t* mfp, cmMidiTrackMsg_t* tmp, unsigned byteN )
  86. {
  87. if( byteN == 0 )
  88. return kOkMfRC;
  89. char* t = (char*)_cmMidiFileMalloc(mfp,byteN+1);
  90. t[byteN] = 0;
  91. if( cmFileReadChar(mfp->fh,t,byteN) != kOkFileRC )
  92. return cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI read text failed.");
  93. tmp->u.text = t;
  94. tmp->byteCnt = byteN;
  95. return kOkMfRC;
  96. }
  97. cmMfRC_t _cmMidiFileReadRecd( _cmMidiFile_t* mfp, cmMidiTrackMsg_t* tmp, unsigned byteN )
  98. {
  99. char* t = (char*)_cmMidiFileMalloc(mfp,byteN);
  100. if( cmFileReadChar(mfp->fh,t,byteN) != kOkFileRC )
  101. return cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI read record failed.");
  102. tmp->byteCnt = byteN;
  103. tmp->u.voidPtr = t;
  104. return kOkMfRC;
  105. }
  106. cmMfRC_t _cmMidiFileReadVarLen( _cmMidiFile_t* mfp, unsigned* p )
  107. {
  108. unsigned char c;
  109. if( cmFileReadUChar(mfp->fh,&c,1) != kOkFileRC )
  110. return cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI read variable length integer failed.");
  111. if( !(c & 0x80) )
  112. *p = c;
  113. else
  114. {
  115. *p = c & 0x7f;
  116. do
  117. {
  118. if( cmFileReadUChar(mfp->fh,&c,1) != kOkFileRC )
  119. return cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI read variable length integer failed.");
  120. *p = (*p << 7) + (c & 0x7f);
  121. }while( c & 0x80 );
  122. }
  123. return kOkMfRC;
  124. }
  125. cmMfRC_t _cmMidiFileAppendTrackMsg( _cmMidiFile_t* mfp, unsigned short trkIdx, unsigned dtick, cmMidiByte_t status, cmMidiTrackMsg_t** trkMsgPtrPtr )
  126. {
  127. cmMidiTrackMsg_t* tmp = (cmMidiTrackMsg_t*)_cmMidiFileMalloc(mfp, sizeof(cmMidiTrackMsg_t) );
  128. // link new record onto track record chain
  129. if( mfp->trkV[trkIdx].base == NULL )
  130. mfp->trkV[trkIdx].base = tmp;
  131. else
  132. mfp->trkV[trkIdx].last->link = tmp;
  133. mfp->trkV[trkIdx].last = tmp;
  134. mfp->trkV[trkIdx].cnt++;
  135. // set the generic track record fields
  136. tmp->dtick = dtick;
  137. tmp->status = status;
  138. tmp->metaId = kInvalidMetaMdId;
  139. tmp->trkIdx = trkIdx;
  140. tmp->byteCnt = 0;
  141. *trkMsgPtrPtr = tmp;
  142. return kOkMfRC;
  143. }
  144. cmMfRC_t _cmMidiFileReadSysEx( _cmMidiFile_t* mfp, cmMidiTrackMsg_t* tmp, unsigned byteN )
  145. {
  146. cmMfRC_t rc = kOkMfRC;
  147. cmMidiByte_t b = 0;
  148. if( byteN == cmInvalidCnt )
  149. {
  150. long offs;
  151. if( cmFileTell(mfp->fh,&offs) != kOkFileRC )
  152. return cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI File 'tell' failed.");
  153. byteN = 0;
  154. // get the length of the sys-ex msg
  155. while( !cmFileEof(mfp->fh) && (b != kSysComEoxMdId) )
  156. {
  157. if((rc = _cmMidiFileRead8(mfp,&b)) != kOkMfRC )
  158. return rc;
  159. ++byteN;
  160. }
  161. // verify that the EOX byte was found
  162. if( b != kSysComEoxMdId )
  163. return cmErrMsg(&mfp->err,kMissingEoxMfRC,"MIDI file missing 'end-of-sys-ex'.");
  164. // rewind to the beginning of the msg
  165. if( cmFileSeek(mfp->fh,kBeginFileFl,offs) != kOkFileRC )
  166. return cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file seek failed on sys-ex read.");
  167. }
  168. // allocate memory to hold the sys-ex msg
  169. cmMidiByte_t* mp = (cmMidiByte_t *)_cmMidiFileMalloc(mfp, byteN );
  170. // read the sys-ex msg from the file into msg memory
  171. if( cmFileReadUChar(mfp->fh,mp,byteN) != kOkFileRC )
  172. return cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI sys-ex read failed.");
  173. tmp->byteCnt = byteN;
  174. tmp->u.sysExPtr = mp;
  175. return rc;
  176. }
  177. cmMfRC_t _cmMidiFileReadChannelMsg( _cmMidiFile_t* mfp, cmMidiByte_t* rsPtr, cmMidiByte_t status, cmMidiTrackMsg_t* tmp )
  178. {
  179. cmMfRC_t rc = kOkMfRC;
  180. cmMidiChMsg_t* p = (cmMidiChMsg_t*)_cmMidiFileMalloc(mfp,sizeof(cmMidiChMsg_t));
  181. unsigned useRsFl = status <= 0x7f;
  182. cmMidiByte_t statusCh = useRsFl ? *rsPtr : status;
  183. if( useRsFl )
  184. p->d0 = status;
  185. else
  186. *rsPtr = status;
  187. tmp->byteCnt = sizeof(cmMidiChMsg_t);
  188. tmp->status = statusCh & 0xf0;
  189. p->ch = statusCh & 0x0f;
  190. p->durMicros = 0;
  191. unsigned byteN = cmMidiStatusToByteCount(tmp->status);
  192. if( byteN==kInvalidMidiByte || byteN > 2 )
  193. return cmErrMsg(&mfp->err,kInvalidStatusMfRC,"Invalid status:0x%x %i.",tmp->status,tmp->status);
  194. unsigned i;
  195. for(i=useRsFl; i<byteN; ++i)
  196. {
  197. cmMidiByte_t* b = i==0 ? &p->d0 : &p->d1;
  198. if((rc = _cmMidiFileRead8(mfp,b)) != kOkMfRC )
  199. return rc;
  200. }
  201. // convert note-on velocity=0 to note off
  202. if( tmp->status == kNoteOnMdId && p->d1==0 )
  203. tmp->status = kNoteOffMdId;
  204. tmp->u.chMsgPtr = p;
  205. return rc;
  206. }
  207. cmMfRC_t _cmMidiFileReadMetaMsg( _cmMidiFile_t* mfp, cmMidiTrackMsg_t* tmp )
  208. {
  209. cmMidiByte_t metaId;
  210. cmMfRC_t rc;
  211. unsigned byteN = 0;
  212. if((rc = _cmMidiFileRead8(mfp,&metaId)) != kOkMfRC )
  213. return rc;
  214. if((rc = _cmMidiFileReadVarLen(mfp,&byteN)) != kOkMfRC )
  215. return rc;
  216. //printf("mt: %i 0x%x n:%i\n",metaId,metaId,byteN);
  217. switch( metaId )
  218. {
  219. case kSeqNumbMdId: rc = _cmMidiFileRead16(mfp,&tmp->u.sVal); break;
  220. case kTextMdId: rc = _cmMidiFileReadText(mfp,tmp,byteN); break;
  221. case kCopyMdId: rc = _cmMidiFileReadText(mfp,tmp,byteN); break;
  222. case kTrkNameMdId: rc = _cmMidiFileReadText(mfp,tmp,byteN); break;
  223. case kInstrNameMdId: rc = _cmMidiFileReadText(mfp,tmp,byteN); break;
  224. case kLyricsMdId: rc = _cmMidiFileReadText(mfp,tmp,byteN); break;
  225. case kMarkerMdId: rc = _cmMidiFileReadText(mfp,tmp,byteN); break;
  226. case kCuePointMdId: rc = _cmMidiFileReadText(mfp,tmp,byteN); break;
  227. case kMidiChMdId: rc = _cmMidiFileRead8(mfp,&tmp->u.bVal); break;
  228. case kEndOfTrkMdId: break;
  229. case kTempoMdId: rc = _cmMidiFileRead24(mfp,&tmp->u.iVal); break;
  230. case kSmpteMdId: rc = _cmMidiFileReadRecd(mfp,tmp,sizeof(cmMidiSmpte_t)); break;
  231. case kTimeSigMdId: rc = _cmMidiFileReadRecd(mfp,tmp,sizeof(cmMidiTimeSig_t)); break;
  232. case kKeySigMdId: rc = _cmMidiFileReadRecd(mfp,tmp,sizeof(cmMidiKeySig_t)); break;
  233. case kSeqSpecMdId: rc = _cmMidiFileReadSysEx(mfp,tmp,byteN); break;
  234. default:
  235. cmFileSeek(mfp->fh,kCurFileFl,byteN);
  236. rc = cmErrMsg(&mfp->err,kUnknownMetaIdMfRC,"Unknown meta status:0x%x %i.",metaId,metaId);
  237. }
  238. tmp->metaId = metaId;
  239. return rc;
  240. }
  241. cmMfRC_t _cmMidiFileReadTrack( _cmMidiFile_t* mfp, unsigned short trkIdx )
  242. {
  243. cmMfRC_t rc = kOkMfRC;
  244. unsigned dticks = 0;
  245. cmMidiByte_t status;
  246. cmMidiByte_t runstatus = 0;
  247. bool contFl = true;
  248. while( contFl && (rc==kOkMfRC))
  249. {
  250. cmMidiTrackMsg_t* tmp = NULL;
  251. // read the tick count
  252. if((rc = _cmMidiFileReadVarLen(mfp,&dticks)) != kOkMfRC )
  253. return rc;
  254. // read the status byte
  255. if((rc = _cmMidiFileRead8(mfp,&status)) != kOkMfRC )
  256. return rc;
  257. //printf("st:%i 0x%x\n",status,status);
  258. // append a track msg
  259. if((rc = _cmMidiFileAppendTrackMsg( mfp, trkIdx, dticks, status, &tmp )) != kOkMfRC )
  260. return rc;
  261. // switch on status
  262. switch( status )
  263. {
  264. // handle sys-ex msg
  265. case kSysExMdId:
  266. rc = _cmMidiFileReadSysEx(mfp,tmp,cmInvalidCnt);
  267. break;
  268. // handle meta msg
  269. case kMetaStId:
  270. rc = _cmMidiFileReadMetaMsg(mfp,tmp);
  271. // ignore unknown meta messages
  272. if( rc == kUnknownMetaIdMfRC )
  273. rc = kOkMfRC;
  274. contFl = tmp->metaId != kEndOfTrkMdId;
  275. break;
  276. default:
  277. // handle channel msg
  278. rc = _cmMidiFileReadChannelMsg(mfp,&runstatus,status,tmp);
  279. }
  280. }
  281. return rc;
  282. }
  283. cmMfRC_t _cmMidiFileReadHdr( _cmMidiFile_t* mfp )
  284. {
  285. cmMfRC_t rc;
  286. unsigned fileId;
  287. unsigned chunkByteN;
  288. // read the file id
  289. if((rc = _cmMidiFileRead32(mfp,&fileId)) != kOkMfRC )
  290. return rc;
  291. // verify the file id
  292. if( fileId != 'MThd' )
  293. return cmErrMsg(&mfp->err,kNotAMidiFileMfRC,"");
  294. // read the file chunk byte count
  295. if((rc = _cmMidiFileRead32(mfp,&chunkByteN)) != kOkMfRC )
  296. return rc;
  297. // read the format id
  298. if((rc = _cmMidiFileRead16(mfp,&mfp->fmtId)) != kOkMfRC )
  299. return rc;
  300. // read the track count
  301. if((rc = _cmMidiFileRead16(mfp,&mfp->trkN)) != kOkMfRC )
  302. return rc;
  303. // read the ticks per quarter note
  304. if((rc = _cmMidiFileRead16(mfp,&mfp->ticksPerQN)) != kOkMfRC )
  305. return rc;
  306. // if the division field was given in smpte
  307. if( mfp->ticksPerQN & 0x8000 )
  308. {
  309. mfp->smpteFmtId = (mfp->ticksPerQN & 0x7f00) >> 8;
  310. mfp->smpteTicksPerFrame = (mfp->ticksPerQN & 0xFF);
  311. mfp->ticksPerQN = 0;
  312. }
  313. // allocate and zero the track array
  314. if( mfp->trkN )
  315. mfp->trkV = _cmMidiFileMalloc( mfp, sizeof(_cmMidiTrack_t)*mfp->trkN);
  316. return rc;
  317. }
  318. int _cmMidiFileSortFunc( const void *p0, const void* p1 )
  319. {
  320. if( (*(cmMidiTrackMsg_t**)p0)->atick == (*(cmMidiTrackMsg_t**)p1)->atick )
  321. return 0;
  322. return (*(cmMidiTrackMsg_t**)p0)->atick < (*(cmMidiTrackMsg_t**)p1)->atick ? -1 : 1;
  323. }
  324. cmMfRC_t _cmMidiFileClose( _cmMidiFile_t* mfp )
  325. {
  326. cmMfRC_t rc = kOkMfRC;
  327. if( mfp == NULL )
  328. return rc;
  329. cmMemPtrFree(&mfp->msgV);
  330. if( cmFileIsValid( mfp->fh ) )
  331. if( cmFileClose( &mfp->fh ) != kOkFileRC )
  332. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file close failed.");
  333. if( cmLHeapIsValid( mfp->lhH ) )
  334. cmLHeapDestroy(&mfp->lhH);
  335. cmMemPtrFree(&mfp);
  336. return rc;
  337. }
  338. cmMfRC_t cmMidiFileOpen( cmCtx_t* ctx, cmMidiFileH_t* hPtr, const char* fn )
  339. {
  340. cmMfRC_t rc = kOkMfRC;
  341. _cmMidiFile_t* mfp = NULL;
  342. unsigned short trkIdx = 0;
  343. cmErr_t err;
  344. if( cmMidiFileIsValid(*hPtr) )
  345. if((rc = _cmMidiFileClose(_cmMidiFileHandleToPtr(*hPtr))) != kOkMfRC )
  346. return rc;
  347. cmErrSetup(&err,&ctx->rpt,"MIDI File");
  348. // allocate the midi file object
  349. if(( mfp = cmMemAllocZ( _cmMidiFile_t, 1)) == NULL )
  350. return rc = cmErrMsg(&err,kMemAllocFailMfRC,"MIDI file memory allocation failed.");
  351. cmErrClone(&mfp->err,&err);
  352. // allocate the linked heap
  353. if( cmLHeapIsValid( mfp->lhH = cmLHeapCreate( 1024, ctx )) == false )
  354. {
  355. rc = cmErrMsg(&err,kMemAllocFailMfRC,"MIDI heap allocation failed.");
  356. goto errLabel;
  357. }
  358. // open the file
  359. if(cmFileOpen(&mfp->fh,fn,kReadFileFl | kBinaryFileFl,mfp->err.rpt) != kOkFileRC )
  360. {
  361. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file open failed.");
  362. goto errLabel;
  363. }
  364. // read header and setup track array
  365. if(( rc = _cmMidiFileReadHdr(mfp)) != kOkMfRC )
  366. goto errLabel;
  367. while( !cmFileEof(mfp->fh) && trkIdx < mfp->trkN )
  368. {
  369. unsigned chkId=0,chkN=0;
  370. // read the chunk id
  371. if((rc = _cmMidiFileRead32(mfp,&chkId)) != kOkMfRC )
  372. goto errLabel;
  373. // read the chunk size
  374. if((rc = _cmMidiFileRead32(mfp,&chkN)) != kOkMfRC )
  375. goto errLabel;
  376. // if this is not a trk chunk then skip it
  377. if( chkId != (unsigned)'MTrk')
  378. {
  379. //if( fseek( mfp->fp, chkN, SEEK_CUR) != 0 )
  380. if( cmFileSeek(mfp->fh,kCurFileFl,chkN) != kOkFileRC )
  381. {
  382. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file seek failed.");
  383. goto errLabel;
  384. }
  385. }
  386. else
  387. {
  388. if((rc = _cmMidiFileReadTrack(mfp,trkIdx)) != kOkMfRC )
  389. goto errLabel;
  390. ++trkIdx;
  391. }
  392. }
  393. // get the total trk msg count
  394. mfp->msgN = 0;
  395. for(trkIdx=0; trkIdx<mfp->trkN; ++trkIdx)
  396. mfp->msgN += mfp->trkV[ trkIdx ].cnt;
  397. // allocate the trk msg index vector: msgV[]
  398. mfp->msgV = cmMemAllocZ(cmMidiTrackMsg_t*, mfp->msgN);
  399. // store a pointer to every trk msg in msgV[]
  400. // and convert tick to absolute tick
  401. mfp->nextUid = 0;
  402. double microsPerQN = 60000000/120; // default tempo;
  403. double microsPerTick;
  404. unsigned i = 0;
  405. for(trkIdx=0; trkIdx<mfp->trkN; ++trkIdx)
  406. {
  407. unsigned tick = 0;
  408. cmMidiTrackMsg_t* tmp = mfp->trkV[ trkIdx ].base;
  409. microsPerTick = microsPerQN / mfp->ticksPerQN;
  410. while( tmp != NULL )
  411. {
  412. assert( i < mfp->msgN);
  413. tick += tmp->dtick; // convert delta-ticks to absolute ticks
  414. tmp->atick = tick;
  415. tmp->uid = mfp->nextUid++; // assign the msg uid
  416. mfp->msgV[i] = tmp;
  417. // track tempo changes
  418. if( tmp->status == kMetaStId && tmp->metaId == kTempoMdId )
  419. microsPerTick = tmp->u.iVal / mfp->ticksPerQN;
  420. // convert dtick to microseconds
  421. tmp->dmicro = round(tmp->dtick * microsPerTick);
  422. tmp = tmp->link;
  423. ++i;
  424. }
  425. }
  426. // sort msgV[] in ascending order on atick
  427. qsort( mfp->msgV, mfp->msgN, sizeof(cmMidiTrackMsg_t*), _cmMidiFileSortFunc );
  428. // set the amicro field of each midi message to the
  429. // absolute time offset in microseconds
  430. unsigned mi;
  431. unsigned amicro = 0;
  432. microsPerTick = microsPerQN / mfp->ticksPerQN;
  433. for(mi=0; mi<mfp->msgN; ++mi)
  434. {
  435. cmMidiTrackMsg_t* mp = mfp->msgV[mi];
  436. // track tempo changes
  437. if( mp->status == kMetaStId && mp->metaId == kTempoMdId )
  438. microsPerTick = mp->u.iVal / mfp->ticksPerQN;
  439. unsigned dtick = 0;
  440. if( mi > 0 )
  441. {
  442. assert( mp->atick >= mfp->msgV[mi-1]->atick );
  443. dtick = mp->atick - mfp->msgV[mi-1]->atick;
  444. }
  445. amicro += round(microsPerTick*dtick);
  446. mp->amicro = amicro;
  447. }
  448. //for(i=0; i<25; ++i)
  449. // printf("%i 0x%x 0x%x\n",mfp->msgV[i]->tick,mfp->msgV[i]->status,mfp->msgV[i]->metaId);
  450. mfp->fn = _cmMidiFileMalloc(mfp,strlen(fn)+1);
  451. assert( mfp->fn != NULL );
  452. strcpy(mfp->fn,fn);
  453. hPtr->h = mfp;
  454. errLabel:
  455. if( cmFileClose(&mfp->fh) != kOkFileRC )
  456. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file close failed.");
  457. if( rc != kOkMfRC )
  458. _cmMidiFileClose(mfp);
  459. return rc;
  460. }
  461. cmMfRC_t cmMidiFileClose( cmMidiFileH_t* h )
  462. {
  463. cmMfRC_t rc;
  464. if( cmMidiFileIsNull(*h) )
  465. return kOkMfRC;
  466. if((rc = _cmMidiFileClose(_cmMidiFileHandleToPtr(*h))) == kOkMfRC )
  467. return rc;
  468. h->h = NULL;
  469. return rc;
  470. }
  471. cmMfRC_t _cmMidiFileWrite8( _cmMidiFile_t* mfp, unsigned char v )
  472. {
  473. cmMfRC_t rc = kOkMfRC;
  474. if( cmFileWriteUChar(mfp->fh,&v,1) != kOkFileRC )
  475. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file byte write failed.");
  476. return rc;
  477. }
  478. cmMfRC_t _cmMidiFileWrite16( _cmMidiFile_t* mfp, unsigned short v )
  479. {
  480. cmMfRC_t rc = kOkMfRC;
  481. v = mfSwap16(v);
  482. if( cmFileWriteUShort(mfp->fh,&v,1) != kOkFileRC )
  483. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file short integer write failed.");
  484. return rc;
  485. }
  486. cmMfRC_t _cmMidiFileWrite24( _cmMidiFile_t* mfp, unsigned v )
  487. {
  488. cmMfRC_t rc = kOkMfRC;
  489. unsigned mask = 0xff0000;
  490. int i;
  491. for(i=2; i>=0; --i)
  492. {
  493. unsigned char c = (v & mask) >> (i*8);
  494. mask >>= 8;
  495. if( cmFileWriteUChar(mfp->fh,&c,1) != kOkFileRC )
  496. {
  497. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file 24 bit integer write failed.");
  498. goto errLabel;
  499. }
  500. }
  501. errLabel:
  502. return rc;
  503. }
  504. cmMfRC_t _cmMidiFileWrite32( _cmMidiFile_t* mfp, unsigned v )
  505. {
  506. cmMfRC_t rc = kOkMfRC;
  507. v = mfSwap32(v);
  508. if( cmFileWriteUInt(mfp->fh,&v,1) != kOkFileRC )
  509. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file integer write failed.");
  510. return rc;
  511. }
  512. cmMfRC_t _cmMidiFileWriteRecd( _cmMidiFile_t* mfp, const void* v, unsigned byteCnt )
  513. {
  514. cmMfRC_t rc = kOkMfRC;
  515. if( cmFileWriteChar(mfp->fh,v,byteCnt) != kOkFileRC )
  516. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file write record failed.");
  517. return rc;
  518. }
  519. cmMfRC_t _cmMidiFileWriteVarLen( _cmMidiFile_t* mfp, unsigned v )
  520. {
  521. cmMfRC_t rc = kOkMfRC;
  522. unsigned buf = v & 0x7f;
  523. while((v >>= 7) > 0 )
  524. {
  525. buf <<= 8;
  526. buf |= 0x80;
  527. buf += (v & 0x7f);
  528. }
  529. while(1)
  530. {
  531. unsigned char c = (unsigned char)(buf & 0xff);
  532. if( cmFileWriteUChar(mfp->fh,&c,1) != kOkFileRC )
  533. {
  534. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file variable length integer write failed.");
  535. goto errLabel;
  536. }
  537. if( buf & 0x80 )
  538. buf >>= 8;
  539. else
  540. break;
  541. }
  542. errLabel:
  543. return rc;
  544. }
  545. cmMfRC_t _cmMidiFileWriteHdr( _cmMidiFile_t* mfp )
  546. {
  547. cmMfRC_t rc;
  548. unsigned fileId = 'MThd';
  549. unsigned chunkByteN = 6;
  550. // write the file id ('MThd')
  551. if((rc = _cmMidiFileWrite32(mfp,fileId)) != kOkMfRC )
  552. return rc;
  553. // write the file chunk byte count (always 6)
  554. if((rc = _cmMidiFileWrite32(mfp,chunkByteN)) != kOkMfRC )
  555. return rc;
  556. // write the MIDI file format id (0,1,2)
  557. if((rc = _cmMidiFileWrite16(mfp,mfp->fmtId)) != kOkMfRC )
  558. return rc;
  559. // write the track count
  560. if((rc = _cmMidiFileWrite16(mfp,mfp->trkN)) != kOkMfRC )
  561. return rc;
  562. unsigned short v = 0;
  563. // if the ticks per quarter note field is valid ...
  564. if( mfp->ticksPerQN )
  565. v = mfp->ticksPerQN;
  566. else
  567. {
  568. // ... otherwise the division field was given in smpte
  569. v = mfp->smpteFmtId << 8;
  570. v += mfp->smpteTicksPerFrame;
  571. }
  572. if((rc = _cmMidiFileWrite16(mfp,v)) != kOkMfRC )
  573. return rc;
  574. return rc;
  575. }
  576. cmMfRC_t _cmMidiFileWriteSysEx( _cmMidiFile_t* mfp, cmMidiTrackMsg_t* tmp )
  577. {
  578. cmMfRC_t rc = kOkMfRC;
  579. if((rc = _cmMidiFileWrite8(mfp,kSysExMdId)) != kOkMfRC )
  580. goto errLabel;
  581. if( cmFileWriteUChar(mfp->fh,tmp->u.sysExPtr,tmp->byteCnt) != kOkFileRC )
  582. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"Sys-ex msg write failed.");
  583. errLabel:
  584. return rc;
  585. }
  586. cmMfRC_t _cmMidiFileWriteChannelMsg( _cmMidiFile_t* mfp, const cmMidiTrackMsg_t* tmp, cmMidiByte_t* runStatus )
  587. {
  588. cmMfRC_t rc = kOkMfRC;
  589. unsigned byteN = cmMidiStatusToByteCount(tmp->status);
  590. cmMidiByte_t status = tmp->status + tmp->u.chMsgPtr->ch;
  591. if( status != *runStatus )
  592. {
  593. *runStatus = status;
  594. if((rc = _cmMidiFileWrite8(mfp,status)) != kOkMfRC )
  595. goto errLabel;
  596. }
  597. if(byteN>=1)
  598. if((rc = _cmMidiFileWrite8(mfp,tmp->u.chMsgPtr->d0)) != kOkMfRC )
  599. goto errLabel;
  600. if(byteN>=2)
  601. if((rc = _cmMidiFileWrite8(mfp,tmp->u.chMsgPtr->d1)) != kOkMfRC )
  602. goto errLabel;
  603. errLabel:
  604. return rc;
  605. }
  606. cmMfRC_t _cmMidiFileWriteMetaMsg( _cmMidiFile_t* mfp, const cmMidiTrackMsg_t* tmp )
  607. {
  608. cmMfRC_t rc;
  609. if((rc = _cmMidiFileWrite8(mfp,kMetaStId)) != kOkMfRC )
  610. return rc;
  611. if((rc = _cmMidiFileWrite8(mfp,tmp->metaId)) != kOkMfRC )
  612. return rc;
  613. switch( tmp->metaId )
  614. {
  615. case kSeqNumbMdId:
  616. if((rc = _cmMidiFileWrite8(mfp,sizeof(tmp->u.sVal))) == kOkMfRC )
  617. rc = _cmMidiFileWrite16(mfp,tmp->u.sVal);
  618. break;
  619. case kTempoMdId:
  620. if((rc = _cmMidiFileWrite8(mfp,3)) == kOkMfRC )
  621. rc = _cmMidiFileWrite24(mfp,tmp->u.iVal);
  622. break;
  623. case kSmpteMdId:
  624. if((rc = _cmMidiFileWrite8(mfp,sizeof(cmMidiSmpte_t))) == kOkMfRC )
  625. rc = _cmMidiFileWriteRecd(mfp,tmp->u.smptePtr,sizeof(cmMidiSmpte_t));
  626. break;
  627. case kTimeSigMdId:
  628. if((rc = _cmMidiFileWrite8(mfp,sizeof(cmMidiTimeSig_t))) == kOkMfRC )
  629. rc = _cmMidiFileWriteRecd(mfp,tmp->u.timeSigPtr,sizeof(cmMidiTimeSig_t));
  630. break;
  631. case kKeySigMdId:
  632. if((rc = _cmMidiFileWrite8(mfp,sizeof(cmMidiKeySig_t))) == kOkMfRC )
  633. rc = _cmMidiFileWriteRecd(mfp,tmp->u.keySigPtr,sizeof(cmMidiKeySig_t));
  634. break;
  635. case kSeqSpecMdId:
  636. if((rc = _cmMidiFileWriteVarLen(mfp,sizeof(tmp->byteCnt))) == kOkMfRC )
  637. rc = _cmMidiFileWriteRecd(mfp,tmp->u.sysExPtr,tmp->byteCnt);
  638. break;
  639. case kMidiChMdId:
  640. if((rc = _cmMidiFileWrite8(mfp,sizeof(tmp->u.bVal))) == kOkMfRC )
  641. rc = _cmMidiFileWrite8(mfp,tmp->u.bVal);
  642. break;
  643. case kEndOfTrkMdId:
  644. rc = _cmMidiFileWrite8(mfp,0);
  645. break;
  646. case kTextMdId:
  647. case kCopyMdId:
  648. case kTrkNameMdId:
  649. case kInstrNameMdId:
  650. case kLyricsMdId:
  651. case kMarkerMdId:
  652. case kCuePointMdId:
  653. {
  654. unsigned n = tmp->u.text==NULL ? 0 : strlen(tmp->u.text);
  655. if((rc = _cmMidiFileWriteVarLen(mfp,n)) == kOkMfRC && n>0 )
  656. rc = _cmMidiFileWriteRecd(mfp,tmp->u.text,n);
  657. }
  658. break;
  659. default:
  660. {
  661. // ignore unknown meta messages
  662. }
  663. }
  664. return rc;
  665. }
  666. cmMfRC_t _cmMidiFileWriteTrack( _cmMidiFile_t* mfp, unsigned trkIdx )
  667. {
  668. cmMfRC_t rc = kOkMfRC;
  669. cmMidiTrackMsg_t* tmp = mfp->trkV[trkIdx].base;
  670. cmMidiByte_t runStatus = 0;
  671. for(; tmp!=NULL; tmp=tmp->link)
  672. {
  673. // write the msg tick count
  674. if((rc = _cmMidiFileWriteVarLen(mfp,tmp->dtick)) != kOkMfRC )
  675. return rc;
  676. // switch on status
  677. switch( tmp->status )
  678. {
  679. // handle sys-ex msg
  680. case kSysExMdId:
  681. rc = _cmMidiFileWriteSysEx(mfp,tmp);
  682. break;
  683. // handle meta msg
  684. case kMetaStId:
  685. rc = _cmMidiFileWriteMetaMsg(mfp,tmp);
  686. break;
  687. default:
  688. // handle channel msg
  689. rc = _cmMidiFileWriteChannelMsg(mfp,tmp,&runStatus);
  690. }
  691. }
  692. return rc;
  693. }
  694. cmMfRC_t cmMidiFileWrite( cmMidiFileH_t h, const char* fn )
  695. {
  696. cmMfRC_t rc = kOkMfRC;
  697. _cmMidiFile_t* mfp = _cmMidiFileHandleToPtr(h);
  698. unsigned i;
  699. // create the output file
  700. if( cmFileOpen(&mfp->fh,fn,kWriteFileFl,mfp->err.rpt) != kOkFileRC )
  701. return cmErrMsg(&mfp->err,kFileFailMfRC,"The MIDI file '%s' could not be created.",cmStringNullGuard(fn));
  702. // write the file header
  703. if((rc = _cmMidiFileWriteHdr(mfp)) != kOkMfRC )
  704. {
  705. rc = cmErrMsg(&mfp->err,rc,"The file header write failed on the MIDI file '%s'.",cmStringNullGuard(fn));
  706. goto errLabel;
  707. }
  708. for(i=0; i < mfp->trkN; ++i )
  709. {
  710. unsigned chkId='MTrk';
  711. long offs0,offs1;
  712. // write the track chunk id ('MTrk')
  713. if((rc = _cmMidiFileWrite32(mfp,chkId)) != kOkMfRC )
  714. goto errLabel;
  715. cmFileTell(mfp->fh,&offs0);
  716. // write the track chunk size as zero
  717. if((rc = _cmMidiFileWrite32(mfp,0)) != kOkMfRC )
  718. goto errLabel;
  719. if((rc = _cmMidiFileWriteTrack(mfp,i)) != kOkMfRC )
  720. goto errLabel;
  721. cmFileTell(mfp->fh,&offs1);
  722. cmFileSeek(mfp->fh,kBeginFileFl,offs0);
  723. _cmMidiFileWrite32(mfp,offs1-offs0-4);
  724. cmFileSeek(mfp->fh,kBeginFileFl,offs1);
  725. }
  726. errLabel:
  727. cmFileClose(&mfp->fh);
  728. return rc;
  729. }
  730. bool cmMidiFileIsValid( cmMidiFileH_t h )
  731. { return !cmMidiFileIsNull(h); }
  732. unsigned cmMidiFileTrackCount( cmMidiFileH_t h )
  733. {
  734. _cmMidiFile_t* mfp;
  735. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  736. return cmInvalidCnt;
  737. return mfp->trkN;
  738. }
  739. unsigned cmMidiFileType( cmMidiFileH_t h )
  740. {
  741. _cmMidiFile_t* mfp;
  742. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  743. return cmInvalidId;
  744. return mfp->fmtId;
  745. }
  746. const char* cmMidiFileName( cmMidiFileH_t h )
  747. {
  748. _cmMidiFile_t* mfp;
  749. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  750. return NULL;
  751. return mfp->fn;
  752. }
  753. unsigned cmMidiFileTicksPerQN( cmMidiFileH_t h )
  754. {
  755. _cmMidiFile_t* mfp;
  756. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  757. return cmInvalidCnt;
  758. return mfp->ticksPerQN;
  759. }
  760. cmMidiByte_t cmMidiFileTicksPerSmpteFrame( cmMidiFileH_t h )
  761. {
  762. _cmMidiFile_t* mfp;
  763. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  764. return kInvalidMidiByte;
  765. if( mfp->ticksPerQN != 0 )
  766. return 0;
  767. return mfp->smpteTicksPerFrame;
  768. }
  769. cmMidiByte_t cmMidiFileSmpteFormatId( cmMidiFileH_t h )
  770. {
  771. _cmMidiFile_t* mfp;
  772. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  773. return kInvalidMidiByte;
  774. if( mfp->ticksPerQN != 0 )
  775. return 0;
  776. return mfp->smpteFmtId;
  777. }
  778. unsigned cmMidiFileTrackMsgCount( cmMidiFileH_t h, unsigned trackIdx )
  779. {
  780. _cmMidiFile_t* mfp;
  781. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  782. return cmInvalidCnt;
  783. return mfp->trkV[trackIdx].cnt;
  784. }
  785. const cmMidiTrackMsg_t* cmMidiFileTrackMsg( cmMidiFileH_t h, unsigned trackIdx )
  786. {
  787. _cmMidiFile_t* mfp;
  788. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  789. return NULL;
  790. return mfp->trkV[trackIdx].base;
  791. }
  792. unsigned cmMidiFileMsgCount( cmMidiFileH_t h )
  793. {
  794. _cmMidiFile_t* mfp;
  795. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  796. return cmInvalidCnt;
  797. return mfp->msgN;
  798. }
  799. const cmMidiTrackMsg_t** cmMidiFileMsgArray( cmMidiFileH_t h )
  800. {
  801. _cmMidiFile_t* mfp;
  802. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  803. return NULL;
  804. // this cast is needed to eliminate an apparently needless 'incompatible type' warning
  805. return (const cmMidiTrackMsg_t**)mfp->msgV;
  806. }
  807. unsigned cmMidiFileSeekUsecs( cmMidiFileH_t h, unsigned offsUSecs, unsigned* msgUsecsPtr, unsigned* microsPerTickPtr )
  808. {
  809. _cmMidiFile_t* p;
  810. if((p = _cmMidiFileHandleToPtr(h)) == NULL )
  811. return cmInvalidIdx;
  812. if( p->msgN == 0 )
  813. return cmInvalidIdx;
  814. unsigned mi;
  815. double microsPerQN = 60000000.0/120.0;
  816. double microsPerTick = microsPerQN / p->ticksPerQN;
  817. double accUSecs = 0;
  818. for(mi=0; mi<p->msgN; ++mi)
  819. {
  820. const cmMidiTrackMsg_t* mp = p->msgV[mi];
  821. /*
  822. if( mp->status == kMetaStId && mp->metaId == kTempoMdId )
  823. microsPerTick = mp->u.iVal / p->ticksPerQN;
  824. unsigned dtick = 0;
  825. if( mi > 0 )
  826. {
  827. assert( mp->atick >= p->msgV[mi-1]->atick )
  828. dtick = mp->atick - p->msgV[mi-1]->atick;
  829. }
  830. accUSecs += dtick * microsPerTick ;
  831. if( accUSecs >= offsUSecs )
  832. break;
  833. */
  834. if( mp->amicro >= offsUSecs )
  835. break;
  836. }
  837. if( mi == p->msgN )
  838. return cmInvalidIdx;
  839. if( msgUsecsPtr != NULL )
  840. *msgUsecsPtr = round(accUSecs - offsUSecs);
  841. if( microsPerTickPtr != NULL )
  842. *microsPerTickPtr = round(microsPerTick);
  843. return mi;
  844. }
  845. double cmMidiFileDurSecs( cmMidiFileH_t h )
  846. {
  847. _cmMidiFile_t* mfp = _cmMidiFileHandleToPtr(h);
  848. if( mfp->msgN == 0 )
  849. return 0;
  850. return mfp->msgV[ mfp->msgN-1 ]->amicro / 1000000.0;
  851. }
  852. typedef struct _cmMidiVoice_str
  853. {
  854. const cmMidiTrackMsg_t* mp;
  855. unsigned durMicros;
  856. bool sustainFl;
  857. struct _cmMidiVoice_str* link;
  858. } _cmMidiVoice_t;
  859. void _cmMidFileCalcNoteDurationReleaseNote( _cmMidiVoice_t** listPtrPtr, _cmMidiVoice_t* pp, _cmMidiVoice_t* vp )
  860. {
  861. assert( (pp==NULL && vp==*listPtrPtr) || pp->link==vp);
  862. // store the duration of the note into the track msg
  863. // assoc'd with the note-on msg
  864. cmMidiChMsg_t* cmp = (cmMidiChMsg_t*)vp->mp->u.chMsgPtr; // cast away const
  865. cmp->durMicros = vp->durMicros;
  866. _cmMidiVoice_t* np = vp->link;
  867. // release the voice msg
  868. cmMemFree(vp);
  869. // unlink the active voice msg
  870. if( pp == NULL )
  871. *listPtrPtr = np;
  872. else
  873. pp->link = np;
  874. }
  875. void _cmMidiFileCalcNoteDurationsAllocVoice( _cmMidiVoice_t** listPtrPtr, cmMidiTrackMsg_t* mp, bool sustainFl )
  876. {
  877. _cmMidiVoice_t* vp = cmMemAllocZ(_cmMidiVoice_t,1);
  878. vp->mp = mp;
  879. vp->sustainFl = sustainFl;
  880. vp->link = *listPtrPtr;
  881. *listPtrPtr = vp;
  882. }
  883. void cmMidiFileCalcNoteDurations( cmMidiFileH_t h )
  884. {
  885. _cmMidiFile_t* p;
  886. if((p = _cmMidiFileHandleToPtr(h)) == NULL )
  887. return;
  888. if( p->msgN == 0 )
  889. return;
  890. unsigned mi = cmInvalidId;
  891. _cmMidiVoice_t* list = NULL; // list of active voices
  892. _cmMidiVoice_t* vp = NULL;
  893. cmMidiTrackMsg_t* sustainPedalDownMsg = NULL;
  894. bool sustainFlagV[ kMidiChCnt ];
  895. // clear the sustain pedal flag
  896. for(mi=0; mi<kMidiChCnt; ++mi)
  897. sustainFlagV[mi]=false;
  898. for(mi=0; mi<p->msgN; ++mi)
  899. {
  900. cmMidiTrackMsg_t* mp = p->msgV[mi];
  901. unsigned d_amicro = 0;
  902. if( mi > 0 )
  903. {
  904. assert( mp->amicro >= p->msgV[mi-1]->amicro );
  905. d_amicro = mp->amicro - p->msgV[mi-1]->amicro;
  906. }
  907. // update the duration of the sounding notes
  908. for(vp = list; vp!=NULL; vp=vp->link)
  909. vp->durMicros += d_amicro;
  910. // update the sustain pedal duration
  911. if( sustainPedalDownMsg != NULL )
  912. ((cmMidiChMsg_t*)(sustainPedalDownMsg->u.chMsgPtr))->durMicros += d_amicro; // cast away const
  913. //
  914. // If this is sustain pedal msg
  915. //
  916. if( mp->status==kCtlMdId && mp->u.chMsgPtr->d0 == kSustainCtlMdId )
  917. {
  918. unsigned chIdx = mp->u.chMsgPtr->ch;
  919. assert( chIdx < kMidiChCnt );
  920. // set the state of the sustain pedal flags
  921. sustainFlagV[chIdx] = mp->u.chMsgPtr->d1 >= 64;
  922. // if the pedal went down ...
  923. if( sustainFlagV[chIdx] )
  924. {
  925. if( sustainPedalDownMsg != NULL )
  926. {
  927. // TODO: the correct way to handle this is to maintain multiple sustain pedals
  928. cmErrMsg(&p->err,kSustainPedalMfRC,"Sustain pedal down with no intervening sustain pedal up.");
  929. }
  930. else
  931. {
  932. sustainPedalDownMsg = mp;
  933. ((cmMidiChMsg_t*)(sustainPedalDownMsg->u.chMsgPtr))->durMicros = 0; // cast away const
  934. }
  935. _cmMidiFileCalcNoteDurationsAllocVoice( &list, mp, true );
  936. }
  937. else // ... if the pedal went up
  938. {
  939. sustainPedalDownMsg = NULL;
  940. // ... then release sustaining notes
  941. _cmMidiVoice_t* pp = NULL;
  942. for(vp=list; vp != NULL; )
  943. {
  944. _cmMidiVoice_t* np = vp->link;
  945. if( vp->sustainFl && (vp->mp->u.chMsgPtr->ch == chIdx) )
  946. _cmMidFileCalcNoteDurationReleaseNote(&list,pp,vp);
  947. else
  948. pp = vp;
  949. vp = np;
  950. }
  951. }
  952. }
  953. //
  954. // if this is a note-on msg
  955. //
  956. if( mp->status==kNoteOnMdId && mp->u.chMsgPtr->d1>0 )
  957. {
  958. _cmMidiFileCalcNoteDurationsAllocVoice( &list, mp, false );
  959. }
  960. else
  961. //
  962. // if this is a note-off msg
  963. //
  964. if( (mp->status==kNoteOnMdId && mp->u.chMsgPtr->d1==0) || (mp->status==kNoteOffMdId) )
  965. {
  966. _cmMidiVoice_t* pp = NULL;
  967. unsigned chIdx = mp->u.chMsgPtr->ch;
  968. assert( chIdx < kMidiChCnt );
  969. // for each active voice
  970. for(vp=list; vp!=NULL; vp=vp->link )
  971. {
  972. // if this active voice ch/pitch matches the note-off msg ch pitch
  973. if( (vp->mp->u.chMsgPtr->d0==mp->u.chMsgPtr->d0) && (vp->mp->u.chMsgPtr->ch==chIdx) )
  974. {
  975. // if the sustain pedal is down for this channel - then defer turning the note off
  976. if( sustainFlagV[chIdx] )
  977. vp->sustainFl = true;
  978. else
  979. _cmMidFileCalcNoteDurationReleaseNote(&list,pp,vp);
  980. break;
  981. }
  982. pp = vp;
  983. } // end for
  984. } // end if
  985. } // end-for
  986. // check for hung notes
  987. _cmMidiVoice_t* np = NULL;
  988. vp = list;
  989. while( vp != NULL )
  990. {
  991. np = vp->link;
  992. if( cmMidiIsNoteOn(vp->mp->status) == false )
  993. cmErrMsg(&p->err,kMissingNoteOffMfRC,"Missing note-off for note-on:%s",cmMidiToSciPitch(vp->mp->u.chMsgPtr->d0,NULL,0));
  994. cmMemFree(vp);
  995. vp = np;
  996. }
  997. }
  998. void cmMidiFileSetDelay( cmMidiFileH_t h, unsigned ticks )
  999. {
  1000. _cmMidiFile_t* p;
  1001. unsigned mi;
  1002. if((p = _cmMidiFileHandleToPtr(h)) == NULL )
  1003. return;
  1004. if( p->msgN == 0 )
  1005. return;
  1006. for(mi=0; mi<p->msgN; ++mi)
  1007. {
  1008. cmMidiTrackMsg_t* mp = p->msgV[mi];
  1009. // locate the first msg which has a non-zero delta tick
  1010. if( mp->dtick > 0 )
  1011. {
  1012. mp->dtick = ticks;
  1013. break;
  1014. }
  1015. }
  1016. }
  1017. unsigned cmMidiFilePackTrackMsgBufByteCount( const cmMidiTrackMsg_t* m )
  1018. { return sizeof(cmMidiTrackMsg_t) + m->byteCnt; }
  1019. cmMidiTrackMsg_t* cmMidiFilePackTrackMsg( const cmMidiTrackMsg_t* m, void* buf, unsigned bufByteCnt )
  1020. {
  1021. unsigned n = sizeof(cmMidiTrackMsg_t) + m->byteCnt;
  1022. if( n < bufByteCnt )
  1023. {
  1024. assert(0);
  1025. return NULL;
  1026. }
  1027. // copy the cmMidiTrackMsg_t into the buffer
  1028. memcpy(buf, m, sizeof(cmMidiTrackMsg_t));
  1029. if( m->byteCnt > 0 )
  1030. {
  1031. // copy any linked data into the buffer
  1032. memcpy(buf + sizeof(cmMidiTrackMsg_t), m->u.voidPtr, m->byteCnt );
  1033. // fixup the linked data ptr
  1034. cmMidiTrackMsg_t* mp = (cmMidiTrackMsg_t*)buf;
  1035. mp->u.voidPtr = buf + sizeof(cmMidiTrackMsg_t);
  1036. }
  1037. return (cmMidiTrackMsg_t*)buf;
  1038. }
  1039. void _cmMidiFilePrintHdr( const _cmMidiFile_t* mfp, cmRpt_t* rpt )
  1040. {
  1041. if( mfp->fn != NULL )
  1042. cmRptPrintf(rpt,"%s ",mfp->fn);
  1043. cmRptPrintf(rpt,"fmt:%i ticksPerQN:%i tracks:%i\n",mfp->fmtId,mfp->ticksPerQN,mfp->trkN);
  1044. }
  1045. void _cmMidiFilePrintMsg( cmRpt_t* rpt, const cmMidiTrackMsg_t* tmp )
  1046. {
  1047. cmRptPrintf(rpt,"%5i %8i %8i %8i %8i : ",
  1048. tmp->uid,
  1049. tmp->dtick,
  1050. tmp->dmicro,
  1051. tmp->atick,
  1052. tmp->amicro );
  1053. if( tmp->status == kMetaStId )
  1054. {
  1055. cmRptPrintf(rpt,"%s ", cmMidiMetaStatusToLabel(tmp->metaId));
  1056. }
  1057. else
  1058. {
  1059. cmRptPrintf(rpt,"%4s %3i %3i %3i",
  1060. cmMidiStatusToLabel(tmp->status),
  1061. tmp->u.chMsgPtr->ch,
  1062. tmp->u.chMsgPtr->d0,
  1063. tmp->u.chMsgPtr->d1);
  1064. }
  1065. if( cmMidiIsChStatus(tmp->status) && cmMidiIsNoteOn(tmp->status) && (tmp->u.chMsgPtr->d1>0) )
  1066. cmRptPrintf(rpt," %4s ",cmMidiToSciPitch(tmp->u.chMsgPtr->d0,NULL,0));
  1067. cmRptPrintf(rpt,"\n");
  1068. }
  1069. void cmMidiFilePrintMsgs( cmMidiFileH_t h, cmRpt_t* rpt )
  1070. {
  1071. const _cmMidiFile_t* p = _cmMidiFileHandleToPtr(h);
  1072. unsigned mi;
  1073. _cmMidiFilePrintHdr(p,rpt);
  1074. for(mi=0; mi<p->msgN; ++mi)
  1075. {
  1076. cmMidiTrackMsg_t* mp = p->msgV[mi];
  1077. if( mp != NULL )
  1078. _cmMidiFilePrintMsg(rpt,mp);
  1079. }
  1080. }
  1081. void cmMidiFilePrintTracks( cmMidiFileH_t h, unsigned trkIdx, cmRpt_t* rpt )
  1082. {
  1083. const _cmMidiFile_t* mfp = _cmMidiFileHandleToPtr(h);
  1084. _cmMidiFilePrintHdr(mfp,rpt);
  1085. int i = trkIdx == cmInvalidIdx ? 0 : trkIdx;
  1086. int n = trkIdx == cmInvalidIdx ? mfp->trkN : trkIdx+1;
  1087. for(; i<n; ++i)
  1088. {
  1089. cmRptPrintf(rpt,"Track:%i\n",i);
  1090. cmMidiTrackMsg_t* tmp = mfp->trkV[i].base;
  1091. while( tmp != NULL )
  1092. {
  1093. _cmMidiFilePrintMsg(rpt,tmp);
  1094. tmp = tmp->link;
  1095. }
  1096. }
  1097. }
  1098. bool cmMidiFileIsNull( cmMidiFileH_t h )
  1099. { return (_cmMidiFile_t*)h.h == NULL; }
  1100. void cmMidiFileTestPrint( void* printDataPtr, const char* fmt, va_list vl )
  1101. { vprintf(fmt,vl); }
  1102. void cmMidiFilePrintControlNumbers( cmCtx_t* ctx, const char* fn )
  1103. {
  1104. cmMidiFileH_t h = cmMidiFileNullHandle;
  1105. cmMfRC_t rc;
  1106. if((rc = cmMidiFileOpen(ctx, &h, fn )) != kOkMfRC )
  1107. {
  1108. cmErrMsg(&ctx->err,rc,"MIDI file open failed on '%s'.",fn);
  1109. goto errLabel;
  1110. }
  1111. const cmMidiTrackMsg_t** mm;
  1112. unsigned n = cmMidiFileMsgCount(h);
  1113. if((mm = cmMidiFileMsgArray(h)) != NULL )
  1114. {
  1115. unsigned j;
  1116. for(j=0; j<n; ++j)
  1117. {
  1118. const cmMidiTrackMsg_t* m = mm[j];
  1119. if( m->status == kCtlMdId && m->u.chMsgPtr->d0==66 )
  1120. printf("%i %i\n",m->u.chMsgPtr->d0,m->u.chMsgPtr->d1);
  1121. }
  1122. }
  1123. errLabel:
  1124. cmMidiFileClose(&h);
  1125. }
  1126. void cmMidiFileTest( const char* fn, cmCtx_t* ctx )
  1127. {
  1128. cmMfRC_t rc;
  1129. cmMidiFileH_t h = cmMidiFileNullHandle;
  1130. if((rc = cmMidiFileOpen(ctx,&h,fn)) != kOkMfRC )
  1131. {
  1132. printf("Error:%i Unable to open the cmMidi file: %s\n",rc,fn);
  1133. return;
  1134. }
  1135. if( 1 )
  1136. {
  1137. //cmMidiFileTickToMicros( h );
  1138. //cmMidiFileTickToSamples(h,96000,false);
  1139. cmMidiFilePrintMsgs(h,&ctx->rpt);
  1140. }
  1141. if( 0 )
  1142. {
  1143. //cmMidiFilePrint(h,cmMidiFileTrackCount(h)-1,&ctx->rpt);
  1144. //cmMidiFilePrint(h,cmInvalidIdx,&ctx->rpt);
  1145. cmMidiFilePrintControlNumbers(ctx, fn );
  1146. }
  1147. if( 0 )
  1148. {
  1149. printf("Tracks:%i\n",cmMidiFileTrackCount(h));
  1150. unsigned i = 0;
  1151. for(i=0; i<cmMidiFileMsgCount(h); ++i)
  1152. {
  1153. cmMidiTrackMsg_t* tmp = (cmMidiTrackMsg_t*)cmMidiFileMsgArray(h)[i];
  1154. if( tmp->status==kMetaStId && tmp->metaId == kTempoMdId )
  1155. {
  1156. double bpm = 60000000.0/tmp->u.iVal;
  1157. printf("Tempo:%i %f\n",tmp->u.iVal,bpm);
  1158. tmp->u.iVal = floor( 60000000.0/69.0 );
  1159. break;
  1160. }
  1161. }
  1162. cmMidiFileWrite(h,"/home/kevin/temp/test0.mid");
  1163. }
  1164. cmMidiFileClose(&h);
  1165. }