libcm is a C development framework with an emphasis on audio signal processing applications.
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

cmMidiFile.c 37KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509
  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->durTicks = 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. //printf("%i %i\n",(*(cmMidiTrackMsg_t**)p0)->dticks,(*(cmMidiTrackMsg_t**)p1)->dticks);
  321. if( (*(cmMidiTrackMsg_t**)p0)->atick == (*(cmMidiTrackMsg_t**)p1)->atick )
  322. return 0;
  323. return (*(cmMidiTrackMsg_t**)p0)->atick < (*(cmMidiTrackMsg_t**)p1)->atick ? -1 : 1;
  324. }
  325. cmMfRC_t _cmMidiFileClose( _cmMidiFile_t* mfp )
  326. {
  327. cmMfRC_t rc = kOkMfRC;
  328. if( mfp == NULL )
  329. return rc;
  330. cmMemPtrFree(&mfp->msgV);
  331. if( cmFileIsValid( mfp->fh ) )
  332. if( cmFileClose( &mfp->fh ) != kOkFileRC )
  333. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file close failed.");
  334. if( cmLHeapIsValid( mfp->lhH ) )
  335. cmLHeapDestroy(&mfp->lhH);
  336. cmMemPtrFree(&mfp);
  337. return rc;
  338. }
  339. cmMfRC_t cmMidiFileOpen( const char* fn, cmMidiFileH_t* hPtr, cmCtx_t* ctx )
  340. {
  341. cmMfRC_t rc = kOkMfRC;
  342. _cmMidiFile_t* mfp = NULL;
  343. unsigned short trkIdx = 0;
  344. cmErr_t err;
  345. if( cmMidiFileIsValid(*hPtr) )
  346. if((rc = _cmMidiFileClose(_cmMidiFileHandleToPtr(*hPtr))) != kOkMfRC )
  347. return rc;
  348. cmErrSetup(&err,&ctx->rpt,"MIDI File");
  349. // allocate the midi file object
  350. if(( mfp = cmMemAllocZ( _cmMidiFile_t, 1)) == NULL )
  351. return rc = cmErrMsg(&err,kMemAllocFailMfRC,"MIDI file memory allocation failed.");
  352. cmErrClone(&mfp->err,&err);
  353. // allocate the linked heap
  354. if( cmLHeapIsValid( mfp->lhH = cmLHeapCreate( 1024, ctx )) == false )
  355. {
  356. rc = cmErrMsg(&err,kMemAllocFailMfRC,"MIDI heap allocation failed.");
  357. goto errLabel;
  358. }
  359. // open the file
  360. if(cmFileOpen(&mfp->fh,fn,kReadFileFl | kBinaryFileFl,mfp->err.rpt) != kOkFileRC )
  361. {
  362. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file open failed.");
  363. goto errLabel;
  364. }
  365. // read header and setup track array
  366. if(( rc = _cmMidiFileReadHdr(mfp)) != kOkMfRC )
  367. goto errLabel;
  368. while( !cmFileEof(mfp->fh) && trkIdx < mfp->trkN )
  369. {
  370. unsigned chkId=0,chkN=0;
  371. // read the chunk id
  372. if((rc = _cmMidiFileRead32(mfp,&chkId)) != kOkMfRC )
  373. goto errLabel;
  374. // read the chunk size
  375. if((rc = _cmMidiFileRead32(mfp,&chkN)) != kOkMfRC )
  376. goto errLabel;
  377. // if this is not a trk chunk then skip it
  378. if( chkId != (unsigned)'MTrk')
  379. {
  380. //if( fseek( mfp->fp, chkN, SEEK_CUR) != 0 )
  381. if( cmFileSeek(mfp->fh,kCurFileFl,chkN) != kOkFileRC )
  382. {
  383. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file seek failed.");
  384. goto errLabel;
  385. }
  386. }
  387. else
  388. {
  389. if((rc = _cmMidiFileReadTrack(mfp,trkIdx)) != kOkMfRC )
  390. goto errLabel;
  391. ++trkIdx;
  392. }
  393. }
  394. // get the total trk msg count
  395. mfp->msgN = 0;
  396. for(trkIdx=0; trkIdx<mfp->trkN; ++trkIdx)
  397. mfp->msgN += mfp->trkV[ trkIdx ].cnt;
  398. // allocate the trk msg index vector: msgV[]
  399. mfp->msgV = cmMemAllocZ(cmMidiTrackMsg_t*, mfp->msgN);
  400. // store a pointer to every trk msg in msgV[]
  401. // and convert tick to absolute tick
  402. mfp->nextUid = 0;
  403. unsigned i = 0;
  404. for(trkIdx=0; trkIdx<mfp->trkN; ++trkIdx)
  405. {
  406. unsigned tick = 0;
  407. cmMidiTrackMsg_t* tmp = mfp->trkV[ trkIdx ].base;
  408. while( tmp != NULL )
  409. {
  410. assert( i < mfp->msgN);
  411. tick += tmp->dtick; // convert delta-ticks to absolute ticks
  412. tmp->atick = tick;
  413. tmp->uid = mfp->nextUid++; // assign the msg uid
  414. mfp->msgV[i] = tmp;
  415. tmp = tmp->link;
  416. ++i;
  417. }
  418. }
  419. // sort msgV[] in ascending order on atick
  420. qsort( mfp->msgV, mfp->msgN, sizeof(cmMidiTrackMsg_t*), _cmMidiFileSortFunc );
  421. //for(i=0; i<25; ++i)
  422. // printf("%i 0x%x 0x%x\n",mfp->msgV[i]->tick,mfp->msgV[i]->status,mfp->msgV[i]->metaId);
  423. mfp->fn = _cmMidiFileMalloc(mfp,strlen(fn)+1);
  424. assert( mfp->fn != NULL );
  425. strcpy(mfp->fn,fn);
  426. hPtr->h = mfp;
  427. errLabel:
  428. if( cmFileClose(&mfp->fh) != kOkFileRC )
  429. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file close failed.");
  430. if( rc != kOkMfRC )
  431. _cmMidiFileClose(mfp);
  432. return rc;
  433. }
  434. cmMfRC_t cmMidiFileClose( cmMidiFileH_t* h )
  435. {
  436. cmMfRC_t rc;
  437. if( cmMidiFileIsNull(*h) )
  438. return kOkMfRC;
  439. if((rc = _cmMidiFileClose(_cmMidiFileHandleToPtr(*h))) == kOkMfRC )
  440. return rc;
  441. h->h = NULL;
  442. return rc;
  443. }
  444. cmMfRC_t _cmMidiFileWrite8( _cmMidiFile_t* mfp, unsigned char v )
  445. {
  446. cmMfRC_t rc = kOkMfRC;
  447. if( cmFileWriteUChar(mfp->fh,&v,1) != kOkFileRC )
  448. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file byte write failed.");
  449. return rc;
  450. }
  451. cmMfRC_t _cmMidiFileWrite16( _cmMidiFile_t* mfp, unsigned short v )
  452. {
  453. cmMfRC_t rc = kOkMfRC;
  454. v = mfSwap16(v);
  455. if( cmFileWriteUShort(mfp->fh,&v,1) != kOkFileRC )
  456. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file short integer write failed.");
  457. return rc;
  458. }
  459. cmMfRC_t _cmMidiFileWrite24( _cmMidiFile_t* mfp, unsigned v )
  460. {
  461. cmMfRC_t rc = kOkMfRC;
  462. unsigned mask = 0xff0000;
  463. int i;
  464. for(i=2; i>=0; --i)
  465. {
  466. unsigned char c = (v & mask) >> (i*8);
  467. mask >>= 8;
  468. if( cmFileWriteUChar(mfp->fh,&c,1) != kOkFileRC )
  469. {
  470. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file 24 bit integer write failed.");
  471. goto errLabel;
  472. }
  473. }
  474. errLabel:
  475. return rc;
  476. }
  477. cmMfRC_t _cmMidiFileWrite32( _cmMidiFile_t* mfp, unsigned v )
  478. {
  479. cmMfRC_t rc = kOkMfRC;
  480. v = mfSwap32(v);
  481. if( cmFileWriteUInt(mfp->fh,&v,1) != kOkFileRC )
  482. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file integer write failed.");
  483. return rc;
  484. }
  485. cmMfRC_t _cmMidiFileWriteRecd( _cmMidiFile_t* mfp, const void* v, unsigned byteCnt )
  486. {
  487. cmMfRC_t rc = kOkMfRC;
  488. if( cmFileWriteChar(mfp->fh,v,byteCnt) != kOkFileRC )
  489. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file write record failed.");
  490. return rc;
  491. }
  492. cmMfRC_t _cmMidiFileWriteVarLen( _cmMidiFile_t* mfp, unsigned v )
  493. {
  494. cmMfRC_t rc = kOkMfRC;
  495. unsigned buf = v & 0x7f;
  496. while((v >>= 7) > 0 )
  497. {
  498. buf <<= 8;
  499. buf |= 0x80;
  500. buf += (v & 0x7f);
  501. }
  502. while(1)
  503. {
  504. unsigned char c = (unsigned char)(buf & 0xff);
  505. if( cmFileWriteUChar(mfp->fh,&c,1) != kOkFileRC )
  506. {
  507. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file variable length integer write failed.");
  508. goto errLabel;
  509. }
  510. if( buf & 0x80 )
  511. buf >>= 8;
  512. else
  513. break;
  514. }
  515. errLabel:
  516. return rc;
  517. }
  518. cmMfRC_t _cmMidiFileWriteHdr( _cmMidiFile_t* mfp )
  519. {
  520. cmMfRC_t rc;
  521. unsigned fileId = 'MThd';
  522. unsigned chunkByteN = 6;
  523. // write the file id ('MThd')
  524. if((rc = _cmMidiFileWrite32(mfp,fileId)) != kOkMfRC )
  525. return rc;
  526. // write the file chunk byte count (always 6)
  527. if((rc = _cmMidiFileWrite32(mfp,chunkByteN)) != kOkMfRC )
  528. return rc;
  529. // write the MIDI file format id (0,1,2)
  530. if((rc = _cmMidiFileWrite16(mfp,mfp->fmtId)) != kOkMfRC )
  531. return rc;
  532. // write the track count
  533. if((rc = _cmMidiFileWrite16(mfp,mfp->trkN)) != kOkMfRC )
  534. return rc;
  535. unsigned short v = 0;
  536. // if the ticks per quarter note field is valid ...
  537. if( mfp->ticksPerQN )
  538. v = mfp->ticksPerQN;
  539. else
  540. {
  541. // ... otherwise the division field was given in smpte
  542. v = mfp->smpteFmtId << 8;
  543. v += mfp->smpteTicksPerFrame;
  544. }
  545. if((rc = _cmMidiFileWrite16(mfp,v)) != kOkMfRC )
  546. return rc;
  547. return rc;
  548. }
  549. cmMfRC_t _cmMidiFileWriteSysEx( _cmMidiFile_t* mfp, cmMidiTrackMsg_t* tmp )
  550. {
  551. cmMfRC_t rc = kOkMfRC;
  552. if((rc = _cmMidiFileWrite8(mfp,kSysExMdId)) != kOkMfRC )
  553. goto errLabel;
  554. if( cmFileWriteUChar(mfp->fh,tmp->u.sysExPtr,tmp->byteCnt) != kOkFileRC )
  555. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"Sys-ex msg write failed.");
  556. errLabel:
  557. return rc;
  558. }
  559. cmMfRC_t _cmMidiFileWriteChannelMsg( _cmMidiFile_t* mfp, const cmMidiTrackMsg_t* tmp, cmMidiByte_t* runStatus )
  560. {
  561. cmMfRC_t rc = kOkMfRC;
  562. unsigned byteN = cmMidiStatusToByteCount(tmp->status);
  563. cmMidiByte_t status = tmp->status + tmp->u.chMsgPtr->ch;
  564. if( status != *runStatus )
  565. {
  566. *runStatus = status;
  567. if((rc = _cmMidiFileWrite8(mfp,status)) != kOkMfRC )
  568. goto errLabel;
  569. }
  570. if(byteN>=1)
  571. if((rc = _cmMidiFileWrite8(mfp,tmp->u.chMsgPtr->d0)) != kOkMfRC )
  572. goto errLabel;
  573. if(byteN>=2)
  574. if((rc = _cmMidiFileWrite8(mfp,tmp->u.chMsgPtr->d1)) != kOkMfRC )
  575. goto errLabel;
  576. errLabel:
  577. return rc;
  578. }
  579. cmMfRC_t _cmMidiFileWriteMetaMsg( _cmMidiFile_t* mfp, const cmMidiTrackMsg_t* tmp )
  580. {
  581. cmMfRC_t rc;
  582. if((rc = _cmMidiFileWrite8(mfp,kMetaStId)) != kOkMfRC )
  583. return rc;
  584. if((rc = _cmMidiFileWrite8(mfp,tmp->metaId)) != kOkMfRC )
  585. return rc;
  586. switch( tmp->metaId )
  587. {
  588. case kSeqNumbMdId:
  589. if((rc = _cmMidiFileWrite8(mfp,sizeof(tmp->u.sVal))) == kOkMfRC )
  590. rc = _cmMidiFileWrite16(mfp,tmp->u.sVal);
  591. break;
  592. case kTempoMdId:
  593. if((rc = _cmMidiFileWrite8(mfp,3)) == kOkMfRC )
  594. rc = _cmMidiFileWrite24(mfp,tmp->u.iVal);
  595. break;
  596. case kSmpteMdId:
  597. if((rc = _cmMidiFileWrite8(mfp,sizeof(cmMidiSmpte_t))) == kOkMfRC )
  598. rc = _cmMidiFileWriteRecd(mfp,tmp->u.smptePtr,sizeof(cmMidiSmpte_t));
  599. break;
  600. case kTimeSigMdId:
  601. if((rc = _cmMidiFileWrite8(mfp,sizeof(cmMidiTimeSig_t))) == kOkMfRC )
  602. rc = _cmMidiFileWriteRecd(mfp,tmp->u.timeSigPtr,sizeof(cmMidiTimeSig_t));
  603. break;
  604. case kKeySigMdId:
  605. if((rc = _cmMidiFileWrite8(mfp,sizeof(cmMidiKeySig_t))) == kOkMfRC )
  606. rc = _cmMidiFileWriteRecd(mfp,tmp->u.keySigPtr,sizeof(cmMidiKeySig_t));
  607. break;
  608. case kSeqSpecMdId:
  609. if((rc = _cmMidiFileWriteVarLen(mfp,sizeof(tmp->byteCnt))) == kOkMfRC )
  610. rc = _cmMidiFileWriteRecd(mfp,tmp->u.sysExPtr,tmp->byteCnt);
  611. break;
  612. case kMidiChMdId:
  613. if((rc = _cmMidiFileWrite8(mfp,sizeof(tmp->u.bVal))) == kOkMfRC )
  614. rc = _cmMidiFileWrite8(mfp,tmp->u.bVal);
  615. break;
  616. case kEndOfTrkMdId:
  617. rc = _cmMidiFileWrite8(mfp,0);
  618. break;
  619. case kTextMdId:
  620. case kCopyMdId:
  621. case kTrkNameMdId:
  622. case kInstrNameMdId:
  623. case kLyricsMdId:
  624. case kMarkerMdId:
  625. case kCuePointMdId:
  626. {
  627. unsigned n = tmp->u.text==NULL ? 0 : strlen(tmp->u.text);
  628. if((rc = _cmMidiFileWriteVarLen(mfp,n)) == kOkMfRC && n>0 )
  629. rc = _cmMidiFileWriteRecd(mfp,tmp->u.text,n);
  630. }
  631. break;
  632. default:
  633. {
  634. // ignore unknown meta messages
  635. }
  636. }
  637. return rc;
  638. }
  639. cmMfRC_t _cmMidiFileWriteTrack( _cmMidiFile_t* mfp, unsigned trkIdx )
  640. {
  641. cmMfRC_t rc = kOkMfRC;
  642. cmMidiTrackMsg_t* tmp = mfp->trkV[trkIdx].base;
  643. cmMidiByte_t runStatus = 0;
  644. for(; tmp!=NULL; tmp=tmp->link)
  645. {
  646. // write the msg tick count
  647. if((rc = _cmMidiFileWriteVarLen(mfp,tmp->dtick)) != kOkMfRC )
  648. return rc;
  649. // switch on status
  650. switch( tmp->status )
  651. {
  652. // handle sys-ex msg
  653. case kSysExMdId:
  654. rc = _cmMidiFileWriteSysEx(mfp,tmp);
  655. break;
  656. // handle meta msg
  657. case kMetaStId:
  658. rc = _cmMidiFileWriteMetaMsg(mfp,tmp);
  659. break;
  660. default:
  661. // handle channel msg
  662. rc = _cmMidiFileWriteChannelMsg(mfp,tmp,&runStatus);
  663. }
  664. }
  665. return rc;
  666. }
  667. cmMfRC_t cmMidiFileWrite( cmMidiFileH_t h, const char* fn )
  668. {
  669. cmMfRC_t rc = kOkMfRC;
  670. _cmMidiFile_t* mfp = _cmMidiFileHandleToPtr(h);
  671. unsigned i;
  672. // create the output file
  673. if( cmFileOpen(&mfp->fh,fn,kWriteFileFl,mfp->err.rpt) != kOkFileRC )
  674. return cmErrMsg(&mfp->err,kFileFailMfRC,"The MIDI file '%s' could not be created.",cmStringNullGuard(fn));
  675. // write the file header
  676. if((rc = _cmMidiFileWriteHdr(mfp)) != kOkMfRC )
  677. {
  678. rc = cmErrMsg(&mfp->err,rc,"The file header write failed on the MIDI file '%s'.",cmStringNullGuard(fn));
  679. goto errLabel;
  680. }
  681. for(i=0; i < mfp->trkN; ++i )
  682. {
  683. unsigned chkId='MTrk';
  684. long offs0,offs1;
  685. // write the track chunk id ('MTrk')
  686. if((rc = _cmMidiFileWrite32(mfp,chkId)) != kOkMfRC )
  687. goto errLabel;
  688. cmFileTell(mfp->fh,&offs0);
  689. // write the track chunk size as zero
  690. if((rc = _cmMidiFileWrite32(mfp,0)) != kOkMfRC )
  691. goto errLabel;
  692. if((rc = _cmMidiFileWriteTrack(mfp,i)) != kOkMfRC )
  693. goto errLabel;
  694. cmFileTell(mfp->fh,&offs1);
  695. cmFileSeek(mfp->fh,kBeginFileFl,offs0);
  696. _cmMidiFileWrite32(mfp,offs1-offs0-4);
  697. cmFileSeek(mfp->fh,kBeginFileFl,offs1);
  698. }
  699. errLabel:
  700. cmFileClose(&mfp->fh);
  701. return rc;
  702. }
  703. bool cmMidiFileIsValid( cmMidiFileH_t h )
  704. { return !cmMidiFileIsNull(h); }
  705. unsigned cmMidiFileTrackCount( cmMidiFileH_t h )
  706. {
  707. _cmMidiFile_t* mfp;
  708. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  709. return cmInvalidCnt;
  710. return mfp->trkN;
  711. }
  712. unsigned cmMidiFileType( cmMidiFileH_t h )
  713. {
  714. _cmMidiFile_t* mfp;
  715. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  716. return cmInvalidId;
  717. return mfp->fmtId;
  718. }
  719. const char* cmMidiFileName( cmMidiFileH_t h )
  720. {
  721. _cmMidiFile_t* mfp;
  722. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  723. return NULL;
  724. return mfp->fn;
  725. }
  726. unsigned cmMidiFileTicksPerQN( cmMidiFileH_t h )
  727. {
  728. _cmMidiFile_t* mfp;
  729. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  730. return cmInvalidCnt;
  731. return mfp->ticksPerQN;
  732. }
  733. cmMidiByte_t cmMidiFileTicksPerSmpteFrame( cmMidiFileH_t h )
  734. {
  735. _cmMidiFile_t* mfp;
  736. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  737. return kInvalidMidiByte;
  738. if( mfp->ticksPerQN != 0 )
  739. return 0;
  740. return mfp->smpteTicksPerFrame;
  741. }
  742. cmMidiByte_t cmMidiFileSmpteFormatId( cmMidiFileH_t h )
  743. {
  744. _cmMidiFile_t* mfp;
  745. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  746. return kInvalidMidiByte;
  747. if( mfp->ticksPerQN != 0 )
  748. return 0;
  749. return mfp->smpteFmtId;
  750. }
  751. unsigned cmMidiFileTrackMsgCount( cmMidiFileH_t h, unsigned trackIdx )
  752. {
  753. _cmMidiFile_t* mfp;
  754. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  755. return cmInvalidCnt;
  756. return mfp->trkV[trackIdx].cnt;
  757. }
  758. const cmMidiTrackMsg_t* cmMidiFileTrackMsg( cmMidiFileH_t h, unsigned trackIdx )
  759. {
  760. _cmMidiFile_t* mfp;
  761. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  762. return NULL;
  763. return mfp->trkV[trackIdx].base;
  764. }
  765. unsigned cmMidiFileMsgCount( cmMidiFileH_t h )
  766. {
  767. _cmMidiFile_t* mfp;
  768. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  769. return cmInvalidCnt;
  770. return mfp->msgN;
  771. }
  772. const cmMidiTrackMsg_t** cmMidiFileMsgArray( cmMidiFileH_t h )
  773. {
  774. _cmMidiFile_t* mfp;
  775. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  776. return NULL;
  777. // this cast is needed to eliminate an apparently needless 'incompatible type' warning
  778. return (const cmMidiTrackMsg_t**)mfp->msgV;
  779. }
  780. unsigned cmMidiFileSeekUsecs( cmMidiFileH_t h, unsigned offsUSecs, unsigned* msgUsecsPtr, unsigned* microsPerTickPtr )
  781. {
  782. _cmMidiFile_t* p;
  783. if((p = _cmMidiFileHandleToPtr(h)) == NULL )
  784. return cmInvalidIdx;
  785. if( p->msgN == 0 )
  786. return cmInvalidIdx;
  787. unsigned mi;
  788. double microsPerQN = 60000000.0/120.0;
  789. double microsPerTick = microsPerQN / p->ticksPerQN;
  790. double accUSecs = 0;
  791. for(mi=0; mi<p->msgN; ++mi)
  792. {
  793. const cmMidiTrackMsg_t* mp = p->msgV[mi];
  794. if( mp->status == kMetaStId && mp->metaId == kTempoMdId )
  795. microsPerTick = mp->u.iVal / p->ticksPerQN;
  796. accUSecs += mp->dtick * microsPerTick ;
  797. if( accUSecs >= offsUSecs )
  798. break;
  799. }
  800. if( mi == p->msgN )
  801. return cmInvalidIdx;
  802. if( msgUsecsPtr != NULL )
  803. *msgUsecsPtr = round(accUSecs - offsUSecs);
  804. if( microsPerTickPtr != NULL )
  805. *microsPerTickPtr = round(microsPerTick);
  806. return mi;
  807. }
  808. double cmMidiFileDurSecs( cmMidiFileH_t h )
  809. {
  810. _cmMidiFile_t* mfp = _cmMidiFileHandleToPtr(h);
  811. unsigned mi;
  812. double durSecs = 0;
  813. double r = 1.0; //1000.0/(1000-.8);
  814. double microsPerQN = r*60000000.0/120.0;
  815. double microsPerTick = microsPerQN / mfp->ticksPerQN;
  816. for(mi=0; mi<mfp->msgN; ++mi)
  817. {
  818. cmMidiTrackMsg_t* mp = mfp->msgV[mi];
  819. if( mp->status == kMetaStId && mp->metaId == kTempoMdId )
  820. microsPerTick = r*mp->u.iVal / mfp->ticksPerQN;
  821. // update the accumulated seconds
  822. durSecs += (mp->dtick * microsPerTick) / 1000000.0;
  823. }
  824. return durSecs;
  825. }
  826. void cmMidiFileTickToMicros( cmMidiFileH_t h )
  827. {
  828. _cmMidiFile_t* p;
  829. if((p = _cmMidiFileHandleToPtr(h)) == NULL )
  830. return;
  831. if( p->msgN == 0 )
  832. return;
  833. unsigned mi;
  834. double r = 1.0; //1000.0/(1000-.8);
  835. double microsPerQN = r*60000000/120; // default tempo
  836. double microsPerTick = microsPerQN / p->ticksPerQN;
  837. for(mi=0; mi<p->msgN; ++mi)
  838. {
  839. cmMidiTrackMsg_t* mp = p->msgV[mi];
  840. if( mp->status == kMetaStId && mp->metaId == kTempoMdId )
  841. microsPerTick = r*mp->u.iVal / p->ticksPerQN;
  842. mp->dtick = round(microsPerTick*mp->dtick);
  843. }
  844. }
  845. void cmMidiFileTickToSamples( cmMidiFileH_t h, double srate, bool absFl )
  846. {
  847. _cmMidiFile_t* p;
  848. if((p = _cmMidiFileHandleToPtr(h)) == NULL )
  849. return;
  850. if( p->msgN == 0 )
  851. return;
  852. unsigned mi;
  853. double r = 1.0; //1000.0/(1000-.8);
  854. double microsPerQN = r*60000000/120; // default tempo
  855. double microsPerTick = microsPerQN / p->ticksPerQN;
  856. double absSmp = 0;
  857. for(mi=0; mi<p->msgN; ++mi)
  858. {
  859. cmMidiTrackMsg_t* mp = p->msgV[mi];
  860. if( mp->status == kMetaStId && mp->metaId == kTempoMdId )
  861. microsPerTick = r*mp->u.iVal / p->ticksPerQN;
  862. double delta = microsPerTick*mp->dtick*srate/1000000.0;
  863. absSmp += delta;
  864. mp->dtick = round(absFl ? absSmp : delta);
  865. }
  866. }
  867. typedef struct _cmMidiVoice_str
  868. {
  869. const cmMidiTrackMsg_t* mp;
  870. unsigned durTicks;
  871. bool sustainFl;
  872. struct _cmMidiVoice_str* link;
  873. } _cmMidiVoice_t;
  874. void _cmMidFileCalcNoteDurationReleaseNote( _cmMidiVoice_t** listPtrPtr, _cmMidiVoice_t* pp, _cmMidiVoice_t* vp )
  875. {
  876. assert( (pp==NULL && vp==*listPtrPtr) || pp->link==vp);
  877. // store the duration of the note into the track msg
  878. // assoc'd with the note-on msg
  879. cmMidiChMsg_t* cmp = (cmMidiChMsg_t*)vp->mp->u.chMsgPtr; // cast away const
  880. cmp->durTicks = vp->durTicks;
  881. _cmMidiVoice_t* np = vp->link;
  882. // release the voice msg
  883. cmMemFree(vp);
  884. // unlink the active voice msg
  885. if( pp == NULL )
  886. *listPtrPtr = np;
  887. else
  888. pp->link = np;
  889. }
  890. void _cmMidiFileCalcNoteDurationsAllocVoice( _cmMidiVoice_t** listPtrPtr, cmMidiTrackMsg_t* mp, bool sustainFl )
  891. {
  892. _cmMidiVoice_t* vp = cmMemAllocZ(_cmMidiVoice_t,1);
  893. vp->mp = mp;
  894. vp->sustainFl = sustainFl;
  895. vp->link = *listPtrPtr;
  896. *listPtrPtr = vp;
  897. }
  898. void cmMidiFileCalcNoteDurations( cmMidiFileH_t h )
  899. {
  900. _cmMidiFile_t* p;
  901. if((p = _cmMidiFileHandleToPtr(h)) == NULL )
  902. return;
  903. if( p->msgN == 0 )
  904. return;
  905. unsigned mi = cmInvalidId;
  906. _cmMidiVoice_t* list = NULL; // list of active voices
  907. _cmMidiVoice_t* vp = NULL;
  908. cmMidiTrackMsg_t* sustainPedalDownMsg = NULL;
  909. bool sustainFlagV[ kMidiChCnt ];
  910. // clear the sustain pedal flag
  911. for(mi=0; mi<kMidiChCnt; ++mi)
  912. sustainFlagV[mi]=false;
  913. for(mi=0; mi<p->msgN; ++mi)
  914. {
  915. cmMidiTrackMsg_t* mp = p->msgV[mi];
  916. // update the duration of the sounding notes
  917. for(vp = list; vp!=NULL; vp=vp->link)
  918. vp->durTicks += mp->dtick;
  919. // update the sustain pedal duration
  920. if( sustainPedalDownMsg != NULL )
  921. ((cmMidiChMsg_t*)(sustainPedalDownMsg->u.chMsgPtr))->durTicks += mp->dtick; // cast away const
  922. //
  923. // If this is sustain pedal msg
  924. //
  925. if( mp->status==kCtlMdId && mp->u.chMsgPtr->d0 == kSustainCtlMdId )
  926. {
  927. unsigned chIdx = mp->u.chMsgPtr->ch;
  928. assert( chIdx < kMidiChCnt );
  929. // set the state of the sustain pedal flags
  930. sustainFlagV[chIdx] = mp->u.chMsgPtr->d1 >= 64;
  931. // if the pedal went down ...
  932. if( sustainFlagV[chIdx] )
  933. {
  934. if( sustainPedalDownMsg != NULL )
  935. {
  936. // TODO: the correct way to handle this is to maintain multiple sustain pedals
  937. cmErrMsg(&p->err,kSustainPedalMfRC,"Sustain pedal down with no intervening sustain pedal up.");
  938. }
  939. else
  940. {
  941. sustainPedalDownMsg = mp;
  942. ((cmMidiChMsg_t*)(sustainPedalDownMsg->u.chMsgPtr))->durTicks = 0; // cast away const
  943. }
  944. _cmMidiFileCalcNoteDurationsAllocVoice( &list, mp, true );
  945. }
  946. else // ... if the pedal went up
  947. {
  948. sustainPedalDownMsg = NULL;
  949. // ... then release sustaining notes
  950. _cmMidiVoice_t* pp = NULL;
  951. for(vp=list; vp != NULL; )
  952. {
  953. _cmMidiVoice_t* np = vp->link;
  954. if( vp->sustainFl && (vp->mp->u.chMsgPtr->ch == chIdx) )
  955. _cmMidFileCalcNoteDurationReleaseNote(&list,pp,vp);
  956. else
  957. pp = vp;
  958. vp = np;
  959. }
  960. }
  961. }
  962. //
  963. // if this is a note-on msg
  964. //
  965. if( mp->status==kNoteOnMdId && mp->u.chMsgPtr->d1>0 )
  966. {
  967. _cmMidiFileCalcNoteDurationsAllocVoice( &list, mp, false );
  968. }
  969. else
  970. //
  971. // if this is a note-off msg
  972. //
  973. if( (mp->status==kNoteOnMdId && mp->u.chMsgPtr->d1==0) || (mp->status==kNoteOffMdId) )
  974. {
  975. _cmMidiVoice_t* pp = NULL;
  976. unsigned chIdx = mp->u.chMsgPtr->ch;
  977. assert( chIdx < kMidiChCnt );
  978. // for each active voice
  979. for(vp=list; vp!=NULL; vp=vp->link )
  980. {
  981. // if this active voice ch/pitch matches the note-off msg ch pitch
  982. if( (vp->mp->u.chMsgPtr->d0==mp->u.chMsgPtr->d0) && (vp->mp->u.chMsgPtr->ch==chIdx) )
  983. {
  984. // if the sustain pedal is down for this channel - then defer turning the note off
  985. if( sustainFlagV[chIdx] )
  986. vp->sustainFl = true;
  987. else
  988. _cmMidFileCalcNoteDurationReleaseNote(&list,pp,vp);
  989. break;
  990. }
  991. pp = vp;
  992. } // end for
  993. } // end if
  994. } // end-for
  995. // check for hung notes
  996. _cmMidiVoice_t* np = NULL;
  997. vp = list;
  998. while( vp != NULL )
  999. {
  1000. np = vp->link;
  1001. if( cmMidiIsNoteOn(vp->mp->status) == false )
  1002. cmErrMsg(&p->err,kMissingNoteOffMfRC,"Missing note-off for note-on:%s",cmMidiToSciPitch(vp->mp->u.chMsgPtr->d0,NULL,0));
  1003. cmMemFree(vp);
  1004. vp = np;
  1005. }
  1006. }
  1007. void cmMidiFileSetDelay( cmMidiFileH_t h, unsigned ticks )
  1008. {
  1009. _cmMidiFile_t* p;
  1010. unsigned mi;
  1011. if((p = _cmMidiFileHandleToPtr(h)) == NULL )
  1012. return;
  1013. if( p->msgN == 0 )
  1014. return;
  1015. for(mi=0; mi<p->msgN; ++mi)
  1016. {
  1017. cmMidiTrackMsg_t* mp = p->msgV[mi];
  1018. // locate the first msg which has a non-zero delta tick
  1019. if( mp->dtick > 0 )
  1020. {
  1021. mp->dtick = ticks;
  1022. break;
  1023. }
  1024. }
  1025. }
  1026. unsigned cmMidiFilePackTrackMsgBufByteCount( const cmMidiTrackMsg_t* m )
  1027. { return sizeof(cmMidiTrackMsg_t) + m->byteCnt; }
  1028. cmMidiTrackMsg_t* cmMidiFilePackTrackMsg( const cmMidiTrackMsg_t* m, void* buf, unsigned bufByteCnt )
  1029. {
  1030. unsigned n = sizeof(cmMidiTrackMsg_t) + m->byteCnt;
  1031. if( n < bufByteCnt )
  1032. {
  1033. assert(0);
  1034. return NULL;
  1035. }
  1036. // copy the cmMidiTrackMsg_t into the buffer
  1037. memcpy(buf, m, sizeof(cmMidiTrackMsg_t));
  1038. if( m->byteCnt > 0 )
  1039. {
  1040. // copy any linked data into the buffer
  1041. memcpy(buf + sizeof(cmMidiTrackMsg_t), m->u.voidPtr, m->byteCnt );
  1042. // fixup the linked data ptr
  1043. cmMidiTrackMsg_t* mp = (cmMidiTrackMsg_t*)buf;
  1044. mp->u.voidPtr = buf + sizeof(cmMidiTrackMsg_t);
  1045. }
  1046. return (cmMidiTrackMsg_t*)buf;
  1047. }
  1048. void cmMidiFilePrint( cmMidiFileH_t h, unsigned trkIdx, cmRpt_t* rpt )
  1049. {
  1050. const _cmMidiFile_t* mfp = _cmMidiFileHandleToPtr(h);
  1051. if( mfp->fn != NULL )
  1052. cmRptPrintf(rpt,"%s ",mfp->fn);
  1053. cmRptPrintf(rpt,"fmt:%i ticksPerQN:%i tracks:%i\n",mfp->fmtId,mfp->ticksPerQN,mfp->trkN);
  1054. int i = trkIdx == cmInvalidIdx ? 0 : trkIdx;
  1055. int n = trkIdx == cmInvalidIdx ? mfp->trkN : trkIdx+1;
  1056. for(; i<n; ++i)
  1057. {
  1058. cmRptPrintf(rpt,"Track:%i\n",i);
  1059. cmMidiTrackMsg_t* tmp = mfp->trkV[i].base;
  1060. while( tmp != NULL )
  1061. {
  1062. cmRptPrintf(rpt,"%5i ", tmp->dtick );
  1063. if( tmp->status == kMetaStId )
  1064. cmRptPrintf(rpt,"%s ", cmMidiMetaStatusToLabel(tmp->metaId));
  1065. else
  1066. {
  1067. cmRptPrintf(rpt,"%4s %3i %3i %3i", cmMidiStatusToLabel(tmp->status),tmp->u.chMsgPtr->ch,tmp->u.chMsgPtr->d0,tmp->u.chMsgPtr->d1);
  1068. }
  1069. cmRptPrintf(rpt,"\n");
  1070. tmp = tmp->link;
  1071. }
  1072. }
  1073. }
  1074. bool cmMidiFileIsNull( cmMidiFileH_t h )
  1075. { return (_cmMidiFile_t*)h.h == NULL; }
  1076. void cmMidiFileTestPrint( void* printDataPtr, const char* fmt, va_list vl )
  1077. { vprintf(fmt,vl); }
  1078. void cmMidiFilePrintControlNumbers( cmCtx_t* ctx, const char* fn )
  1079. {
  1080. cmMidiFileH_t h = cmMidiFileNullHandle;
  1081. cmMfRC_t rc;
  1082. if((rc = cmMidiFileOpen(fn, &h, ctx )) != kOkMfRC )
  1083. {
  1084. cmErrMsg(&ctx->err,rc,"MIDI file open failed on '%s'.",fn);
  1085. goto errLabel;
  1086. }
  1087. const cmMidiTrackMsg_t** mm;
  1088. unsigned n = cmMidiFileMsgCount(h);
  1089. if((mm = cmMidiFileMsgArray(h)) != NULL )
  1090. {
  1091. unsigned j;
  1092. for(j=0; j<n; ++j)
  1093. {
  1094. const cmMidiTrackMsg_t* m = mm[j];
  1095. if( m->status == kCtlMdId && m->u.chMsgPtr->d0==66 )
  1096. printf("%i %i\n",m->u.chMsgPtr->d0,m->u.chMsgPtr->d1);
  1097. }
  1098. }
  1099. errLabel:
  1100. cmMidiFileClose(&h);
  1101. }
  1102. void cmMidiFileTest( const char* fn, cmCtx_t* ctx )
  1103. {
  1104. cmMfRC_t rc;
  1105. cmMidiFileH_t h = cmMidiFileNullHandle;
  1106. if((rc = cmMidiFileOpen(fn,&h,ctx)) != kOkMfRC )
  1107. {
  1108. printf("Error:%i Unable to open the cmMidi file: %s\n",rc,fn);
  1109. return;
  1110. }
  1111. if(1)
  1112. {
  1113. //cmMidiFilePrint(h,cmMidiFileTrackCount(h)-1,&ctx->rpt);
  1114. //cmMidiFilePrint(h,cmInvalidIdx,&ctx->rpt);
  1115. cmMidiFilePrintControlNumbers(ctx, fn );
  1116. }
  1117. if( 0 )
  1118. {
  1119. printf("Tracks:%i\n",cmMidiFileTrackCount(h));
  1120. unsigned i = 0;
  1121. for(i=0; i<cmMidiFileMsgCount(h); ++i)
  1122. {
  1123. cmMidiTrackMsg_t* tmp = (cmMidiTrackMsg_t*)cmMidiFileMsgArray(h)[i];
  1124. if( tmp->status==kMetaStId && tmp->metaId == kTempoMdId )
  1125. {
  1126. double bpm = 60000000.0/tmp->u.iVal;
  1127. printf("Tempo:%i %f\n",tmp->u.iVal,bpm);
  1128. tmp->u.iVal = floor( 60000000.0/69.0 );
  1129. break;
  1130. }
  1131. }
  1132. cmMidiFileWrite(h,"/home/kevin/temp/test0.mid");
  1133. }
  1134. cmMidiFileClose(&h);
  1135. }