libcm is a C development framework with an emphasis on audio signal processing applications.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

cmMidiFilePlay.c 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. //| Copyright: (C) 2009-2020 Kevin Larke <contact AT larke DOT org>
  2. //| License: GNU GPL version 3.0 or above. See the accompanying LICENSE file.
  3. #include <sys/time.h> // gettimeofday()
  4. #include "cmPrefix.h"
  5. #include "cmGlobal.h"
  6. #include "cmRpt.h"
  7. #include "cmErr.h"
  8. #include "cmCtx.h"
  9. #include "cmMem.h"
  10. #include "cmMallocDebug.h"
  11. #include "cmFile.h"
  12. #include "cmTime.h"
  13. #include "cmMidi.h"
  14. #include "cmMidiPort.h"
  15. #include "cmMidiFile.h"
  16. #include "cmMidiFilePlay.h"
  17. #include "cmThread.h" // cmSleepUs()
  18. #include "cmTime.h"
  19. typedef struct
  20. {
  21. cmErr_t err;
  22. cmCtx_t ctx;
  23. cmMfpCallback_t cbFunc;
  24. void* userCbPtr;
  25. void* printDataPtr;
  26. unsigned memBlockByteCnt;
  27. cmMidiFileH_t mfH; // midi file handle
  28. bool closeFileFl; // true mfH should be closed when this midi file player is closed
  29. unsigned ticksPerQN; // global for file
  30. unsigned microsPerTick; // set via tempo
  31. unsigned etime; // usecs elapsed since transmitting prev msg
  32. unsigned mtime; // usecs to wait before transmitting next msg
  33. unsigned msgN; // count of pointers in msgV[]
  34. unsigned msgIdx; // index into msgV[] of next msg to transmit
  35. const cmMidiTrackMsg_t** msgV; // array of msg pointers
  36. } cmMfp_t;
  37. cmMfpH_t cmMfpNullHandle = cmSTATIC_NULL_HANDLE;
  38. #define _cmMfpError( mfp, rc ) _cmMfpOnError(mfp, rc, __LINE__,__FILE__,__FUNCTION__ )
  39. // note: mfp may be NULL
  40. cmMfpRC_t _cmMfpOnError( cmMfp_t* mfp, cmMfpRC_t rc, int line, const char* fn, const char* func )
  41. {
  42. return cmErrMsg(&mfp->err,rc,"rc:%i %i %s %s\n",rc,line,func,fn);
  43. }
  44. cmMfp_t* _cmMfpHandleToPtr( cmMfpH_t h )
  45. {
  46. cmMfp_t* p = (cmMfp_t*)h.h;
  47. assert(p != NULL);
  48. return p;
  49. }
  50. void _cmMfpUpdateMicrosPerTick( cmMfp_t* mfp, unsigned microsPerQN )
  51. {
  52. mfp->microsPerTick = microsPerQN / mfp->ticksPerQN;
  53. printf("microsPerTick: %i bpm:%i ticksPerQN:%i\n", mfp->microsPerTick,microsPerQN,mfp->ticksPerQN);
  54. }
  55. cmMfpRC_t cmMfpCreate( cmMfpH_t* hp, cmMfpCallback_t cbFunc, void* userCbPtr, cmCtx_t* ctx )
  56. {
  57. cmMfp_t* p = cmMemAllocZ( cmMfp_t, 1 );
  58. cmErrSetup(&p->err,&ctx->rpt,"MIDI File Player");
  59. p->ctx = *ctx;
  60. p->cbFunc = cbFunc;
  61. p->userCbPtr = userCbPtr;
  62. p->mfH.h = NULL;
  63. p->closeFileFl = false;
  64. p->ticksPerQN = 0;
  65. p->microsPerTick = 0;
  66. p->etime = 0;
  67. p->msgN = 0;
  68. p->msgV = NULL;
  69. p->msgIdx = 0;
  70. hp->h = p;
  71. return kOkMfpRC;
  72. }
  73. cmMfpRC_t cmMfpDestroy( cmMfpH_t* hp )
  74. {
  75. if( hp == NULL )
  76. return kOkMfpRC;
  77. if( cmMfpIsValid(*hp) )
  78. {
  79. cmMfp_t* p = _cmMfpHandleToPtr(*hp);
  80. if( cmMidiFileIsValid(p->mfH)==false && p->closeFileFl==true )
  81. cmMidiFileClose(&p->mfH);
  82. cmMemFree(p);
  83. hp->h = NULL;
  84. }
  85. return kOkMfpRC;
  86. }
  87. bool cmMfpIsValid( cmMfpH_t h )
  88. { return h.h != NULL; }
  89. cmMfpRC_t cmMfpLoadFile( cmMfpH_t h, const char* fn )
  90. {
  91. cmMfpRC_t rc = kOkMfpRC;
  92. cmMfp_t* p = _cmMfpHandleToPtr(h);
  93. cmMidiFileH_t mfH = cmMidiFileNullHandle;
  94. if((rc = cmMidiFileOpen( &p->ctx, &mfH, fn )) != kOkMfRC )
  95. return _cmMfpError(p,kFileOpenFailMfpRC);
  96. if((rc= cmMfpLoadHandle( h, mfH )) == kOkMfpRC )
  97. p->closeFileFl = true;
  98. return rc;
  99. }
  100. cmMfpRC_t cmMfpLoadHandle( cmMfpH_t h, cmMidiFileH_t mfH )
  101. {
  102. cmMfp_t* p = _cmMfpHandleToPtr(h);
  103. // if a file has already been assigned to this player
  104. if( (cmMidiFileIsValid(p->mfH) == false) && p->closeFileFl)
  105. {
  106. // close the existing file
  107. cmMidiFileClose(&p->mfH);
  108. }
  109. // get the count of msg's in the new midi file
  110. if((p->msgN = cmMidiFileMsgCount(mfH)) == cmInvalidCnt )
  111. return _cmMfpError(p,kInvalidFileMfpRC);
  112. // get a pointer to the first mesage
  113. if((p->msgV = cmMidiFileMsgArray(mfH)) == NULL )
  114. return _cmMfpError(p,kInvalidFileMfpRC);
  115. // get the count of ticks per qn
  116. if((p->ticksPerQN = cmMidiFileTicksPerQN( mfH )) == 0 )
  117. return _cmMfpError(p,kSmpteTickNotImplMfpRC);
  118. // set the initial tempo to 120
  119. _cmMfpUpdateMicrosPerTick(p,60000000/120);
  120. p->msgIdx = 0;
  121. p->mfH = mfH;
  122. p->etime = 0;
  123. p->mtime = 0;
  124. p->closeFileFl= false;
  125. return kOkMfpRC;
  126. }
  127. cmMfpRC_t cmMfpSeek( cmMfpH_t h, unsigned offsUsecs )
  128. {
  129. cmMfp_t* p = _cmMfpHandleToPtr(h);
  130. unsigned msgOffsUsecs = 0;
  131. unsigned msgIdx;
  132. unsigned newMicrosPerTick;
  133. // if the requested offset is past the end of the file then return EOF
  134. if((msgIdx = cmMidiFileSeekUsecs( p->mfH, offsUsecs, &msgOffsUsecs, &newMicrosPerTick )) == cmInvalidIdx )
  135. {
  136. p->msgIdx = p->msgN;
  137. return _cmMfpError(p,kEndOfFileMfpRC);
  138. }
  139. if( msgIdx < p->msgIdx )
  140. p->msgIdx = 0;
  141. p->mtime = msgOffsUsecs;
  142. p->etime = 0;
  143. p->microsPerTick = newMicrosPerTick;
  144. p->msgIdx = msgIdx;
  145. assert(p->mtime >= 0);
  146. return kOkMfpRC;
  147. }
  148. // p 0 1 n 2
  149. // v v v v v
  150. // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
  151. // 012345678901234567890123456780
  152. // 0 1 2
  153. //
  154. // p = 3 = prev msg sent
  155. // n = 19 = next msg to send
  156. // 0 = 6 = call to cmMfpClock()
  157. // 1 = 12 = call to cmMfpClock()
  158. // 2 = 22 = call to cmMfpClock()
  159. //
  160. // dusecs etime mtime
  161. // 0 n/a 3 13
  162. // 1 6 9 7
  163. // 2 10 19 -3
  164. //
  165. cmMfpRC_t cmMfpClock( cmMfpH_t h, unsigned dusecs )
  166. {
  167. cmMfp_t* p = _cmMfpHandleToPtr(h);
  168. if( p->msgIdx >= p->msgN )
  169. return kEndOfFileMfpRC;
  170. // get a pointer to the next msg to send
  171. const cmMidiTrackMsg_t* mp = p->msgV[p->msgIdx];
  172. // p->etime is the interval of time between when the last msg was
  173. // sent and the end of the time window for this mfpClock() cycle
  174. p->etime += dusecs;
  175. // if the elapsed time (etime) since the last msg is greater or equal
  176. // to the delta time to the next msg (mtime)
  177. while( p->etime >= p->mtime )
  178. {
  179. // send the current message
  180. p->cbFunc( p->userCbPtr, p->mtime, mp );
  181. unsigned long long amicro = mp->amicro;
  182. ++(p->msgIdx);
  183. if( p->msgIdx >= p->msgN )
  184. break;
  185. // get the next msg to send
  186. mp = p->msgV[p->msgIdx];
  187. // we probably went past the actual mtime - so update etime
  188. // with the delta usecs from the msg just sent and the current time
  189. p->etime -= p->mtime;
  190. // calc the delta usecs from the message just sent to the next msg to send
  191. p->mtime = mp->amicro - amicro;
  192. }
  193. return p->msgIdx >= p->msgN ? kEndOfFileMfpRC : kOkMfpRC;
  194. }
  195. void mfpPrint( void* userDataPtr, const char* fmt, va_list vl )
  196. {
  197. vprintf(fmt,vl);
  198. }
  199. // this assumes that the seconds have been normalized to a recent start time
  200. // so as to avoid overflow
  201. unsigned _cmMfpElapsedMicroSecs( const struct timespec* t0, const struct timespec* t1 )
  202. {
  203. // convert seconds to usecs
  204. long u0 = t0->tv_sec * 1000000;
  205. long u1 = t1->tv_sec * 1000000;
  206. // convert nanoseconds to usec
  207. u0 += t0->tv_nsec / 1000;
  208. u1 += t1->tv_nsec / 1000;
  209. // take diff between t1 and t0
  210. return u1 - u0;
  211. }
  212. void _cmMfpTestTimer()
  213. {
  214. useconds_t suspendUsecs = 15 * 1000;
  215. struct timespec t0,t1,t2;
  216. unsigned accum = 0;
  217. unsigned i;
  218. unsigned n = 4000;
  219. // t0 will be the base time which all other times will be
  220. // set relative to.
  221. cmTimeGet(&t0);
  222. t2 = t0;
  223. t2.tv_sec = 0;
  224. for(i=0; i<n; ++i)
  225. {
  226. cmSleepUs(suspendUsecs);
  227. cmTimeGet(&t1);
  228. t1.tv_sec -= t0.tv_sec;
  229. unsigned d0usec = _cmMfpElapsedMicroSecs(&t0,&t1);
  230. unsigned d1usec = _cmMfpElapsedMicroSecs(&t2,&t1);
  231. accum += d1usec;
  232. if( i == n-1 )
  233. printf("%i %i %i\n",d0usec,d1usec,accum);
  234. t2 = t1;
  235. }
  236. }
  237. // midi file player callback test function
  238. void _cmMfpCallbackTest( void* userCbPtr, unsigned dmicros, const cmMidiTrackMsg_t* msgPtr )
  239. {
  240. if( kNoteOffMdId <= msgPtr->status && msgPtr->status <= kPbendMdId )
  241. cmMpDeviceSend( 0, 0, msgPtr->status+msgPtr->u.chMsgPtr->ch, msgPtr->u.chMsgPtr->d0,msgPtr->u.chMsgPtr->d1);
  242. //printf("%i 0x%x 0x%x %i\n",msgPtr->tick,msgPtr->status,msgPtr->metaId,msgPtr->trkIdx);
  243. }
  244. // midi port callback test function
  245. void _cmMpCallbackTest( const cmMidiPacket_t* pktArray, unsigned pktCnt )
  246. {}
  247. cmMfpRC_t cmMfpTest( const char* fn, cmCtx_t* ctx )
  248. {
  249. cmMfpH_t mfpH = cmMfpNullHandle;
  250. cmMfpRC_t rc;
  251. useconds_t suspendUsecs = 15 * 1000;
  252. struct timespec t0,t1,base;
  253. //unsigned i;
  254. //unsigned n = 4000;
  255. unsigned mdParserBufByteCnt = 1024;
  256. printf("Initializing MIDI Devices...\n");
  257. cmMpInitialize( ctx, _cmMpCallbackTest, NULL, mdParserBufByteCnt,"app" );
  258. //mdReport();
  259. printf("Creating Player...\n");
  260. if((rc = cmMfpCreate( &mfpH, _cmMfpCallbackTest, NULL, ctx )) != kOkMfpRC )
  261. return rc;
  262. printf("Loading MIDI file...\n");
  263. if((rc = cmMfpLoadFile( mfpH, fn )) != kOkMfpRC )
  264. goto errLabel;
  265. if((rc = cmMfpSeek( mfpH, 60 * 1000000 )) != kOkMfpRC )
  266. goto errLabel;
  267. cmTimeGet(&base);
  268. t0 = base;
  269. t0.tv_sec = 0;
  270. //for(i=0; i<n; ++i)
  271. while(rc != kEndOfFileMfpRC)
  272. {
  273. cmSleepUs(suspendUsecs);
  274. cmTimeGet(&t1);
  275. t1.tv_sec -= base.tv_sec;
  276. unsigned dusecs = _cmMfpElapsedMicroSecs(&t0,&t1);
  277. rc = cmMfpClock( mfpH, dusecs );
  278. //printf("%i %i\n",dusecs,rc);
  279. t0 = t1;
  280. }
  281. errLabel:
  282. cmMfpDestroy(&mfpH);
  283. cmMpFinalize();
  284. return rc;
  285. }
  286. //------------------------------------------------------------------------------------------------------------
  287. #include "cmFloatTypes.h"
  288. #include "cmComplexTypes.h"
  289. #include "cmLinkedHeap.h"
  290. #include "cmSymTbl.h"
  291. #include "cmAudioFile.h"
  292. #include "cmProcObj.h"
  293. #include "cmProcTemplateMain.h"
  294. #include "cmVectOps.h"
  295. #include "cmProc.h"
  296. #include "cmProc2.h"
  297. enum
  298. {
  299. kOkMfptRC = cmOkRC,
  300. kMfpFailMfptRC,
  301. kAudioFileFailMfptRC,
  302. kProcObjFailMfptRC
  303. };
  304. typedef struct
  305. {
  306. cmErr_t* err;
  307. cmMidiSynth* msp;
  308. } _cmMfpTest2CbData_t;
  309. // Called by the MIDI file player to send a msg to the MIDI synth.
  310. void _cmMfpCb( void* userCbPtr, unsigned dmicros, const cmMidiTrackMsg_t* msgPtr )
  311. {
  312. if( kNoteOffMdId <= msgPtr->status && msgPtr->status <= kPbendMdId )
  313. {
  314. cmMidiPacket_t pkt;
  315. cmMidiMsg msg;
  316. _cmMfpTest2CbData_t* d = (_cmMfpTest2CbData_t*)userCbPtr;
  317. msg.timeStamp.tv_sec = 0;
  318. msg.timeStamp.tv_nsec = 0;
  319. msg.status = msgPtr->status + msgPtr->u.chMsgPtr->ch;
  320. msg.d0 = msgPtr->u.chMsgPtr->d0;
  321. msg.d1 = msgPtr->u.chMsgPtr->d1;
  322. pkt.cbDataPtr = NULL;
  323. pkt.devIdx = cmInvalidIdx;
  324. pkt.portIdx = cmInvalidIdx;
  325. pkt.msgArray = &msg;
  326. pkt.sysExMsg = NULL;
  327. pkt.msgCnt = 1;
  328. if( cmMidiSynthOnMidi( d->msp, &pkt, 1 ) != cmOkRC )
  329. cmErrMsg(d->err,kProcObjFailMfptRC,"Synth. MIDI receive failed.");
  330. }
  331. }
  332. // Called by the MIDI synth to send a msg to the voice bank.
  333. int _cmMidiSynthCb( struct cmMidiVoice_str* voicePtr, unsigned sel, cmSample_t* outChArray[], unsigned outChCnt )
  334. {
  335. return cmWtVoiceBankExec( ((cmWtVoiceBank*)voicePtr->pgm.cbDataPtr), voicePtr, sel, outChArray, outChCnt );
  336. }
  337. // BUG BUG BUG: THIS FUNCTION IS NOT TESTED!!!!!
  338. cmRC_t cmMfpTest2( const char* midiFn, const char* audioFn, cmCtx_t* ctx )
  339. {
  340. cmRC_t rc = kOkMfptRC;
  341. cmMfpH_t mfpH = cmMfpNullHandle;
  342. _cmMfpTest2CbData_t cbData;
  343. cmErr_t err;
  344. cmAudioFileH_t afH = cmNullAudioFileH;
  345. cmRC_t afRC = kOkAfRC;
  346. double afSrate = 44100;
  347. unsigned afBits = 16;
  348. unsigned afChCnt = 1;
  349. cmCtx* cctx;
  350. cmMidiSynth* msp;
  351. cmWtVoiceBank* vbp;
  352. unsigned msPgmCnt = 127;
  353. cmMidiSynthPgm msPgmArray[ msPgmCnt ];
  354. unsigned msVoiceCnt = 36;
  355. unsigned procSmpCnt = 64;
  356. unsigned i;
  357. cmErrSetup(&err,&ctx->rpt,"MFP Test 2");
  358. // create the MIDI file player
  359. if( cmMfpCreate(&mfpH, _cmMfpCb, &cbData, ctx ) != kOkMfpRC )
  360. return cmErrMsg(&err,kMfpFailMfptRC,"MIDI file player create failed.");
  361. // create an output audio file
  362. if( cmAudioFileIsValid( afH = cmAudioFileNewCreate(audioFn, afSrate, afBits, afChCnt, &afRC, &ctx->rpt))==false)
  363. {
  364. rc = cmErrMsg(&err,kAudioFileFailMfptRC,"The audio file create failed.");
  365. goto errLabel;
  366. }
  367. // load the midi file into the player
  368. if( cmMfpLoadFile( mfpH, midiFn ) != kOkMfpRC )
  369. {
  370. rc = cmErrMsg(&err,kMfpFailMfptRC,"MIDI file load failed.");
  371. goto errLabel;
  372. }
  373. // create the proc obj context
  374. if((cctx = cmCtxAlloc(NULL, &ctx->rpt, cmLHeapNullHandle, cmSymTblNullHandle )) == NULL)
  375. {
  376. rc = cmErrMsg(&err,kProcObjFailMfptRC,"cmCtx allocate failed.");
  377. goto errLabel;
  378. }
  379. // create the voice bank
  380. if((vbp = cmWtVoiceBankAlloc(cctx, NULL, afSrate, procSmpCnt, msVoiceCnt, afChCnt )) == NULL)
  381. {
  382. rc = cmErrMsg(&err,kProcObjFailMfptRC,"WT voice bank allocate failed.");
  383. goto errLabel;
  384. }
  385. // a MIDI synth
  386. if((msp = cmMidiSynthAlloc(cctx, NULL, msPgmArray, msPgmCnt, msVoiceCnt, procSmpCnt, afChCnt, afSrate )) == NULL )
  387. {
  388. rc = cmErrMsg(&err,kProcObjFailMfptRC,"MIDI synth allocate failed.");
  389. goto errLabel;
  390. }
  391. cbData.msp = msp;
  392. cbData.err = &err;
  393. // load all of the the MIDI pgm recds with the same settings
  394. for(i=0; i<msPgmCnt; ++i)
  395. {
  396. msPgmArray[i].pgm = i;
  397. msPgmArray[i].cbPtr = _cmMidiSynthCb; // Call this function to update voices using this pgm
  398. msPgmArray[i].cbDataPtr = vbp; // Voice bank containing the voice states.
  399. }
  400. unsigned dusecs = floor((double)procSmpCnt * 1000000. / afSrate);
  401. while(rc != kEndOfFileMfpRC)
  402. {
  403. // update the MFP's current time and call _cmMfpCb() for MIDI msgs whose time has elapsed
  404. rc = cmMfpClock( mfpH, dusecs );
  405. // check for MFP errors
  406. if(rc!=kOkMfpRC && rc!=kEndOfFileMfpRC)
  407. {
  408. cmErrMsg(&err,kMfpFailMfptRC,"MIDI file player exec failed.");
  409. goto errLabel;
  410. }
  411. // generate audio based on the current state of the synth voices
  412. if( cmMidiSynthExec(msp, NULL, 0 ) != cmOkRC )
  413. {
  414. cmErrMsg(&err,kProcObjFailMfptRC,"MIDI synth exec. failed.");
  415. goto errLabel;
  416. }
  417. // write the last frame of synth. generated audio to the output file
  418. if( cmAudioFileWriteSample(afH, procSmpCnt, msp->outChCnt, msp->outChArray ) != kOkAfRC )
  419. {
  420. cmErrMsg(&err,kProcObjFailMfptRC,"Audio file write failed.");
  421. goto errLabel;
  422. }
  423. }
  424. errLabel:
  425. if( cmMidiSynthFree(&msp) != cmOkRC )
  426. cmErrMsg(&err,kProcObjFailMfptRC,"MIDI synth. free failed.");
  427. if( cmWtVoiceBankFree(&vbp) != cmOkRC )
  428. cmErrMsg(&err,kProcObjFailMfptRC,"WT voice free failed.");
  429. if( cmCtxFree(&cctx) != cmOkRC )
  430. cmErrMsg(&err,kProcObjFailMfptRC,"cmCtx free failed.");
  431. if( cmAudioFileDelete(&afH) )
  432. cmErrMsg(&err,kAudioFileFailMfptRC,"The audio file close failed.");
  433. if( cmMfpDestroy(&mfpH) != kOkMfpRC )
  434. cmErrMsg(&err,kMfpFailMfptRC,"MIDI file player destroy failed.");
  435. return rc;
  436. }