libcm is a C development framework with an emphasis on audio signal processing applications.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

cmMidiFile.c 25KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036
  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 "cmMidi.h"
  11. #include "cmMidiFile.h"
  12. #ifdef cmBIG_ENDIAN
  13. #define mfSwap16(v) (v)
  14. #define mfSwap32(v) (v)
  15. #else
  16. #define mfSwap16(v) cmSwap16(v)
  17. #define mfSwap32(v) cmSwap32(v)
  18. #endif
  19. typedef struct
  20. {
  21. unsigned cnt; // count of track records
  22. cmMidiTrackMsg_t* base; // pointer to first track recd
  23. cmMidiTrackMsg_t* last; // pointer to last track recd
  24. } _cmMidiTrack_t;
  25. typedef struct
  26. {
  27. cmErr_t err; // this objects error object
  28. cmLHeapH_t lhH; // linked heap used for all dynamically alloc'd data space
  29. cmFileH_t fh; // cmFile handle (only used in fmMidiFileOpen())
  30. unsigned short fmtId; // midi file type id: 0,1,2
  31. unsigned short ticksPerQN; // ticks per quarter note or 0 if smpteFmtId is valid
  32. cmMidiByte_t smpteFmtId; // smpte format or 0 if ticksPerQN is valid
  33. cmMidiByte_t smpteTicksPerFrame; // smpte ticks per frame or 0 if ticksPerQN is valid
  34. unsigned short trkN; // track count
  35. _cmMidiTrack_t* trkV; // track vector
  36. char* fn; // file name or NULL if this object did not originate from a file
  37. unsigned msgN; // count of msg's in msgV[]
  38. cmMidiTrackMsg_t** msgV; // sorted msg list
  39. } _cmMidiFile_t;
  40. #define _cmMidiFileError( err, rc ) _cmMidiFileOnError(err, rc, __LINE__,__FILE__,__FUNCTION__ )
  41. cmMidiFileH_t cmMidiFileNullHandle = cmSTATIC_NULL_HANDLE;
  42. cmMfRC_t _cmMidiFileOnError( cmErr_t* err, cmMfRC_t rc, int line, const char* fn, const char* func )
  43. {
  44. return cmErrMsg(err,rc,"rc:%i line:%i %s %s\n",rc,line,func,fn);
  45. }
  46. _cmMidiFile_t* _cmMidiFileHandleToPtr( cmMidiFileH_t h )
  47. {
  48. _cmMidiFile_t* p = (_cmMidiFile_t*)h.h;
  49. assert( p != NULL );
  50. return p;
  51. }
  52. void* _cmMidiFileMalloc( _cmMidiFile_t* mfp, unsigned byteN )
  53. { return cmLHeapAllocZ(mfp->lhH,byteN); }
  54. cmMfRC_t _cmMidiFileRead8( _cmMidiFile_t* mfp, cmMidiByte_t* p )
  55. {
  56. if( cmFileReadUChar(mfp->fh,p,1) != kOkFileRC )
  57. return _cmMidiFileError(&mfp->err,kSysFreadFailMfRC);
  58. return kOkMfRC;
  59. }
  60. cmMfRC_t _cmMidiFileRead16( _cmMidiFile_t* mfp, unsigned short* p )
  61. {
  62. if( cmFileReadUShort(mfp->fh,p,1) != kOkFileRC )
  63. return _cmMidiFileError(&mfp->err,kSysFreadFailMfRC);
  64. *p = mfSwap16(*p);
  65. return kOkMfRC;
  66. }
  67. cmMfRC_t _cmMidiFileRead24( _cmMidiFile_t* mfp, unsigned* p )
  68. {
  69. *p = 0;
  70. int i = 0;
  71. for(; i<3; ++i)
  72. {
  73. unsigned char c;
  74. if( cmFileReadUChar(mfp->fh,&c,1) != kOkFileRC )
  75. return _cmMidiFileError(&mfp->err,kSysFreadFailMfRC);
  76. *p = (*p << 8) + c;
  77. }
  78. //*p =mfSwap32(*p);
  79. return kOkMfRC;
  80. }
  81. cmMfRC_t _cmMidiFileRead32( _cmMidiFile_t* mfp, unsigned* p )
  82. {
  83. if( cmFileReadUInt(mfp->fh,p,1) != kOkFileRC )
  84. return _cmMidiFileError(&mfp->err,kSysFreadFailMfRC);
  85. *p = mfSwap32(*p);
  86. return kOkMfRC;
  87. }
  88. cmMfRC_t _cmMidiFileReadText( _cmMidiFile_t* mfp, cmMidiTrackMsg_t* tmp, unsigned byteN )
  89. {
  90. if( byteN == 0 )
  91. return kOkMfRC;
  92. char* t = (char*)_cmMidiFileMalloc(mfp,byteN+1);
  93. t[byteN] = 0;
  94. if( cmFileReadChar(mfp->fh,t,byteN) != kOkFileRC )
  95. return _cmMidiFileError(&mfp->err,kSysFreadFailMfRC);
  96. tmp->u.text = t;
  97. tmp->byteCnt = byteN;
  98. return kOkMfRC;
  99. }
  100. cmMfRC_t _cmMidiFileReadRecd( _cmMidiFile_t* mfp, cmMidiTrackMsg_t* tmp, unsigned byteN )
  101. {
  102. char* t = (char*)_cmMidiFileMalloc(mfp,byteN);
  103. if( cmFileReadChar(mfp->fh,t,byteN) != kOkFileRC )
  104. return _cmMidiFileError(&mfp->err,kSysFreadFailMfRC);
  105. tmp->byteCnt = byteN;
  106. tmp->u.voidPtr = t;
  107. return kOkMfRC;
  108. }
  109. cmMfRC_t _cmMidiFileReadVarLen( _cmMidiFile_t* mfp, unsigned* p )
  110. {
  111. unsigned char c;
  112. if( cmFileReadUChar(mfp->fh,&c,1) != kOkFileRC )
  113. return _cmMidiFileError(&mfp->err,kSysFreadFailMfRC);
  114. if( !(c & 0x80) )
  115. *p = c;
  116. else
  117. {
  118. *p = c & 0x7f;
  119. do
  120. {
  121. if( cmFileReadUChar(mfp->fh,&c,1) != kOkFileRC )
  122. return _cmMidiFileError(&mfp->err,kSysFreadFailMfRC);
  123. *p = (*p << 7) + (c & 0x7f);
  124. }while( c & 0x80 );
  125. }
  126. return kOkMfRC;
  127. }
  128. cmMfRC_t _cmMidiFileAppendTrackMsg( _cmMidiFile_t* mfp, unsigned short trkIdx, unsigned dtick, cmMidiByte_t status, cmMidiTrackMsg_t** trkMsgPtrPtr )
  129. {
  130. cmMidiTrackMsg_t* tmp = (cmMidiTrackMsg_t*)_cmMidiFileMalloc(mfp, sizeof(cmMidiTrackMsg_t) );
  131. // link new record onto track record chain
  132. if( mfp->trkV[trkIdx].base == NULL )
  133. mfp->trkV[trkIdx].base = tmp;
  134. else
  135. mfp->trkV[trkIdx].last->link = tmp;
  136. mfp->trkV[trkIdx].last = tmp;
  137. mfp->trkV[trkIdx].cnt++;
  138. // set the generic track record fields
  139. tmp->dtick = dtick;
  140. tmp->status = status;
  141. tmp->metaId = kInvalidMetaMdId;
  142. tmp->trkIdx = trkIdx;
  143. tmp->byteCnt = 0;
  144. *trkMsgPtrPtr = tmp;
  145. return kOkMfRC;
  146. }
  147. cmMfRC_t _cmMidiFileReadSysEx( _cmMidiFile_t* mfp, cmMidiTrackMsg_t* tmp, unsigned byteN )
  148. {
  149. cmMfRC_t rc = kOkMfRC;
  150. cmMidiByte_t b = 0;
  151. if( byteN == cmInvalidCnt )
  152. {
  153. long offs;
  154. if( cmFileTell(mfp->fh,&offs) != kOkFileRC )
  155. return _cmMidiFileError(&mfp->err,kSysFtellFailMfRC);
  156. byteN = 0;
  157. // get the length of the sys-ex msg
  158. while( !cmFileEof(mfp->fh) && (b != kSysComEoxMdId) )
  159. {
  160. if((rc = _cmMidiFileRead8(mfp,&b)) != kOkMfRC )
  161. return rc;
  162. ++byteN;
  163. }
  164. // verify that the EOX byte was found
  165. if( b != kSysComEoxMdId )
  166. return _cmMidiFileError(&mfp->err,kMissingEoxMfRC);
  167. // rewind to the beginning of the msg
  168. if( cmFileSeek(mfp->fh,kBeginFileFl,offs) != kOkFileRC )
  169. return _cmMidiFileError(&mfp->err,kSysFseekFailMfRC);
  170. }
  171. // allocate memory to hold the sys-ex msg
  172. cmMidiByte_t* mp = (cmMidiByte_t *)_cmMidiFileMalloc(mfp, byteN );
  173. // read the sys-ex msg from the file into msg memory
  174. if( cmFileReadUChar(mfp->fh,mp,byteN) != kOkFileRC )
  175. return _cmMidiFileError(&mfp->err,kSysFreadFailMfRC);
  176. tmp->byteCnt = byteN;
  177. tmp->u.sysExPtr = mp;
  178. return rc;
  179. }
  180. cmMfRC_t _cmMidiFileReadChannelMsg( _cmMidiFile_t* mfp, cmMidiByte_t* rsPtr, cmMidiByte_t status, cmMidiTrackMsg_t* tmp )
  181. {
  182. cmMfRC_t rc = kOkMfRC;
  183. cmMidiChMsg_t* p = (cmMidiChMsg_t*)_cmMidiFileMalloc(mfp,sizeof(cmMidiChMsg_t));
  184. unsigned useRsFl = status <= 0x7f;
  185. cmMidiByte_t statusCh = useRsFl ? *rsPtr : status;
  186. if( useRsFl )
  187. p->d0 = status;
  188. else
  189. *rsPtr = status;
  190. tmp->byteCnt = sizeof(cmMidiChMsg_t);
  191. tmp->status = statusCh & 0xf0;
  192. p->ch = statusCh & 0x0f;
  193. p->durTicks = 0;
  194. unsigned byteN = cmMidiStatusToByteCount(tmp->status);
  195. if( byteN==kInvalidMidiByte || byteN > 2 )
  196. return cmErrMsg(&mfp->err,kInvalidStatusMfRC,"Invalid status:0x%x %i.",tmp->status,tmp->status);
  197. unsigned i;
  198. for(i=useRsFl; i<byteN; ++i)
  199. {
  200. cmMidiByte_t* b = i==0 ? &p->d0 : &p->d1;
  201. if((rc = _cmMidiFileRead8(mfp,b)) != kOkMfRC )
  202. return rc;
  203. }
  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. cmErrMsg(&mfp->err,kUnknownMetaIdMfRC,"Unknown meta status:0x%x %i.",metaId,metaId);
  237. rc = _cmMidiFileError(&mfp->err,kUnknownMetaIdMfRC);
  238. }
  239. tmp->metaId = metaId;
  240. return rc;
  241. }
  242. cmMfRC_t _cmMidiFileReadTrack( _cmMidiFile_t* mfp, unsigned short trkIdx )
  243. {
  244. cmMfRC_t rc = kOkMfRC;
  245. unsigned dticks = 0;
  246. cmMidiByte_t status;
  247. cmMidiByte_t runstatus = 0;
  248. bool contFl = true;
  249. while( contFl && (rc==kOkMfRC))
  250. {
  251. cmMidiTrackMsg_t* tmp = NULL;
  252. // read the tick count
  253. if((rc = _cmMidiFileReadVarLen(mfp,&dticks)) != kOkMfRC )
  254. return rc;
  255. // read the status byte
  256. if((rc = _cmMidiFileRead8(mfp,&status)) != kOkMfRC )
  257. return rc;
  258. //printf("st:%i 0x%x\n",status,status);
  259. // append a track msg
  260. if((rc = _cmMidiFileAppendTrackMsg( mfp, trkIdx, dticks, status, &tmp )) != kOkMfRC )
  261. return rc;
  262. // switch on status
  263. switch( status )
  264. {
  265. // handle sys-ex msg
  266. case kSysExMdId:
  267. rc = _cmMidiFileReadSysEx(mfp,tmp,cmInvalidCnt);
  268. break;
  269. // handle meta msg
  270. case kMetaStId:
  271. rc = _cmMidiFileReadMetaMsg(mfp,tmp);
  272. // ignore unknown meta messages
  273. if( rc == kUnknownMetaIdMfRC )
  274. rc = kOkMfRC;
  275. contFl = tmp->metaId != kEndOfTrkMdId;
  276. break;
  277. default:
  278. // handle channel msg
  279. rc = _cmMidiFileReadChannelMsg(mfp,&runstatus,status,tmp);
  280. }
  281. }
  282. return rc;
  283. }
  284. cmMfRC_t _cmMidiFileReadHdr( _cmMidiFile_t* mfp )
  285. {
  286. cmMfRC_t rc;
  287. unsigned fileId;
  288. unsigned chunkByteN;
  289. // read the file id
  290. if((rc = _cmMidiFileRead32(mfp,&fileId)) != kOkMfRC )
  291. return rc;
  292. // verify the file id
  293. if( fileId != 'MThd' )
  294. return _cmMidiFileError(&mfp->err,kNotAMidiFileMfRC);
  295. // read the file chunk byte count
  296. if((rc = _cmMidiFileRead32(mfp,&chunkByteN)) != kOkMfRC )
  297. return rc;
  298. // read the format id
  299. if((rc = _cmMidiFileRead16(mfp,&mfp->fmtId)) != kOkMfRC )
  300. return rc;
  301. // read the track count
  302. if((rc = _cmMidiFileRead16(mfp,&mfp->trkN)) != kOkMfRC )
  303. return rc;
  304. // read the ticks per quarter note
  305. if((rc = _cmMidiFileRead16(mfp,&mfp->ticksPerQN)) != kOkMfRC )
  306. return rc;
  307. // if the division field was given in smpte
  308. if( mfp->ticksPerQN & 0x8000 )
  309. {
  310. mfp->smpteFmtId = (mfp->ticksPerQN & 0x7f00) >> 8;
  311. mfp->smpteTicksPerFrame = (mfp->ticksPerQN & 0xFF);
  312. mfp->ticksPerQN = 0;
  313. }
  314. // allocate and zero the track array
  315. if( mfp->trkN )
  316. mfp->trkV = _cmMidiFileMalloc( mfp, sizeof(_cmMidiTrack_t)*mfp->trkN);
  317. return rc;
  318. }
  319. int _cmMidiFileSortFunc( const void *p0, const void* p1 )
  320. {
  321. //printf("%i %i\n",(*(cmMidiTrackMsg_t**)p0)->dticks,(*(cmMidiTrackMsg_t**)p1)->dticks);
  322. if( (*(cmMidiTrackMsg_t**)p0)->dtick == (*(cmMidiTrackMsg_t**)p1)->dtick )
  323. return 0;
  324. return (*(cmMidiTrackMsg_t**)p0)->dtick < (*(cmMidiTrackMsg_t**)p1)->dtick ? -1 : 1;
  325. }
  326. cmMfRC_t _cmMidiFileClose( _cmMidiFile_t* mfp )
  327. {
  328. cmMfRC_t rc = kOkMfRC;
  329. if( mfp == NULL )
  330. return rc;
  331. cmMemPtrFree(&mfp->msgV);
  332. if( cmFileIsValid( mfp->fh ) )
  333. if( cmFileClose( &mfp->fh ) != kOkFileRC )
  334. rc = _cmMidiFileError(&mfp->err,kSysFcloseFailMfRC);
  335. if( cmLHeapIsValid( mfp->lhH ) )
  336. cmLHeapDestroy(&mfp->lhH);
  337. cmMemPtrFree(&mfp);
  338. return rc;
  339. }
  340. cmMfRC_t cmMidiFileOpen( const char* fn, cmMidiFileH_t* hPtr, cmCtx_t* ctx )
  341. {
  342. cmMfRC_t rc = kOkMfRC;
  343. _cmMidiFile_t* mfp = NULL;
  344. unsigned short trkIdx = 0;
  345. cmErr_t err;
  346. cmErrSetup(&err,&ctx->rpt,"MIDI File");
  347. // allocate the midi file object
  348. if(( mfp = cmMemAllocZ( _cmMidiFile_t, 1)) == NULL )
  349. return rc = _cmMidiFileError(&err,kMemAllocFailMfRC);
  350. cmErrClone(&mfp->err,&err);
  351. // allocate the linked heap
  352. if( cmLHeapIsValid( mfp->lhH = cmLHeapCreate( 1024, ctx )) == false )
  353. {
  354. rc = _cmMidiFileError(&err,kMemAllocFailMfRC);
  355. goto errLabel;
  356. }
  357. // open the file
  358. if(cmFileOpen(&mfp->fh,fn,kReadFileFl | kBinaryFileFl,mfp->err.rpt) != kOkFileRC )
  359. {
  360. rc = _cmMidiFileError(&mfp->err,kSysFopenFailMfRC);
  361. goto errLabel;
  362. }
  363. // read header and setup track array
  364. if(( rc = _cmMidiFileReadHdr(mfp)) != kOkMfRC )
  365. goto errLabel;
  366. while( !cmFileEof(mfp->fh) && trkIdx < mfp->trkN )
  367. {
  368. unsigned chkId=0,chkN=0;
  369. // read the chunk id
  370. if((rc = _cmMidiFileRead32(mfp,&chkId)) != kOkMfRC )
  371. goto errLabel;
  372. // read the chunk size
  373. if((rc = _cmMidiFileRead32(mfp,&chkN)) != kOkMfRC )
  374. goto errLabel;
  375. // if this is not a trk chunk then skip it
  376. if( chkId != (unsigned)'MTrk')
  377. {
  378. //if( fseek( mfp->fp, chkN, SEEK_CUR) != 0 )
  379. if( cmFileSeek(mfp->fh,kCurFileFl,chkN) != kOkFileRC )
  380. {
  381. rc = _cmMidiFileError(&mfp->err,kSysFseekFailMfRC);
  382. goto errLabel;
  383. }
  384. }
  385. else
  386. {
  387. if((rc = _cmMidiFileReadTrack(mfp,trkIdx)) != kOkMfRC )
  388. goto errLabel;
  389. ++trkIdx;
  390. }
  391. }
  392. // get the total trk msg count
  393. mfp->msgN = 0;
  394. for(trkIdx=0; trkIdx<mfp->trkN; ++trkIdx)
  395. mfp->msgN += mfp->trkV[ trkIdx ].cnt;
  396. // allocate the trk msg index vector: msgV[]
  397. mfp->msgV = cmMemAllocZ(cmMidiTrackMsg_t*, mfp->msgN);
  398. // store a pointer to every trk msg in msgV[]
  399. // and convert tick to absolute tick
  400. unsigned i = 0;
  401. for(trkIdx=0; trkIdx<mfp->trkN; ++trkIdx)
  402. {
  403. unsigned tick = 0;
  404. cmMidiTrackMsg_t* tmp = mfp->trkV[ trkIdx ].base;
  405. while( tmp != NULL )
  406. {
  407. assert( i < mfp->msgN);
  408. tick += tmp->dtick; // convert delta-ticks to absolute ticks
  409. tmp->dtick = tick;
  410. mfp->msgV[i] = tmp;
  411. tmp = tmp->link;
  412. ++i;
  413. }
  414. }
  415. // sort msgV[] in ascending order on dtick
  416. qsort( mfp->msgV, mfp->msgN, sizeof(cmMidiTrackMsg_t*), _cmMidiFileSortFunc );
  417. //for(i=0; i<25; ++i)
  418. // printf("%i 0x%x 0x%x\n",mfp->msgV[i]->tick,mfp->msgV[i]->status,mfp->msgV[i]->metaId);
  419. mfp->fn = _cmMidiFileMalloc(mfp,strlen(fn)+1);
  420. assert( mfp->fn != NULL );
  421. strcpy(mfp->fn,fn);
  422. //
  423. // calculate the total duration of the MIDI file and convert absolute ticks back to delta ticks
  424. //
  425. unsigned mi;
  426. unsigned prvTick = 0;
  427. for(mi=0; mi<mfp->msgN; ++mi)
  428. {
  429. cmMidiTrackMsg_t* mp = mfp->msgV[mi];
  430. // convert absolute ticks back to delta ticks
  431. unsigned dtick = mp->dtick - prvTick;
  432. prvTick = mp->dtick;
  433. mp->dtick = dtick;
  434. }
  435. hPtr->h = mfp;
  436. errLabel:
  437. if( cmFileClose(&mfp->fh) != kOkFileRC )
  438. rc = _cmMidiFileError(&mfp->err,kCloseFailFileRC);
  439. if( rc != kOkMfRC )
  440. _cmMidiFileClose(mfp);
  441. return rc;
  442. }
  443. cmMfRC_t cmMidiFileClose( cmMidiFileH_t* h )
  444. {
  445. cmMfRC_t rc;
  446. if( cmMidiFileIsNull(*h) )
  447. return kOkMfRC;
  448. if((rc = _cmMidiFileClose(_cmMidiFileHandleToPtr(*h))) == kOkMfRC )
  449. return rc;
  450. h->h = NULL;
  451. return rc;
  452. }
  453. unsigned cmMidiFileTrackCount( cmMidiFileH_t h )
  454. {
  455. _cmMidiFile_t* mfp;
  456. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  457. return cmInvalidCnt;
  458. return mfp->trkN;
  459. }
  460. unsigned cmMidiFileType( cmMidiFileH_t h )
  461. {
  462. _cmMidiFile_t* mfp;
  463. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  464. return cmInvalidId;
  465. return mfp->fmtId;
  466. }
  467. const char* cmMidiFileName( cmMidiFileH_t h )
  468. {
  469. _cmMidiFile_t* mfp;
  470. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  471. return NULL;
  472. return mfp->fn;
  473. }
  474. unsigned cmMidiFileTicksPerQN( cmMidiFileH_t h )
  475. {
  476. _cmMidiFile_t* mfp;
  477. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  478. return cmInvalidCnt;
  479. return mfp->ticksPerQN;
  480. }
  481. cmMidiByte_t cmMidiFileTicksPerSmpteFrame( cmMidiFileH_t h )
  482. {
  483. _cmMidiFile_t* mfp;
  484. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  485. return kInvalidMidiByte;
  486. if( mfp->ticksPerQN != 0 )
  487. return 0;
  488. return mfp->smpteTicksPerFrame;
  489. }
  490. cmMidiByte_t cmMidiFileSmpteFormatId( cmMidiFileH_t h )
  491. {
  492. _cmMidiFile_t* mfp;
  493. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  494. return kInvalidMidiByte;
  495. if( mfp->ticksPerQN != 0 )
  496. return 0;
  497. return mfp->smpteFmtId;
  498. }
  499. unsigned cmMidiFileTrackMsgCount( cmMidiFileH_t h, unsigned trackIdx )
  500. {
  501. _cmMidiFile_t* mfp;
  502. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  503. return cmInvalidCnt;
  504. return mfp->trkV[trackIdx].cnt;
  505. }
  506. const cmMidiTrackMsg_t* cmMidiFileTrackMsg( cmMidiFileH_t h, unsigned trackIdx )
  507. {
  508. _cmMidiFile_t* mfp;
  509. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  510. return NULL;
  511. return mfp->trkV[trackIdx].base;
  512. }
  513. unsigned cmMidiFileMsgCount( cmMidiFileH_t h )
  514. {
  515. _cmMidiFile_t* mfp;
  516. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  517. return cmInvalidCnt;
  518. return mfp->msgN;
  519. }
  520. const cmMidiTrackMsg_t** cmMidiFileMsgArray( cmMidiFileH_t h )
  521. {
  522. _cmMidiFile_t* mfp;
  523. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  524. return NULL;
  525. // this cast is needed to eliminate an apparently needless 'incompatible type' warning
  526. return (const cmMidiTrackMsg_t**)mfp->msgV;
  527. }
  528. unsigned cmMidiFileSeekUsecs( cmMidiFileH_t h, unsigned offsUSecs, unsigned* msgUsecsPtr, unsigned* microsPerTickPtr )
  529. {
  530. _cmMidiFile_t* p;
  531. if((p = _cmMidiFileHandleToPtr(h)) == NULL )
  532. return cmInvalidIdx;
  533. if( p->msgN == 0 )
  534. return cmInvalidIdx;
  535. unsigned mi;
  536. unsigned microsPerQN = 60000000/120;
  537. unsigned microsPerTick = microsPerQN / p->ticksPerQN;
  538. unsigned accUSecs = 0;
  539. for(mi=0; mi<p->msgN; ++mi)
  540. {
  541. const cmMidiTrackMsg_t* mp = p->msgV[mi];
  542. if( mp->status == kMetaStId && mp->metaId == kTempoMdId )
  543. microsPerTick = mp->u.iVal / p->ticksPerQN;
  544. accUSecs += mp->dtick * microsPerTick ;
  545. if( accUSecs >= offsUSecs )
  546. break;
  547. }
  548. if( mi == p->msgN )
  549. return cmInvalidIdx;
  550. if( msgUsecsPtr != NULL )
  551. *msgUsecsPtr = accUSecs - offsUSecs;
  552. if( microsPerTickPtr != NULL )
  553. *microsPerTickPtr = microsPerTick;
  554. return mi;
  555. }
  556. double cmMidiFileDurSecs( cmMidiFileH_t h )
  557. {
  558. _cmMidiFile_t* mfp = _cmMidiFileHandleToPtr(h);
  559. unsigned mi;
  560. double durSecs = 0;
  561. unsigned microsPerQN = 60000000/120;
  562. unsigned microsPerTick = microsPerQN / mfp->ticksPerQN;
  563. for(mi=0; mi<mfp->msgN; ++mi)
  564. {
  565. cmMidiTrackMsg_t* mp = mfp->msgV[mi];
  566. if( mp->status == kMetaStId && mp->metaId == kTempoMdId )
  567. microsPerTick = mp->u.iVal / mfp->ticksPerQN;
  568. // update the accumulated seconds
  569. durSecs += (mp->dtick * microsPerTick) / 1000000.0;
  570. }
  571. return durSecs;
  572. }
  573. void cmMidiFileTickToMicros( cmMidiFileH_t h )
  574. {
  575. _cmMidiFile_t* p;
  576. if((p = _cmMidiFileHandleToPtr(h)) == NULL )
  577. return;
  578. if( p->msgN == 0 )
  579. return;
  580. unsigned mi;
  581. unsigned microsPerQN = 60000000/120; // default tempo
  582. unsigned microsPerTick = microsPerQN / p->ticksPerQN;
  583. for(mi=0; mi<p->msgN; ++mi)
  584. {
  585. cmMidiTrackMsg_t* mp = p->msgV[mi];
  586. if( mp->status == kMetaStId && mp->metaId == kTempoMdId )
  587. microsPerTick = mp->u.iVal / p->ticksPerQN;
  588. mp->dtick *= microsPerTick;
  589. }
  590. }
  591. typedef struct _cmMidiVoice_str
  592. {
  593. const cmMidiTrackMsg_t* mp;
  594. unsigned durTicks;
  595. bool sustainFl;
  596. struct _cmMidiVoice_str* link;
  597. } _cmMidiVoice_t;
  598. void _cmMidFileCalcNoteDurationReleaseNote( _cmMidiVoice_t** listPtrPtr, _cmMidiVoice_t* pp, _cmMidiVoice_t* vp )
  599. {
  600. // store the duration of the note into the track msg
  601. // assoc'd with the note-on msg
  602. cmMidiChMsg_t* cmp = (cmMidiChMsg_t*)vp->mp->u.chMsgPtr; // cast away const
  603. cmp->durTicks = vp->durTicks;
  604. // unlink the active voice msg
  605. if( pp == NULL )
  606. *listPtrPtr = vp->link;
  607. else
  608. pp->link = vp->link;
  609. // release the voice msg
  610. cmMemFree(vp);
  611. }
  612. void cmMidiFileCalcNoteDurations( cmMidiFileH_t h )
  613. {
  614. _cmMidiFile_t* p;
  615. if((p = _cmMidiFileHandleToPtr(h)) == NULL )
  616. return;
  617. if( p->msgN == 0 )
  618. return;
  619. unsigned mi;
  620. _cmMidiVoice_t* list = NULL;
  621. _cmMidiVoice_t* vp;
  622. bool sustainFlagV[ kMidiChCnt ];
  623. for(mi=0; mi<p->msgN; ++mi)
  624. {
  625. cmMidiTrackMsg_t* mp = p->msgV[mi];
  626. // update the duration of the sounding notes
  627. for(vp = list; vp!=NULL; vp=vp->link)
  628. vp->durTicks += mp->dtick;
  629. //
  630. // If this is sustain pedal msg
  631. //
  632. if( mp->status==kCtlMdId && mp->u.chMsgPtr->d0 == kSustainCtlMdId )
  633. {
  634. assert( mp->u.chMsgPtr->ch < kMidiChCnt );
  635. // set the state of the sustain pedal flags
  636. sustainFlagV[mp->u.chMsgPtr->ch] = mp->u.chMsgPtr->d1 >= 64;
  637. // if the pedal went up ...
  638. if( sustainFlagV[mp->u.chMsgPtr->ch] == false )
  639. {
  640. // ... then release sustaining notes
  641. _cmMidiVoice_t* pp = NULL;
  642. for(vp=list; vp != NULL; )
  643. {
  644. _cmMidiVoice_t* np = vp->link;
  645. if( vp->sustainFl && (vp->mp->u.chMsgPtr->ch == mp->u.chMsgPtr->ch) )
  646. _cmMidFileCalcNoteDurationReleaseNote(&list,pp,vp);
  647. else
  648. pp = vp;
  649. vp = np;
  650. }
  651. }
  652. }
  653. //
  654. // if this is a note-on msg
  655. //
  656. if( mp->status==kNoteOnMdId && mp->u.chMsgPtr->d1>0 )
  657. {
  658. vp = cmMemAllocZ(_cmMidiVoice_t,1);
  659. vp->mp = mp;
  660. vp->sustainFl = false;
  661. vp->link = list;
  662. list = vp;
  663. }
  664. else
  665. //
  666. // if this is a note-off msg
  667. //
  668. if( (mp->status==kNoteOnMdId && mp->u.chMsgPtr->d1==0) || (mp->status==kNoteOffMdId) )
  669. {
  670. _cmMidiVoice_t* pp = NULL;
  671. // for each active voice
  672. for(vp=list; vp!=NULL; vp=vp->link )
  673. {
  674. // if this active voice ch/pitch matches the note-off msg ch pitch
  675. if( (vp->mp->u.chMsgPtr->d0==mp->u.chMsgPtr->d0) && (vp->mp->u.chMsgPtr->ch==mp->u.chMsgPtr->ch) )
  676. {
  677. if( sustainFlagV[mp->u.chMsgPtr->ch] )
  678. vp->sustainFl = true;
  679. else
  680. _cmMidFileCalcNoteDurationReleaseNote(&list,pp,vp);
  681. break;
  682. }
  683. pp = vp;
  684. } // end while
  685. } // end if
  686. } // end-for
  687. // check for hung notes
  688. _cmMidiVoice_t* np = NULL;
  689. vp = list;
  690. while( vp != NULL )
  691. {
  692. np = vp->link;
  693. cmErrMsg(&p->err,kMissingNoteOffMfRC,"Missing note-off for note-on:%s",cmMidiToSciPitch(vp->mp->u.chMsgPtr->d0,NULL,0));
  694. cmMemFree(vp);
  695. vp = np;
  696. }
  697. }
  698. void cmMidiFileSetDelay( cmMidiFileH_t h, unsigned ticks )
  699. {
  700. _cmMidiFile_t* p;
  701. unsigned mi;
  702. if((p = _cmMidiFileHandleToPtr(h)) == NULL )
  703. return;
  704. if( p->msgN == 0 )
  705. return;
  706. for(mi=0; mi<p->msgN; ++mi)
  707. {
  708. cmMidiTrackMsg_t* mp = p->msgV[mi];
  709. // locate the first msg which has a non-zero delta tick
  710. if( mp->dtick > 0 )
  711. {
  712. mp->dtick = ticks;
  713. break;
  714. }
  715. }
  716. }
  717. unsigned cmMidiFilePackTrackMsgBufByteCount( const cmMidiTrackMsg_t* m )
  718. { return sizeof(cmMidiTrackMsg_t) + m->byteCnt; }
  719. cmMidiTrackMsg_t* cmMidiFilePackTrackMsg( const cmMidiTrackMsg_t* m, void* buf, unsigned bufByteCnt )
  720. {
  721. unsigned n = sizeof(cmMidiTrackMsg_t) + m->byteCnt;
  722. if( n < bufByteCnt )
  723. {
  724. assert(0);
  725. return NULL;
  726. }
  727. // copy the cmMidiTrackMsg_t into the buffer
  728. memcpy(buf, m, sizeof(cmMidiTrackMsg_t));
  729. if( m->byteCnt > 0 )
  730. {
  731. // copy any linked data into the buffer
  732. memcpy(buf + sizeof(cmMidiTrackMsg_t), m->u.voidPtr, m->byteCnt );
  733. // fixup the linked data ptr
  734. cmMidiTrackMsg_t* mp = (cmMidiTrackMsg_t*)buf;
  735. mp->u.voidPtr = buf + sizeof(cmMidiTrackMsg_t);
  736. }
  737. return (cmMidiTrackMsg_t*)buf;
  738. }
  739. void cmMidiFilePrint( cmMidiFileH_t h, unsigned trkIdx, cmRpt_t* rpt )
  740. {
  741. const _cmMidiFile_t* mfp = _cmMidiFileHandleToPtr(h);
  742. if( mfp->fn != NULL )
  743. cmRptPrintf(rpt,"%s ",mfp->fn);
  744. cmRptPrintf(rpt,"fmt:%i ticksPerQN:%i tracks:%i\n",mfp->fmtId,mfp->ticksPerQN,mfp->trkN);
  745. int i = trkIdx == cmInvalidIdx ? 0 : trkIdx;
  746. int n = trkIdx == cmInvalidIdx ? mfp->trkN : trkIdx+1;
  747. for(; i<n; ++i)
  748. {
  749. cmRptPrintf(rpt,"Track:%i\n",i);
  750. cmMidiTrackMsg_t* tmp = mfp->trkV[i].base;
  751. while( tmp != NULL )
  752. {
  753. cmRptPrintf(rpt,"%5i ", tmp->dtick );
  754. if( tmp->status == kMetaStId )
  755. cmRptPrintf(rpt,"%s ", cmMidiMetaStatusToLabel(tmp->metaId));
  756. else
  757. {
  758. cmRptPrintf(rpt,"%4s %3i %3i %3i", cmMidiStatusToLabel(tmp->status),tmp->u.chMsgPtr->ch,tmp->u.chMsgPtr->d0,tmp->u.chMsgPtr->d1);
  759. }
  760. cmRptPrintf(rpt,"\n");
  761. tmp = tmp->link;
  762. }
  763. }
  764. }
  765. bool cmMidiFileIsNull( cmMidiFileH_t h )
  766. { return (_cmMidiFile_t*)h.h == NULL; }
  767. void cmMidiFileTestPrint( void* printDataPtr, const char* fmt, va_list vl )
  768. { vprintf(fmt,vl); }
  769. void cmMidiFileTest( const char* fn, cmCtx_t* ctx )
  770. {
  771. cmMfRC_t rc;
  772. cmMidiFileH_t h;
  773. if((rc = cmMidiFileOpen(fn,&h,ctx)) != kOkMfRC )
  774. {
  775. printf("Error:%i Unable to open the cmMidi file: %s\n",rc,fn);
  776. return;
  777. }
  778. cmMidiFilePrint(h,cmMidiFileTrackCount(h)-1,&ctx->rpt);
  779. printf("Tracks:%i\n",cmMidiFileTrackCount(h));
  780. cmMidiFileClose(&h);
  781. }