libcm is a C development framework with an emphasis on audio signal processing applications.
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

cmMidiFile.c 56KB

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