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

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