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 50KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956
  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. bool msgVDirtyFl; // msgV[] needs to be refreshed from trkV[] because new msg's were inserted.
  41. unsigned nextUid; // next available msg uid
  42. } _cmMidiFile_t;
  43. cmMidiFileH_t cmMidiFileNullHandle = cmSTATIC_NULL_HANDLE;
  44. const cmMidiTrackMsg_t** _cmMidiFileMsgArray( _cmMidiFile_t* p );
  45. _cmMidiFile_t* _cmMidiFileHandleToPtr( cmMidiFileH_t h )
  46. {
  47. _cmMidiFile_t* p = (_cmMidiFile_t*)h.h;
  48. assert( p != NULL );
  49. return p;
  50. }
  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 = cmLhAllocZ(mfp->lhH,char,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 = cmLhAllocZ(mfp->lhH,char,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. cmMidiTrackMsg_t* _cmMidiFileAllocMsg( _cmMidiFile_t* mfp, unsigned short trkIdx, unsigned dtick, cmMidiByte_t status )
  126. {
  127. cmMidiTrackMsg_t* tmp = cmLhAllocZ(mfp->lhH,cmMidiTrackMsg_t, 1 );
  128. // set the generic track record fields
  129. tmp->dtick = dtick;
  130. tmp->status = status;
  131. tmp->metaId = kInvalidMetaMdId;
  132. tmp->trkIdx = trkIdx;
  133. tmp->byteCnt = 0;
  134. tmp->uid = mfp->nextUid++;
  135. return tmp;
  136. }
  137. cmMfRC_t _cmMidiFileAppendTrackMsg( _cmMidiFile_t* mfp, unsigned short trkIdx, unsigned dtick, cmMidiByte_t status, cmMidiTrackMsg_t** trkMsgPtrPtr )
  138. {
  139. cmMidiTrackMsg_t* tmp = _cmMidiFileAllocMsg( mfp, trkIdx, dtick, status );
  140. // link new record onto track record chain
  141. if( mfp->trkV[trkIdx].base == NULL )
  142. mfp->trkV[trkIdx].base = tmp;
  143. else
  144. mfp->trkV[trkIdx].last->link = tmp;
  145. mfp->trkV[trkIdx].last = tmp;
  146. mfp->trkV[trkIdx].cnt++;
  147. *trkMsgPtrPtr = tmp;
  148. return kOkMfRC;
  149. }
  150. cmMfRC_t _cmMidiFileReadSysEx( _cmMidiFile_t* mfp, cmMidiTrackMsg_t* tmp, unsigned byteN )
  151. {
  152. cmMfRC_t rc = kOkMfRC;
  153. cmMidiByte_t b = 0;
  154. if( byteN == cmInvalidCnt )
  155. {
  156. long offs;
  157. if( cmFileTell(mfp->fh,&offs) != kOkFileRC )
  158. return cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI File 'tell' failed.");
  159. byteN = 0;
  160. // get the length of the sys-ex msg
  161. while( !cmFileEof(mfp->fh) && (b != kSysComEoxMdId) )
  162. {
  163. if((rc = _cmMidiFileRead8(mfp,&b)) != kOkMfRC )
  164. return rc;
  165. ++byteN;
  166. }
  167. // verify that the EOX byte was found
  168. if( b != kSysComEoxMdId )
  169. return cmErrMsg(&mfp->err,kMissingEoxMfRC,"MIDI file missing 'end-of-sys-ex'.");
  170. // rewind to the beginning of the msg
  171. if( cmFileSeek(mfp->fh,kBeginFileFl,offs) != kOkFileRC )
  172. return cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file seek failed on sys-ex read.");
  173. }
  174. // allocate memory to hold the sys-ex msg
  175. cmMidiByte_t* mp = cmLhAllocZ(mfp->lhH,cmMidiByte_t, byteN );
  176. // read the sys-ex msg from the file into msg memory
  177. if( cmFileReadUChar(mfp->fh,mp,byteN) != kOkFileRC )
  178. return cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI sys-ex read failed.");
  179. tmp->byteCnt = byteN;
  180. tmp->u.sysExPtr = mp;
  181. return rc;
  182. }
  183. cmMfRC_t _cmMidiFileReadChannelMsg( _cmMidiFile_t* mfp, cmMidiByte_t* rsPtr, cmMidiByte_t status, cmMidiTrackMsg_t* tmp )
  184. {
  185. cmMfRC_t rc = kOkMfRC;
  186. cmMidiChMsg_t* p = cmLhAllocZ(mfp->lhH,cmMidiChMsg_t,1);
  187. unsigned useRsFl = status <= 0x7f;
  188. cmMidiByte_t statusCh = useRsFl ? *rsPtr : status;
  189. if( useRsFl )
  190. p->d0 = status;
  191. else
  192. *rsPtr = status;
  193. tmp->byteCnt = sizeof(cmMidiChMsg_t);
  194. tmp->status = statusCh & 0xf0;
  195. p->ch = statusCh & 0x0f;
  196. p->durMicros = 0;
  197. unsigned byteN = cmMidiStatusToByteCount(tmp->status);
  198. if( byteN==kInvalidMidiByte || byteN > 2 )
  199. return cmErrMsg(&mfp->err,kInvalidStatusMfRC,"Invalid status:0x%x %i.",tmp->status,tmp->status);
  200. unsigned i;
  201. for(i=useRsFl; i<byteN; ++i)
  202. {
  203. cmMidiByte_t* b = i==0 ? &p->d0 : &p->d1;
  204. if((rc = _cmMidiFileRead8(mfp,b)) != kOkMfRC )
  205. return rc;
  206. }
  207. // convert note-on velocity=0 to note off
  208. if( tmp->status == kNoteOnMdId && p->d1==0 )
  209. tmp->status = kNoteOffMdId;
  210. tmp->u.chMsgPtr = p;
  211. return rc;
  212. }
  213. cmMfRC_t _cmMidiFileReadMetaMsg( _cmMidiFile_t* mfp, cmMidiTrackMsg_t* tmp )
  214. {
  215. cmMidiByte_t metaId;
  216. cmMfRC_t rc;
  217. unsigned byteN = 0;
  218. if((rc = _cmMidiFileRead8(mfp,&metaId)) != kOkMfRC )
  219. return rc;
  220. if((rc = _cmMidiFileReadVarLen(mfp,&byteN)) != kOkMfRC )
  221. return rc;
  222. //printf("mt: %i 0x%x n:%i\n",metaId,metaId,byteN);
  223. switch( metaId )
  224. {
  225. case kSeqNumbMdId: rc = _cmMidiFileRead16(mfp,&tmp->u.sVal); break;
  226. case kTextMdId: rc = _cmMidiFileReadText(mfp,tmp,byteN); break;
  227. case kCopyMdId: rc = _cmMidiFileReadText(mfp,tmp,byteN); break;
  228. case kTrkNameMdId: rc = _cmMidiFileReadText(mfp,tmp,byteN); break;
  229. case kInstrNameMdId: rc = _cmMidiFileReadText(mfp,tmp,byteN); break;
  230. case kLyricsMdId: rc = _cmMidiFileReadText(mfp,tmp,byteN); break;
  231. case kMarkerMdId: rc = _cmMidiFileReadText(mfp,tmp,byteN); break;
  232. case kCuePointMdId: rc = _cmMidiFileReadText(mfp,tmp,byteN); break;
  233. case kMidiChMdId: rc = _cmMidiFileRead8(mfp,&tmp->u.bVal); break;
  234. case kEndOfTrkMdId: break;
  235. case kTempoMdId: rc = _cmMidiFileRead24(mfp,&tmp->u.iVal); break;
  236. case kSmpteMdId: rc = _cmMidiFileReadRecd(mfp,tmp,sizeof(cmMidiSmpte_t)); break;
  237. case kTimeSigMdId: rc = _cmMidiFileReadRecd(mfp,tmp,sizeof(cmMidiTimeSig_t)); break;
  238. case kKeySigMdId: rc = _cmMidiFileReadRecd(mfp,tmp,sizeof(cmMidiKeySig_t)); break;
  239. case kSeqSpecMdId: rc = _cmMidiFileReadSysEx(mfp,tmp,byteN); break;
  240. default:
  241. cmFileSeek(mfp->fh,kCurFileFl,byteN);
  242. rc = cmErrMsg(&mfp->err,kUnknownMetaIdMfRC,"Unknown meta status:0x%x %i.",metaId,metaId);
  243. }
  244. tmp->metaId = metaId;
  245. return rc;
  246. }
  247. cmMfRC_t _cmMidiFileReadTrack( _cmMidiFile_t* mfp, unsigned short trkIdx )
  248. {
  249. cmMfRC_t rc = kOkMfRC;
  250. unsigned dticks = 0;
  251. cmMidiByte_t status;
  252. cmMidiByte_t runstatus = 0;
  253. bool contFl = true;
  254. while( contFl && (rc==kOkMfRC))
  255. {
  256. cmMidiTrackMsg_t* tmp = NULL;
  257. // read the tick count
  258. if((rc = _cmMidiFileReadVarLen(mfp,&dticks)) != kOkMfRC )
  259. return rc;
  260. // read the status byte
  261. if((rc = _cmMidiFileRead8(mfp,&status)) != kOkMfRC )
  262. return rc;
  263. //printf("st:%i 0x%x\n",status,status);
  264. // append a track msg
  265. if((rc = _cmMidiFileAppendTrackMsg( mfp, trkIdx, dticks, status, &tmp )) != kOkMfRC )
  266. return rc;
  267. // switch on status
  268. switch( status )
  269. {
  270. // handle sys-ex msg
  271. case kSysExMdId:
  272. rc = _cmMidiFileReadSysEx(mfp,tmp,cmInvalidCnt);
  273. break;
  274. // handle meta msg
  275. case kMetaStId:
  276. rc = _cmMidiFileReadMetaMsg(mfp,tmp);
  277. // ignore unknown meta messages
  278. if( rc == kUnknownMetaIdMfRC )
  279. rc = kOkMfRC;
  280. contFl = tmp->metaId != kEndOfTrkMdId;
  281. break;
  282. default:
  283. // handle channel msg
  284. rc = _cmMidiFileReadChannelMsg(mfp,&runstatus,status,tmp);
  285. }
  286. }
  287. return rc;
  288. }
  289. cmMfRC_t _cmMidiFileReadHdr( _cmMidiFile_t* mfp )
  290. {
  291. cmMfRC_t rc;
  292. unsigned fileId;
  293. unsigned chunkByteN;
  294. // read the file id
  295. if((rc = _cmMidiFileRead32(mfp,&fileId)) != kOkMfRC )
  296. return rc;
  297. // verify the file id
  298. if( fileId != 'MThd' )
  299. return cmErrMsg(&mfp->err,kNotAMidiFileMfRC,"");
  300. // read the file chunk byte count
  301. if((rc = _cmMidiFileRead32(mfp,&chunkByteN)) != kOkMfRC )
  302. return rc;
  303. // read the format id
  304. if((rc = _cmMidiFileRead16(mfp,&mfp->fmtId)) != kOkMfRC )
  305. return rc;
  306. // read the track count
  307. if((rc = _cmMidiFileRead16(mfp,&mfp->trkN)) != kOkMfRC )
  308. return rc;
  309. // read the ticks per quarter note
  310. if((rc = _cmMidiFileRead16(mfp,&mfp->ticksPerQN)) != kOkMfRC )
  311. return rc;
  312. // if the division field was given in smpte
  313. if( mfp->ticksPerQN & 0x8000 )
  314. {
  315. mfp->smpteFmtId = (mfp->ticksPerQN & 0x7f00) >> 8;
  316. mfp->smpteTicksPerFrame = (mfp->ticksPerQN & 0xFF);
  317. mfp->ticksPerQN = 0;
  318. }
  319. // allocate and zero the track array
  320. if( mfp->trkN )
  321. mfp->trkV = cmLhAllocZ(mfp->lhH, _cmMidiTrack_t, mfp->trkN);
  322. return rc;
  323. }
  324. int _cmMidiFileSortFunc( const void *p0, const void* p1 )
  325. {
  326. if( (*(cmMidiTrackMsg_t**)p0)->atick == (*(cmMidiTrackMsg_t**)p1)->atick )
  327. return 0;
  328. return (*(cmMidiTrackMsg_t**)p0)->atick < (*(cmMidiTrackMsg_t**)p1)->atick ? -1 : 1;
  329. }
  330. // Set the absolute accumulated ticks (atick) value of each track message.
  331. // The absolute accumulated ticks gives a global time ordering for all
  332. // messages in the file.
  333. void _cmMidiFileSetAccumulateTicks( _cmMidiFile_t* p )
  334. {
  335. cmMidiTrackMsg_t* nextTrkMsg[ p->trkN ]; // next msg in each track
  336. unsigned long long atick = 0;
  337. unsigned i;
  338. bool fl = true;
  339. // iniitalize nextTrkTick[] and nextTrkMsg[] to the first msg in each track
  340. for(i=0; i<p->trkN; ++i)
  341. if((nextTrkMsg[i] = p->trkV[i].base) != NULL )
  342. nextTrkMsg[i]->atick = nextTrkMsg[i]->dtick;
  343. while(1)
  344. {
  345. unsigned k = cmInvalidIdx;
  346. // find the trk which has the next msg (min atick time)
  347. for(i=0; i<p->trkN; ++i)
  348. if( nextTrkMsg[i]!=NULL && (k==cmInvalidIdx || nextTrkMsg[i]->atick < nextTrkMsg[k]->atick) )
  349. k = i;
  350. // no next msg was found - we're done
  351. if( k == cmInvalidIdx )
  352. break;
  353. if( fl && nextTrkMsg[k]->dtick > 0 )
  354. {
  355. fl = false;
  356. nextTrkMsg[k]->dtick = 1;
  357. nextTrkMsg[k]->atick = 1;
  358. }
  359. // store the current atick
  360. atick = nextTrkMsg[k]->atick;
  361. // advance the selected track to it's next message
  362. nextTrkMsg[k] = nextTrkMsg[k]->link;
  363. // set the selected tracks next atick time
  364. if( nextTrkMsg[k] != NULL )
  365. nextTrkMsg[k]->atick = atick + nextTrkMsg[k]->dtick;
  366. }
  367. }
  368. void _cmMidiFileSetAbsoluteTime( _cmMidiFile_t* mfp )
  369. {
  370. const cmMidiTrackMsg_t** msgV = _cmMidiFileMsgArray(mfp);
  371. double microsPerQN = 60000000/120; // default tempo;
  372. double microsPerTick = microsPerQN / mfp->ticksPerQN;
  373. unsigned long long amicro = 0;
  374. unsigned i;
  375. for(i=0; i<mfp->msgN; ++i)
  376. {
  377. cmMidiTrackMsg_t* mp = (cmMidiTrackMsg_t*)msgV[i]; // cast away const
  378. unsigned dtick = 0;
  379. if( i > 0 )
  380. {
  381. // atick must have already been set and sorted
  382. assert( mp->atick >= msgV[i-1]->atick );
  383. dtick = mp->atick - msgV[i-1]->atick;
  384. }
  385. amicro += microsPerTick * dtick;
  386. mp->amicro = amicro;
  387. // track tempo changes
  388. if( mp->status == kMetaStId && mp->metaId == kTempoMdId )
  389. microsPerTick = mp->u.iVal / mfp->ticksPerQN;
  390. }
  391. }
  392. cmMfRC_t _cmMidiFileClose( _cmMidiFile_t* mfp )
  393. {
  394. cmMfRC_t rc = kOkMfRC;
  395. if( mfp == NULL )
  396. return rc;
  397. cmMemPtrFree(&mfp->msgV);
  398. if( cmFileIsValid( mfp->fh ) )
  399. if( cmFileClose( &mfp->fh ) != kOkFileRC )
  400. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file close failed.");
  401. if( cmLHeapIsValid( mfp->lhH ) )
  402. cmLHeapDestroy(&mfp->lhH);
  403. cmMemPtrFree(&mfp);
  404. return rc;
  405. }
  406. void _cmMidiFileLinearize( _cmMidiFile_t* mfp )
  407. {
  408. unsigned trkIdx,i,j;
  409. if( mfp->msgVDirtyFl == false )
  410. return;
  411. mfp->msgVDirtyFl = false;
  412. // get the total trk msg count
  413. mfp->msgN = 0;
  414. for(trkIdx=0; trkIdx<mfp->trkN; ++trkIdx)
  415. mfp->msgN += mfp->trkV[ trkIdx ].cnt;
  416. // allocate the trk msg index vector: msgV[]
  417. mfp->msgV = cmMemResizeZ(cmMidiTrackMsg_t*, mfp->msgV, mfp->msgN);
  418. // store a pointer to every trk msg in msgV[]
  419. for(i=0,j=0; i<mfp->trkN; ++i)
  420. {
  421. cmMidiTrackMsg_t* m = mfp->trkV[i].base;
  422. for(; m!=NULL; m=m->link)
  423. {
  424. assert( j < mfp->msgN );
  425. mfp->msgV[j++] = m;
  426. }
  427. }
  428. // set the atick value in each msg
  429. _cmMidiFileSetAccumulateTicks(mfp);
  430. // sort msgV[] in ascending order on atick
  431. qsort( mfp->msgV, mfp->msgN, sizeof(cmMidiTrackMsg_t*), _cmMidiFileSortFunc );
  432. // set the amicro value in each msg
  433. _cmMidiFileSetAbsoluteTime(mfp);
  434. }
  435. // Note that p->msgV[] should always be accessed through this function
  436. // to guarantee that the p->msgVDirtyFl is checked and msgV[] is updated
  437. // in case msgV[] is out of sync (due to inserted msgs (see cmMidiFileInsertTrackMsg())
  438. // with trkV[].
  439. const cmMidiTrackMsg_t** _cmMidiFileMsgArray( _cmMidiFile_t* p )
  440. {
  441. _cmMidiFileLinearize(p);
  442. // this cast is needed to eliminate an apparently needless 'incompatible type' warning
  443. return (const cmMidiTrackMsg_t**)p->msgV;
  444. }
  445. cmMfRC_t _cmMidiFileCreate( cmCtx_t* ctx, cmMidiFileH_t* hp )
  446. {
  447. cmMfRC_t rc = kOkMfRC;
  448. _cmMidiFile_t* p = NULL;
  449. if((rc = cmMidiFileClose(hp)) != kOkMfRC )
  450. return rc;
  451. // allocate the midi file object
  452. if(( p = cmMemAllocZ( _cmMidiFile_t, 1)) == NULL )
  453. return rc = cmErrMsg(&ctx->err,kMemAllocFailMfRC,"MIDI file memory allocation failed.");
  454. cmErrSetup(&p->err,&ctx->rpt,"MIDI File");
  455. // allocate the linked heap
  456. if( cmLHeapIsValid( p->lhH = cmLHeapCreate( 1024, ctx )) == false )
  457. rc = cmErrMsg(&p->err,kMemAllocFailMfRC,"MIDI heap allocation failed.");
  458. if( rc != kOkMfRC )
  459. _cmMidiFileClose(p);
  460. else
  461. hp->h = p;
  462. return rc;
  463. }
  464. cmMfRC_t cmMidiFileOpen( cmCtx_t* ctx, cmMidiFileH_t* hp, const char* fn )
  465. {
  466. cmMfRC_t rc = kOkMfRC;
  467. unsigned short trkIdx = 0;
  468. if((rc = _cmMidiFileCreate(ctx,hp)) != kOkMfRC )
  469. return rc;
  470. _cmMidiFile_t* p = _cmMidiFileHandleToPtr(*hp);
  471. // open the file
  472. if(cmFileOpen(&p->fh,fn,kReadFileFl | kBinaryFileFl,p->err.rpt) != kOkFileRC )
  473. {
  474. rc = cmErrMsg(&p->err,kFileFailMfRC,"MIDI file open failed.");
  475. goto errLabel;
  476. }
  477. // read header and setup track array
  478. if(( rc = _cmMidiFileReadHdr(p)) != kOkMfRC )
  479. goto errLabel;
  480. while( !cmFileEof(p->fh) && trkIdx < p->trkN )
  481. {
  482. unsigned chkId = 0,chkN=0;
  483. // read the chunk id
  484. if((rc = _cmMidiFileRead32(p,&chkId)) != kOkMfRC )
  485. goto errLabel;
  486. // read the chunk size
  487. if((rc = _cmMidiFileRead32(p,&chkN)) != kOkMfRC )
  488. goto errLabel;
  489. // if this is not a trk chunk then skip it
  490. if( chkId != (unsigned)'MTrk')
  491. {
  492. //if( fseek( p->fp, chkN, SEEK_CUR) != 0 )
  493. if( cmFileSeek(p->fh,kCurFileFl,chkN) != kOkFileRC )
  494. {
  495. rc = cmErrMsg(&p->err,kFileFailMfRC,"MIDI file seek failed.");
  496. goto errLabel;
  497. }
  498. }
  499. else
  500. {
  501. if((rc = _cmMidiFileReadTrack(p,trkIdx)) != kOkMfRC )
  502. goto errLabel;
  503. ++trkIdx;
  504. }
  505. }
  506. // store the file name
  507. p->fn = cmLhAllocZ(p->lhH,char,strlen(fn)+1);
  508. assert( p->fn != NULL );
  509. strcpy(p->fn,fn);
  510. p->msgVDirtyFl = true;
  511. _cmMidiFileLinearize(p);
  512. errLabel:
  513. if( cmFileClose(&p->fh) != kOkFileRC )
  514. rc = cmErrMsg(&p->err,kFileFailMfRC,"MIDI file close failed.");
  515. if( rc != kOkMfRC )
  516. _cmMidiFileClose(p);
  517. return rc;
  518. }
  519. cmMfRC_t cmMidiFileCreate( cmCtx_t* ctx, cmMidiFileH_t* hp, unsigned trkN, unsigned ticksPerQN )
  520. {
  521. cmMfRC_t rc = kOkMfRC;
  522. if((rc = _cmMidiFileCreate(ctx,hp)) != kOkMfRC )
  523. return rc;
  524. _cmMidiFile_t* p = _cmMidiFileHandleToPtr(*hp);
  525. p->ticksPerQN = ticksPerQN;
  526. p->fmtId = 1;
  527. p->trkN = trkN;
  528. p->trkV = cmLhAllocZ(p->lhH, _cmMidiTrack_t, p->trkN);
  529. return rc;
  530. }
  531. cmMfRC_t cmMidiFileClose( cmMidiFileH_t* hp )
  532. {
  533. cmMfRC_t rc = kOkMfRC;
  534. if( hp==NULL || cmMidiFileIsValid(*hp)==false )
  535. return kOkMfRC;
  536. _cmMidiFile_t* p = _cmMidiFileHandleToPtr(*hp);
  537. if((rc = _cmMidiFileClose(p)) != kOkMfRC )
  538. return rc;
  539. hp->h = NULL;
  540. return rc;
  541. }
  542. cmMfRC_t _cmMidiFileWrite8( _cmMidiFile_t* mfp, unsigned char v )
  543. {
  544. cmMfRC_t rc = kOkMfRC;
  545. if( cmFileWriteUChar(mfp->fh,&v,1) != kOkFileRC )
  546. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file byte write failed.");
  547. return rc;
  548. }
  549. cmMfRC_t _cmMidiFileWrite16( _cmMidiFile_t* mfp, unsigned short v )
  550. {
  551. cmMfRC_t rc = kOkMfRC;
  552. v = mfSwap16(v);
  553. if( cmFileWriteUShort(mfp->fh,&v,1) != kOkFileRC )
  554. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file short integer write failed.");
  555. return rc;
  556. }
  557. cmMfRC_t _cmMidiFileWrite24( _cmMidiFile_t* mfp, unsigned v )
  558. {
  559. cmMfRC_t rc = kOkMfRC;
  560. unsigned mask = 0xff0000;
  561. int i;
  562. for(i = 2; i>=0; --i)
  563. {
  564. unsigned char c = (v & mask) >> (i*8);
  565. mask >>= 8;
  566. if( cmFileWriteUChar(mfp->fh,&c,1) != kOkFileRC )
  567. {
  568. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file 24 bit integer write failed.");
  569. goto errLabel;
  570. }
  571. }
  572. errLabel:
  573. return rc;
  574. }
  575. cmMfRC_t _cmMidiFileWrite32( _cmMidiFile_t* mfp, unsigned v )
  576. {
  577. cmMfRC_t rc = kOkMfRC;
  578. v = mfSwap32(v);
  579. if( cmFileWriteUInt(mfp->fh,&v,1) != kOkFileRC )
  580. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file integer write failed.");
  581. return rc;
  582. }
  583. cmMfRC_t _cmMidiFileWriteRecd( _cmMidiFile_t* mfp, const void* v, unsigned byteCnt )
  584. {
  585. cmMfRC_t rc = kOkMfRC;
  586. if( cmFileWriteChar(mfp->fh,v,byteCnt) != kOkFileRC )
  587. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file write record failed.");
  588. return rc;
  589. }
  590. cmMfRC_t _cmMidiFileWriteVarLen( _cmMidiFile_t* mfp, unsigned v )
  591. {
  592. cmMfRC_t rc = kOkMfRC;
  593. unsigned buf = v & 0x7f;
  594. while((v >>= 7) > 0 )
  595. {
  596. buf <<= 8;
  597. buf |= 0x80;
  598. buf += (v & 0x7f);
  599. }
  600. while(1)
  601. {
  602. unsigned char c = (unsigned char)(buf & 0xff);
  603. if( cmFileWriteUChar(mfp->fh,&c,1) != kOkFileRC )
  604. {
  605. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file variable length integer write failed.");
  606. goto errLabel;
  607. }
  608. if( buf & 0x80 )
  609. buf >>= 8;
  610. else
  611. break;
  612. }
  613. errLabel:
  614. return rc;
  615. }
  616. cmMfRC_t _cmMidiFileWriteHdr( _cmMidiFile_t* mfp )
  617. {
  618. cmMfRC_t rc;
  619. unsigned fileId = 'MThd';
  620. unsigned chunkByteN = 6;
  621. // write the file id ('MThd')
  622. if((rc = _cmMidiFileWrite32(mfp,fileId)) != kOkMfRC )
  623. return rc;
  624. // write the file chunk byte count (always 6)
  625. if((rc = _cmMidiFileWrite32(mfp,chunkByteN)) != kOkMfRC )
  626. return rc;
  627. // write the MIDI file format id (0,1,2)
  628. if((rc = _cmMidiFileWrite16(mfp,mfp->fmtId)) != kOkMfRC )
  629. return rc;
  630. // write the track count
  631. if((rc = _cmMidiFileWrite16(mfp,mfp->trkN)) != kOkMfRC )
  632. return rc;
  633. unsigned short v = 0;
  634. // if the ticks per quarter note field is valid ...
  635. if( mfp->ticksPerQN )
  636. v = mfp->ticksPerQN;
  637. else
  638. {
  639. // ... otherwise the division field was given in smpte
  640. v = mfp->smpteFmtId << 8;
  641. v += mfp->smpteTicksPerFrame;
  642. }
  643. if((rc = _cmMidiFileWrite16(mfp,v)) != kOkMfRC )
  644. return rc;
  645. return rc;
  646. }
  647. cmMfRC_t _cmMidiFileWriteSysEx( _cmMidiFile_t* mfp, cmMidiTrackMsg_t* tmp )
  648. {
  649. cmMfRC_t rc = kOkMfRC;
  650. if((rc = _cmMidiFileWrite8(mfp,kSysExMdId)) != kOkMfRC )
  651. goto errLabel;
  652. if( cmFileWriteUChar(mfp->fh,tmp->u.sysExPtr,tmp->byteCnt) != kOkFileRC )
  653. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"Sys-ex msg write failed.");
  654. errLabel:
  655. return rc;
  656. }
  657. cmMfRC_t _cmMidiFileWriteChannelMsg( _cmMidiFile_t* mfp, const cmMidiTrackMsg_t* tmp, cmMidiByte_t* runStatus )
  658. {
  659. cmMfRC_t rc = kOkMfRC;
  660. unsigned byteN = cmMidiStatusToByteCount(tmp->status);
  661. cmMidiByte_t status = tmp->status + tmp->u.chMsgPtr->ch;
  662. if( status != *runStatus )
  663. {
  664. *runStatus = status;
  665. if((rc = _cmMidiFileWrite8(mfp,status)) != kOkMfRC )
  666. goto errLabel;
  667. }
  668. if(byteN>=1)
  669. if((rc = _cmMidiFileWrite8(mfp,tmp->u.chMsgPtr->d0)) != kOkMfRC )
  670. goto errLabel;
  671. if(byteN>=2)
  672. if((rc = _cmMidiFileWrite8(mfp,tmp->u.chMsgPtr->d1)) != kOkMfRC )
  673. goto errLabel;
  674. errLabel:
  675. return rc;
  676. }
  677. cmMfRC_t _cmMidiFileWriteMetaMsg( _cmMidiFile_t* mfp, const cmMidiTrackMsg_t* tmp )
  678. {
  679. cmMfRC_t rc;
  680. if((rc = _cmMidiFileWrite8(mfp,kMetaStId)) != kOkMfRC )
  681. return rc;
  682. if((rc = _cmMidiFileWrite8(mfp,tmp->metaId)) != kOkMfRC )
  683. return rc;
  684. switch( tmp->metaId )
  685. {
  686. case kSeqNumbMdId:
  687. if((rc = _cmMidiFileWrite8(mfp,sizeof(tmp->u.sVal))) == kOkMfRC )
  688. rc = _cmMidiFileWrite16(mfp,tmp->u.sVal);
  689. break;
  690. case kTempoMdId:
  691. if((rc = _cmMidiFileWrite8(mfp,3)) == kOkMfRC )
  692. rc = _cmMidiFileWrite24(mfp,tmp->u.iVal);
  693. break;
  694. case kSmpteMdId:
  695. if((rc = _cmMidiFileWrite8(mfp,sizeof(cmMidiSmpte_t))) == kOkMfRC )
  696. rc = _cmMidiFileWriteRecd(mfp,tmp->u.smptePtr,sizeof(cmMidiSmpte_t));
  697. break;
  698. case kTimeSigMdId:
  699. if((rc = _cmMidiFileWrite8(mfp,sizeof(cmMidiTimeSig_t))) == kOkMfRC )
  700. rc = _cmMidiFileWriteRecd(mfp,tmp->u.timeSigPtr,sizeof(cmMidiTimeSig_t));
  701. break;
  702. case kKeySigMdId:
  703. if((rc = _cmMidiFileWrite8(mfp,sizeof(cmMidiKeySig_t))) == kOkMfRC )
  704. rc = _cmMidiFileWriteRecd(mfp,tmp->u.keySigPtr,sizeof(cmMidiKeySig_t));
  705. break;
  706. case kSeqSpecMdId:
  707. if((rc = _cmMidiFileWriteVarLen(mfp,sizeof(tmp->byteCnt))) == kOkMfRC )
  708. rc = _cmMidiFileWriteRecd(mfp,tmp->u.sysExPtr,tmp->byteCnt);
  709. break;
  710. case kMidiChMdId:
  711. if((rc = _cmMidiFileWrite8(mfp,sizeof(tmp->u.bVal))) == kOkMfRC )
  712. rc = _cmMidiFileWrite8(mfp,tmp->u.bVal);
  713. break;
  714. case kEndOfTrkMdId:
  715. rc = _cmMidiFileWrite8(mfp,0);
  716. break;
  717. case kTextMdId:
  718. case kCopyMdId:
  719. case kTrkNameMdId:
  720. case kInstrNameMdId:
  721. case kLyricsMdId:
  722. case kMarkerMdId:
  723. case kCuePointMdId:
  724. {
  725. unsigned n = tmp->u.text==NULL ? 0 : strlen(tmp->u.text);
  726. if((rc = _cmMidiFileWriteVarLen(mfp,n)) == kOkMfRC && n>0 )
  727. rc = _cmMidiFileWriteRecd(mfp,tmp->u.text,n);
  728. }
  729. break;
  730. default:
  731. {
  732. // ignore unknown meta messages
  733. }
  734. }
  735. return rc;
  736. }
  737. cmMfRC_t _cmMidiFileWriteTrack( _cmMidiFile_t* mfp, unsigned trkIdx )
  738. {
  739. cmMfRC_t rc = kOkMfRC;
  740. cmMidiTrackMsg_t* tmp = mfp->trkV[trkIdx].base;
  741. cmMidiByte_t runStatus = 0;
  742. for(; tmp != NULL; tmp=tmp->link)
  743. {
  744. // write the msg tick count
  745. if((rc = _cmMidiFileWriteVarLen(mfp,tmp->dtick)) != kOkMfRC )
  746. return rc;
  747. // switch on status
  748. switch( tmp->status )
  749. {
  750. // handle sys-ex msg
  751. case kSysExMdId:
  752. rc = _cmMidiFileWriteSysEx(mfp,tmp);
  753. break;
  754. // handle meta msg
  755. case kMetaStId:
  756. rc = _cmMidiFileWriteMetaMsg(mfp,tmp);
  757. break;
  758. default:
  759. // handle channel msg
  760. rc = _cmMidiFileWriteChannelMsg(mfp,tmp,&runStatus);
  761. }
  762. }
  763. return rc;
  764. }
  765. cmMfRC_t cmMidiFileWrite( cmMidiFileH_t h, const char* fn )
  766. {
  767. cmMfRC_t rc = kOkMfRC;
  768. _cmMidiFile_t* mfp = _cmMidiFileHandleToPtr(h);
  769. unsigned i;
  770. // create the output file
  771. if( cmFileOpen(&mfp->fh,fn,kWriteFileFl,mfp->err.rpt) != kOkFileRC )
  772. return cmErrMsg(&mfp->err,kFileFailMfRC,"The MIDI file '%s' could not be created.",cmStringNullGuard(fn));
  773. // write the file header
  774. if((rc = _cmMidiFileWriteHdr(mfp)) != kOkMfRC )
  775. {
  776. rc = cmErrMsg(&mfp->err,rc,"The file header write failed on the MIDI file '%s'.",cmStringNullGuard(fn));
  777. goto errLabel;
  778. }
  779. for(i=0; i < mfp->trkN; ++i )
  780. {
  781. unsigned chkId = 'MTrk';
  782. long offs0,offs1;
  783. // write the track chunk id ('MTrk')
  784. if((rc = _cmMidiFileWrite32(mfp,chkId)) != kOkMfRC )
  785. goto errLabel;
  786. cmFileTell(mfp->fh,&offs0);
  787. // write the track chunk size as zero
  788. if((rc = _cmMidiFileWrite32(mfp,0)) != kOkMfRC )
  789. goto errLabel;
  790. if((rc = _cmMidiFileWriteTrack(mfp,i)) != kOkMfRC )
  791. goto errLabel;
  792. cmFileTell(mfp->fh,&offs1);
  793. cmFileSeek(mfp->fh,kBeginFileFl,offs0);
  794. _cmMidiFileWrite32(mfp,offs1-offs0-4);
  795. cmFileSeek(mfp->fh,kBeginFileFl,offs1);
  796. }
  797. errLabel:
  798. cmFileClose(&mfp->fh);
  799. return rc;
  800. }
  801. bool cmMidiFileIsValid( cmMidiFileH_t h )
  802. { return h.h != NULL; }
  803. unsigned cmMidiFileTrackCount( cmMidiFileH_t h )
  804. {
  805. _cmMidiFile_t* mfp;
  806. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  807. return cmInvalidCnt;
  808. return mfp->trkN;
  809. }
  810. unsigned cmMidiFileType( cmMidiFileH_t h )
  811. {
  812. _cmMidiFile_t* mfp;
  813. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  814. return cmInvalidId;
  815. return mfp->fmtId;
  816. }
  817. const char* cmMidiFileName( cmMidiFileH_t h )
  818. {
  819. _cmMidiFile_t* mfp;
  820. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  821. return NULL;
  822. return mfp->fn;
  823. }
  824. unsigned cmMidiFileTicksPerQN( cmMidiFileH_t h )
  825. {
  826. _cmMidiFile_t* mfp;
  827. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  828. return cmInvalidCnt;
  829. return mfp->ticksPerQN;
  830. }
  831. cmMidiByte_t cmMidiFileTicksPerSmpteFrame( cmMidiFileH_t h )
  832. {
  833. _cmMidiFile_t* mfp;
  834. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  835. return kInvalidMidiByte;
  836. if( mfp->ticksPerQN != 0 )
  837. return 0;
  838. return mfp->smpteTicksPerFrame;
  839. }
  840. cmMidiByte_t cmMidiFileSmpteFormatId( cmMidiFileH_t h )
  841. {
  842. _cmMidiFile_t* mfp;
  843. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  844. return kInvalidMidiByte;
  845. if( mfp->ticksPerQN != 0 )
  846. return 0;
  847. return mfp->smpteFmtId;
  848. }
  849. unsigned cmMidiFileTrackMsgCount( cmMidiFileH_t h, unsigned trackIdx )
  850. {
  851. _cmMidiFile_t* mfp;
  852. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  853. return cmInvalidCnt;
  854. return mfp->trkV[trackIdx].cnt;
  855. }
  856. const cmMidiTrackMsg_t* cmMidiFileTrackMsg( cmMidiFileH_t h, unsigned trackIdx )
  857. {
  858. _cmMidiFile_t* mfp;
  859. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  860. return NULL;
  861. return mfp->trkV[trackIdx].base;
  862. }
  863. unsigned cmMidiFileMsgCount( cmMidiFileH_t h )
  864. {
  865. _cmMidiFile_t* mfp;
  866. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  867. return cmInvalidCnt;
  868. return mfp->msgN;
  869. }
  870. const cmMidiTrackMsg_t** cmMidiFileMsgArray( cmMidiFileH_t h )
  871. {
  872. _cmMidiFile_t* mfp;
  873. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  874. return NULL;
  875. return _cmMidiFileMsgArray(mfp);
  876. }
  877. cmMidiTrackMsg_t* _cmMidiFileUidToMsg( _cmMidiFile_t* mfp, unsigned uid )
  878. {
  879. unsigned i;
  880. const cmMidiTrackMsg_t** msgV = _cmMidiFileMsgArray(mfp);
  881. for(i=0; i<mfp->msgN; ++i)
  882. if( msgV[i]->uid == uid )
  883. return (cmMidiTrackMsg_t*)msgV[i];
  884. return NULL;
  885. }
  886. cmMfRC_t cmMidiFileSetVelocity( cmMidiFileH_t h, unsigned uid, cmMidiByte_t vel )
  887. {
  888. cmMidiTrackMsg_t* r;
  889. _cmMidiFile_t* mfp = _cmMidiFileHandleToPtr(h);
  890. assert( mfp != NULL );
  891. if((r = _cmMidiFileUidToMsg(mfp,uid)) == NULL )
  892. return cmErrMsg(&mfp->err,kUidNotFoundMfRC,"The MIDI file uid %i could not be found.",uid);
  893. if( cmMidiIsNoteOn(r->status) == false && cmMidiIsNoteOff(r->status,0)==false )
  894. return cmErrMsg(&mfp->err,kUidNotANoteMsgMfRC,"Cannot set velocity on a non-Note-On/Off msg.");
  895. cmMidiChMsg_t* chm = (cmMidiChMsg_t*)r->u.chMsgPtr;
  896. chm->d1 = vel;
  897. return kOkMfRC;
  898. }
  899. // Returns NULL if uid is not found or if it the first msg on the track.
  900. cmMidiTrackMsg_t* _cmMidiFileMsgBeforeUid( _cmMidiFile_t* p, unsigned uid )
  901. {
  902. cmMidiTrackMsg_t* m;
  903. if((m = _cmMidiFileUidToMsg(p,uid)) == NULL )
  904. return NULL;
  905. assert( m->trkIdx < p->trkN );
  906. cmMidiTrackMsg_t* m0 = NULL;
  907. cmMidiTrackMsg_t* m1 = p->trkV[ m->trkIdx ].base;
  908. for(; m1!=NULL; m1 = m1->link)
  909. {
  910. if( m1->uid == uid )
  911. break;
  912. m0 = m1;
  913. }
  914. return m0;
  915. }
  916. unsigned _cmMidiFileIsMsgFirstOnTrack( _cmMidiFile_t* p, unsigned uid )
  917. {
  918. unsigned i;
  919. for(i=0; i<p->trkN; ++i)
  920. if( p->trkV[i].base!=NULL && p->trkV[i].base->uid == uid )
  921. return i;
  922. return cmInvalidIdx;
  923. }
  924. cmMfRC_t cmMidiFileInsertMsg( cmMidiFileH_t h, unsigned uid, int dtick, cmMidiByte_t ch, cmMidiByte_t status, cmMidiByte_t d0, cmMidiByte_t d1 )
  925. {
  926. _cmMidiFile_t* mfp = _cmMidiFileHandleToPtr(h);
  927. assert( mfp != NULL );
  928. cmMidiTrackMsg_t* ref = NULL;
  929. unsigned trkIdx = cmInvalidIdx;
  930. // if dtick is positive ...
  931. if( dtick >= 0 )
  932. {
  933. ref = _cmMidiFileUidToMsg(mfp,uid); // ... then get the ref. msg.
  934. trkIdx = ref->trkIdx;
  935. }
  936. else // if dtick is negative ...
  937. {
  938. // ... get get the msg before the ref. msg.
  939. if((ref = _cmMidiFileMsgBeforeUid(mfp,uid)) != NULL )
  940. trkIdx = ref->trkIdx;
  941. else
  942. {
  943. // ... the ref. msg was first in the track so there is no msg before it
  944. trkIdx = _cmMidiFileIsMsgFirstOnTrack(mfp,uid);
  945. }
  946. }
  947. // verify that the reference msg was found
  948. if( trkIdx == cmInvalidIdx )
  949. return cmErrMsg(&mfp->err,kUidNotFoundMfRC,"The UID (%i) reference note could not be located.",uid);
  950. assert( trkIdx < mfp->trkN );
  951. // complete the msg setup
  952. _cmMidiTrack_t* trk = mfp->trkV + trkIdx;
  953. cmMidiTrackMsg_t* m = _cmMidiFileAllocMsg(mfp, trkIdx, abs(dtick), status );
  954. cmMidiChMsg_t* c = cmLhAllocZ(mfp->lhH,cmMidiChMsg_t,1);
  955. m->u.chMsgPtr = c;
  956. c->ch = ch;
  957. c->d0 = d0;
  958. c->d1 = d1;
  959. // if 'm' is prior to the first msg in the track
  960. if( ref == NULL )
  961. {
  962. // ... then make 'm' the first msg in the first msg
  963. m->link = trk->base;
  964. trk->base = m;
  965. // 'm' is before ref and the track cannot be empty (because ref is in it) 'm'
  966. // can never be the last msg in the list
  967. }
  968. else // ref is the msg before 'm'
  969. {
  970. m->link = ref->link;
  971. ref->link = m;
  972. // if ref was the last msg in the trk ...
  973. if( trk->last == ref )
  974. trk->last = m; //... then 'm' is now the last msg in the trk
  975. }
  976. trk->cnt += 1;
  977. mfp->msgVDirtyFl = true;
  978. return kOkMfRC;
  979. }
  980. cmMfRC_t cmMidiFileInsertTrackMsg( cmMidiFileH_t h, unsigned trkIdx, const cmMidiTrackMsg_t* msg )
  981. {
  982. _cmMidiFile_t* p = _cmMidiFileHandleToPtr(h);
  983. // validate the track index
  984. if( trkIdx >= p->trkN )
  985. return cmErrMsg(&p->err,kInvalidTrkIndexMfRC,"The track index (%i) is invalid.",trkIdx);
  986. // allocate a new track record
  987. cmMidiTrackMsg_t* m = (cmMidiTrackMsg_t*)cmLhAllocZ(p->lhH,char,sizeof(cmMidiTrackMsg_t)+msg->byteCnt);
  988. // fill the track record
  989. m->uid = p->nextUid++;
  990. m->atick = msg->atick;
  991. m->status = msg->status;
  992. m->metaId = msg->metaId;
  993. m->trkIdx = trkIdx;
  994. m->byteCnt = msg->byteCnt;
  995. memcpy(&m->u,&msg->u,sizeof(msg->u));
  996. // copy the exernal data
  997. if( msg->byteCnt > 0 )
  998. {
  999. m->u.voidPtr = (m+1);
  1000. memcpy((void*)m->u.voidPtr,msg->u.voidPtr,msg->byteCnt);
  1001. }
  1002. cmMidiTrackMsg_t* m0 = NULL; // msg before insertion
  1003. cmMidiTrackMsg_t* m1 = p->trkV[trkIdx].base; // msg after insertion
  1004. // locate the track record before and after the new msg based on 'atick' value
  1005. for(; m1!=NULL; m1=m1->link)
  1006. {
  1007. if( m1->atick > m->atick )
  1008. {
  1009. if( m0 == NULL )
  1010. p->trkV[trkIdx].base = m;
  1011. else
  1012. m0->link = m;
  1013. m->link = m1;
  1014. break;
  1015. }
  1016. m0 = m1;
  1017. }
  1018. // if the new track record was not inserted then it is the last msg
  1019. if( m1 == NULL )
  1020. {
  1021. assert(m0 == p->trkV[trkIdx].last);
  1022. // link in the new msg
  1023. if( m0 != NULL )
  1024. m0->link = m;
  1025. // the new msg always becomes the last msg
  1026. p->trkV[trkIdx].last = m;
  1027. // if the new msg is the first msg inserted in this track
  1028. if( p->trkV[trkIdx].base == NULL )
  1029. p->trkV[trkIdx].base = m;
  1030. }
  1031. // set the dtick field of the new msg
  1032. if( m0 != NULL )
  1033. {
  1034. assert( m->atick >= m0->atick );
  1035. m->dtick = m->atick - m0->atick;
  1036. }
  1037. // update the dtick field of the msg following the new msg
  1038. if( m1 != NULL )
  1039. {
  1040. assert( m1->atick >= m->atick );
  1041. m1->dtick = m1->atick - m->atick;
  1042. }
  1043. p->msgVDirtyFl = true;
  1044. return kOkMfRC;
  1045. }
  1046. cmMfRC_t cmMidiFileInsertTrackChMsg( cmMidiFileH_t h, unsigned trkIdx, unsigned atick, cmMidiByte_t status, cmMidiByte_t d0, cmMidiByte_t d1 )
  1047. {
  1048. cmMidiTrackMsg_t m;
  1049. cmMidiChMsg_t cm;
  1050. memset(&m,0,sizeof(m));
  1051. memset(&cm,0,sizeof(cm));
  1052. cm.ch = status & 0x0f;
  1053. cm.d0 = d0;
  1054. cm.d1 = d1;
  1055. m.atick = atick;
  1056. m.status = status & 0xf0;
  1057. m.byteCnt = sizeof(cm);
  1058. m.u.chMsgPtr = &cm;
  1059. return cmMidiFileInsertTrackMsg(h,trkIdx,&m);
  1060. }
  1061. cmMfRC_t cmMidFileInsertTrackTempoMsg( cmMidiFileH_t h, unsigned trkIdx, unsigned atick, unsigned bpm )
  1062. {
  1063. cmMidiTrackMsg_t m;
  1064. memset(&m,0,sizeof(m));
  1065. m.atick = atick;
  1066. m.status = kMetaStId;
  1067. m.metaId = kTempoMdId;
  1068. m.u.iVal = 60000000/bpm; // convert BPM to microsPerQN
  1069. return cmMidiFileInsertTrackMsg(h,trkIdx,&m);
  1070. }
  1071. unsigned cmMidiFileSeekUsecs( cmMidiFileH_t h, unsigned long long offsUSecs, unsigned* msgUsecsPtr, unsigned* microsPerTickPtr )
  1072. {
  1073. _cmMidiFile_t* p;
  1074. if((p = _cmMidiFileHandleToPtr(h)) == NULL )
  1075. return cmInvalidIdx;
  1076. if( p->msgN == 0 )
  1077. return cmInvalidIdx;
  1078. unsigned mi;
  1079. double microsPerQN = 60000000.0/120.0;
  1080. double microsPerTick = microsPerQN / p->ticksPerQN;
  1081. double accUSecs = 0;
  1082. const cmMidiTrackMsg_t** msgV = _cmMidiFileMsgArray(p);
  1083. for(mi=0; mi<p->msgN; ++mi)
  1084. {
  1085. const cmMidiTrackMsg_t* mp = msgV[mi];
  1086. if( mp->amicro >= offsUSecs )
  1087. break;
  1088. }
  1089. if( mi == p->msgN )
  1090. return cmInvalidIdx;
  1091. if( msgUsecsPtr != NULL )
  1092. *msgUsecsPtr = round(accUSecs - offsUSecs);
  1093. if( microsPerTickPtr != NULL )
  1094. *microsPerTickPtr = round(microsPerTick);
  1095. return mi;
  1096. }
  1097. double cmMidiFileDurSecs( cmMidiFileH_t h )
  1098. {
  1099. _cmMidiFile_t* mfp = _cmMidiFileHandleToPtr(h);
  1100. if( mfp->msgN == 0 )
  1101. return 0;
  1102. const cmMidiTrackMsg_t** msgV = _cmMidiFileMsgArray(mfp);
  1103. return msgV[ mfp->msgN-1 ]->amicro / 1000000.0;
  1104. }
  1105. typedef struct _cmMidiVoice_str
  1106. {
  1107. const cmMidiTrackMsg_t* mp;
  1108. unsigned durMicros;
  1109. bool sustainFl;
  1110. struct _cmMidiVoice_str* link;
  1111. } _cmMidiVoice_t;
  1112. void _cmMidiFileSetDur( cmMidiTrackMsg_t* m0, cmMidiTrackMsg_t* m1 )
  1113. {
  1114. // calculate the duration of the sounding note
  1115. ((cmMidiChMsg_t*)m0->u.chMsgPtr)->durMicros = m1->amicro - m0->amicro;
  1116. // set the note-off msg pointer
  1117. ((cmMidiChMsg_t*)m0->u.chMsgPtr)->end = m1;
  1118. }
  1119. bool _cmMidiFileCalcNoteDur( cmMidiTrackMsg_t* m0, cmMidiTrackMsg_t* m1, int noteGateFl, int sustainGateFl, bool sostGateFl )
  1120. {
  1121. // if the note is being kept sounding because the key is still depressed,
  1122. // the sustain pedal is down or it is being held by the sostenuto pedal ....
  1123. if( noteGateFl>0 || sustainGateFl>0 || sostGateFl )
  1124. return false; // ... do nothing
  1125. _cmMidiFileSetDur(m0,m1);
  1126. return true;
  1127. }
  1128. void cmMidiFileCalcNoteDurations( cmMidiFileH_t h )
  1129. {
  1130. _cmMidiFile_t* p;
  1131. if((p = _cmMidiFileHandleToPtr(h)) == NULL )
  1132. return;
  1133. if( p->msgN == 0 )
  1134. return;
  1135. unsigned mi = cmInvalidId;
  1136. cmMidiTrackMsg_t* noteM[ kMidiNoteCnt * kMidiChCnt ]; // ptr to note-on or NULL if the note is not sounding
  1137. cmMidiTrackMsg_t* sustV[ kMidiChCnt ];
  1138. cmMidiTrackMsg_t* sostV[ kMidiChCnt ];
  1139. int noteGateM[ kMidiNoteCnt * kMidiChCnt ]; // true if the associated note key is depressed
  1140. bool sostGateM[ kMidiNoteCnt * kMidiChCnt ]; // true if the associated note was active when the sost. pedal went down
  1141. int sustGateV[ kMidiChCnt]; // true if the associated sustain pedal is down
  1142. int sostGateV[ kMidiChCnt]; // true if the associated sostenuto pedal is down
  1143. unsigned i,j;
  1144. const cmMidiTrackMsg_t** msgV = _cmMidiFileMsgArray(p);
  1145. // initialize the state tracking variables
  1146. for(i=0; i<kMidiChCnt; ++i)
  1147. {
  1148. sustV[i] = NULL;
  1149. sustGateV[i] = 0;
  1150. sostV[i] = NULL;
  1151. sostGateV[i] = 0;
  1152. for(j=0; j<kMidiNoteCnt; ++j)
  1153. {
  1154. noteM[ i*kMidiNoteCnt + j ] = NULL;
  1155. noteGateM[ i*kMidiNoteCnt + j ] = 0;
  1156. sostGateM[ i*kMidiNoteCnt + j ] = false;
  1157. }
  1158. }
  1159. // for each midi event
  1160. for(mi=0; mi<p->msgN; ++mi)
  1161. {
  1162. cmMidiTrackMsg_t* m = (cmMidiTrackMsg_t*)msgV[mi]; // cast away const
  1163. // verify that time is also incrementing
  1164. assert( mi==0 || (mi>0 && m->amicro >= msgV[mi-1]->amicro) );
  1165. // ignore all non-channel messages
  1166. if( !cmMidiIsChStatus( m->status ) )
  1167. continue;
  1168. cmMidiByte_t ch = m->u.chMsgPtr->ch; // get the midi msg channel
  1169. cmMidiByte_t d0 = m->u.chMsgPtr->d0; // get the midi msg data value
  1170. // if this is a note-on msg
  1171. if( cmMidiFileIsNoteOn(m) )
  1172. {
  1173. unsigned k = ch*kMidiNoteCnt + d0;
  1174. // there should be no existing sounding note instance for this pitch
  1175. //if( noteGateM[k] == 0 && noteM[k] != NULL )
  1176. // cmErrWarnMsg(&p->err,kMissingNoteOffMfRC,"%i : Missing note-off instance for note on:%s",m->uid,cmMidiToSciPitch(d0,NULL,0));
  1177. if( noteM[k] != NULL )
  1178. noteGateM[k] += 1;
  1179. else
  1180. {
  1181. noteM[k] = m;
  1182. noteGateM[k] = 1;
  1183. }
  1184. }
  1185. else
  1186. // if this is a note-off msg
  1187. if( cmMidiFileIsNoteOff(m) )
  1188. {
  1189. unsigned k = ch*kMidiNoteCnt + d0;
  1190. cmMidiTrackMsg_t* m0 = noteM[k];
  1191. if( m0 == NULL )
  1192. cmErrWarnMsg(&p->err,kMissingNoteOffMfRC,"%i : Missing note-on instance for note-off:%s",m->uid,cmMidiToSciPitch(d0,NULL,0));
  1193. else
  1194. {
  1195. // a key was released - so it should not already be up
  1196. if( noteGateM[k]==0 )
  1197. cmErrWarnMsg(&p->err,kMissingNoteOffMfRC,"%i : Missing note-on for note-off:%s",m->uid,cmMidiToSciPitch(d0,NULL,0));
  1198. else
  1199. {
  1200. noteGateM[k] -= 1; // update the note gate state
  1201. // update the sounding note status
  1202. if( _cmMidiFileCalcNoteDur(m0, m, noteGateM[k], sustGateV[ch], sostGateM[k]) )
  1203. noteM[k] = NULL;
  1204. }
  1205. }
  1206. }
  1207. else
  1208. // This is a sustain-pedal down msg
  1209. if( cmMidiFileIsSustainPedalDown(m) )
  1210. {
  1211. // if the sustain channel is already down
  1212. //if( sustGateV[ch] )
  1213. // cmErrWarnMsg(&p->err,kSustainPedalMfRC,"%i : The sustain pedal went down twice with no intervening release.",m->uid);
  1214. sustGateV[ch] += 1;
  1215. if( sustV[ch] == NULL )
  1216. sustV[ch] = m;
  1217. }
  1218. else
  1219. // This is a sustain-pedal up msg
  1220. if( cmMidiFileIsSustainPedalUp(m) )
  1221. {
  1222. // if the sustain channel is already up
  1223. if( sustGateV[ch]==0 )
  1224. cmErrWarnMsg(&p->err,kSustainPedalMfRC,"%i : The sustain pedal release message was received with no previous pedal down.",m->uid);
  1225. if( sustGateV[ch] >= 1 )
  1226. {
  1227. sustGateV[ch] -= 1;
  1228. if( sustGateV[ch] == 0 )
  1229. {
  1230. unsigned k = ch*kMidiNoteCnt;
  1231. // for each sounding note on this channel
  1232. for(; k<ch*kMidiNoteCnt+kMidiNoteCnt; ++k)
  1233. if( noteM[k]!=NULL && _cmMidiFileCalcNoteDur(noteM[k], m, noteGateM[k], sustGateV[ch], sostGateM[k]) )
  1234. noteM[k] = NULL;
  1235. if( sustV[ch] != NULL )
  1236. {
  1237. _cmMidiFileSetDur(sustV[ch],m);
  1238. ((cmMidiChMsg_t*)sustV[ch]->u.chMsgPtr)->end = m; // set the pedal-up msg ptr. in the pedal-down msg.
  1239. sustV[ch] = NULL;
  1240. }
  1241. }
  1242. }
  1243. }
  1244. else
  1245. // This is a sostenuto pedal-down msg
  1246. if( cmMidiFileIsSostenutoPedalDown(m) )
  1247. {
  1248. // if the sustain channel is already down
  1249. //if( sostGateV[ch] )
  1250. // cmErrWarnMsg(&p->err,kSostenutoPedalMfRC,"%i : The sostenuto pedal went down twice with no intervening release.",m->uid);
  1251. // record the notes that are active when the sostenuto pedal went down
  1252. unsigned k = ch * kMidiNoteCnt;
  1253. for(i=0; i<kMidiNoteCnt; ++i)
  1254. sostGateM[k+i] = noteGateM[k+i] > 0;
  1255. sostGateV[ch] += 1;
  1256. }
  1257. else
  1258. // This is a sostenuto pedal-up msg
  1259. if( cmMidiFileIsSostenutoPedalUp(m) )
  1260. {
  1261. // if the sustain channel is already up
  1262. if( sostGateV[ch]==0 )
  1263. cmErrWarnMsg(&p->err,kSostenutoPedalMfRC,"%i : The sostenuto pedal release message was received with no previous pedal down.",m->uid);
  1264. if( sostGateV[ch] >= 1 )
  1265. {
  1266. sostGateV[ch] -= 1;
  1267. if( sostGateV[ch] == 0 )
  1268. {
  1269. unsigned k = ch*kMidiNoteCnt;
  1270. // for each note on this channel
  1271. for(; k<ch*kMidiNoteCnt+kMidiNoteCnt; ++k)
  1272. {
  1273. sostGateM[k] = false;
  1274. if( noteM[k]!=NULL && _cmMidiFileCalcNoteDur(noteM[k], m, noteGateM[k], sustGateV[ch], sostGateM[k]) )
  1275. noteM[k] = NULL;
  1276. }
  1277. if( sostV[ch] != NULL )
  1278. {
  1279. _cmMidiFileSetDur(sostV[ch],m);
  1280. ((cmMidiChMsg_t*)sostV[ch]->u.chMsgPtr)->end = m; // set the pedal-up msg ptr. in the pedal-down msg.
  1281. sostV[ch] = NULL;
  1282. }
  1283. }
  1284. }
  1285. }
  1286. } // for each midi file event
  1287. }
  1288. void cmMidiFileSetDelay( cmMidiFileH_t h, unsigned ticks )
  1289. {
  1290. _cmMidiFile_t* p;
  1291. unsigned mi;
  1292. if((p = _cmMidiFileHandleToPtr(h)) == NULL )
  1293. return;
  1294. const cmMidiTrackMsg_t** msgV = _cmMidiFileMsgArray(p);
  1295. if( p->msgN == 0 )
  1296. return;
  1297. for(mi=0; mi<p->msgN; ++mi)
  1298. {
  1299. cmMidiTrackMsg_t* mp = (cmMidiTrackMsg_t*)msgV[mi]; // cast away const
  1300. // locate the first msg which has a non-zero delta tick
  1301. if( mp->dtick > 0 )
  1302. {
  1303. mp->dtick = ticks;
  1304. break;
  1305. }
  1306. }
  1307. }
  1308. unsigned cmMidiFilePackTrackMsgBufByteCount( const cmMidiTrackMsg_t* m )
  1309. { return sizeof(cmMidiTrackMsg_t) + m->byteCnt; }
  1310. cmMidiTrackMsg_t* cmMidiFilePackTrackMsg( const cmMidiTrackMsg_t* m, void* buf, unsigned bufByteCnt )
  1311. {
  1312. unsigned n = sizeof(cmMidiTrackMsg_t) + m->byteCnt;
  1313. if( n < bufByteCnt )
  1314. {
  1315. assert(0);
  1316. return NULL;
  1317. }
  1318. // copy the cmMidiTrackMsg_t into the buffer
  1319. memcpy(buf, m, sizeof(cmMidiTrackMsg_t));
  1320. if( m->byteCnt > 0 )
  1321. {
  1322. // copy any linked data into the buffer
  1323. memcpy(buf + sizeof(cmMidiTrackMsg_t), m->u.voidPtr, m->byteCnt );
  1324. // fixup the linked data ptr
  1325. cmMidiTrackMsg_t* mp = (cmMidiTrackMsg_t*)buf;
  1326. mp->u.voidPtr = buf + sizeof(cmMidiTrackMsg_t);
  1327. }
  1328. return (cmMidiTrackMsg_t*)buf;
  1329. }
  1330. void _cmMidiFilePrintHdr( const _cmMidiFile_t* mfp, cmRpt_t* rpt )
  1331. {
  1332. if( mfp->fn != NULL )
  1333. cmRptPrintf(rpt,"%s ",mfp->fn);
  1334. cmRptPrintf(rpt,"fmt:%i ticksPerQN:%i tracks:%i\n",mfp->fmtId,mfp->ticksPerQN,mfp->trkN);
  1335. cmRptPrintf(rpt," UID dtick atick amicro type ch D0 D1\n");
  1336. cmRptPrintf(rpt,"----- ---------- ---------- ---------- : ---- --- --- ---\n");
  1337. }
  1338. void _cmMidiFilePrintMsg( cmRpt_t* rpt, const cmMidiTrackMsg_t* tmp )
  1339. {
  1340. cmRptPrintf(rpt,"%5i %10u %10llu %10llu : ",
  1341. tmp->uid,
  1342. tmp->dtick,
  1343. tmp->atick,
  1344. tmp->amicro );
  1345. if( tmp->status == kMetaStId )
  1346. {
  1347. cmRptPrintf(rpt,"%s ", cmMidiMetaStatusToLabel(tmp->metaId));
  1348. }
  1349. else
  1350. {
  1351. cmRptPrintf(rpt,"%4s %3i %3i %3i",
  1352. cmMidiStatusToLabel(tmp->status),
  1353. tmp->u.chMsgPtr->ch,
  1354. tmp->u.chMsgPtr->d0,
  1355. tmp->u.chMsgPtr->d1);
  1356. }
  1357. if( cmMidiIsChStatus(tmp->status) && cmMidiIsNoteOn(tmp->status) && (tmp->u.chMsgPtr->d1>0) )
  1358. cmRptPrintf(rpt," %4s ",cmMidiToSciPitch(tmp->u.chMsgPtr->d0,NULL,0));
  1359. cmRptPrintf(rpt,"\n");
  1360. }
  1361. void cmMidiFilePrintMsgs( cmMidiFileH_t h, cmRpt_t* rpt )
  1362. {
  1363. _cmMidiFile_t* p = _cmMidiFileHandleToPtr(h);
  1364. unsigned mi;
  1365. _cmMidiFilePrintHdr(p,rpt);
  1366. const cmMidiTrackMsg_t** msgV = _cmMidiFileMsgArray(p);
  1367. for(mi=0; mi<p->msgN; ++mi)
  1368. {
  1369. const cmMidiTrackMsg_t* mp = msgV[mi];
  1370. if( mp != NULL )
  1371. _cmMidiFilePrintMsg(rpt,mp);
  1372. }
  1373. }
  1374. void cmMidiFilePrintTracks( cmMidiFileH_t h, unsigned trkIdx, cmRpt_t* rpt )
  1375. {
  1376. const _cmMidiFile_t* mfp = _cmMidiFileHandleToPtr(h);
  1377. _cmMidiFilePrintHdr(mfp,rpt);
  1378. int i = trkIdx == cmInvalidIdx ? 0 : trkIdx;
  1379. int n = trkIdx == cmInvalidIdx ? mfp->trkN : trkIdx+1;
  1380. for(; i<n; ++i)
  1381. {
  1382. cmRptPrintf(rpt,"Track:%i\n",i);
  1383. cmMidiTrackMsg_t* tmp = mfp->trkV[i].base;
  1384. while( tmp != NULL )
  1385. {
  1386. _cmMidiFilePrintMsg(rpt,tmp);
  1387. tmp = tmp->link;
  1388. }
  1389. }
  1390. }
  1391. void cmMidiFileTestPrint( void* printDataPtr, const char* fmt, va_list vl )
  1392. { vprintf(fmt,vl); }
  1393. cmMfRC_t cmMidiFileGenPlotFile( cmCtx_t* ctx, const cmChar_t* midiFn, const cmChar_t* outFn )
  1394. {
  1395. cmMfRC_t rc = kOkMfRC;
  1396. cmMidiFileH_t mfH = cmMidiFileNullHandle;
  1397. cmFileH_t fH = cmFileNullHandle;
  1398. unsigned i = 0;
  1399. const cmMidiTrackMsg_t** m = NULL;
  1400. unsigned mN = 0;
  1401. if((rc = cmMidiFileOpen(ctx, &mfH, midiFn )) != kOkMfRC )
  1402. return cmErrMsg(&ctx->err,rc,"The MIDI file object could not be opened from '%s'.",cmStringNullGuard(midiFn));
  1403. _cmMidiFile_t* p = _cmMidiFileHandleToPtr(mfH);
  1404. if( (m = cmMidiFileMsgArray(mfH)) == NULL || (mN = cmMidiFileMsgCount(mfH)) == 0 )
  1405. {
  1406. rc = cmErrMsg(&p->err,kFileFailMfRC,"The MIDI file object appears to be empty.");
  1407. goto errLabel;
  1408. }
  1409. cmMidiFileCalcNoteDurations( mfH );
  1410. if( cmFileOpen(&fH,outFn,kWriteFileFl,p->err.rpt) != kOkFileRC )
  1411. return cmErrMsg(&p->err,kFileFailMfRC,"Unable to create the file '%s'.",cmStringNullGuard(outFn));
  1412. for(i=0; i<mN; ++i)
  1413. if( (m[i]!=NULL) && cmMidiIsChStatus(m[i]->status) && cmMidiIsNoteOn(m[i]->status) && (m[i]->u.chMsgPtr->d1>0) )
  1414. cmFilePrintf(fH,"n %f %f %i %s\n",m[i]->amicro/1000000.0,m[i]->u.chMsgPtr->durMicros/1000000.0,m[i]->uid,cmMidiToSciPitch(m[i]->u.chMsgPtr->d0,NULL,0));
  1415. errLabel:
  1416. cmMidiFileClose(&mfH);
  1417. cmFileClose(&fH);
  1418. return rc;
  1419. }
  1420. void cmMidiFilePrintControlNumbers( cmCtx_t* ctx, const char* fn )
  1421. {
  1422. cmMidiFileH_t h = cmMidiFileNullHandle;
  1423. cmMfRC_t rc;
  1424. if((rc = cmMidiFileOpen(ctx, &h, fn )) != kOkMfRC )
  1425. {
  1426. cmErrMsg(&ctx->err,rc,"MIDI file open failed on '%s'.",fn);
  1427. goto errLabel;
  1428. }
  1429. const cmMidiTrackMsg_t** mm;
  1430. unsigned n = cmMidiFileMsgCount(h);
  1431. if((mm = cmMidiFileMsgArray(h)) != NULL )
  1432. {
  1433. unsigned j;
  1434. for(j=0; j<n; ++j)
  1435. {
  1436. const cmMidiTrackMsg_t* m = mm[j];
  1437. if( m->status == kCtlMdId && m->u.chMsgPtr->d0==66 )
  1438. printf("%i %i\n",m->u.chMsgPtr->d0,m->u.chMsgPtr->d1);
  1439. }
  1440. }
  1441. errLabel:
  1442. cmMidiFileClose(&h);
  1443. }
  1444. void cmMidiFileTest( const char* fn, cmCtx_t* ctx )
  1445. {
  1446. cmMfRC_t rc;
  1447. cmMidiFileH_t h = cmMidiFileNullHandle;
  1448. if((rc = cmMidiFileOpen(ctx,&h,fn)) != kOkMfRC )
  1449. {
  1450. printf("Error:%i Unable to open the cmMidi file: %s\n",rc,fn);
  1451. return;
  1452. }
  1453. cmMidiFileCalcNoteDurations( h );
  1454. if( 1 )
  1455. {
  1456. //cmMidiFileTickToMicros( h );
  1457. //cmMidiFileTickToSamples(h,96000,false);
  1458. cmMidiFilePrintMsgs(h,&ctx->rpt);
  1459. }
  1460. if( 0 )
  1461. {
  1462. //cmMidiFilePrint(h,cmMidiFileTrackCount(h)-1,&ctx->rpt);
  1463. //cmMidiFilePrint(h,cmInvalidIdx,&ctx->rpt);
  1464. cmMidiFilePrintControlNumbers(ctx, fn );
  1465. }
  1466. if( 0 )
  1467. {
  1468. printf("Tracks:%i\n",cmMidiFileTrackCount(h));
  1469. unsigned i = 0;
  1470. for(i=0; i<cmMidiFileMsgCount(h); ++i)
  1471. {
  1472. cmMidiTrackMsg_t* tmp = (cmMidiTrackMsg_t*)cmMidiFileMsgArray(h)[i];
  1473. if( tmp->status==kMetaStId && tmp->metaId == kTempoMdId )
  1474. {
  1475. double bpm = 60000000.0/tmp->u.iVal;
  1476. printf("Tempo:%i %f\n",tmp->u.iVal,bpm);
  1477. tmp->u.iVal = floor( 60000000.0/69.0 );
  1478. break;
  1479. }
  1480. }
  1481. cmMidiFileWrite(h,"/home/kevin/temp/test0.mid");
  1482. }
  1483. cmMidiFileClose(&h);
  1484. }