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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586
  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 long long 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 microsPerTick = microsPerQN / mfp->ticksPerQN;
  359. unsigned long long amicro = 0;
  360. unsigned i;
  361. for(i=0; i<mfp->msgN; ++i)
  362. {
  363. cmMidiTrackMsg_t* mp = mfp->msgV[i];
  364. unsigned dtick = 0;
  365. if( i > 0 )
  366. {
  367. // atick must have already been set and sorted
  368. assert( mp->atick >= mfp->msgV[i-1]->atick );
  369. dtick = mp->atick - mfp->msgV[i-1]->atick;
  370. }
  371. amicro += microsPerTick * dtick;
  372. mp->amicro = amicro;
  373. // track tempo changes
  374. if( mp->status == kMetaStId && mp->metaId == kTempoMdId )
  375. microsPerTick = mp->u.iVal / mfp->ticksPerQN;
  376. }
  377. }
  378. cmMfRC_t _cmMidiFileClose( _cmMidiFile_t* mfp )
  379. {
  380. cmMfRC_t rc = kOkMfRC;
  381. if( mfp == NULL )
  382. return rc;
  383. cmMemPtrFree(&mfp->msgV);
  384. if( cmFileIsValid( mfp->fh ) )
  385. if( cmFileClose( &mfp->fh ) != kOkFileRC )
  386. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file close failed.");
  387. if( cmLHeapIsValid( mfp->lhH ) )
  388. cmLHeapDestroy(&mfp->lhH);
  389. cmMemPtrFree(&mfp);
  390. return rc;
  391. }
  392. cmMfRC_t cmMidiFileOpen( cmCtx_t* ctx, cmMidiFileH_t* hPtr, const char* fn )
  393. {
  394. cmMfRC_t rc = kOkMfRC;
  395. _cmMidiFile_t* mfp = NULL;
  396. unsigned short trkIdx = 0;
  397. cmErr_t err;
  398. unsigned i,j;
  399. if( cmMidiFileIsValid(*hPtr) )
  400. if((rc = _cmMidiFileClose(_cmMidiFileHandleToPtr(*hPtr))) != kOkMfRC )
  401. return rc;
  402. cmErrSetup(&err,&ctx->rpt,"MIDI File");
  403. // allocate the midi file object
  404. if(( mfp = cmMemAllocZ( _cmMidiFile_t, 1)) == NULL )
  405. return rc = cmErrMsg(&err,kMemAllocFailMfRC,"MIDI file memory allocation failed.");
  406. cmErrClone(&mfp->err,&err);
  407. // allocate the linked heap
  408. if( cmLHeapIsValid( mfp->lhH = cmLHeapCreate( 1024, ctx )) == false )
  409. {
  410. rc = cmErrMsg(&err,kMemAllocFailMfRC,"MIDI heap allocation failed.");
  411. goto errLabel;
  412. }
  413. // open the file
  414. if(cmFileOpen(&mfp->fh,fn,kReadFileFl | kBinaryFileFl,mfp->err.rpt) != kOkFileRC )
  415. {
  416. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file open failed.");
  417. goto errLabel;
  418. }
  419. // read header and setup track array
  420. if(( rc = _cmMidiFileReadHdr(mfp)) != kOkMfRC )
  421. goto errLabel;
  422. while( !cmFileEof(mfp->fh) && trkIdx < mfp->trkN )
  423. {
  424. unsigned chkId=0,chkN=0;
  425. // read the chunk id
  426. if((rc = _cmMidiFileRead32(mfp,&chkId)) != kOkMfRC )
  427. goto errLabel;
  428. // read the chunk size
  429. if((rc = _cmMidiFileRead32(mfp,&chkN)) != kOkMfRC )
  430. goto errLabel;
  431. // if this is not a trk chunk then skip it
  432. if( chkId != (unsigned)'MTrk')
  433. {
  434. //if( fseek( mfp->fp, chkN, SEEK_CUR) != 0 )
  435. if( cmFileSeek(mfp->fh,kCurFileFl,chkN) != kOkFileRC )
  436. {
  437. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file seek failed.");
  438. goto errLabel;
  439. }
  440. }
  441. else
  442. {
  443. if((rc = _cmMidiFileReadTrack(mfp,trkIdx)) != kOkMfRC )
  444. goto errLabel;
  445. ++trkIdx;
  446. }
  447. }
  448. // get the total trk msg count
  449. mfp->msgN = 0;
  450. for(trkIdx=0; trkIdx<mfp->trkN; ++trkIdx)
  451. mfp->msgN += mfp->trkV[ trkIdx ].cnt;
  452. // allocate the trk msg index vector: msgV[]
  453. mfp->msgV = cmMemAllocZ(cmMidiTrackMsg_t*, mfp->msgN);
  454. mfp->nextUid = 0;
  455. // store a pointer to every trk msg in msgV[] and set 'uid'
  456. for(i=0,j=0; i<mfp->trkN; ++i)
  457. {
  458. cmMidiTrackMsg_t* m = mfp->trkV[i].base;
  459. for(; m!=NULL; m=m->link)
  460. {
  461. assert( j < mfp->msgN );
  462. mfp->msgV[j++] = m;
  463. m->uid = mfp->nextUid++;
  464. }
  465. }
  466. mfp->fn = _cmMidiFileMalloc(mfp,strlen(fn)+1);
  467. assert( mfp->fn != NULL );
  468. strcpy(mfp->fn,fn);
  469. // set the atick value in each msg
  470. _cmMidiFileSetAccumulateTicks(mfp);
  471. // sort msgV[] in ascending order on atick
  472. qsort( mfp->msgV, mfp->msgN, sizeof(cmMidiTrackMsg_t*), _cmMidiFileSortFunc );
  473. // set the amicro value in each msg
  474. _cmMidiFileSetAbsoluteTime(mfp);
  475. hPtr->h = mfp;
  476. errLabel:
  477. if( cmFileClose(&mfp->fh) != kOkFileRC )
  478. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file close failed.");
  479. if( rc != kOkMfRC )
  480. _cmMidiFileClose(mfp);
  481. return rc;
  482. }
  483. cmMfRC_t cmMidiFileClose( cmMidiFileH_t* h )
  484. {
  485. cmMfRC_t rc;
  486. if( cmMidiFileIsNull(*h) )
  487. return kOkMfRC;
  488. if((rc = _cmMidiFileClose(_cmMidiFileHandleToPtr(*h))) == kOkMfRC )
  489. return rc;
  490. h->h = NULL;
  491. return rc;
  492. }
  493. cmMfRC_t _cmMidiFileWrite8( _cmMidiFile_t* mfp, unsigned char v )
  494. {
  495. cmMfRC_t rc = kOkMfRC;
  496. if( cmFileWriteUChar(mfp->fh,&v,1) != kOkFileRC )
  497. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file byte write failed.");
  498. return rc;
  499. }
  500. cmMfRC_t _cmMidiFileWrite16( _cmMidiFile_t* mfp, unsigned short v )
  501. {
  502. cmMfRC_t rc = kOkMfRC;
  503. v = mfSwap16(v);
  504. if( cmFileWriteUShort(mfp->fh,&v,1) != kOkFileRC )
  505. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file short integer write failed.");
  506. return rc;
  507. }
  508. cmMfRC_t _cmMidiFileWrite24( _cmMidiFile_t* mfp, unsigned v )
  509. {
  510. cmMfRC_t rc = kOkMfRC;
  511. unsigned mask = 0xff0000;
  512. int i;
  513. for(i=2; i>=0; --i)
  514. {
  515. unsigned char c = (v & mask) >> (i*8);
  516. mask >>= 8;
  517. if( cmFileWriteUChar(mfp->fh,&c,1) != kOkFileRC )
  518. {
  519. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file 24 bit integer write failed.");
  520. goto errLabel;
  521. }
  522. }
  523. errLabel:
  524. return rc;
  525. }
  526. cmMfRC_t _cmMidiFileWrite32( _cmMidiFile_t* mfp, unsigned v )
  527. {
  528. cmMfRC_t rc = kOkMfRC;
  529. v = mfSwap32(v);
  530. if( cmFileWriteUInt(mfp->fh,&v,1) != kOkFileRC )
  531. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file integer write failed.");
  532. return rc;
  533. }
  534. cmMfRC_t _cmMidiFileWriteRecd( _cmMidiFile_t* mfp, const void* v, unsigned byteCnt )
  535. {
  536. cmMfRC_t rc = kOkMfRC;
  537. if( cmFileWriteChar(mfp->fh,v,byteCnt) != kOkFileRC )
  538. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file write record failed.");
  539. return rc;
  540. }
  541. cmMfRC_t _cmMidiFileWriteVarLen( _cmMidiFile_t* mfp, unsigned v )
  542. {
  543. cmMfRC_t rc = kOkMfRC;
  544. unsigned buf = v & 0x7f;
  545. while((v >>= 7) > 0 )
  546. {
  547. buf <<= 8;
  548. buf |= 0x80;
  549. buf += (v & 0x7f);
  550. }
  551. while(1)
  552. {
  553. unsigned char c = (unsigned char)(buf & 0xff);
  554. if( cmFileWriteUChar(mfp->fh,&c,1) != kOkFileRC )
  555. {
  556. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"MIDI file variable length integer write failed.");
  557. goto errLabel;
  558. }
  559. if( buf & 0x80 )
  560. buf >>= 8;
  561. else
  562. break;
  563. }
  564. errLabel:
  565. return rc;
  566. }
  567. cmMfRC_t _cmMidiFileWriteHdr( _cmMidiFile_t* mfp )
  568. {
  569. cmMfRC_t rc;
  570. unsigned fileId = 'MThd';
  571. unsigned chunkByteN = 6;
  572. // write the file id ('MThd')
  573. if((rc = _cmMidiFileWrite32(mfp,fileId)) != kOkMfRC )
  574. return rc;
  575. // write the file chunk byte count (always 6)
  576. if((rc = _cmMidiFileWrite32(mfp,chunkByteN)) != kOkMfRC )
  577. return rc;
  578. // write the MIDI file format id (0,1,2)
  579. if((rc = _cmMidiFileWrite16(mfp,mfp->fmtId)) != kOkMfRC )
  580. return rc;
  581. // write the track count
  582. if((rc = _cmMidiFileWrite16(mfp,mfp->trkN)) != kOkMfRC )
  583. return rc;
  584. unsigned short v = 0;
  585. // if the ticks per quarter note field is valid ...
  586. if( mfp->ticksPerQN )
  587. v = mfp->ticksPerQN;
  588. else
  589. {
  590. // ... otherwise the division field was given in smpte
  591. v = mfp->smpteFmtId << 8;
  592. v += mfp->smpteTicksPerFrame;
  593. }
  594. if((rc = _cmMidiFileWrite16(mfp,v)) != kOkMfRC )
  595. return rc;
  596. return rc;
  597. }
  598. cmMfRC_t _cmMidiFileWriteSysEx( _cmMidiFile_t* mfp, cmMidiTrackMsg_t* tmp )
  599. {
  600. cmMfRC_t rc = kOkMfRC;
  601. if((rc = _cmMidiFileWrite8(mfp,kSysExMdId)) != kOkMfRC )
  602. goto errLabel;
  603. if( cmFileWriteUChar(mfp->fh,tmp->u.sysExPtr,tmp->byteCnt) != kOkFileRC )
  604. rc = cmErrMsg(&mfp->err,kFileFailMfRC,"Sys-ex msg write failed.");
  605. errLabel:
  606. return rc;
  607. }
  608. cmMfRC_t _cmMidiFileWriteChannelMsg( _cmMidiFile_t* mfp, const cmMidiTrackMsg_t* tmp, cmMidiByte_t* runStatus )
  609. {
  610. cmMfRC_t rc = kOkMfRC;
  611. unsigned byteN = cmMidiStatusToByteCount(tmp->status);
  612. cmMidiByte_t status = tmp->status + tmp->u.chMsgPtr->ch;
  613. if( status != *runStatus )
  614. {
  615. *runStatus = status;
  616. if((rc = _cmMidiFileWrite8(mfp,status)) != kOkMfRC )
  617. goto errLabel;
  618. }
  619. if(byteN>=1)
  620. if((rc = _cmMidiFileWrite8(mfp,tmp->u.chMsgPtr->d0)) != kOkMfRC )
  621. goto errLabel;
  622. if(byteN>=2)
  623. if((rc = _cmMidiFileWrite8(mfp,tmp->u.chMsgPtr->d1)) != kOkMfRC )
  624. goto errLabel;
  625. errLabel:
  626. return rc;
  627. }
  628. cmMfRC_t _cmMidiFileWriteMetaMsg( _cmMidiFile_t* mfp, const cmMidiTrackMsg_t* tmp )
  629. {
  630. cmMfRC_t rc;
  631. if((rc = _cmMidiFileWrite8(mfp,kMetaStId)) != kOkMfRC )
  632. return rc;
  633. if((rc = _cmMidiFileWrite8(mfp,tmp->metaId)) != kOkMfRC )
  634. return rc;
  635. switch( tmp->metaId )
  636. {
  637. case kSeqNumbMdId:
  638. if((rc = _cmMidiFileWrite8(mfp,sizeof(tmp->u.sVal))) == kOkMfRC )
  639. rc = _cmMidiFileWrite16(mfp,tmp->u.sVal);
  640. break;
  641. case kTempoMdId:
  642. if((rc = _cmMidiFileWrite8(mfp,3)) == kOkMfRC )
  643. rc = _cmMidiFileWrite24(mfp,tmp->u.iVal);
  644. break;
  645. case kSmpteMdId:
  646. if((rc = _cmMidiFileWrite8(mfp,sizeof(cmMidiSmpte_t))) == kOkMfRC )
  647. rc = _cmMidiFileWriteRecd(mfp,tmp->u.smptePtr,sizeof(cmMidiSmpte_t));
  648. break;
  649. case kTimeSigMdId:
  650. if((rc = _cmMidiFileWrite8(mfp,sizeof(cmMidiTimeSig_t))) == kOkMfRC )
  651. rc = _cmMidiFileWriteRecd(mfp,tmp->u.timeSigPtr,sizeof(cmMidiTimeSig_t));
  652. break;
  653. case kKeySigMdId:
  654. if((rc = _cmMidiFileWrite8(mfp,sizeof(cmMidiKeySig_t))) == kOkMfRC )
  655. rc = _cmMidiFileWriteRecd(mfp,tmp->u.keySigPtr,sizeof(cmMidiKeySig_t));
  656. break;
  657. case kSeqSpecMdId:
  658. if((rc = _cmMidiFileWriteVarLen(mfp,sizeof(tmp->byteCnt))) == kOkMfRC )
  659. rc = _cmMidiFileWriteRecd(mfp,tmp->u.sysExPtr,tmp->byteCnt);
  660. break;
  661. case kMidiChMdId:
  662. if((rc = _cmMidiFileWrite8(mfp,sizeof(tmp->u.bVal))) == kOkMfRC )
  663. rc = _cmMidiFileWrite8(mfp,tmp->u.bVal);
  664. break;
  665. case kEndOfTrkMdId:
  666. rc = _cmMidiFileWrite8(mfp,0);
  667. break;
  668. case kTextMdId:
  669. case kCopyMdId:
  670. case kTrkNameMdId:
  671. case kInstrNameMdId:
  672. case kLyricsMdId:
  673. case kMarkerMdId:
  674. case kCuePointMdId:
  675. {
  676. unsigned n = tmp->u.text==NULL ? 0 : strlen(tmp->u.text);
  677. if((rc = _cmMidiFileWriteVarLen(mfp,n)) == kOkMfRC && n>0 )
  678. rc = _cmMidiFileWriteRecd(mfp,tmp->u.text,n);
  679. }
  680. break;
  681. default:
  682. {
  683. // ignore unknown meta messages
  684. }
  685. }
  686. return rc;
  687. }
  688. cmMfRC_t _cmMidiFileWriteTrack( _cmMidiFile_t* mfp, unsigned trkIdx )
  689. {
  690. cmMfRC_t rc = kOkMfRC;
  691. cmMidiTrackMsg_t* tmp = mfp->trkV[trkIdx].base;
  692. cmMidiByte_t runStatus = 0;
  693. for(; tmp!=NULL; tmp=tmp->link)
  694. {
  695. // write the msg tick count
  696. if((rc = _cmMidiFileWriteVarLen(mfp,tmp->dtick)) != kOkMfRC )
  697. return rc;
  698. // switch on status
  699. switch( tmp->status )
  700. {
  701. // handle sys-ex msg
  702. case kSysExMdId:
  703. rc = _cmMidiFileWriteSysEx(mfp,tmp);
  704. break;
  705. // handle meta msg
  706. case kMetaStId:
  707. rc = _cmMidiFileWriteMetaMsg(mfp,tmp);
  708. break;
  709. default:
  710. // handle channel msg
  711. rc = _cmMidiFileWriteChannelMsg(mfp,tmp,&runStatus);
  712. }
  713. }
  714. return rc;
  715. }
  716. cmMfRC_t cmMidiFileWrite( cmMidiFileH_t h, const char* fn )
  717. {
  718. cmMfRC_t rc = kOkMfRC;
  719. _cmMidiFile_t* mfp = _cmMidiFileHandleToPtr(h);
  720. unsigned i;
  721. // create the output file
  722. if( cmFileOpen(&mfp->fh,fn,kWriteFileFl,mfp->err.rpt) != kOkFileRC )
  723. return cmErrMsg(&mfp->err,kFileFailMfRC,"The MIDI file '%s' could not be created.",cmStringNullGuard(fn));
  724. // write the file header
  725. if((rc = _cmMidiFileWriteHdr(mfp)) != kOkMfRC )
  726. {
  727. rc = cmErrMsg(&mfp->err,rc,"The file header write failed on the MIDI file '%s'.",cmStringNullGuard(fn));
  728. goto errLabel;
  729. }
  730. for(i=0; i < mfp->trkN; ++i )
  731. {
  732. unsigned chkId='MTrk';
  733. long offs0,offs1;
  734. // write the track chunk id ('MTrk')
  735. if((rc = _cmMidiFileWrite32(mfp,chkId)) != kOkMfRC )
  736. goto errLabel;
  737. cmFileTell(mfp->fh,&offs0);
  738. // write the track chunk size as zero
  739. if((rc = _cmMidiFileWrite32(mfp,0)) != kOkMfRC )
  740. goto errLabel;
  741. if((rc = _cmMidiFileWriteTrack(mfp,i)) != kOkMfRC )
  742. goto errLabel;
  743. cmFileTell(mfp->fh,&offs1);
  744. cmFileSeek(mfp->fh,kBeginFileFl,offs0);
  745. _cmMidiFileWrite32(mfp,offs1-offs0-4);
  746. cmFileSeek(mfp->fh,kBeginFileFl,offs1);
  747. }
  748. errLabel:
  749. cmFileClose(&mfp->fh);
  750. return rc;
  751. }
  752. bool cmMidiFileIsValid( cmMidiFileH_t h )
  753. { return !cmMidiFileIsNull(h); }
  754. unsigned cmMidiFileTrackCount( cmMidiFileH_t h )
  755. {
  756. _cmMidiFile_t* mfp;
  757. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  758. return cmInvalidCnt;
  759. return mfp->trkN;
  760. }
  761. unsigned cmMidiFileType( cmMidiFileH_t h )
  762. {
  763. _cmMidiFile_t* mfp;
  764. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  765. return cmInvalidId;
  766. return mfp->fmtId;
  767. }
  768. const char* cmMidiFileName( cmMidiFileH_t h )
  769. {
  770. _cmMidiFile_t* mfp;
  771. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  772. return NULL;
  773. return mfp->fn;
  774. }
  775. unsigned cmMidiFileTicksPerQN( cmMidiFileH_t h )
  776. {
  777. _cmMidiFile_t* mfp;
  778. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  779. return cmInvalidCnt;
  780. return mfp->ticksPerQN;
  781. }
  782. cmMidiByte_t cmMidiFileTicksPerSmpteFrame( cmMidiFileH_t h )
  783. {
  784. _cmMidiFile_t* mfp;
  785. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  786. return kInvalidMidiByte;
  787. if( mfp->ticksPerQN != 0 )
  788. return 0;
  789. return mfp->smpteTicksPerFrame;
  790. }
  791. cmMidiByte_t cmMidiFileSmpteFormatId( cmMidiFileH_t h )
  792. {
  793. _cmMidiFile_t* mfp;
  794. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  795. return kInvalidMidiByte;
  796. if( mfp->ticksPerQN != 0 )
  797. return 0;
  798. return mfp->smpteFmtId;
  799. }
  800. unsigned cmMidiFileTrackMsgCount( cmMidiFileH_t h, unsigned trackIdx )
  801. {
  802. _cmMidiFile_t* mfp;
  803. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  804. return cmInvalidCnt;
  805. return mfp->trkV[trackIdx].cnt;
  806. }
  807. const cmMidiTrackMsg_t* cmMidiFileTrackMsg( cmMidiFileH_t h, unsigned trackIdx )
  808. {
  809. _cmMidiFile_t* mfp;
  810. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  811. return NULL;
  812. return mfp->trkV[trackIdx].base;
  813. }
  814. unsigned cmMidiFileMsgCount( cmMidiFileH_t h )
  815. {
  816. _cmMidiFile_t* mfp;
  817. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  818. return cmInvalidCnt;
  819. return mfp->msgN;
  820. }
  821. const cmMidiTrackMsg_t** cmMidiFileMsgArray( cmMidiFileH_t h )
  822. {
  823. _cmMidiFile_t* mfp;
  824. if((mfp = _cmMidiFileHandleToPtr(h)) == NULL )
  825. return NULL;
  826. // this cast is needed to eliminate an apparently needless 'incompatible type' warning
  827. return (const cmMidiTrackMsg_t**)mfp->msgV;
  828. }
  829. unsigned cmMidiFileSeekUsecs( cmMidiFileH_t h, unsigned long long offsUSecs, unsigned* msgUsecsPtr, unsigned* microsPerTickPtr )
  830. {
  831. _cmMidiFile_t* p;
  832. if((p = _cmMidiFileHandleToPtr(h)) == NULL )
  833. return cmInvalidIdx;
  834. if( p->msgN == 0 )
  835. return cmInvalidIdx;
  836. unsigned mi;
  837. double microsPerQN = 60000000.0/120.0;
  838. double microsPerTick = microsPerQN / p->ticksPerQN;
  839. double accUSecs = 0;
  840. for(mi=0; mi<p->msgN; ++mi)
  841. {
  842. const cmMidiTrackMsg_t* mp = p->msgV[mi];
  843. if( mp->amicro >= offsUSecs )
  844. break;
  845. }
  846. if( mi == p->msgN )
  847. return cmInvalidIdx;
  848. if( msgUsecsPtr != NULL )
  849. *msgUsecsPtr = round(accUSecs - offsUSecs);
  850. if( microsPerTickPtr != NULL )
  851. *microsPerTickPtr = round(microsPerTick);
  852. return mi;
  853. }
  854. double cmMidiFileDurSecs( cmMidiFileH_t h )
  855. {
  856. _cmMidiFile_t* mfp = _cmMidiFileHandleToPtr(h);
  857. if( mfp->msgN == 0 )
  858. return 0;
  859. return mfp->msgV[ mfp->msgN-1 ]->amicro / 1000000.0;
  860. }
  861. typedef struct _cmMidiVoice_str
  862. {
  863. const cmMidiTrackMsg_t* mp;
  864. unsigned durMicros;
  865. bool sustainFl;
  866. struct _cmMidiVoice_str* link;
  867. } _cmMidiVoice_t;
  868. void _cmMidFileCalcNoteDurationReleaseNote( _cmMidiVoice_t** listPtrPtr, _cmMidiVoice_t* pp, _cmMidiVoice_t* vp )
  869. {
  870. assert( (pp==NULL && vp==*listPtrPtr) || pp->link==vp);
  871. // store the duration of the note into the track msg
  872. // assoc'd with the note-on msg
  873. cmMidiChMsg_t* cmp = (cmMidiChMsg_t*)vp->mp->u.chMsgPtr; // cast away const
  874. cmp->durMicros = vp->durMicros;
  875. _cmMidiVoice_t* np = vp->link;
  876. // release the voice msg
  877. cmMemFree(vp);
  878. // unlink the active voice msg
  879. if( pp == NULL )
  880. *listPtrPtr = np;
  881. else
  882. pp->link = np;
  883. }
  884. void _cmMidiFileCalcNoteDurationsAllocVoice( _cmMidiVoice_t** listPtrPtr, cmMidiTrackMsg_t* mp, bool sustainFl )
  885. {
  886. _cmMidiVoice_t* vp = cmMemAllocZ(_cmMidiVoice_t,1);
  887. vp->mp = mp;
  888. vp->sustainFl = sustainFl;
  889. vp->link = *listPtrPtr;
  890. *listPtrPtr = vp;
  891. }
  892. void cmMidiFileCalcNoteDurations( cmMidiFileH_t h )
  893. {
  894. _cmMidiFile_t* p;
  895. if((p = _cmMidiFileHandleToPtr(h)) == NULL )
  896. return;
  897. if( p->msgN == 0 )
  898. return;
  899. unsigned mi = cmInvalidId;
  900. _cmMidiVoice_t* list = NULL; // list of active voices
  901. _cmMidiVoice_t* vp = NULL;
  902. cmMidiTrackMsg_t* sustainPedalDownMsg = NULL;
  903. bool sustainFlagV[ kMidiChCnt ];
  904. // clear the sustain pedal flag
  905. for(mi=0; mi<kMidiChCnt; ++mi)
  906. sustainFlagV[mi]=false;
  907. for(mi=0; mi<p->msgN; ++mi)
  908. {
  909. cmMidiTrackMsg_t* mp = p->msgV[mi];
  910. unsigned d_amicro = 0;
  911. if( mi > 0 )
  912. {
  913. assert( mp->amicro >= p->msgV[mi-1]->amicro );
  914. d_amicro = mp->amicro - p->msgV[mi-1]->amicro;
  915. }
  916. // update the duration of the sounding notes
  917. for(vp = list; vp!=NULL; vp=vp->link)
  918. vp->durMicros += d_amicro;
  919. // update the sustain pedal duration
  920. if( sustainPedalDownMsg != NULL )
  921. ((cmMidiChMsg_t*)(sustainPedalDownMsg->u.chMsgPtr))->durMicros += d_amicro; // cast away const
  922. //
  923. // If this is sustain pedal msg
  924. //
  925. if( mp->status==kCtlMdId && mp->u.chMsgPtr->d0 == kSustainCtlMdId )
  926. {
  927. unsigned chIdx = mp->u.chMsgPtr->ch;
  928. assert( chIdx < kMidiChCnt );
  929. // set the state of the sustain pedal flags
  930. sustainFlagV[chIdx] = mp->u.chMsgPtr->d1 >= 64;
  931. // if the pedal went down ...
  932. if( sustainFlagV[chIdx] )
  933. {
  934. if( sustainPedalDownMsg != NULL )
  935. {
  936. // TODO: the correct way to handle this is to maintain multiple sustain pedals
  937. cmErrMsg(&p->err,kSustainPedalMfRC,"Sustain pedal down with no intervening sustain pedal up.");
  938. }
  939. else
  940. {
  941. sustainPedalDownMsg = mp;
  942. ((cmMidiChMsg_t*)(sustainPedalDownMsg->u.chMsgPtr))->durMicros = 0; // cast away const
  943. }
  944. _cmMidiFileCalcNoteDurationsAllocVoice( &list, mp, true );
  945. }
  946. else // ... if the pedal went up
  947. {
  948. sustainPedalDownMsg = NULL;
  949. // ... then release sustaining notes
  950. _cmMidiVoice_t* pp = NULL;
  951. for(vp=list; vp != NULL; )
  952. {
  953. _cmMidiVoice_t* np = vp->link;
  954. if( vp->sustainFl && (vp->mp->u.chMsgPtr->ch == chIdx) )
  955. _cmMidFileCalcNoteDurationReleaseNote(&list,pp,vp);
  956. else
  957. pp = vp;
  958. vp = np;
  959. }
  960. }
  961. }
  962. //
  963. // if this is a note-on msg
  964. //
  965. if( mp->status==kNoteOnMdId && mp->u.chMsgPtr->d1>0 )
  966. {
  967. _cmMidiFileCalcNoteDurationsAllocVoice( &list, mp, false );
  968. }
  969. else
  970. //
  971. // if this is a note-off msg
  972. //
  973. if( (mp->status==kNoteOnMdId && mp->u.chMsgPtr->d1==0) || (mp->status==kNoteOffMdId) )
  974. {
  975. _cmMidiVoice_t* pp = NULL;
  976. unsigned chIdx = mp->u.chMsgPtr->ch;
  977. assert( chIdx < kMidiChCnt );
  978. // for each active voice
  979. for(vp=list; vp!=NULL; vp=vp->link )
  980. {
  981. // if this active voice ch/pitch matches the note-off msg ch pitch
  982. if( (vp->mp->u.chMsgPtr->d0==mp->u.chMsgPtr->d0) && (vp->mp->u.chMsgPtr->ch==chIdx) )
  983. {
  984. // if the sustain pedal is down for this channel - then defer turning the note off
  985. if( sustainFlagV[chIdx] )
  986. vp->sustainFl = true;
  987. else
  988. _cmMidFileCalcNoteDurationReleaseNote(&list,pp,vp);
  989. break;
  990. }
  991. pp = vp;
  992. } // end for
  993. } // end if
  994. } // end-for
  995. // check for hung notes
  996. _cmMidiVoice_t* np = NULL;
  997. vp = list;
  998. while( vp != NULL )
  999. {
  1000. np = vp->link;
  1001. if( cmMidiIsNoteOn(vp->mp->status) == false )
  1002. cmErrMsg(&p->err,kMissingNoteOffMfRC,"Missing note-off for note-on:%s",cmMidiToSciPitch(vp->mp->u.chMsgPtr->d0,NULL,0));
  1003. cmMemFree(vp);
  1004. vp = np;
  1005. }
  1006. }
  1007. void cmMidiFileSetDelay( cmMidiFileH_t h, unsigned ticks )
  1008. {
  1009. _cmMidiFile_t* p;
  1010. unsigned mi;
  1011. if((p = _cmMidiFileHandleToPtr(h)) == NULL )
  1012. return;
  1013. if( p->msgN == 0 )
  1014. return;
  1015. for(mi=0; mi<p->msgN; ++mi)
  1016. {
  1017. cmMidiTrackMsg_t* mp = p->msgV[mi];
  1018. // locate the first msg which has a non-zero delta tick
  1019. if( mp->dtick > 0 )
  1020. {
  1021. mp->dtick = ticks;
  1022. break;
  1023. }
  1024. }
  1025. }
  1026. unsigned cmMidiFilePackTrackMsgBufByteCount( const cmMidiTrackMsg_t* m )
  1027. { return sizeof(cmMidiTrackMsg_t) + m->byteCnt; }
  1028. cmMidiTrackMsg_t* cmMidiFilePackTrackMsg( const cmMidiTrackMsg_t* m, void* buf, unsigned bufByteCnt )
  1029. {
  1030. unsigned n = sizeof(cmMidiTrackMsg_t) + m->byteCnt;
  1031. if( n < bufByteCnt )
  1032. {
  1033. assert(0);
  1034. return NULL;
  1035. }
  1036. // copy the cmMidiTrackMsg_t into the buffer
  1037. memcpy(buf, m, sizeof(cmMidiTrackMsg_t));
  1038. if( m->byteCnt > 0 )
  1039. {
  1040. // copy any linked data into the buffer
  1041. memcpy(buf + sizeof(cmMidiTrackMsg_t), m->u.voidPtr, m->byteCnt );
  1042. // fixup the linked data ptr
  1043. cmMidiTrackMsg_t* mp = (cmMidiTrackMsg_t*)buf;
  1044. mp->u.voidPtr = buf + sizeof(cmMidiTrackMsg_t);
  1045. }
  1046. return (cmMidiTrackMsg_t*)buf;
  1047. }
  1048. void _cmMidiFilePrintHdr( const _cmMidiFile_t* mfp, cmRpt_t* rpt )
  1049. {
  1050. if( mfp->fn != NULL )
  1051. cmRptPrintf(rpt,"%s ",mfp->fn);
  1052. cmRptPrintf(rpt,"fmt:%i ticksPerQN:%i tracks:%i\n",mfp->fmtId,mfp->ticksPerQN,mfp->trkN);
  1053. cmRptPrintf(rpt," UID dtick atick amicro type ch D0 D1\n");
  1054. cmRptPrintf(rpt,"----- ---------- ---------- ---------- : ---- --- --- ---\n");
  1055. }
  1056. void _cmMidiFilePrintMsg( cmRpt_t* rpt, const cmMidiTrackMsg_t* tmp )
  1057. {
  1058. cmRptPrintf(rpt,"%5i %10u %10llu %10llu : ",
  1059. tmp->uid,
  1060. tmp->dtick,
  1061. tmp->atick,
  1062. tmp->amicro );
  1063. if( tmp->status == kMetaStId )
  1064. {
  1065. cmRptPrintf(rpt,"%s ", cmMidiMetaStatusToLabel(tmp->metaId));
  1066. }
  1067. else
  1068. {
  1069. cmRptPrintf(rpt,"%4s %3i %3i %3i",
  1070. cmMidiStatusToLabel(tmp->status),
  1071. tmp->u.chMsgPtr->ch,
  1072. tmp->u.chMsgPtr->d0,
  1073. tmp->u.chMsgPtr->d1);
  1074. }
  1075. if( cmMidiIsChStatus(tmp->status) && cmMidiIsNoteOn(tmp->status) && (tmp->u.chMsgPtr->d1>0) )
  1076. cmRptPrintf(rpt," %4s ",cmMidiToSciPitch(tmp->u.chMsgPtr->d0,NULL,0));
  1077. cmRptPrintf(rpt,"\n");
  1078. }
  1079. void cmMidiFilePrintMsgs( cmMidiFileH_t h, cmRpt_t* rpt )
  1080. {
  1081. const _cmMidiFile_t* p = _cmMidiFileHandleToPtr(h);
  1082. unsigned mi;
  1083. _cmMidiFilePrintHdr(p,rpt);
  1084. for(mi=0; mi<p->msgN; ++mi)
  1085. {
  1086. cmMidiTrackMsg_t* mp = p->msgV[mi];
  1087. if( mp != NULL )
  1088. _cmMidiFilePrintMsg(rpt,mp);
  1089. }
  1090. }
  1091. void cmMidiFilePrintTracks( cmMidiFileH_t h, unsigned trkIdx, cmRpt_t* rpt )
  1092. {
  1093. const _cmMidiFile_t* mfp = _cmMidiFileHandleToPtr(h);
  1094. _cmMidiFilePrintHdr(mfp,rpt);
  1095. int i = trkIdx == cmInvalidIdx ? 0 : trkIdx;
  1096. int n = trkIdx == cmInvalidIdx ? mfp->trkN : trkIdx+1;
  1097. for(; i<n; ++i)
  1098. {
  1099. cmRptPrintf(rpt,"Track:%i\n",i);
  1100. cmMidiTrackMsg_t* tmp = mfp->trkV[i].base;
  1101. while( tmp != NULL )
  1102. {
  1103. _cmMidiFilePrintMsg(rpt,tmp);
  1104. tmp = tmp->link;
  1105. }
  1106. }
  1107. }
  1108. bool cmMidiFileIsNull( cmMidiFileH_t h )
  1109. { return (_cmMidiFile_t*)h.h == NULL; }
  1110. void cmMidiFileTestPrint( void* printDataPtr, const char* fmt, va_list vl )
  1111. { vprintf(fmt,vl); }
  1112. cmMfRC_t cmMidiFileGenPlotFile( cmCtx_t* ctx, const cmChar_t* midiFn, const cmChar_t* outFn )
  1113. {
  1114. cmMfRC_t rc = kOkMfRC;
  1115. cmMidiFileH_t mfH = cmMidiFileNullHandle;
  1116. cmFileH_t fH = cmFileNullHandle;
  1117. unsigned i = 0;
  1118. const cmMidiTrackMsg_t** m = NULL;
  1119. unsigned mN = 0;
  1120. if((rc = cmMidiFileOpen(ctx, &mfH, midiFn )) != kOkMfRC )
  1121. return cmErrMsg(&ctx->err,rc,"The MIDI file object could not be opened from '%s'.",cmStringNullGuard(midiFn));
  1122. _cmMidiFile_t* p = _cmMidiFileHandleToPtr(mfH);
  1123. if( (m = cmMidiFileMsgArray(mfH)) == NULL || (mN = cmMidiFileMsgCount(mfH)) == 0 )
  1124. {
  1125. rc = cmErrMsg(&p->err,kFileFailMfRC,"The MIDI file object appears to be empty.");
  1126. goto errLabel;
  1127. }
  1128. cmMidiFileCalcNoteDurations( mfH );
  1129. if( cmFileOpen(&fH,outFn,kWriteFileFl,p->err.rpt) != kOkFileRC )
  1130. return cmErrMsg(&p->err,kFileFailMfRC,"Unable to create the file '%s'.",cmStringNullGuard(outFn));
  1131. for(i=0; i<mN; ++i)
  1132. if( (m[i]!=NULL) && cmMidiIsChStatus(m[i]->status) && cmMidiIsNoteOn(m[i]->status) && (m[i]->u.chMsgPtr->d1>0) )
  1133. 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));
  1134. errLabel:
  1135. cmMidiFileClose(&mfH);
  1136. cmFileClose(&fH);
  1137. return rc;
  1138. }
  1139. void cmMidiFilePrintControlNumbers( cmCtx_t* ctx, const char* fn )
  1140. {
  1141. cmMidiFileH_t h = cmMidiFileNullHandle;
  1142. cmMfRC_t rc;
  1143. if((rc = cmMidiFileOpen(ctx, &h, fn )) != kOkMfRC )
  1144. {
  1145. cmErrMsg(&ctx->err,rc,"MIDI file open failed on '%s'.",fn);
  1146. goto errLabel;
  1147. }
  1148. const cmMidiTrackMsg_t** mm;
  1149. unsigned n = cmMidiFileMsgCount(h);
  1150. if((mm = cmMidiFileMsgArray(h)) != NULL )
  1151. {
  1152. unsigned j;
  1153. for(j=0; j<n; ++j)
  1154. {
  1155. const cmMidiTrackMsg_t* m = mm[j];
  1156. if( m->status == kCtlMdId && m->u.chMsgPtr->d0==66 )
  1157. printf("%i %i\n",m->u.chMsgPtr->d0,m->u.chMsgPtr->d1);
  1158. }
  1159. }
  1160. errLabel:
  1161. cmMidiFileClose(&h);
  1162. }
  1163. void cmMidiFileTest( const char* fn, cmCtx_t* ctx )
  1164. {
  1165. cmMfRC_t rc;
  1166. cmMidiFileH_t h = cmMidiFileNullHandle;
  1167. if((rc = cmMidiFileOpen(ctx,&h,fn)) != kOkMfRC )
  1168. {
  1169. printf("Error:%i Unable to open the cmMidi file: %s\n",rc,fn);
  1170. return;
  1171. }
  1172. //cmMidiFileCalcNoteDurations( h );
  1173. if( 1 )
  1174. {
  1175. //cmMidiFileTickToMicros( h );
  1176. //cmMidiFileTickToSamples(h,96000,false);
  1177. cmMidiFilePrintMsgs(h,&ctx->rpt);
  1178. }
  1179. if( 0 )
  1180. {
  1181. //cmMidiFilePrint(h,cmMidiFileTrackCount(h)-1,&ctx->rpt);
  1182. //cmMidiFilePrint(h,cmInvalidIdx,&ctx->rpt);
  1183. cmMidiFilePrintControlNumbers(ctx, fn );
  1184. }
  1185. if( 0 )
  1186. {
  1187. printf("Tracks:%i\n",cmMidiFileTrackCount(h));
  1188. unsigned i = 0;
  1189. for(i=0; i<cmMidiFileMsgCount(h); ++i)
  1190. {
  1191. cmMidiTrackMsg_t* tmp = (cmMidiTrackMsg_t*)cmMidiFileMsgArray(h)[i];
  1192. if( tmp->status==kMetaStId && tmp->metaId == kTempoMdId )
  1193. {
  1194. double bpm = 60000000.0/tmp->u.iVal;
  1195. printf("Tempo:%i %f\n",tmp->u.iVal,bpm);
  1196. tmp->u.iVal = floor( 60000000.0/69.0 );
  1197. break;
  1198. }
  1199. }
  1200. cmMidiFileWrite(h,"/home/kevin/temp/test0.mid");
  1201. }
  1202. cmMidiFileClose(&h);
  1203. }