libcm is a C development framework with an emphasis on audio signal processing applications.
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

cmMidiFile.c 55KB

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