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

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