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

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