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

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