libcm is a C development framework with an emphasis on audio signal processing applications.
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

cmProc4.c 113KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572
  1. #include "cmPrefix.h"
  2. #include "cmGlobal.h"
  3. #include "cmRpt.h"
  4. #include "cmErr.h"
  5. #include "cmCtx.h"
  6. #include "cmMem.h"
  7. #include "cmMallocDebug.h"
  8. #include "cmLinkedHeap.h"
  9. #include "cmFloatTypes.h"
  10. #include "cmComplexTypes.h"
  11. #include "cmFile.h"
  12. #include "cmFileSys.h"
  13. #include "cmJson.h"
  14. #include "cmSymTbl.h"
  15. #include "cmAudioFile.h"
  16. #include "cmText.h"
  17. #include "cmProcObj.h"
  18. #include "cmProcTemplate.h"
  19. #include "cmMath.h"
  20. #include "cmTime.h"
  21. #include "cmMidi.h"
  22. #include "cmMidiFile.h"
  23. #include "cmProc.h"
  24. #include "cmProc2.h"
  25. #include "cmVectOps.h"
  26. #include "cmTimeLine.h"
  27. #include "cmScore.h"
  28. #include "cmProc4.h"
  29. cmScFol* cmScFolAlloc( cmCtx* c, cmScFol* p, cmReal_t srate, cmScH_t scH, unsigned bufN, unsigned minWndLookAhead, unsigned maxWndCnt, unsigned minVel )
  30. {
  31. cmScFol* op = cmObjAlloc(cmScFol,c,p);
  32. if( srate != 0 )
  33. if( cmScFolInit(op,srate,scH,bufN,minWndLookAhead,maxWndCnt,minVel) != cmOkRC )
  34. cmScFolFree(&op);
  35. return op;
  36. }
  37. cmRC_t cmScFolFree( cmScFol** pp )
  38. {
  39. cmRC_t rc = cmOkRC;
  40. if( pp==NULL || *pp==NULL )
  41. return rc;
  42. cmScFol* p = *pp;
  43. if((rc = cmScFolFinal(p)) != cmOkRC )
  44. return rc;
  45. unsigned i;
  46. for(i=0; i<p->locN; ++i)
  47. cmMemFree(p->loc[i].evtV);
  48. cmMemFree(p->loc);
  49. cmMemFree(p->bufV);
  50. cmObjFree(pp);
  51. return rc;
  52. }
  53. cmRC_t cmScFolFinal( cmScFol* p )
  54. {
  55. cmMemFree(p->edWndMtx);
  56. return cmOkRC;
  57. }
  58. void _cmScFolPrint( cmScFol* p )
  59. {
  60. int i,j;
  61. for(i=0; i<p->locN; ++i)
  62. {
  63. printf("%2i %5i ",p->loc[i].barNumb,p->loc[i].scIdx);
  64. for(j=0; j<p->loc[i].evtCnt; ++j)
  65. printf("%s ",cmMidiToSciPitch(p->loc[i].evtV[j].pitch,NULL,0));
  66. printf("\n");
  67. }
  68. }
  69. unsigned* _cmScFolAllocEditDistMtx(unsigned maxN)
  70. {
  71. maxN += 1;
  72. unsigned* m = cmMemAllocZ(unsigned,maxN*maxN);
  73. unsigned* p = m;
  74. unsigned i;
  75. // initialize the comparison matrix with the default costs in the
  76. // first row and column
  77. // (Note that this matrix is not oriented in column major order like most 'cm' matrices.)
  78. for(i=0; i<maxN; ++i)
  79. {
  80. p[i] = i; // 0th row
  81. p[ i * maxN ] = i; // 0th col
  82. }
  83. return m;
  84. }
  85. cmRC_t cmScFolInit( cmScFol* p, cmReal_t srate, cmScH_t scH, unsigned bufN, unsigned minWndLookAhead, unsigned maxWndCnt, unsigned minVel )
  86. {
  87. cmRC_t rc;
  88. if((rc = cmScFolFinal(p)) != cmOkRC )
  89. return rc;
  90. if( bufN > maxWndCnt )
  91. return cmCtxRtCondition( &p->obj, cmInvalidArgRC, "The score follower buffer count (%i) must be less than the max. window length (%i).",bufN,maxWndCnt );
  92. if( minWndLookAhead > maxWndCnt )
  93. return cmCtxRtCondition( &p->obj, cmInvalidArgRC, "The score follower look-ahead count (%i) must be less than the max. window length (%i).",minWndLookAhead,maxWndCnt);
  94. p->srate = srate;
  95. p->scH = scH;
  96. p->bufN = bufN;
  97. p->bufV = cmMemResizeZ(cmScFolBufEle_t,p->bufV,bufN);
  98. p->locN = cmScoreEvtCount(scH);
  99. p->loc = cmMemResizeZ(cmScFolLoc_t,p->loc,p->locN);
  100. p->sbi = cmInvalidIdx;
  101. p->sei = cmInvalidIdx;
  102. p->msln = minWndLookAhead;
  103. p->mswn = maxWndCnt;
  104. p->forwardCnt = 2;
  105. p->maxDist = 4;
  106. p->edWndMtx = _cmScFolAllocEditDistMtx(p->bufN);
  107. p->minVel = minVel;
  108. p->printFl = true;
  109. p->noBackFl = true;
  110. p->missCnt = 0;
  111. p->matchCnt = 0;
  112. p->eventIdx = 0;
  113. p->skipCnt = 0;
  114. p->ret_idx = cmInvalidIdx;
  115. // for each score location
  116. unsigned li,ei;
  117. for(li=0,ei=0; li<cmScoreLocCount(p->scH); ++li)
  118. {
  119. unsigned i,n;
  120. const cmScoreLoc_t* lp = cmScoreLoc(p->scH,li);
  121. // count the number of note events at location li
  122. for(n=0,i=0; i<lp->evtCnt; ++i)
  123. if( lp->evtArray[i]->type == kNonEvtScId )
  124. ++n;
  125. assert( ei+n <= p->locN );
  126. // duplicate each note at location li n times
  127. for(i=0; i<n; ++i)
  128. {
  129. unsigned j,k;
  130. p->loc[ei+i].evtCnt = n;
  131. p->loc[ei+i].evtV = cmMemAllocZ(cmScFolEvt_t,n);
  132. p->loc[ei+i].scIdx = li;
  133. p->loc[ei+i].barNumb = lp->barNumb;
  134. for(j=0,k=0; j<lp->evtCnt; ++j)
  135. if( lp->evtArray[j]->type == kNonEvtScId )
  136. {
  137. p->loc[ei+i].evtV[k].pitch = lp->evtArray[j]->pitch;
  138. p->loc[ei+i].evtV[k].scEvtIdx = lp->evtArray[j]->index;
  139. ++k;
  140. }
  141. }
  142. ei += n;
  143. }
  144. p->locN = ei;
  145. //_cmScFolPrint(p);
  146. return rc;
  147. }
  148. cmRC_t cmScFolReset( cmScFol* p, unsigned scEvtIdx )
  149. {
  150. int i,j;
  151. // empty the event buffer
  152. memset(p->bufV,0,sizeof(cmScFolBufEle_t)*p->bufN);
  153. // don't allow the score index to be prior to the first note
  154. //if( scEvtIdx < p->loc[0].scIdx )
  155. // scEvtIdx = p->loc[0].scIdx;
  156. p->sei = cmInvalidIdx;
  157. p->sbi = cmInvalidIdx;
  158. p->missCnt = 0;
  159. p->matchCnt = 0;
  160. p->eventIdx = 0;
  161. p->skipCnt = 0;
  162. p->ret_idx = cmInvalidIdx;
  163. // locate the score element in svV[] that is closest to,
  164. // and possibly after, scEvtIdx.
  165. for(i=0; i<p->locN-1; ++i)
  166. {
  167. for(j=0; j<p->loc[i].evtCnt; ++j)
  168. if( p->loc[i].evtV[j].scEvtIdx <= scEvtIdx )
  169. p->sbi = i;
  170. else
  171. break;
  172. }
  173. // locate the score element at the end of the look-ahead region
  174. for(; i<p->locN; ++i)
  175. {
  176. for(j=0; j<p->loc[i].evtCnt; ++j)
  177. if( p->loc[i].evtV[j].scEvtIdx <= scEvtIdx + p->msln )
  178. p->sei = i;
  179. }
  180. return cmOkRC;
  181. }
  182. bool _cmScFolIsMatch( const cmScFolLoc_t* loc, unsigned pitch )
  183. {
  184. unsigned i;
  185. for(i=0; i<loc->evtCnt; ++i)
  186. if( loc->evtV[i].pitch == pitch )
  187. return true;
  188. return false;
  189. }
  190. int _cmScFolMatchCost( const cmScFolLoc_t* loc, unsigned li, const cmScFolBufEle_t* pitch, unsigned pi )
  191. {
  192. if( _cmScFolIsMatch(loc+li,pitch[pi].val) )
  193. return 0;
  194. if( li>0 && pi>0 )
  195. if( _cmScFolIsMatch(loc+li-1,pitch[pi].val) && _cmScFolIsMatch(loc+li,pitch[pi-1].val) )
  196. return 0;
  197. return 1;
  198. }
  199. int _cmScFolDist(unsigned mtxMaxN, unsigned* m, const cmScFolBufEle_t* s1, const cmScFolLoc_t* s0, int n )
  200. {
  201. mtxMaxN += 1;
  202. assert( n < mtxMaxN );
  203. int v = 0;
  204. unsigned i;
  205. // Note that m[maxN,maxN] is not oriented in column major order like most 'cm' matrices.
  206. for(i=1; i<n+1; ++i)
  207. {
  208. unsigned ii = i * mtxMaxN; // current row
  209. unsigned i_1 = ii - mtxMaxN; // previous row
  210. unsigned j;
  211. for( j=1; j<n+1; ++j)
  212. {
  213. //int cost = s0[i-1] == s1[j-1] ? 0 : 1;
  214. //int cost = _cmScFolIsMatch(s0 + i-1, s1[j-1]) ? 0 : 1;
  215. int cost = _cmScFolMatchCost(s0,i-1,s1,j-1);
  216. //m[i][j] = min( m[i-1][j] + 1, min( m[i][j-1] + 1, m[i-1][j-1] + cost ) );
  217. m[ ii + j ] = v = cmMin( m[ i_1 + j] + 1, cmMin( m[ ii + j - 1] + 1, m[ i_1 + j - 1 ] + cost ) );
  218. }
  219. }
  220. return v;
  221. }
  222. void _cmScFolRpt0( cmScFol* p, unsigned locIdx, unsigned locN, const cmScFolBufEle_t* b, unsigned bn, unsigned min_idx )
  223. {
  224. unsigned i;
  225. int n;
  226. printf("--------------- event:%i ------------- \n",p->eventIdx);
  227. printf("loc: ");
  228. for(i=0; i<locN; ++i)
  229. printf("%4i ",i+locIdx);
  230. printf("\n");
  231. for(n=0,i=0; i<locN; ++i)
  232. if( p->loc[locIdx+i].evtCnt > n )
  233. n = p->loc[locIdx+i].evtCnt;
  234. --n;
  235. for(; n>=0; --n)
  236. {
  237. printf("sc%1i: ",n);
  238. for(i=0; i<locN; ++i)
  239. {
  240. if( n < p->loc[locIdx+i].evtCnt )
  241. printf("%4s ",cmMidiToSciPitch(p->loc[locIdx+i].evtV[n].pitch,NULL,0));
  242. else
  243. printf(" ");
  244. }
  245. printf("\n");
  246. }
  247. printf("perf:");
  248. for(i=0; i<min_idx; ++i)
  249. printf(" ");
  250. for(i=0; i<bn; ++i)
  251. printf("%4s ",cmMidiToSciPitch(b[i].val,NULL,0));
  252. printf("\n");
  253. }
  254. void _cmScFolRpt1( cmScFol*p, unsigned minDist, unsigned ret_idx, unsigned d1, unsigned missCnt, unsigned matchCnt )
  255. {
  256. printf("dist:%i miss:%i match:%i skip:%i vel:%i ",minDist,missCnt,matchCnt,p->skipCnt,d1);
  257. if( ret_idx != cmInvalidIdx )
  258. printf("ret_idx:%i ",ret_idx);
  259. printf("\n");
  260. }
  261. unsigned cmScFolExec( cmScFol* p, unsigned smpIdx, unsigned status, cmMidiByte_t d0, cmMidiByte_t d1 )
  262. {
  263. unsigned ret_idx = cmInvalidIdx;
  264. if( p->sbi == cmInvalidIdx )
  265. {
  266. cmCtxRtCondition( &p->obj, cmInvalidArgRC, "An initial score search location has not been set." );
  267. return ret_idx;
  268. }
  269. if( (status&0xf0) != kNoteOnMdId )
  270. return ret_idx;
  271. ++p->eventIdx;
  272. // reject notes with very low velocity
  273. if( d1 < p->minVel )
  274. {
  275. ++p->skipCnt;
  276. return ret_idx;
  277. }
  278. // left shift bufV[] to make the right-most element available - then copy in the new element
  279. memmove(p->bufV, p->bufV+1, sizeof(cmScFolBufEle_t)*(p->bufN-1));
  280. p->bufV[ p->bufN-1 ].smpIdx = smpIdx;
  281. p->bufV[ p->bufN-1 ].val = d0;
  282. p->bufV[ p->bufN-1 ].validFl= true;
  283. // fill in ebuf[] with the valid values in bufV[]
  284. int en = cmMin(p->eventIdx,p->bufN);
  285. int bbi = p->eventIdx>=p->bufN ? 0 : p->bufN-p->eventIdx;
  286. // en is the count of valid elements in ebuf[].
  287. // ebuf[p->boi] is the first valid element
  288. int j = 0;
  289. int minDist = INT_MAX;
  290. int minIdx = cmInvalidIdx;
  291. int dist;
  292. // the score wnd must always be as long as the buffer n
  293. // at the end of the score this may not be the case
  294. // (once sei hits locN - at this point we must begin
  295. // shrinking ewnd[] to contain only the last p->sei-p->sbi+1 elements)
  296. assert( p->sei-p->sbi+1 >= en );
  297. for(j=0; p->sbi+en+j-1 <= p->sei; ++j)
  298. {
  299. // use <= minDist to choose the latest window with the lowest match
  300. if((dist = _cmScFolDist(p->bufN, p->edWndMtx, p->bufV+bbi, p->loc + p->sbi+j, en )) < minDist )
  301. {
  302. // only make an eql match if the posn is greater than the last location
  303. if( dist==minDist && p->ret_idx != cmInvalidId && p->ret_idx >= p->sbi+minIdx+en-1 )
  304. continue;
  305. minDist = dist;
  306. minIdx = j;
  307. }
  308. }
  309. // The best fit is on the score window: p->loc[sbi+minIdx : sbi+minIdx+en-1 ]
  310. if( p->printFl )
  311. _cmScFolRpt0( p, p->sbi, p->sei-p->sbi+1, p->bufV+bbi, en, minIdx );
  312. // save current missCnt for later printing
  313. unsigned missCnt = p->missCnt;
  314. // if a perfect match occurred
  315. if( minDist == 0 )
  316. {
  317. ret_idx = p->sbi + minIdx + en - 1;
  318. p->missCnt = 0;
  319. // we had a perfect match - shrink the window to it's minumum size
  320. p->sbi += (en==p->bufN) ? minIdx + 1 : 0; // move wnd begin forward to just past first match
  321. p->sei = p->sbi + minIdx + en + p->msln; // move wnd end forward to lead by the min look-ahead
  322. }
  323. else
  324. {
  325. if( minDist > p->maxDist )
  326. ret_idx = cmInvalidIdx;
  327. else
  328. // if the last event matched - then return the match location as the current score location
  329. if( _cmScFolIsMatch(p->loc+(p->sbi+minIdx+en-1),p->bufV[p->bufN-1].val) )
  330. {
  331. ret_idx = p->sbi + minIdx + en - 1;
  332. p->missCnt = 0;
  333. // this is probably a pretty good match reduce the part of the window prior to
  334. // the first match (bring the end of the window almost up to the end of the
  335. // buffers sync position)
  336. if( en >= p->bufN-1 && (en+2) <= ret_idx )
  337. p->sbi = ret_idx - (en+2);
  338. }
  339. else // the last event does not match based on the optimal edit-distance alignment
  340. {
  341. // Look backward from the closest match location for a match to the current pitch.
  342. // The backward search scope is limited by the current value of 'missCnt'.
  343. unsigned i;
  344. j = p->sbi+minIdx+en-2;
  345. for(i=1; i+1 <= p->bufN && j>=p->sbi && i<=p->missCnt; ++i,--j)
  346. {
  347. // if this look-back location already matched then stop the backward search
  348. if(_cmScFolIsMatch(p->loc+j,p->bufV[p->bufN-1-i].val))
  349. break;
  350. // does this look-back location match the current pitch
  351. if(_cmScFolIsMatch(p->loc+j,p->bufV[p->bufN-1].val))
  352. {
  353. ret_idx = j;
  354. p->missCnt = i; // set missCnt to the cnt of steps backward necessary for a match
  355. break;
  356. }
  357. }
  358. // If the backward search did not find a match - look forward
  359. if( ret_idx == cmInvalidIdx )
  360. {
  361. unsigned i;
  362. j = p->sbi+minIdx+en;
  363. for(i=0; j<=p->sei && i<p->forwardCnt; ++i,++j)
  364. if( _cmScFolIsMatch(p->loc+j,p->bufV[p->bufN-1].val) )
  365. {
  366. ret_idx = j;
  367. break;
  368. }
  369. p->missCnt = ret_idx == cmInvalidIdx ? p->missCnt + 1 : 0;
  370. }
  371. }
  372. // Adjust the end window position (sei) based on the match location
  373. if( ret_idx == cmInvalidIdx )
  374. {
  375. // even though we didn't match move the end of the score window forward
  376. // this will enlarge the score window by one
  377. p->sei += 1;
  378. }
  379. else
  380. {
  381. assert( p->sei>=ret_idx);
  382. // force sei to lead by min look-ahead
  383. if( p->sei - ret_idx < p->msln )
  384. p->sei = ret_idx + p->msln;
  385. }
  386. assert( p->sei > p->sbi );
  387. // Adjust the begin window position
  388. if( p->noBackFl && ret_idx != cmInvalidIdx && en>=p->bufN && p->sbi > p->bufN )
  389. p->sbi = ret_idx - p->bufN;
  390. // if the score window length surpasses the max score window size
  391. // move the beginning index forward
  392. if( p->sei - p->sbi + 1 > p->mswn && p->sei > p->mswn )
  393. p->sbi = p->sei - p->mswn + 1;
  394. }
  395. if( p->printFl )
  396. _cmScFolRpt1(p, minDist, ret_idx, d1, missCnt, p->matchCnt );
  397. // don't allow the returned location to repeat or go backwards
  398. if( p->noBackFl && p->ret_idx != cmInvalidIdx && ret_idx <= p->ret_idx )
  399. ret_idx = cmInvalidIdx;
  400. // track the number of consecutive matches
  401. if( ret_idx == cmInvalidIdx )
  402. p->matchCnt = 0;
  403. else
  404. {
  405. ++p->matchCnt;
  406. p->ret_idx = ret_idx;
  407. }
  408. // Force the window to remain valid when it is at the end of the score
  409. // - sbi and sei must be inside 0:locN
  410. // - sei-sbi + 1 must be >= en
  411. if( p->sei >= p->locN )
  412. {
  413. p->sei = p->locN - 1;
  414. p->sbi = p->sei - p->bufN + 1;
  415. }
  416. if( ret_idx != cmInvalidIdx )
  417. ret_idx = p->loc[ret_idx].scIdx;
  418. return ret_idx;
  419. }
  420. //=======================================================================================================================
  421. cmScTrk* cmScTrkAlloc( cmCtx* c, cmScTrk* p, cmReal_t srate, cmScH_t scH, unsigned bufN, unsigned minWndLookAhead, unsigned maxWndCnt, unsigned minVel )
  422. {
  423. cmScTrk* op = cmObjAlloc(cmScTrk,c,p);
  424. op->sfp = cmScFolAlloc(c,NULL,srate,scH,bufN,minWndLookAhead,maxWndCnt,minVel);
  425. if( srate != 0 )
  426. if( cmScTrkInit(op,srate,scH,bufN,minWndLookAhead,maxWndCnt,minVel) != cmOkRC )
  427. cmScTrkFree(&op);
  428. return op;
  429. }
  430. cmRC_t cmScTrkFree( cmScTrk** pp )
  431. {
  432. cmRC_t rc = cmOkRC;
  433. if( pp==NULL || *pp==NULL )
  434. return rc;
  435. cmScTrk* p = *pp;
  436. if((rc = cmScTrkFinal(p)) != cmOkRC )
  437. return rc;
  438. cmScFolFree(&p->sfp);
  439. cmObjFree(pp);
  440. return rc;
  441. }
  442. void _cmScTrkPrint( cmScTrk* p )
  443. {
  444. int i,j;
  445. for(i=0; i<p->locN; ++i)
  446. {
  447. printf("%2i %5i ",p->loc[i].barNumb,p->loc[i].scIdx);
  448. for(j=0; j<p->loc[i].evtCnt; ++j)
  449. printf("%s ",cmMidiToSciPitch(p->loc[i].evtV[j].pitch,NULL,0));
  450. printf("\n");
  451. }
  452. }
  453. cmRC_t cmScTrkInit( cmScTrk* p, cmReal_t srate, cmScH_t scH, unsigned bufN, unsigned minWndLookAhead, unsigned maxWndCnt, unsigned minVel )
  454. {
  455. cmRC_t rc;
  456. if((rc = cmScTrkFinal(p)) != cmOkRC )
  457. return rc;
  458. if( minWndLookAhead > maxWndCnt )
  459. return cmCtxRtCondition( &p->obj, cmInvalidArgRC, "The score follower look-ahead count (%i) must be less than the max. window length (%i).",minWndLookAhead,maxWndCnt);
  460. if((rc = cmScFolInit(p->sfp,srate,scH,bufN,minWndLookAhead,maxWndCnt,minVel)) != cmOkRC )
  461. return rc;
  462. p->srate = srate;
  463. p->scH = scH;
  464. p->locN = cmScoreLocCount(scH);
  465. p->loc = cmMemResizeZ(cmScTrkLoc_t,p->loc,p->locN);
  466. p->minVel = minVel;
  467. p->maxWndCnt = maxWndCnt;
  468. p->minWndLookAhead= 4; //minWndLookAhead;
  469. p->printFl = true;
  470. p->curLocIdx = cmInvalidIdx;
  471. p->evtIndex = 0;
  472. // for each score location
  473. unsigned li;
  474. for(li=0; li<cmScoreLocCount(p->scH); ++li)
  475. {
  476. unsigned i,j,k,n;
  477. const cmScoreLoc_t* lp = cmScoreLoc(p->scH,li);
  478. // count the number of note events at location li
  479. for(n=0,i=0; i<lp->evtCnt; ++i)
  480. if( lp->evtArray[i]->type == kNonEvtScId )
  481. ++n;
  482. p->loc[li].evtCnt = n;
  483. p->loc[li].evtV = cmMemAllocZ(cmScTrkEvt_t,n);
  484. p->loc[li].scIdx = li;
  485. p->loc[li].barNumb = lp->barNumb;
  486. for(j=0,k=0; j<lp->evtCnt; ++j)
  487. if( lp->evtArray[j]->type == kNonEvtScId )
  488. {
  489. p->loc[li].evtV[k].pitch = lp->evtArray[j]->pitch;
  490. p->loc[li].evtV[k].scEvtIdx = lp->evtArray[j]->index;
  491. ++k;
  492. }
  493. }
  494. //_cmScTrkPrint(p);
  495. return rc;
  496. }
  497. cmRC_t cmScTrkFinal( cmScTrk* p )
  498. {
  499. unsigned i;
  500. for(i=0; i<p->locN; ++i)
  501. cmMemPtrFree(&p->loc[i].evtV);
  502. return cmOkRC;
  503. }
  504. cmRC_t cmScTrkReset( cmScTrk* p, unsigned scEvtIdx )
  505. {
  506. unsigned i;
  507. cmScFolReset(p->sfp,scEvtIdx);
  508. p->curLocIdx = cmInvalidIdx;
  509. p->evtIndex = 0;
  510. // locate the score element in svV[] that is closest to,
  511. // and possibly after, scEvtIdx.
  512. for(i=0; i<p->locN; ++i)
  513. {
  514. unsigned j;
  515. for(j=0; j<p->loc[i].evtCnt; ++j)
  516. {
  517. p->loc[i].evtV[j].matchFl = false;
  518. // it is possible that scEvtIdx is before the first event included in p->loc[0]
  519. // using the p->curLocIdx==cmInvalidIdx forces the first evt in p->loc[0] to be
  520. // selected in this case
  521. if( p->loc[i].evtV[j].scEvtIdx <= scEvtIdx || p->curLocIdx==cmInvalidIdx )
  522. p->curLocIdx = i;
  523. }
  524. }
  525. if( p->curLocIdx == cmInvalidIdx )
  526. return cmCtxRtCondition( &p->obj, cmInvalidArgRC, "The initial score search location event %i was not found.", scEvtIdx );
  527. return cmOkRC;
  528. }
  529. unsigned _cmScTrkIsMatch(cmScTrk* p, int d, unsigned pitch )
  530. {
  531. if( 0 <= p->curLocIdx + d && p->curLocIdx+1 < p->locN )
  532. {
  533. unsigned i;
  534. const cmScTrkLoc_t* lp = p->loc + p->curLocIdx + d;
  535. for(i=0; i<lp->evtCnt; ++i)
  536. if( lp->evtV[i].pitch == pitch && lp->evtV[i].matchFl==false)
  537. return i;
  538. }
  539. return cmInvalidIdx;
  540. }
  541. void _cmScTrkRpt0( cmScTrk* p, unsigned pitch, unsigned vel, unsigned nli, unsigned nei )
  542. {
  543. bool missFl = nli==cmInvalidIdx || nei==cmInvalidIdx;
  544. printf("------- event:%i %s vel:%i cur:%i new:%i %s-------\n",p->evtIndex,cmMidiToSciPitch(pitch,NULL,0),vel,p->curLocIdx,nli,missFl?"MISS ":"");
  545. int bi = p->curLocIdx < p->minWndLookAhead ? 0 : p->curLocIdx - p->minWndLookAhead;
  546. int ei = cmMin(p->locN-1,p->curLocIdx+p->minWndLookAhead);
  547. unsigned i,n=0;
  548. for(i=bi; i<=ei; ++i)
  549. if( p->loc[i].evtCnt>n )
  550. n = p->loc[i].evtCnt;
  551. printf("loc ");
  552. for(i=bi; i<=ei; ++i)
  553. printf("%4i ",i);
  554. printf("\n");
  555. for(i=0; i<n; ++i)
  556. {
  557. unsigned j;
  558. printf("sc%2i ",i);
  559. for(j=bi; j<=ei; ++j)
  560. {
  561. if( i < p->loc[j].evtCnt )
  562. {
  563. char* X = p->loc[j].evtV[i].matchFl ? "__" : " ";
  564. if( nli==j && nei==i)
  565. {
  566. X = "**";
  567. assert( p->loc[j].evtV[i].pitch == pitch );
  568. }
  569. printf("%4s%s ",cmMidiToSciPitch(p->loc[j].evtV[i].pitch,NULL,0),X);
  570. }
  571. else
  572. printf(" ");
  573. }
  574. printf("\n");
  575. }
  576. }
  577. unsigned cmScTrkExec( cmScTrk* p, unsigned smpIdx, unsigned status, cmMidiByte_t d0, cmMidiByte_t d1 )
  578. {
  579. unsigned ret_idx = cmInvalidIdx;
  580. //cmScFolExec(p->sfp, smpIdx, status, d0, d1);
  581. if( (status&0xf0) != kNoteOnMdId )
  582. return cmInvalidIdx;
  583. if( p->curLocIdx == cmInvalidIdx )
  584. {
  585. cmCtxRtCondition( &p->obj, cmInvalidArgRC, "An initial score search location has not been set." );
  586. return cmInvalidIdx;
  587. }
  588. int i,nei,nli=cmInvalidIdx;
  589. // try to match curLocIdx first
  590. if((nei = _cmScTrkIsMatch(p,0,d0)) != cmInvalidIdx )
  591. nli = p->curLocIdx;
  592. for(i=1; nei==cmInvalidIdx && i<p->minWndLookAhead; ++i)
  593. {
  594. // go forward
  595. if((nei = _cmScTrkIsMatch(p,i,d0)) != cmInvalidIdx )
  596. nli = p->curLocIdx + i;
  597. else
  598. // go backward
  599. if((nei = _cmScTrkIsMatch(p,-i,d0)) != cmInvalidIdx )
  600. nli = p->curLocIdx - i;
  601. }
  602. if( p->printFl )
  603. {
  604. _cmScTrkRpt0(p, d0, d1, nli, nei );
  605. }
  606. if( nli != cmInvalidIdx )
  607. {
  608. p->loc[nli].evtV[nei].matchFl = true;
  609. ret_idx = p->loc[nli].scIdx;
  610. if( nli > p->curLocIdx )
  611. p->curLocIdx = nli;
  612. }
  613. ++p->evtIndex;
  614. return ret_idx;
  615. }
  616. //=======================================================================================================================
  617. //----------------------------------------------------------------------------------------
  618. void ed_print_mtx( ed_r* r)
  619. {
  620. unsigned i,j,k;
  621. for(i=0; i<r->rn; ++i)
  622. {
  623. for(j=0; j<r->cn; ++j)
  624. {
  625. printf("(");
  626. const ed_val* vp = r->m + i + (j*r->rn);
  627. for(k=0; k<kEdCnt; ++k)
  628. {
  629. printf("%i",vp->v[k]);
  630. if( k<kEdCnt-1)
  631. printf(", ");
  632. else
  633. printf(" ");
  634. }
  635. printf("%c)",vp->transFl?'t':' ');
  636. }
  637. printf("\n");
  638. }
  639. }
  640. void ed_init( ed_r* r, const char* s0, const char* s1 )
  641. {
  642. unsigned i,j,k;
  643. r->rn = strlen(s0)+1;
  644. r->cn = strlen(s1)+1;
  645. r->m = cmMemAllocZ(ed_val, r->rn*r->cn );
  646. r->pn = r->rn + r->cn;
  647. r->p_mem = cmMemAllocZ(ed_path, 2*r->pn );
  648. r->p_avl = r->p_mem;
  649. r->p_cur = NULL;
  650. r->p_opt = r->p_mem + r->pn;
  651. r->s_opt = DBL_MAX;
  652. r->s0 = s0;
  653. r->s1 = s1;
  654. for(i=0; i<r->rn; ++i)
  655. for(j=0; j<r->cn; ++j)
  656. {
  657. unsigned v[] = {0,0,0,0};
  658. if( i == 0 )
  659. {
  660. v[kEdMinIdx] = j;
  661. v[kEdInsIdx] = j;
  662. }
  663. else
  664. if( j == 0 )
  665. {
  666. v[kEdMinIdx] = i;
  667. v[kEdDelIdx] = i;
  668. }
  669. for(k=0; k<kEdCnt; ++k)
  670. r->m[ i + (j*r->rn) ].v[k] = v[k];
  671. }
  672. // put pn path records on the available list
  673. for(i=0; i<r->pn; ++i)
  674. r->p_mem[i].next = i<r->pn-1 ? r->p_mem + i + 1 : NULL;
  675. }
  676. unsigned _ed_min( ed_r* r, unsigned i, unsigned j )
  677. {
  678. assert( i<r->rn && j<r->cn );
  679. return r->m[ i + (j*r->rn) ].v[kEdMinIdx];
  680. }
  681. bool _ed_is_trans( ed_r* r, const ed_val* v1p, unsigned i, unsigned j )
  682. {
  683. bool fl = false;
  684. ed_val* v0p = r->m + i + (j*r->rn);
  685. if( i>=1 && j>=1 &&
  686. v1p->v[kEdMinIdx] == v1p->v[kEdSubIdx]
  687. && v1p->matchFl == false
  688. && v0p->v[kEdMinIdx] == v0p->v[kEdSubIdx]
  689. && v0p->matchFl == false )
  690. {
  691. char c00 = r->s0[i-1];
  692. char c01 = r->s0[i ];
  693. char c10 = r->s1[j-1];
  694. char c11 = r->s1[j ];
  695. fl = c00==c11 && c01==c10;
  696. }
  697. return fl;
  698. }
  699. void ed_calc_mtx( ed_r* r )
  700. {
  701. unsigned i,j;
  702. for(i=1; i<r->rn; ++i)
  703. for(j=1; j<r->cn; ++j)
  704. {
  705. ed_val* vp = r->m + i + (j*r->rn);
  706. vp->matchFl = r->s0[i-1] == r->s1[j-1];
  707. unsigned cost = vp->matchFl ? 0 : 1;
  708. vp->v[kEdSubIdx] = _ed_min(r,i-1,j-1) + cost;
  709. vp->v[kEdDelIdx] = _ed_min(r,i-1,j ) + 1;
  710. vp->v[kEdInsIdx] = _ed_min(r,i, j-1) + 1;
  711. vp->v[kEdMinIdx] = cmMin( vp->v[kEdSubIdx], cmMin(vp->v[kEdDelIdx],vp->v[kEdInsIdx]));
  712. vp->transFl = _ed_is_trans(r,vp,i-1,j-1);
  713. }
  714. }
  715. void ed_path_push( ed_r* r, unsigned code, unsigned ri, unsigned ci, bool matchFl, bool transFl )
  716. {
  717. assert(r->p_avl != NULL );
  718. ed_path* p = r->p_avl;
  719. r->p_avl = r->p_avl->next;
  720. p->code = code;
  721. p->ri = ri;
  722. p->ci = ci;
  723. p->matchFl = matchFl;
  724. p->transFl = transFl;
  725. p->next = r->p_cur;
  726. r->p_cur = p;
  727. }
  728. void ed_path_pop( ed_r* r )
  729. {
  730. assert( r->p_cur != NULL );
  731. ed_path* tp = r->p_cur->next;
  732. r->p_cur->next = r->p_avl;
  733. r->p_avl = r->p_cur;
  734. r->p_cur = tp;
  735. }
  736. double ed_score_candidate( ed_r* r )
  737. {
  738. ed_path* cp = r->p_cur;
  739. ed_path* bp = r->p_cur;
  740. ed_path* ep = NULL;
  741. for(; cp!=NULL; cp=cp->next)
  742. if( cp->code != kEdInsIdx )
  743. {
  744. bp = cp;
  745. break;
  746. }
  747. for(; cp!=NULL; cp=cp->next)
  748. if( cp->code!=kEdInsIdx )
  749. ep = cp;
  750. assert( ep!=NULL && bp!=ep);
  751. unsigned n=1;
  752. for(cp=bp; cp!=ep; cp=cp->next)
  753. ++n;
  754. double gapCnt = 0;
  755. double penalty = 0;
  756. bool pfl = bp->matchFl;
  757. unsigned i;
  758. cp = bp;
  759. for(i=0; i<n; ++i,cp=cp->next)
  760. {
  761. // a gap is a transition from a matching subst. to an insert or deletion
  762. //if( pc != cp->code && cp->code != kEdSubIdx && pc==kEdSubIdx && pfl==true )
  763. if( pfl==true && cp->matchFl==false )
  764. ++gapCnt;
  765. //
  766. switch( cp->code )
  767. {
  768. case kEdSubIdx:
  769. penalty += cp->matchFl ? 0 : 1;
  770. penalty -= cp->transFl ? 1 : 0;
  771. break;
  772. case kEdDelIdx:
  773. penalty += 1;
  774. break;
  775. case kEdInsIdx:
  776. penalty += 1;
  777. break;
  778. }
  779. pfl = cp->matchFl;
  780. }
  781. double score = gapCnt/n + penalty;
  782. printf("n:%i gaps:%f gap_score:%f penalty:%f score:%f\n",n,gapCnt,gapCnt/n,penalty,score);
  783. return score;
  784. }
  785. void ed_eval_candidate( ed_r* r, double score )
  786. {
  787. if( r->s_opt == DBL_MAX || r->s_opt > score)
  788. {
  789. // copy the p_cur to p_opt[]
  790. ed_path* cp = r->p_cur;
  791. unsigned i;
  792. for(i=0; cp!=NULL && i<r->pn; cp=cp->next,++i)
  793. {
  794. r->p_opt[i].code = cp->code;
  795. r->p_opt[i].ri = cp->ri;
  796. r->p_opt[i].ci = cp->ci;
  797. r->p_opt[i].matchFl = cp->matchFl;
  798. r->p_opt[i].transFl = cp->transFl;
  799. }
  800. assert( i < r->pn );
  801. r->p_opt[i].code = 0; // terminate with code=0
  802. r->s_opt = score;
  803. }
  804. }
  805. void ed_print_opt( ed_r* r )
  806. {
  807. unsigned i;
  808. for(i=0; r->p_opt[i].code!=0; ++i)
  809. {
  810. ed_path* cp = r->p_opt + i;
  811. char c0 = cp->matchFl ? 'm' : ' ';
  812. char c1 = cp->transFl ? 't' : ' ';
  813. printf("%2i code:%i ri:%2i ci:%2i %c%c\n",i,cp->code,cp->ri,cp->ci,c0,c1);
  814. }
  815. printf("score:%f\n",r->s_opt);
  816. }
  817. void ed_print_candidate( ed_r* r )
  818. {
  819. ed_path* cp = r->p_cur;
  820. unsigned pn = r->pn;
  821. unsigned i;
  822. char s0[pn+1];
  823. char s1[pn+1];
  824. char s2[pn+1];
  825. char s3[pn+1];
  826. s0[pn] = 0;
  827. s1[pn] = 0;
  828. s2[pn] = 0;
  829. s3[pn] = 0;
  830. for(i=0; i<pn && cp!=NULL; ++i,cp=cp->next)
  831. {
  832. switch(cp->code)
  833. {
  834. case kEdSubIdx: // subst
  835. assert( 0 <= cp->ri && cp->ri <= r->rn );
  836. assert( 0 <= cp->ci && cp->ci <= r->cn );
  837. s0[i] = r->s0[cp->ri];
  838. s1[i] = r->s1[cp->ci];
  839. s2[i] = 's';
  840. s3[i] = cp->matchFl ? 'm' : ' ';
  841. break;
  842. case kEdDelIdx: // delete
  843. assert( 0 <= cp->ri && cp->ri <= r->rn );
  844. s0[i] = r->s0[cp->ri];
  845. s1[i] = ' ';
  846. s2[i] = 'd';
  847. s3[i] = ' ';
  848. break;
  849. case kEdInsIdx: // insert
  850. assert( 0 <= cp->ci && cp->ci <= r->cn );
  851. s0[i] = ' ';
  852. s1[i] = r->s1[cp->ci];
  853. s2[i] = 'i';
  854. s3[i] = ' ';
  855. break;
  856. }
  857. }
  858. if( i < pn )
  859. {
  860. s0[i] = 0;
  861. s1[i] = 0;
  862. s2[i] = 0;
  863. s3[i] = 0;
  864. }
  865. printf("\ns0:%s\n",s0);
  866. printf("s1:%s\n",s1);
  867. printf("s2:%s\n",s2);
  868. printf("s3:%s\n",s3);
  869. }
  870. // traverse the solution matrix from the lower-right to
  871. // the upper-left.
  872. void ed_node( ed_r* r, int i, int j )
  873. {
  874. unsigned m;
  875. // stop when the upper-right is encountered
  876. if( i==0 && j==0 )
  877. {
  878. ed_print_candidate(r);
  879. ed_eval_candidate(r, ed_score_candidate(r) );
  880. return;
  881. }
  882. ed_val* vp = r->m + i + (j*r->rn);
  883. // for each possible dir: up,left,up-left
  884. for(m=1; m<kEdCnt; ++m)
  885. if( vp->v[m] == vp->v[kEdMinIdx] )
  886. {
  887. unsigned ii = i-1;
  888. unsigned jj = j-1;
  889. switch(m)
  890. {
  891. case kEdSubIdx:
  892. break;
  893. case kEdDelIdx:
  894. jj = j;
  895. break;
  896. case kEdInsIdx:
  897. ii = i;
  898. break;
  899. }
  900. // prepend to the current candidate path: r->p_cur
  901. ed_path_push(r,m,ii,jj,vp->matchFl,vp->transFl);
  902. // recurse!
  903. ed_node(r,ii,jj);
  904. // remove the first element from the current path
  905. ed_path_pop(r);
  906. }
  907. }
  908. void ed_align( ed_r* r )
  909. {
  910. int i = r->rn-1;
  911. int j = r->cn-1;
  912. unsigned m = r->m[i + (j*r->rn)].v[kEdMinIdx];
  913. if( m==cmMax(r->rn,r->cn) )
  914. printf("Edit distance is at max: %i. No Match.\n",m);
  915. else
  916. ed_node(r,i,j);
  917. }
  918. void ed_free( ed_r* r )
  919. {
  920. cmMemFree(r->m);
  921. cmMemFree(r->p_mem);
  922. }
  923. void ed_main()
  924. {
  925. const char* s0 = "YHCQPGK";
  926. const char* s1 = "LAHYQQKPGKA";
  927. s0 = "ABCDE";
  928. s1 = "ABDCE";
  929. //s1 = "FGHIJK";
  930. ed_r r;
  931. ed_init(&r,s0,s1);
  932. ed_calc_mtx(&r);
  933. ed_print_mtx(&r);
  934. ed_align(&r);
  935. ed_print_opt(&r);
  936. ed_free(&r);
  937. }
  938. //=======================================================================================================================
  939. cmScMatch* cmScMatchAlloc( cmCtx* c, cmScMatch* p, cmScH_t scH, unsigned maxScWndN, unsigned maxMidiWndN )
  940. {
  941. cmScMatch* op = cmObjAlloc(cmScMatch,c,p);
  942. if( cmScoreIsValid(scH) )
  943. if( cmScMatchInit(op,scH,maxScWndN,maxMidiWndN) != cmOkRC )
  944. cmScMatchFree(&op);
  945. return op;
  946. }
  947. cmRC_t cmScMatchFree( cmScMatch** pp )
  948. {
  949. cmRC_t rc = cmOkRC;
  950. if( pp==NULL || *pp==NULL )
  951. return rc;
  952. cmScMatch* p = *pp;
  953. if((rc = cmScMatchFinal(p)) != cmOkRC )
  954. return rc;
  955. cmMemFree(p->loc);
  956. cmMemFree(p->m);
  957. cmMemFree(p->p_mem);
  958. cmObjFree(pp);
  959. return rc;
  960. }
  961. void _cmScMatchInitLoc( cmScMatch* p )
  962. {
  963. unsigned li,ei;
  964. p->locN = cmScoreEvtCount(p->scH);
  965. p->loc = cmMemResizeZ(cmScMatchLoc_t,p->loc,p->locN);
  966. // for each score location
  967. for(li=0,ei=0; li<cmScoreLocCount(p->scH); ++li)
  968. {
  969. unsigned i,n;
  970. const cmScoreLoc_t* lp = cmScoreLoc(p->scH,li);
  971. // count the number of note events at location li
  972. for(n=0,i=0; i<lp->evtCnt; ++i)
  973. if( lp->evtArray[i]->type == kNonEvtScId )
  974. ++n;
  975. assert( ei+n <= p->locN );
  976. // duplicate each note at location li n times
  977. for(i=0; i<n; ++i)
  978. {
  979. unsigned j,k;
  980. p->loc[ei+i].evtCnt = n;
  981. p->loc[ei+i].evtV = cmMemAllocZ(cmScMatchEvt_t,n);
  982. p->loc[ei+i].scLocIdx = li;
  983. p->loc[ei+i].barNumb = lp->barNumb;
  984. for(j=0,k=0; j<lp->evtCnt; ++j)
  985. if( lp->evtArray[j]->type == kNonEvtScId )
  986. {
  987. p->loc[ei+i].evtV[k].pitch = lp->evtArray[j]->pitch;
  988. p->loc[ei+i].evtV[k].scEvtIdx = lp->evtArray[j]->index;
  989. ++k;
  990. }
  991. }
  992. ei += n;
  993. }
  994. assert(ei<=p->locN);
  995. p->locN = ei;
  996. }
  997. cmRC_t cmScMatchInit( cmScMatch* p, cmScH_t scH, unsigned maxScWndN, unsigned maxMidiWndN )
  998. {
  999. unsigned i;
  1000. cmRC_t rc;
  1001. if((rc = cmScMatchFinal(p)) != cmOkRC )
  1002. return rc;
  1003. p->scH = scH;
  1004. p->mrn = maxMidiWndN + 1;
  1005. p->mcn = maxScWndN + 1;
  1006. p->mmn = maxMidiWndN;
  1007. p->msn = maxScWndN;
  1008. _cmScMatchInitLoc(p);
  1009. p->m = cmMemResizeZ(cmScMatchVal_t, p->m, p->mrn*p->mcn );
  1010. p->pn = p->mrn + p->mcn;
  1011. p->p_mem = cmMemResizeZ(cmScMatchPath_t, p->p_mem, 2*p->pn );
  1012. p->p_avl = p->p_mem;
  1013. p->p_cur = NULL;
  1014. p->p_opt = p->p_mem + p->pn;
  1015. // put pn path records on the available list
  1016. for(i=0; i<p->pn; ++i)
  1017. {
  1018. p->p_mem[i].next = i<p->pn-1 ? p->p_mem + i + 1 : NULL;
  1019. p->p_opt[i].next = i<p->pn-1 ? p->p_opt + i + 1 : NULL;
  1020. }
  1021. return rc;
  1022. }
  1023. cmRC_t cmScMatchFinal( cmScMatch* p )
  1024. {
  1025. unsigned i;
  1026. if( p != NULL )
  1027. for(i=0; i<p->locN; ++i)
  1028. cmMemPtrFree(&p->loc[i].evtV);
  1029. return cmOkRC;
  1030. }
  1031. cmRC_t _cmScMatchInitMtx( cmScMatch* p, unsigned rn, unsigned cn )
  1032. {
  1033. //if( rn >p->mrn && cn > p->mcn )
  1034. if( rn*cn > p->mrn*p->mcn )
  1035. {
  1036. return cmCtxRtCondition( &p->obj, cmInvalidArgRC, "MIDI sequence length must be less than %i. Score sequence length must be less than %i.",p->mmn,p->msn);
  1037. }
  1038. // if the size of the mtx is not changing then there is nothing to do
  1039. if( rn == p->rn && cn == p->cn )
  1040. return cmOkRC;
  1041. // update the mtx size
  1042. p->rn = rn;
  1043. p->cn = cn;
  1044. // fill in the default values for the first row
  1045. // and column of the DP matrix
  1046. unsigned i,j,k;
  1047. for(i=0; i<rn; ++i)
  1048. for(j=0; j<cn; ++j)
  1049. {
  1050. unsigned v[] = {0,0,0,0};
  1051. if( i == 0 )
  1052. {
  1053. v[kSmMinIdx] = j;
  1054. v[kSmInsIdx] = j;
  1055. }
  1056. else
  1057. if( j == 0 )
  1058. {
  1059. v[kSmMinIdx] = i;
  1060. v[kSmDelIdx] = i;
  1061. }
  1062. // zero the value field
  1063. for(k=0; k<kSmCnt; ++k)
  1064. p->m[ i + (j*rn) ].v[k] = v[k];
  1065. }
  1066. return cmOkRC;
  1067. }
  1068. cmScMatchVal_t* _cmScMatchValPtr( cmScMatch* p, unsigned i, unsigned j, unsigned rn, unsigned cn )
  1069. {
  1070. assert( i < rn && j < cn );
  1071. return p->m + i + (j*rn);
  1072. }
  1073. unsigned _cmScMatchIsMatchIndex( const cmScMatchLoc_t* loc, unsigned pitch )
  1074. {
  1075. unsigned i;
  1076. for(i=0; i<loc->evtCnt; ++i)
  1077. if( loc->evtV[i].pitch == pitch )
  1078. return i;
  1079. return cmInvalidIdx;
  1080. }
  1081. bool _cmScMatchIsMatch( const cmScMatchLoc_t* loc, unsigned pitch )
  1082. { return _cmScMatchIsMatchIndex(loc,pitch) != cmInvalidIdx; }
  1083. bool _cmScMatchIsTrans( cmScMatch* p, const cmScMatchMidi_t* midiV, const cmScMatchVal_t* v1p, unsigned bsi, unsigned i, unsigned j, unsigned rn, unsigned cn )
  1084. {
  1085. bool fl = false;
  1086. cmScMatchVal_t* v0p = _cmScMatchValPtr(p,i,j,rn,cn);
  1087. if( i>=1 && j>=1
  1088. && v1p->v[kSmMinIdx] == v1p->v[kSmSubIdx]
  1089. && cmIsNotFlag(v1p->flags,kSmMatchFl)
  1090. && v0p->v[kSmMinIdx] == v0p->v[kSmSubIdx]
  1091. && cmIsNotFlag(v0p->flags,kSmMatchFl)
  1092. )
  1093. {
  1094. unsigned c00 = midiV[i-1].pitch;
  1095. unsigned c01 = midiV[i ].pitch;
  1096. cmScMatchLoc_t* c10 = p->loc + bsi + j - 1;
  1097. cmScMatchLoc_t* c11 = p->loc + bsi + j;
  1098. fl = _cmScMatchIsMatch(c11,c00) && _cmScMatchIsMatch(c10,c01);
  1099. }
  1100. return fl;
  1101. }
  1102. unsigned _cmScMatchMin( cmScMatch* p, unsigned i, unsigned j, unsigned rn, unsigned cn )
  1103. {
  1104. return _cmScMatchValPtr(p,i,j,rn,cn)->v[kSmMinIdx];
  1105. }
  1106. // Return false if bsi + cn > p->locN
  1107. // pitchV[rn-1]
  1108. bool _cmScMatchCalcMtx( cmScMatch* p, unsigned bsi, const cmScMatchMidi_t* midiV, unsigned rn, unsigned cn )
  1109. {
  1110. // loc[begScanLocIdx:begScanLocIdx+cn-1] must be valid
  1111. if( bsi + cn > p->locN )
  1112. return false;
  1113. unsigned i,j;
  1114. for(j=1; j<cn; ++j)
  1115. for(i=1; i<rn; ++i)
  1116. {
  1117. cmScMatchLoc_t* loc = p->loc + bsi + j - 1;
  1118. unsigned pitch = midiV[i-1].pitch;
  1119. cmScMatchVal_t* vp = _cmScMatchValPtr(p,i,j,rn,cn);
  1120. unsigned idx = _cmScMatchIsMatchIndex(loc,pitch);
  1121. vp->flags = idx==cmInvalidIdx ? 0 : kSmMatchFl;
  1122. vp->scEvtIdx = idx==cmInvalidIdx ? cmInvalidIdx : loc->evtV[idx].scEvtIdx;
  1123. unsigned cost = cmIsFlag(vp->flags,kSmMatchFl) ? 0 : 1;
  1124. vp->v[kSmSubIdx] = _cmScMatchMin(p,i-1,j-1, rn, cn) + cost;
  1125. vp->v[kSmDelIdx] = _cmScMatchMin(p,i-1,j , rn, cn) + 1;
  1126. vp->v[kSmInsIdx] = _cmScMatchMin(p,i, j-1, rn, cn) + 1;
  1127. vp->v[kSmMinIdx] = cmMin( vp->v[kSmSubIdx], cmMin(vp->v[kSmDelIdx],vp->v[kSmInsIdx]));
  1128. vp->flags |= _cmScMatchIsTrans(p,midiV,vp,bsi,i-1,j-1,rn,cn) ? kSmTransFl : 0;
  1129. }
  1130. return true;
  1131. }
  1132. void _cmScMatchPrintMtx( cmScMatch* r, unsigned rn, unsigned cn)
  1133. {
  1134. unsigned i,j,k;
  1135. for(i=0; i<rn; ++i)
  1136. {
  1137. for(j=0; j<cn; ++j)
  1138. {
  1139. printf("(");
  1140. const cmScMatchVal_t* vp = _cmScMatchValPtr(r,i,j,rn,cn);
  1141. for(k=0; k<kSmCnt; ++k)
  1142. {
  1143. printf("%i",vp->v[k]);
  1144. if( k<kSmCnt-1)
  1145. printf(", ");
  1146. else
  1147. printf(" ");
  1148. }
  1149. printf("%c%c)",cmIsFlag(vp->flags,kSmMatchFl)?'m':' ',cmIsFlag(vp->flags,kSmTransFl)?'t':' ');
  1150. }
  1151. printf("\n");
  1152. }
  1153. }
  1154. void _cmScMatchPathPush( cmScMatch* r, unsigned code, unsigned ri, unsigned ci, unsigned flags, unsigned scEvtIdx )
  1155. {
  1156. assert(r->p_avl != NULL );
  1157. cmScMatchPath_t* p = r->p_avl;
  1158. r->p_avl = r->p_avl->next;
  1159. p->code = code;
  1160. p->ri = ri;
  1161. p->ci = ci;
  1162. p->flags = code==kSmSubIdx && cmIsFlag(flags,kSmMatchFl) ? kSmMatchFl : 0;
  1163. p->flags |= cmIsFlag(flags,kSmTransFl) ? kSmTransFl : 0;
  1164. p->scEvtIdx= scEvtIdx;
  1165. p->next = r->p_cur;
  1166. r->p_cur = p;
  1167. }
  1168. void _cmScMatchPathPop( cmScMatch* r )
  1169. {
  1170. assert( r->p_cur != NULL );
  1171. cmScMatchPath_t* tp = r->p_cur->next;
  1172. r->p_cur->next = r->p_avl;
  1173. r->p_avl = r->p_cur;
  1174. r->p_cur = tp;
  1175. }
  1176. double _cmScMatchCalcCandidateCost( cmScMatch* r )
  1177. {
  1178. cmScMatchPath_t* cp = r->p_cur;
  1179. cmScMatchPath_t* bp = r->p_cur;
  1180. cmScMatchPath_t* ep = NULL;
  1181. // skip leading inserts
  1182. for(; cp!=NULL; cp=cp->next)
  1183. if( cp->code != kSmInsIdx )
  1184. {
  1185. bp = cp;
  1186. break;
  1187. }
  1188. // skip to trailing inserts
  1189. for(; cp!=NULL; cp=cp->next)
  1190. if( cp->code!=kSmInsIdx )
  1191. ep = cp;
  1192. // count remaining path length
  1193. assert( ep!=NULL );
  1194. unsigned n=1;
  1195. for(cp=bp; cp!=ep; cp=cp->next)
  1196. ++n;
  1197. double gapCnt = 0;
  1198. double penalty = 0;
  1199. bool pfl = cmIsFlag(bp->flags,kSmMatchFl);
  1200. unsigned i;
  1201. cp = bp;
  1202. for(i=0; i<n; ++i,cp=cp->next)
  1203. {
  1204. // a gap is a transition from a matching subst. to an insert or deletion
  1205. //if( pc != cp->code && cp->code != kSmSubIdx && pc==kSmSubIdx && pfl==true )
  1206. if( pfl==true && cmIsFlag(cp->flags,kSmMatchFl)==false )
  1207. ++gapCnt;
  1208. //
  1209. switch( cp->code )
  1210. {
  1211. case kSmSubIdx:
  1212. penalty += cmIsFlag(cp->flags,kSmMatchFl) ? 0 : 1;
  1213. penalty -= cmIsFlag(cp->flags,kSmTransFl) ? 1 : 0;
  1214. break;
  1215. case kSmDelIdx:
  1216. penalty += 1;
  1217. break;
  1218. case kSmInsIdx:
  1219. penalty += 1;
  1220. break;
  1221. }
  1222. pfl = cmIsFlag(cp->flags,kSmMatchFl);
  1223. }
  1224. double cost = gapCnt/n + penalty;
  1225. //printf("n:%i gaps:%f gap_score:%f penalty:%f score:%f\n",n,gapCnt,gapCnt/n,penalty,score);
  1226. return cost;
  1227. }
  1228. double _cmScMatchEvalCandidate( cmScMatch* r, double min_cost, double cost )
  1229. {
  1230. if( min_cost == DBL_MAX || cost < min_cost)
  1231. {
  1232. // copy the p_cur to p_opt[]
  1233. cmScMatchPath_t* cp = r->p_cur;
  1234. unsigned i;
  1235. for(i=0; cp!=NULL && i<r->pn; cp=cp->next,++i)
  1236. {
  1237. r->p_opt[i].code = cp->code;
  1238. r->p_opt[i].ri = cp->ri;
  1239. r->p_opt[i].ci = cp->ci;
  1240. r->p_opt[i].flags = cp->flags;
  1241. r->p_opt[i].scEvtIdx= cp->scEvtIdx;
  1242. r->p_opt[i].next = cp->next==NULL ? NULL : r->p_opt + i + 1;
  1243. }
  1244. assert( i < r->pn );
  1245. r->p_opt[i].code = 0; // terminate with code=0
  1246. min_cost = cost;
  1247. }
  1248. return min_cost;
  1249. }
  1250. // NOTE: IF THE COST CALCULATION WAS BUILT INTO THE RECURSION THEN
  1251. // THIS FUNCTION COULD BE MADE MORE EFFICIENT BECAUSE PATHS WHICH
  1252. // EXCEEDED THE min_cost COULD BE SHORT CIRCUITED.
  1253. //
  1254. // traverse the solution matrix from the lower-right to
  1255. // the upper-left.
  1256. double _cmScMatchGenPaths( cmScMatch* r, int i, int j, unsigned rn, unsigned cn, double min_cost )
  1257. {
  1258. unsigned m;
  1259. // stop when the upper-right is encountered
  1260. if( i==0 && j==0 )
  1261. return _cmScMatchEvalCandidate(r, min_cost, _cmScMatchCalcCandidateCost(r) );
  1262. cmScMatchVal_t* vp = _cmScMatchValPtr(r,i,j,rn,cn);
  1263. // for each possible dir: up,left,up-left
  1264. for(m=1; m<kSmCnt; ++m)
  1265. if( vp->v[m] == vp->v[kSmMinIdx] )
  1266. {
  1267. // prepend to the current candidate path: r->p_cur
  1268. _cmScMatchPathPush(r,m,i,j,vp->flags,vp->scEvtIdx);
  1269. int ii = i-1;
  1270. int jj = j-1;
  1271. switch(m)
  1272. {
  1273. case kSmSubIdx:
  1274. break;
  1275. case kSmDelIdx:
  1276. jj = j;
  1277. break;
  1278. case kSmInsIdx:
  1279. ii = i;
  1280. break;
  1281. default:
  1282. { assert(0); }
  1283. }
  1284. // recurse!
  1285. min_cost = _cmScMatchGenPaths(r,ii,jj,rn,cn,min_cost);
  1286. // remove the first element from the current path
  1287. _cmScMatchPathPop(r);
  1288. }
  1289. return min_cost;
  1290. }
  1291. double _cmScMatchAlign( cmScMatch* p, unsigned rn, unsigned cn, double min_cost )
  1292. {
  1293. int i = rn-1;
  1294. int j = cn-1;
  1295. unsigned m = _cmScMatchMin(p,i,j,rn,cn);
  1296. if( m==cmMax(rn,cn) )
  1297. printf("Edit distance is at max: %i. No Match.\n",m);
  1298. else
  1299. min_cost = _cmScMatchGenPaths(p,i,j,rn,cn,min_cost);
  1300. return min_cost;
  1301. }
  1302. cmRC_t cmScMatchExec( cmScMatch* p, unsigned locIdx, unsigned locN, const cmScMatchMidi_t* midiV, unsigned midiN, double min_cost )
  1303. {
  1304. cmRC_t rc;
  1305. unsigned rn = midiN + 1;
  1306. unsigned cn = locN + 1;
  1307. // set the DP matrix default values
  1308. if((rc = _cmScMatchInitMtx(p, rn, cn )) != cmOkRC )
  1309. return rc;
  1310. // _cmScMatchCalcMtx() returns false if the score window exceeds the length of the score
  1311. if(!_cmScMatchCalcMtx(p,locIdx, midiV, rn, cn) )
  1312. return cmEofRC;
  1313. //_cmScMatchPrintMtx(p,rn,cn);
  1314. // locate the path through the DP matrix with the lowest edit distance (cost)
  1315. p->opt_cost = _cmScMatchAlign(p, rn, cn, min_cost);
  1316. return rc;
  1317. }
  1318. // Traverse the least cost path and:
  1319. // 1) Return, esi, the score location index of the last MIDI note
  1320. // which has a positive match with the score and assign
  1321. // the internal score index to cp->locIdx.
  1322. //
  1323. // 2) Set cmScAlignPath_t.locIdx - index into p->loc[] associated
  1324. // with each path element that is a 'substitute' or an 'insert'.
  1325. //
  1326. // 3) Set *missCnPtr: the count of trailing non-positive matches.
  1327. //
  1328. // i_opt is index into p->loc[] of p->p_opt.
  1329. unsigned cmScMatchDoSync( cmScMatch* p, unsigned i_opt, cmScMatchMidi_t* midiBuf, unsigned midiN, unsigned* missCntPtr )
  1330. {
  1331. cmScMatchPath_t* cp = p->p_opt;
  1332. unsigned missCnt = 0;
  1333. unsigned esi = cmInvalidIdx;
  1334. unsigned i;
  1335. for(i=0; cp!=NULL; cp=cp->next)
  1336. {
  1337. // there is no MIDI note associated with 'inserts'
  1338. if( cp->code != kSmInsIdx )
  1339. {
  1340. assert( cp->ri > 0 );
  1341. midiBuf[ cp->ri-1 ].locIdx = cmInvalidIdx;
  1342. }
  1343. switch( cp->code )
  1344. {
  1345. case kSmSubIdx:
  1346. midiBuf[ cp->ri-1 ].locIdx = i_opt + i;
  1347. midiBuf[ cp->ri-1 ].scEvtIdx = cp->scEvtIdx;
  1348. if( cmIsFlag(cp->flags,kSmMatchFl) )
  1349. {
  1350. esi = i_opt + i;
  1351. missCnt = 0;
  1352. }
  1353. else
  1354. {
  1355. ++missCnt;
  1356. }
  1357. // fall through
  1358. case kSmInsIdx:
  1359. cp->locIdx = i_opt + i;
  1360. ++i;
  1361. break;
  1362. case kSmDelIdx:
  1363. cp->locIdx = cmInvalidIdx;
  1364. ++missCnt;
  1365. break;
  1366. }
  1367. }
  1368. if( missCntPtr != NULL )
  1369. *missCntPtr = missCnt;
  1370. return esi;
  1371. }
  1372. void _cmScMatchMidiEvtFlags( cmScMatch* p, const cmScMatchLoc_t* lp, unsigned evtIdx, char* s, unsigned sn )
  1373. {
  1374. const cmScoreLoc_t* slp = cmScoreLoc(p->scH,lp->scLocIdx);
  1375. assert( evtIdx < slp->evtCnt );
  1376. const cmScoreEvt_t* ep = slp->evtArray[evtIdx];
  1377. unsigned i = 0;
  1378. s[0] = 0;
  1379. if( cmIsFlag(ep->flags,kEvenScFl) )
  1380. s[i++] = 'e';
  1381. if( cmIsFlag(ep->flags,kTempoScFl) )
  1382. s[i++] = 't';
  1383. if( cmIsFlag(ep->flags,kDynScFl) )
  1384. s[i++] = 'd';
  1385. if( cmIsFlag(ep->flags,kGraceScFl) )
  1386. s[i++] = 'g';
  1387. s[i++] = 0;
  1388. assert( i <= sn );
  1389. }
  1390. void _cmScMatchPrintPath( cmScMatch* p, cmScMatchPath_t* cp, unsigned bsi, const cmScMatchMidi_t* midiV )
  1391. {
  1392. assert( bsi != cmInvalidIdx );
  1393. cmScMatchPath_t* pp = cp;
  1394. int polyN = 0;
  1395. int i;
  1396. printf("loc: ");
  1397. // get the polyphony count for the score window
  1398. for(i=0; pp!=NULL; pp=pp->next)
  1399. {
  1400. cmScMatchLoc_t* lp = p->loc + bsi + pp->ci;
  1401. if( pp->code!=kSmDelIdx )
  1402. {
  1403. if(lp->evtCnt > polyN)
  1404. polyN = lp->evtCnt;
  1405. printf("%4i%4s ",bsi+i," ");
  1406. ++i;
  1407. }
  1408. else
  1409. printf("%4s%4s "," "," ");
  1410. }
  1411. printf("\n");
  1412. // print the score notes
  1413. for(i=polyN; i>0; --i)
  1414. {
  1415. printf("%3i: ",i);
  1416. for(pp=cp; pp!=NULL; pp=pp->next)
  1417. {
  1418. if( pp->code!=kSmDelIdx )
  1419. {
  1420. int locIdx = bsi + pp->ci - 1;
  1421. assert(0 <= locIdx && locIdx <= p->locN);
  1422. cmScMatchLoc_t* lp = p->loc + locIdx;
  1423. if( lp->evtCnt >= i )
  1424. {
  1425. unsigned sn = 6;
  1426. char s[sn];
  1427. _cmScMatchMidiEvtFlags(p,lp,i-1,s,sn );
  1428. printf("%4s%-4s ",cmMidiToSciPitch(lp->evtV[i-1].pitch,NULL,0),s);
  1429. }
  1430. else
  1431. printf("%4s%4s "," "," ");
  1432. }
  1433. else
  1434. printf("%4s%4s ", (pp->code==kSmDelIdx? "-" : " ")," ");
  1435. /*
  1436. int locIdx = bsi + pp->ci - 1;
  1437. assert(0 <= locIdx && locIdx <= p->locN);
  1438. cmScMatchLoc_t* lp = p->loc + locIdx;
  1439. if( pp->code!=kSmDelIdx && lp->evtCnt >= i )
  1440. printf("%4s ",cmMidiToSciPitch(lp->evtV[i-1].pitch,NULL,0));
  1441. else
  1442. printf("%4s ", pp->code==kSmDelIdx? "-" : " ");
  1443. */
  1444. }
  1445. printf("\n");
  1446. }
  1447. printf("mid: ");
  1448. // print the MIDI buffer
  1449. for(pp=cp; pp!=NULL; pp=pp->next)
  1450. {
  1451. if( pp->code!=kSmInsIdx )
  1452. printf("%4s%4s ",cmMidiToSciPitch(midiV[pp->ri-1].pitch,NULL,0)," ");
  1453. else
  1454. printf("%4s%4s ",pp->code==kSmInsIdx?"-":" "," ");
  1455. }
  1456. printf("\nvel: ");
  1457. // print the MIDI velocity
  1458. for(pp=cp; pp!=NULL; pp=pp->next)
  1459. {
  1460. if( pp->code!=kSmInsIdx )
  1461. printf("%4i%4s ",midiV[pp->ri-1].vel," ");
  1462. else
  1463. printf("%4s%4s ",pp->code==kSmInsIdx?"-":" "," ");
  1464. }
  1465. printf("\nmni: ");
  1466. // print the MIDI buffer index (mni)
  1467. for(pp=cp; pp!=NULL; pp=pp->next)
  1468. {
  1469. if( pp->code!=kSmInsIdx )
  1470. printf("%4i%4s ",midiV[pp->ri-1].mni," ");
  1471. else
  1472. printf("%4s%4s ",pp->code==kSmInsIdx?"-":" "," ");
  1473. }
  1474. printf("\n op: ");
  1475. // print the substitute/insert/delete operation
  1476. for(pp=cp; pp!=NULL; pp=pp->next)
  1477. {
  1478. char c = ' ';
  1479. switch( pp->code )
  1480. {
  1481. case kSmSubIdx: c = 's'; break;
  1482. case kSmDelIdx: c = 'd'; break;
  1483. case kSmInsIdx: c = 'i'; break;
  1484. default:
  1485. { assert(0); }
  1486. }
  1487. printf("%4c%4s ",c," ");
  1488. }
  1489. printf("\n ");
  1490. // give substitute attribute (match or transpose)
  1491. for(pp=cp; pp!=NULL; pp=pp->next)
  1492. {
  1493. cmChar_t s[3];
  1494. int k = 0;
  1495. if( cmIsFlag(pp->flags,kSmMatchFl) )
  1496. s[k++] = 'm';
  1497. if( cmIsFlag(pp->flags,kSmTransFl) )
  1498. s[k++] = 't';
  1499. s[k] = 0;
  1500. printf("%4s%4s ",s," ");
  1501. }
  1502. printf("\nscl: ");
  1503. // print the stored location index
  1504. for(pp=cp; pp!=NULL; pp=pp->next)
  1505. {
  1506. if( pp->locIdx == cmInvalidIdx )
  1507. printf("%4s%4s "," "," ");
  1508. else
  1509. printf("%4i%4s ",p->loc[pp->locIdx].scLocIdx," ");
  1510. }
  1511. printf("\nbar: ");
  1512. // print the stored location index
  1513. for(pp=cp; pp!=NULL; pp=pp->next)
  1514. {
  1515. if( pp->locIdx==cmInvalidIdx || pp->scEvtIdx==cmInvalidIdx )
  1516. printf("%4s%4s "," "," ");
  1517. else
  1518. {
  1519. const cmScoreEvt_t* ep = cmScoreEvt(p->scH, pp->scEvtIdx );
  1520. printf("%4i%4s ",ep->barNumb," ");
  1521. }
  1522. }
  1523. printf("\nsec: ");
  1524. // print seconds
  1525. unsigned begSmpIdx = cmInvalidIdx;
  1526. for(pp=cp; pp!=NULL; pp=pp->next)
  1527. {
  1528. if( pp->code!=kSmInsIdx )
  1529. {
  1530. if( begSmpIdx == cmInvalidIdx )
  1531. begSmpIdx = midiV[pp->ri-1].smpIdx;
  1532. printf("%2.2f%4s ", (double)(midiV[pp->ri-1].smpIdx - begSmpIdx)/96000.0," ");
  1533. }
  1534. else
  1535. printf("%4s%4s ",pp->code==kSmInsIdx?"-":" "," ");
  1536. }
  1537. printf("\n\n");
  1538. }
  1539. //=======================================================================================================================
  1540. cmScMatcher* cmScMatcherAlloc( cmCtx* c, cmScMatcher* p, double srate, cmScH_t scH, unsigned scWndN, unsigned midiWndN, cmScMatcherCb_t cbFunc, void* cbArg )
  1541. {
  1542. cmScMatcher* op = cmObjAlloc(cmScMatcher,c,p);
  1543. if( op != NULL )
  1544. op->mp = cmScMatchAlloc(c,NULL,cmScNullHandle,0,0);
  1545. if( srate != 0 )
  1546. {
  1547. if( cmScMatcherInit(op,srate,scH,scWndN,midiWndN,cbFunc,cbArg) != cmOkRC )
  1548. cmScMatcherFree(&op);
  1549. }
  1550. return op;
  1551. }
  1552. cmRC_t cmScMatcherFree( cmScMatcher** pp )
  1553. {
  1554. cmRC_t rc = cmOkRC;
  1555. if( pp==NULL || *pp==NULL )
  1556. return rc;
  1557. cmScMatcher* p = *pp;
  1558. if((rc = cmScMatcherFinal(p)) != cmOkRC )
  1559. return rc;
  1560. cmScMatchFree(&p->mp);
  1561. cmMemFree(p->midiBuf);
  1562. cmMemFree(p->res);
  1563. cmObjFree(pp);
  1564. return rc;
  1565. }
  1566. cmRC_t cmScMatcherInit( cmScMatcher* p, double srate, cmScH_t scH, unsigned scWndN, unsigned midiWndN, cmScMatcherCb_t cbFunc, void* cbArg )
  1567. {
  1568. cmRC_t rc;
  1569. if((rc = cmScMatcherFinal(p)) != cmOkRC )
  1570. return rc;
  1571. if( midiWndN > scWndN )
  1572. return cmCtxRtCondition( &p->obj, cmInvalidArgRC, "The score alignment MIDI event buffer length (%i) must be less than the score window length (%i).",midiWndN,scWndN);
  1573. if(( rc = cmScMatchInit(p->mp,scH,scWndN,midiWndN)) != cmOkRC )
  1574. return rc;
  1575. p->cbFunc = cbFunc;
  1576. p->cbArg = cbArg;
  1577. p->mn = midiWndN;
  1578. p->midiBuf = cmMemResizeZ(cmScMatchMidi_t,p->midiBuf,p->mn);
  1579. p->initHopCnt = 50;
  1580. p->stepCnt = 3;
  1581. p->maxMissCnt = p->stepCnt+1;
  1582. p->rn = 2 * cmScoreEvtCount(scH);
  1583. p->res = cmMemResizeZ(cmScMatcherResult_t,p->res,p->rn);
  1584. p->printFl = false;
  1585. cmScMatcherReset(p,0);
  1586. return rc;
  1587. }
  1588. cmRC_t cmScMatcherFinal( cmScMatcher* p )
  1589. {
  1590. return cmScMatchFinal(p->mp);
  1591. }
  1592. cmRC_t cmScMatcherReset( cmScMatcher* p, unsigned scLocIdx )
  1593. {
  1594. p->mbi = p->mp->mmn;
  1595. p->mni = 0;
  1596. p->begSyncLocIdx = cmInvalidIdx;
  1597. p->s_opt = DBL_MAX;
  1598. p->missCnt = 0;
  1599. p->scanCnt = 0;
  1600. p->ri = 0;
  1601. p->eli = cmInvalidIdx;
  1602. p->ili = 0;
  1603. // convert scLocIdx to an index into p->mp->loc[]
  1604. unsigned i = 0;
  1605. while(1)
  1606. {
  1607. for(i=0; i<p->mp->locN; ++i)
  1608. if( p->mp->loc[i].scLocIdx == scLocIdx )
  1609. {
  1610. p->ili = i;
  1611. break;
  1612. }
  1613. assert(p->mp->locN>0);
  1614. if( i!=p->mp->locN || scLocIdx==p->mp->loc[p->mp->locN-1].scLocIdx)
  1615. break;
  1616. scLocIdx += 1;
  1617. }
  1618. if( i==p->mp->locN)
  1619. return cmCtxRtCondition( &p->obj, cmSubSysFailRC, "Score matcher reset failed.");
  1620. return cmOkRC;
  1621. }
  1622. bool cmScMatcherInputMidi( cmScMatcher* p, unsigned smpIdx, unsigned status, cmMidiByte_t d0, cmMidiByte_t d1 )
  1623. {
  1624. if( (status&0xf0) != kNoteOnMdId)
  1625. return false;
  1626. if( d1 == 0 )
  1627. return false;
  1628. unsigned mi = p->mn-1;
  1629. //printf("%3i %4s\n",p->mni,cmMidiToSciPitch(d0,NULL,0));
  1630. // shift the new MIDI event onto the end of the MIDI buffer
  1631. memmove(p->midiBuf, p->midiBuf+1, sizeof(cmScMatchMidi_t)*mi);
  1632. p->midiBuf[mi].locIdx = cmInvalidIdx;
  1633. p->midiBuf[mi].scEvtIdx = cmInvalidIdx;
  1634. p->midiBuf[mi].mni = p->mni++;
  1635. p->midiBuf[mi].smpIdx = smpIdx;
  1636. p->midiBuf[mi].pitch = d0;
  1637. p->midiBuf[mi].vel = d1;
  1638. if( p->mbi > 0 )
  1639. --p->mbi;
  1640. return true;
  1641. }
  1642. void _cmScMatcherStoreResult( cmScMatcher* p, unsigned locIdx, unsigned scEvtIdx, unsigned flags, const cmScMatchMidi_t* mp )
  1643. {
  1644. // don't store missed score note results
  1645. assert( mp != NULL );
  1646. bool matchFl = cmIsFlag(flags,kSmMatchFl);
  1647. bool tpFl = locIdx!=cmInvalidIdx && matchFl;
  1648. bool fpFl = locIdx==cmInvalidIdx || matchFl==false;
  1649. cmScMatcherResult_t * rp = NULL;
  1650. unsigned i;
  1651. cmScMatcherResult_t r;
  1652. assert( tpFl==false || (tpFl==true && locIdx != cmInvalidIdx ) );
  1653. // it is possible that the same MIDI event is reported more than once
  1654. // (due to step->scan back tracking) - try to find previous result records
  1655. // associated with this MIDI event
  1656. for(i=0; i<p->ri; ++i)
  1657. if( p->res[i].mni == mp->mni )
  1658. {
  1659. // if this is not the first time this note was reported and it is a true positive
  1660. if( tpFl )
  1661. {
  1662. rp = p->res + i;
  1663. break;
  1664. }
  1665. // a match was found but this was not a true-pos so ignore it
  1666. return;
  1667. }
  1668. if( rp == NULL )
  1669. {
  1670. if( p->ri >= p->rn )
  1671. {
  1672. rp = &r;
  1673. memset(rp,0,sizeof(r));
  1674. }
  1675. else
  1676. {
  1677. rp = p->res + p->ri;
  1678. ++p->ri;
  1679. }
  1680. }
  1681. rp->locIdx = locIdx;
  1682. rp->scEvtIdx = scEvtIdx;
  1683. rp->mni = mp->mni;
  1684. rp->smpIdx = mp->smpIdx;
  1685. rp->pitch = mp->pitch;
  1686. rp->vel = mp->vel;
  1687. rp->flags = flags | (tpFl ? kSmTruePosFl : 0) | (fpFl ? kSmFalsePosFl : 0);
  1688. if( p->cbFunc != NULL )
  1689. p->cbFunc(p,p->cbArg,rp);
  1690. }
  1691. void cmScMatcherPrintPath( cmScMatcher* p )
  1692. {
  1693. _cmScMatchPrintPath(p->mp, p->mp->p_opt, p->begSyncLocIdx, p->midiBuf );
  1694. }
  1695. unsigned cmScMatcherScan( cmScMatcher* p, unsigned bli, unsigned hopCnt )
  1696. {
  1697. assert( p->mp != NULL && p->mp->mmn > 0 );
  1698. unsigned i_opt = cmInvalidIdx;
  1699. double s_opt = DBL_MAX;
  1700. cmRC_t rc = cmOkRC;
  1701. unsigned i;
  1702. // initialize the internal values set by this function
  1703. p->missCnt = 0;
  1704. p->eli = cmInvalidIdx;
  1705. p->s_opt = DBL_MAX;
  1706. // if the MIDI buf is not full
  1707. if( p->mbi != 0 )
  1708. return cmInvalidIdx;
  1709. // calc the edit distance from pitchV[] to a sliding score window
  1710. for(i=0; rc==cmOkRC && (hopCnt==cmInvalidCnt || i<hopCnt); ++i)
  1711. {
  1712. rc = cmScMatchExec(p->mp, bli + i, p->mp->msn, p->midiBuf, p->mp->mmn, s_opt );
  1713. switch(rc)
  1714. {
  1715. case cmOkRC: // normal result
  1716. if( p->mp->opt_cost < s_opt )
  1717. {
  1718. s_opt = p->mp->opt_cost;
  1719. i_opt = bli + i;
  1720. }
  1721. break;
  1722. case cmEofRC: // score window encountered the end of the score
  1723. break;
  1724. default: // error state
  1725. return cmInvalidIdx;
  1726. }
  1727. }
  1728. // store the cost assoc'd with i_opt
  1729. p->s_opt = s_opt;
  1730. if( i_opt == cmInvalidIdx )
  1731. return cmInvalidIdx;
  1732. // set the locIdx field in midiBuf[], trailing miss count and
  1733. // return the latest positive-match locIdx
  1734. p->eli = cmScMatchDoSync(p->mp,i_opt,p->midiBuf,p->mp->mmn,&p->missCnt);
  1735. // if no positive matches were found
  1736. if( p->eli == cmInvalidIdx )
  1737. i_opt = cmInvalidIdx;
  1738. else
  1739. {
  1740. cmScMatchPath_t* cp;
  1741. // record result
  1742. for(cp=p->mp->p_opt; cp!=NULL; cp=cp->next)
  1743. if( cp->code != kSmInsIdx )
  1744. _cmScMatcherStoreResult(p, cp->locIdx, cp->scEvtIdx, cp->flags, p->midiBuf + cp->ri - 1);
  1745. }
  1746. return i_opt;
  1747. }
  1748. cmRC_t cmScMatcherStep( cmScMatcher* p )
  1749. {
  1750. int i;
  1751. unsigned pitch = p->midiBuf[ p->mn-1 ].pitch;
  1752. unsigned locIdx = cmInvalidIdx;
  1753. unsigned pidx = cmInvalidIdx;
  1754. // the tracker must be sync'd to step
  1755. if( p->eli == cmInvalidIdx )
  1756. return cmCtxRtCondition( &p->obj, cmInvalidArgRC, "The p->eli value must be valid to perform a step operation.");
  1757. // if the end of the score has been reached
  1758. if( p->eli + 1 >= p->mp->locN )
  1759. return cmEofRC;
  1760. // attempt to match to next location first
  1761. if( (pidx = _cmScMatchIsMatchIndex(p->mp->loc + p->eli + 1, pitch)) != cmInvalidIdx )
  1762. {
  1763. locIdx = p->eli + 1;
  1764. }
  1765. else
  1766. {
  1767. //
  1768. for(i=2; i<p->stepCnt; ++i)
  1769. {
  1770. // go forward
  1771. if( p->eli+i < p->mp->locN && (pidx=_cmScMatchIsMatchIndex(p->mp->loc + p->eli + i, pitch))!=cmInvalidIdx )
  1772. {
  1773. locIdx = p->eli + i;
  1774. break;
  1775. }
  1776. // go backward
  1777. if( p->eli >= (i-1) && (pidx=_cmScMatchIsMatchIndex(p->mp->loc + p->eli - (i-1), pitch))!=cmInvalidIdx )
  1778. {
  1779. locIdx = p->eli - (i-1);
  1780. break;
  1781. }
  1782. }
  1783. }
  1784. unsigned scEvtIdx = locIdx==cmInvalidIdx ? cmInvalidIdx : p->mp->loc[locIdx].evtV[pidx].scEvtIdx;
  1785. p->midiBuf[ p->mn-1 ].locIdx = locIdx;
  1786. p->midiBuf[ p->mn-1 ].scEvtIdx = scEvtIdx;
  1787. if( locIdx == cmInvalidIdx )
  1788. ++p->missCnt;
  1789. else
  1790. {
  1791. p->missCnt = 0;
  1792. p->eli = locIdx;
  1793. }
  1794. // store the result
  1795. _cmScMatcherStoreResult(p, locIdx, scEvtIdx, locIdx!=cmInvalidIdx ? kSmMatchFl : 0, p->midiBuf + p->mn - 1);
  1796. if( p->missCnt >= p->maxMissCnt )
  1797. {
  1798. unsigned begScanLocIdx = p->eli > p->mn ? p->eli - p->mn : 0;
  1799. p->s_opt = DBL_MAX;
  1800. unsigned bli = cmScMatcherScan(p,begScanLocIdx,p->mn*2);
  1801. ++p->scanCnt;
  1802. // if the scan failed find a match
  1803. if( bli == cmInvalidIdx )
  1804. return cmCtxRtCondition( &p->obj, cmSubSysFailRC, "Scan resync. failed.");
  1805. }
  1806. return cmOkRC;
  1807. }
  1808. cmRC_t cmScMatcherExec( cmScMatcher* p, unsigned smpIdx, unsigned status, cmMidiByte_t d0, cmMidiByte_t d1, unsigned* scLocIdxPtr )
  1809. {
  1810. bool fl = p->mbi > 0;
  1811. cmRC_t rc = cmOkRC;
  1812. unsigned org_eli = p->eli;
  1813. if( scLocIdxPtr != NULL )
  1814. *scLocIdxPtr = cmInvalidIdx;
  1815. // update the MIDI buffer with the incoming note
  1816. if( cmScMatcherInputMidi(p,smpIdx,status,d0,d1) == false )
  1817. return rc;
  1818. // if the MIDI buffer transitioned to full then perform an initial scan sync.
  1819. if( fl && p->mbi == 0 )
  1820. {
  1821. if( (p->begSyncLocIdx = cmScMatcherScan(p,p->ili,p->initHopCnt)) == cmInvalidIdx )
  1822. {
  1823. rc = cmInvalidArgRC; // signal init. scan sync. fail
  1824. }
  1825. else
  1826. {
  1827. //cmScMatcherPrintPath(p);
  1828. }
  1829. }
  1830. else
  1831. {
  1832. // if the MIDI buffer is full then perform a step sync.
  1833. if( !fl && p->mbi == 0 )
  1834. rc = cmScMatcherStep(p);
  1835. }
  1836. // if we lost sync
  1837. if( p->eli == cmInvalidIdx )
  1838. {
  1839. // IF WE LOST SYNC THEN WE BETTER DO SOMETHING - LIKE INCREASE THE SCAN HOPS
  1840. // ON THE NEXT EVENT.
  1841. p->eli = org_eli;
  1842. }
  1843. else
  1844. {
  1845. if( scLocIdxPtr!=NULL && p->eli != org_eli )
  1846. {
  1847. //printf("LOC:%i bar:%i\n",p->eli,p->mp->loc[p->eli].barNumb);
  1848. *scLocIdxPtr = p->mp->loc[p->eli].scLocIdx;
  1849. }
  1850. }
  1851. return rc;
  1852. }
  1853. double cmScMatcherFMeas( cmScMatcher* p )
  1854. {
  1855. unsigned bli = p->mp->locN;
  1856. unsigned eli = 0;
  1857. unsigned scNoteCnt = 0; // total count of score notes
  1858. unsigned matchCnt = 0; // count of matched notes (true positives)
  1859. unsigned wrongCnt = 0; // count of incorrect notes (false positives)
  1860. unsigned missCnt = 0; // count of missed score notes (false negatives)
  1861. unsigned i;
  1862. for(i=0; i<p->ri; ++i)
  1863. if( p->res[i].locIdx != cmInvalidIdx )
  1864. {
  1865. bli = cmMin(bli,p->res[i].locIdx);
  1866. eli = cmMax(eli,p->res[i].locIdx);
  1867. if( cmIsFlag(p->res[i].flags,kSmTruePosFl) )
  1868. ++matchCnt;
  1869. if( cmIsFlag(p->res[i].flags,kSmFalsePosFl) )
  1870. ++wrongCnt;
  1871. }
  1872. scNoteCnt = eli - bli + 1;
  1873. missCnt = scNoteCnt - matchCnt;
  1874. double prec = (double)2.0 * matchCnt / (matchCnt + wrongCnt);
  1875. double rcal = (double)2.0 * matchCnt / (matchCnt + missCnt);
  1876. double fmeas = prec * rcal / (prec + rcal);
  1877. //printf("total:%i match:%i wrong:%i miss:%i\n",scNoteCnt,matchCnt,wrongCnt,missCnt);
  1878. return fmeas;
  1879. }
  1880. typedef struct cmScMatcherPrint_str
  1881. {
  1882. unsigned flags;
  1883. unsigned scLocIdx;
  1884. unsigned mni;
  1885. unsigned pitch;
  1886. unsigned vel;
  1887. unsigned barNumb;
  1888. } cmScMatcherPrint_t;
  1889. void _cmScMatcherInsertPrint(cmScMatcherPrint_t* a, unsigned i, unsigned* anp, unsigned aan, const cmScMatcherResult_t* rp, unsigned scLocIdx )
  1890. {
  1891. assert( *anp + 1 <= aan );
  1892. memmove(a + i + 1, a + i, (*anp-i)*sizeof(cmScMatcherPrint_t));
  1893. memset( a + i, 0, sizeof(cmScMatcherPrint_t));
  1894. *anp += 1;
  1895. a[i].flags = rp->flags;
  1896. a[i].scLocIdx = scLocIdx;
  1897. a[i].mni = rp->mni;
  1898. a[i].pitch = rp->pitch;
  1899. a[i].vel = rp->vel;
  1900. }
  1901. void cmScMatcherPrint( cmScMatcher* p )
  1902. {
  1903. unsigned bsli = cmScoreEvtCount(p->mp->scH);
  1904. unsigned esli = 0;
  1905. unsigned i,j,k;
  1906. // get first/last scLocIdx from res[] - this is the range of
  1907. // score events that the score matcher has identified
  1908. for(i=0; i<p->ri; ++i)
  1909. if( p->res[i].locIdx != cmInvalidIdx )
  1910. {
  1911. bsli = cmMin(bsli,p->mp->loc[p->res[i].locIdx].scLocIdx);
  1912. esli = cmMax(esli,p->mp->loc[p->res[i].locIdx].scLocIdx);
  1913. }
  1914. unsigned an = 0;
  1915. unsigned aan = p->ri;
  1916. // calc the count of score events between bsli and esli.
  1917. for(i=bsli; i<=esli; ++i)
  1918. {
  1919. cmScoreLoc_t* lp = cmScoreLoc(p->mp->scH, i);
  1920. assert(lp != NULL);
  1921. aan += lp->evtCnt;
  1922. }
  1923. // allocate an array of 'aan' print records
  1924. cmScMatcherPrint_t* a = cmMemAllocZ(cmScMatcherPrint_t,aan);
  1925. // fill the cmScMatcherPrint_t array with note and bar events from the score
  1926. for(i=bsli; i<=esli; ++i)
  1927. {
  1928. unsigned scLocIdx = i;
  1929. cmScoreLoc_t* lp = cmScoreLoc(p->mp->scH, scLocIdx );
  1930. // for each score event which occurs at this location
  1931. for(j=0; j<lp->evtCnt; ++j)
  1932. {
  1933. assert( an < aan );
  1934. cmScoreEvt_t* ep = lp->evtArray[j];
  1935. cmScMatcherPrint_t* pp = a + an;
  1936. an += 1;
  1937. switch( ep->type )
  1938. {
  1939. case kBarEvtScId:
  1940. pp->flags = kSmBarFl;
  1941. break;
  1942. case kNonEvtScId:
  1943. pp->flags = kSmNoteFl;
  1944. break;
  1945. }
  1946. pp->scLocIdx = scLocIdx;
  1947. pp->mni = cmInvalidIdx;
  1948. pp->pitch = ep->pitch;
  1949. pp->vel = kInvalidMidiVelocity;
  1950. pp->barNumb = ep->barNumb;
  1951. }
  1952. }
  1953. //
  1954. // a[an] now contains a record for each note and bar event in the
  1955. // time range associated with the score matcher's result array.
  1956. //
  1957. // for each result record
  1958. for(i=0; i<p->ri; ++i)
  1959. {
  1960. cmScMatcherResult_t* rp = p->res + i;
  1961. // if this result recd matched a score event
  1962. if( cmIsFlag(rp->flags,kSmTruePosFl) )
  1963. {
  1964. // locate the matching score event in a[an]
  1965. for(k=0; k<an; ++k)
  1966. if( a[k].scLocIdx==p->mp->loc[rp->locIdx].scLocIdx && a[k].pitch==rp->pitch )
  1967. {
  1968. a[k].mni = rp->mni;
  1969. a[k].vel = rp->vel;
  1970. a[k].flags |= kSmMatchFl;
  1971. break;
  1972. }
  1973. }
  1974. // if this result did not match a score event
  1975. if( cmIsFlag(rp->flags,kSmFalsePosFl) )
  1976. {
  1977. unsigned d_min = 0;
  1978. cmScMatcherPrint_t* dp = NULL;
  1979. unsigned scLocIdx = cmInvalidIdx;
  1980. // if this result does not have a valid locIdx
  1981. // (e.g. errant MIDI notes: scan:'delete' note or a step:mis-match note)
  1982. if( rp->locIdx == cmInvalidIdx )
  1983. {
  1984. // find the print recd with the closet 'mni'
  1985. for(k=0; k<an; ++k)
  1986. if( a[k].mni != cmInvalidIdx )
  1987. {
  1988. unsigned d;
  1989. if( a[k].mni > rp->mni )
  1990. d = a[k].mni - rp->mni;
  1991. else
  1992. d = rp->mni - a[k].mni;
  1993. if( dp==NULL || d < d_min )
  1994. {
  1995. dp = a + k;
  1996. d_min = d;
  1997. }
  1998. }
  1999. k = dp - a;
  2000. assert( k < an );
  2001. scLocIdx = p->mp->loc[k].scLocIdx;
  2002. if( a[k].mni < rp->mni )
  2003. ++k;
  2004. }
  2005. else // result w/ a valid locIdx (e.g. scan 'substitute' with no match)
  2006. {
  2007. scLocIdx = p->mp->loc[rp->locIdx].scLocIdx;
  2008. // find the print recd with the closest scIdx
  2009. for(k=0; k<an; ++k)
  2010. if( a[k].scLocIdx != cmInvalidIdx )
  2011. {
  2012. unsigned d;
  2013. if( a[k].scLocIdx > scLocIdx )
  2014. d = a[k].scLocIdx - scLocIdx;
  2015. else
  2016. d = scLocIdx - a[k].scLocIdx;
  2017. if( dp==NULL || d < d_min )
  2018. {
  2019. dp = a + k;
  2020. d_min = d;
  2021. }
  2022. }
  2023. k = dp - a;
  2024. assert( k < an );
  2025. if( a[k].scLocIdx < scLocIdx )
  2026. ++k;
  2027. }
  2028. // create a new print recd to represent the false-positive result recd
  2029. assert( dp != NULL );
  2030. _cmScMatcherInsertPrint(a, k, &an,aan,rp,scLocIdx);
  2031. }
  2032. }
  2033. printf("sloc bar mni ptch flag\n");
  2034. printf("---- ---- ---- ---- ----\n");
  2035. for(i=0; i<an; ++i)
  2036. {
  2037. printf("%4i %4i %4i %4s %c%c%c\n",a[i].scLocIdx,a[i].barNumb,a[i].mni,
  2038. cmIsFlag(a[i].flags,kSmBarFl) ? "|" : cmMidiToSciPitch(a[i].pitch,NULL,0),
  2039. cmIsFlag(a[i].flags,kSmNoteFl) ? 'n' : ' ',
  2040. cmIsFlag(a[i].flags,kSmMatchFl) ? 'm' : (cmIsFlag(a[i].flags,kSmTransFl) ? 't' : ' '),
  2041. cmIsFlag(a[i].flags,kSmFalsePosFl) ? '*' : ' '
  2042. );
  2043. }
  2044. cmMemFree(a);
  2045. }
  2046. //=======================================================================================================================
  2047. cmScMeas* cmScMeasAlloc( cmCtx* c, cmScMeas* p, cmScH_t scH, double srate, const unsigned* dynRefArray, unsigned dynRefCnt )
  2048. {
  2049. cmScMeas* op = cmObjAlloc(cmScMeas,c,p);
  2050. op->mp = cmScMatchAlloc( c, NULL, cmScNullHandle, 0, 0 );
  2051. if( cmScoreIsValid(scH) )
  2052. if( cmScMeasInit(op,scH,srate,dynRefArray,dynRefCnt) != cmOkRC )
  2053. cmScMeasFree(&op);
  2054. return op;
  2055. }
  2056. cmRC_t cmScMeasFree( cmScMeas** pp )
  2057. {
  2058. cmRC_t rc = cmOkRC;
  2059. if( pp==NULL || *pp==NULL )
  2060. return rc;
  2061. cmScMeas* p = *pp;
  2062. if((rc = cmScMeasFinal(p)) != cmOkRC )
  2063. return rc;
  2064. cmScMatchFree(&p->mp);
  2065. cmMemFree(p->midiBuf);
  2066. cmMemFree(p->set);
  2067. cmMemFree(p->dynRef);
  2068. cmObjFree(pp);
  2069. return rc;
  2070. }
  2071. void _cmScMeasPrint( cmScMeas* p )
  2072. {
  2073. unsigned i;
  2074. for(i=0; i<p->sn; ++i)
  2075. {
  2076. cmScMeasSet_t* sp = p->set + i;
  2077. printf("%4i: sli:%4i %4i li:%4i %4i\n", i, sp->bsli, sp->esli, sp->bli, sp->eli );
  2078. }
  2079. }
  2080. int _cmScMeasSortFunc( const void* p0, const void* p1 )
  2081. {
  2082. const cmScMeasSet_t* s0 = (const cmScMeasSet_t*)p0;
  2083. const cmScMeasSet_t* s1 = (const cmScMeasSet_t*)p1;
  2084. return s0->esli - s1->esli;
  2085. }
  2086. cmRC_t cmScMeasInit( cmScMeas* p, cmScH_t scH, double srate, const unsigned* dynRefArray, unsigned dynRefCnt )
  2087. {
  2088. cmRC_t rc;
  2089. unsigned i,j;
  2090. unsigned si;
  2091. unsigned maxScWndN = 0;
  2092. if((rc = cmScMeasFinal(p)) != cmOkRC )
  2093. return rc;
  2094. p->mii = 0;
  2095. p->mn = 2 * cmScoreEvtCount(scH);
  2096. p->midiBuf = cmMemResizeZ(cmScMatchMidi_t,p->midiBuf,p->mn);
  2097. p->sn = cmScoreSetCount(scH);
  2098. p->set = cmMemResizeZ(cmScMeasSet_t,p->set,p->sn);
  2099. p->dynRef = cmMemResizeZ(unsigned,p->dynRef,dynRefCnt);
  2100. p->dn = dynRefCnt;
  2101. p->srate = srate;
  2102. memcpy(p->dynRef,dynRefArray,sizeof(dynRefArray[0])*dynRefCnt);
  2103. unsigned n = cmScoreLocCount(scH);
  2104. // for each score location
  2105. for(i=0,si=0; i<n; ++i)
  2106. {
  2107. cmScoreLoc_t* lp = cmScoreLoc(scH,i);
  2108. cmScoreSet_t* sp = lp->setList;
  2109. // for each set that ends on this score location
  2110. for(; sp!=NULL; sp=sp->llink,++si)
  2111. {
  2112. assert(si < p->sn);
  2113. cmScMeasSet_t* msp = p->set + si;
  2114. msp->sp = sp;
  2115. msp->bsli = cmScoreLocCount(scH);
  2116. msp->esli = 0;
  2117. msp->bsei = cmScoreEvtCount(scH);
  2118. msp->esei = 0;
  2119. msp->bli = cmInvalidIdx;
  2120. msp->eli = cmInvalidIdx;
  2121. for(j=0; j<sp->eleCnt; ++j)
  2122. {
  2123. msp->bsli = cmMin(msp->bsli,sp->eleArray[j]->locIdx);
  2124. msp->esli = cmMax(msp->esli,sp->eleArray[j]->locIdx);
  2125. msp->bsei = cmMin(msp->bsei,sp->eleArray[j]->index);
  2126. msp->esei = cmMax(msp->esei,sp->eleArray[j]->index);
  2127. }
  2128. }
  2129. }
  2130. // initialize p->mp so that mp->loc[] is loaded - use dummy scWndN and midiN
  2131. if((rc = cmScMatchInit(p->mp, scH, 11, 10 )) != cmOkRC )
  2132. return rc;
  2133. // assign set[].bli and set[].eli
  2134. for(j=0; j<p->sn; ++j)
  2135. {
  2136. cmScMeasSet_t* msp = p->set + j;
  2137. for(i=0; i<p->mp->locN; ++i)
  2138. {
  2139. if( msp->bli==cmInvalidIdx && msp->bsli==p->mp->loc[i].scLocIdx )
  2140. msp->bli = i;
  2141. if( msp->esli==p->mp->loc[i].scLocIdx )
  2142. msp->eli = i;
  2143. }
  2144. assert( msp->eli > msp->bli );
  2145. maxScWndN = cmMax( maxScWndN, msp->eli - msp->bli + 1 );
  2146. }
  2147. // setup the match
  2148. if((rc = cmScMatchInit(p->mp, scH, 2*maxScWndN+1, 2*maxScWndN )) != cmOkRC )
  2149. return rc;
  2150. // sort set[] on cmScMeasSet_t.esli
  2151. qsort(p->set, p->sn, sizeof(cmScMeasSet_t), _cmScMeasSortFunc );
  2152. //_cmScMeasPrint(p);
  2153. cmScMeasReset(p);
  2154. return rc;
  2155. }
  2156. cmRC_t cmScMeasFinal( cmScMeas* p )
  2157. { return cmScMatchFinal(p->mp); }
  2158. cmRC_t cmScMeasReset( cmScMeas* p )
  2159. {
  2160. cmRC_t rc = cmOkRC;
  2161. p->mii = 0;
  2162. p->nsi = cmInvalidIdx;
  2163. p->vsi = cmInvalidIdx;
  2164. p->nsli = cmInvalidIdx;
  2165. unsigned i;
  2166. for(i=0; i<p->sn; ++i)
  2167. {
  2168. p->set[i].value = DBL_MAX;
  2169. p->set[i].tempo = 0;
  2170. p->set[i].match_cost = 0;
  2171. }
  2172. return rc;
  2173. }
  2174. typedef struct
  2175. {
  2176. unsigned scLocIdx; // score loc index
  2177. double frac; // score based fraction of beat
  2178. unsigned smpIdx; // time of assoc'd MIDI event
  2179. unsigned cnt; //
  2180. double val; //
  2181. } _cmScMeasTimeEle_t;
  2182. typedef struct
  2183. {
  2184. unsigned setN; // set length
  2185. unsigned midiN; // count of MIDI events to match to score
  2186. unsigned alignN; // count of score events in the alignment (<= setN)
  2187. unsigned matchN; // count of positive matches
  2188. double tempo;
  2189. double value;
  2190. } _cmScMeasResult_t;
  2191. double _cmScMeasCalcTempo( const _cmScMeasTimeEle_t* b, unsigned bn, double srate )
  2192. {
  2193. assert( bn >= 2 );
  2194. assert( b[bn-1].smpIdx != cmInvalidIdx );
  2195. assert( b[0].smpIdx != cmInvalidIdx );
  2196. double durSmpCnt = b[bn-1].smpIdx - b[0].smpIdx;
  2197. double beats = 0;
  2198. unsigned i;
  2199. for(i=0; i<bn; ++i)
  2200. beats += b[i].frac;
  2201. assert(beats != 0);
  2202. return beats / (durSmpCnt / (srate * 60.0));
  2203. }
  2204. // Note: On successful completion (return!=0) the first
  2205. // and last record returned in c[cn] will be matched records.
  2206. unsigned _cmScMeasTimeAlign( cmScMeas* p, cmScMeasSet_t* sp, cmScMatchMidi_t* m, unsigned mn, _cmScMeasTimeEle_t* c, unsigned cn, _cmScMeasResult_t* rp )
  2207. {
  2208. int i,j,k;
  2209. int an = sp->sp->eleCnt;
  2210. _cmScMeasTimeEle_t* b = NULL;
  2211. int bn = 0;
  2212. bool tempoFl = false;
  2213. unsigned matchN = 0;
  2214. assert( an!=0);
  2215. // alloc a 'score set' element array
  2216. _cmScMeasTimeEle_t a[an];
  2217. // get the scLocIdx of each set element from the score
  2218. for(i=0,j=0; i<an; ++i)
  2219. if( i==0 || sp->sp->eleArray[i-1]->locIdx != sp->sp->eleArray[i]->locIdx )
  2220. {
  2221. assert( sp->sp->eleArray[i]->locIdx != cmInvalidIdx );
  2222. a[j].scLocIdx = sp->sp->eleArray[i]->locIdx;
  2223. a[j].frac = sp->sp->eleArray[i]->frac;
  2224. a[j].smpIdx = cmInvalidIdx;
  2225. a[j].cnt = 0;
  2226. ++j;
  2227. }
  2228. an = j; // set the count of unique score locations (new length of a[])
  2229. // collect the 'smpIdx' for each MIDI event which matches a set element
  2230. for(i=0; i<mn; ++i)
  2231. if( m[i].locIdx != cmInvalidIdx )
  2232. {
  2233. for(j=0; j<an; ++j)
  2234. if( p->mp->loc[m[i].locIdx].scLocIdx == a[j].scLocIdx )
  2235. {
  2236. a[j].smpIdx += m[i].smpIdx;
  2237. a[j].cnt += 1;
  2238. if( a[j].cnt == 1 )
  2239. matchN += 1; // only cnt one match per sc loc.
  2240. break;
  2241. }
  2242. }
  2243. // remove leading missing values
  2244. for(i=0; i<an; ++i)
  2245. if( a[i].smpIdx != cmInvalidIdx )
  2246. {
  2247. b = a + i;
  2248. bn = an - i;
  2249. break;
  2250. }
  2251. // remove trailing missing values
  2252. for(i=bn-1; i>=0; --i,--bn)
  2253. if( b[i].smpIdx != cmInvalidIdx )
  2254. break;
  2255. // can't measure evenness against less than 2 values
  2256. if( bn < 2 )
  2257. {
  2258. return 0;
  2259. }
  2260. assert(b[0].smpIdx != cmInvalidIdx && b[bn-1].smpIdx != cmInvalidIdx);
  2261. // calc avg. smpIdx, insert missing values, and convert b[].smpIdx to delta smp index
  2262. for(i=0,j=0; i<bn; ++i)
  2263. {
  2264. if( b[i].cnt > 1 )
  2265. b[i].smpIdx /= b[i].cnt;
  2266. if( b[i].smpIdx == cmInvalidIdx )
  2267. ++j; // incr missing value count
  2268. else
  2269. {
  2270. if( i > 0 )
  2271. {
  2272. // fill in missing values
  2273. ++j;
  2274. unsigned d = (b[i].smpIdx - b[i-j].smpIdx)/j;
  2275. for(k=0; k<j; ++k)
  2276. b[i-j+k].val = d;
  2277. }
  2278. j=0;
  2279. }
  2280. if( b[i].frac != 0 )
  2281. tempoFl = true;
  2282. }
  2283. rp->setN = an;
  2284. rp->midiN = mn;
  2285. rp->alignN = bn;
  2286. rp->matchN = matchN;
  2287. rp->tempo = 0;
  2288. rp->value = 0;
  2289. // calculate tempo
  2290. if( tempoFl )
  2291. rp->tempo = _cmScMeasCalcTempo(b,bn,p->srate);
  2292. assert(bn<=cn);
  2293. // TODO: this copy should be eliminated
  2294. // copy to output
  2295. for(i=0; i<bn && i<cn; ++i)
  2296. c[i] = b[i];
  2297. return bn;
  2298. }
  2299. double _cmScMeasEven( cmScMeas* p, cmScMeasSet_t* sp, cmScMatchMidi_t* m, unsigned mn, _cmScMeasResult_t* rp )
  2300. {
  2301. unsigned bn = sp->sp->eleCnt;
  2302. _cmScMeasTimeEle_t b[bn];
  2303. unsigned i;
  2304. if((bn = _cmScMeasTimeAlign(p,sp,m,mn,b,bn,rp)) == 0 )
  2305. return DBL_MAX;
  2306. // calc avg. delta time
  2307. double d_avg = 0;
  2308. for(i=0; i<bn-1; ++i)
  2309. d_avg += b[i].val;
  2310. d_avg /= (bn-1);
  2311. // calc std-dev of delta time
  2312. double d_sd = 0;
  2313. for(i=0; i<bn-1; ++i)
  2314. d_sd += (b[i].val-d_avg) * (b[i].val-d_avg);
  2315. // if there is no deviation then we can't compute a z-score
  2316. // (this will happen if we fill in all the missing values based on 2 values)
  2317. if( d_sd == 0 )
  2318. return 1.0;
  2319. d_sd = sqrt(d_sd/(bn-1));
  2320. // calc avg. z-score
  2321. double z = 0;
  2322. for(i=0; i<bn-1; ++i)
  2323. z += fabs(b[i].val - d_avg)/d_sd;
  2324. double val = z / (bn-1);
  2325. rp->value = val;
  2326. return val;
  2327. }
  2328. // return Tempo estimation in BPM
  2329. double _cmScMeasTempo( cmScMeas* p, cmScMeasSet_t* sp, cmScMatchMidi_t* m, unsigned mn, _cmScMeasResult_t* rp )
  2330. {
  2331. unsigned bn = sp->sp->eleCnt;
  2332. _cmScMeasTimeEle_t b[bn];
  2333. if((bn= _cmScMeasTimeAlign(p,sp,m,mn,b,bn,rp)) == 0 )
  2334. return DBL_MAX;
  2335. return rp->tempo;
  2336. }
  2337. double _cmScMeasDyn( cmScMeas* p, cmScMeasSet_t* sp, cmScMatchMidi_t* m, unsigned mn, _cmScMeasResult_t* rp )
  2338. {
  2339. typedef struct
  2340. {
  2341. unsigned scEvtIdx;
  2342. unsigned vel;
  2343. double val;
  2344. } ele_t;
  2345. int i,j;
  2346. int n = sp->sp->eleCnt;
  2347. double vv = 0;
  2348. unsigned vn = 0;
  2349. unsigned matchN = 0;
  2350. unsigned alignN = 0;
  2351. assert( n!=0);
  2352. ele_t a[n];
  2353. // get the scEvtIdx of each set element
  2354. for(i=0; i<n; ++i)
  2355. {
  2356. cmScoreEvt_t* ep = cmScoreEvt( p->mp->scH, sp->sp->eleArray[i]->index );
  2357. assert( ep != NULL );
  2358. a[i].scEvtIdx = sp->sp->eleArray[i]->index;
  2359. a[i].vel = 0;
  2360. a[i].val = ep->dynVal;
  2361. }
  2362. // set the performed vel. of each note in the set
  2363. // (if a note was not played it's a[].vel is left at 0)
  2364. for(i=0; i<mn; ++i)
  2365. if( m[i].scEvtIdx != cmInvalidIdx )
  2366. {
  2367. alignN += 1;
  2368. for(j=0; j<n; ++j)
  2369. if( m[i].scEvtIdx == a[j].scEvtIdx )
  2370. {
  2371. matchN += 1;
  2372. a[j].vel = m[i].vel;
  2373. break;
  2374. }
  2375. }
  2376. // assign a dynamics category to each note in the set
  2377. for(i=0; i<n; ++i)
  2378. if( a[i].vel > 0 )
  2379. {
  2380. unsigned mnv = 0; // lower bound for first dyn's category
  2381. for(j=0; j<p->dn; ++j)
  2382. {
  2383. if( mnv <= a[i].vel && a[i].vel < p->dynRef[j] )
  2384. {
  2385. // accum. the diff. between the ref. and performed dyn. category
  2386. vv += fabs(a[i].val - j);
  2387. vn += 1;
  2388. break;
  2389. }
  2390. mnv = p->dynRef[j];
  2391. }
  2392. assert(j<p->dn);
  2393. }
  2394. rp->setN = n;
  2395. rp->midiN = mn;
  2396. rp->alignN = alignN;
  2397. rp->matchN = matchN;
  2398. rp->tempo = 0;
  2399. rp->value = vn == 0 ? DBL_MAX : vv/vn;
  2400. return rp->value;
  2401. }
  2402. unsigned MEAS_MATCH_CNT = 0;
  2403. void _cmScMeasPrintResult( cmScMeas* p, cmScMeasSet_t* sp, _cmScMeasResult_t* rp, unsigned bli, const cmScMatchMidi_t* mb )
  2404. {
  2405. const char* label = "<none>";
  2406. switch( sp->sp->varId )
  2407. {
  2408. case kEvenVarScId:
  2409. label = "even";
  2410. break;
  2411. case kDynVarScId:
  2412. label = "dyn";
  2413. break;
  2414. case kTempoVarScId:
  2415. label = "tempo";
  2416. break;
  2417. }
  2418. const cmChar_t* msg = "";
  2419. if( rp->value == DBL_MAX )
  2420. {
  2421. msg = "Measure FAILED.";
  2422. sp->value = 0;
  2423. }
  2424. printf("%i set:%i %s bsli:%i esli:%i [set:%i match:%i] cost:%f val:%f %s",MEAS_MATCH_CNT, p->nsi, label, sp->bsli, sp->esli, rp->setN, rp->matchN, p->mp->opt_cost, sp->value, msg);
  2425. if( rp->tempo != 0 )
  2426. printf(" tempo:%f ",rp->tempo);
  2427. printf("\n");
  2428. _cmScMatchPrintPath(p->mp, p->mp->p_opt, bli, mb );
  2429. }
  2430. void _cmScMeasCalcVal( cmScMeas* p, cmScMeasSet_t* sp, int n_mii )
  2431. {
  2432. unsigned mn = 0;
  2433. int i,k = cmInvalidIdx;
  2434. if( n_mii == 0 )
  2435. return;
  2436. // Determine the count of MIDI notes to match to the set score
  2437. // by searching from the MIDI note just recieved (midiBuf[n_mii]
  2438. // back toward the beginning until a MIDI event which occurs just
  2439. // prior to the set's begScLocIdx.
  2440. for(i=n_mii; i>=0; --i)
  2441. {
  2442. if( p->midiBuf[i].locIdx != cmInvalidIdx )
  2443. {
  2444. k = i;
  2445. unsigned scLocIdx = p->mp->loc[ p->midiBuf[i].locIdx ].scLocIdx;
  2446. if( scLocIdx < sp->bsli )
  2447. break;
  2448. }
  2449. }
  2450. assert(k != cmInvalidIdx);
  2451. mn = n_mii - k + 1;
  2452. i = k;
  2453. assert(i>=0);
  2454. assert(mn>0);
  2455. // Create a copy of the the MIDI buffer to prevent the
  2456. // p->midiBuf[].locIdx from being overwritten by cmScMatchDoSync().
  2457. cmScMatchMidi_t mb[ mn ];
  2458. unsigned j;
  2459. for(j=0; j<mn; ++j)
  2460. {
  2461. mb[j] = p->midiBuf[i+j];
  2462. mb[j].locIdx = cmInvalidIdx;
  2463. }
  2464. // In general the first and last MIDI event should be assigned
  2465. // to a score location - it's possible however that no MIDI
  2466. // event's prior to the one at p->midiBuf[n_mii] were assigned.
  2467. assert( (i==0 || p->midiBuf[i].locIdx!=cmInvalidIdx) && p->midiBuf[i+mn-1].locIdx != cmInvalidIdx);
  2468. unsigned l0i = cmMin(p->midiBuf[i].locIdx,p->midiBuf[i+mn-1].locIdx);
  2469. unsigned l1i = cmMax(p->midiBuf[i].locIdx,p->midiBuf[i+mn-1].locIdx);
  2470. unsigned bli = l0i;
  2471. unsigned ln = l1i - bli + 1;
  2472. double min_cost = DBL_MAX;
  2473. _cmScMeasResult_t r;
  2474. memset(&r,0,sizeof(r));
  2475. // match MIDI to score
  2476. if( cmScMatchExec(p->mp, bli, ln, mb, mn, min_cost ) != cmOkRC )
  2477. return;
  2478. // sync the score and MIDI based on the match information
  2479. if( cmScMatchDoSync(p->mp, bli, mb, mn, NULL ) == cmInvalidIdx )
  2480. return;
  2481. if( p->mp->opt_cost != DBL_MAX )
  2482. sp->match_cost = p->mp->opt_cost / sp->sp->eleCnt;
  2483. switch( sp->sp->varId )
  2484. {
  2485. case kEvenVarScId:
  2486. sp->value = _cmScMeasEven(p, sp, mb, mn, &r );
  2487. break;
  2488. case kDynVarScId:
  2489. sp->value = _cmScMeasDyn(p, sp, mb, mn, &r );
  2490. break;
  2491. case kTempoVarScId:
  2492. sp->value = _cmScMeasTempo(p, sp, mb, mn, &r );
  2493. break;
  2494. default:
  2495. { assert(0); }
  2496. }
  2497. sp->tempo = r.tempo;
  2498. // print the result
  2499. //_cmScMeasPrintResult(p, sp, &r, bli, mb );
  2500. MEAS_MATCH_CNT++;
  2501. }
  2502. cmRC_t cmScMeasExec( cmScMeas* p, unsigned mni, unsigned locIdx, unsigned scEvtIdx, unsigned flags, unsigned smpIdx, unsigned pitch, unsigned vel )
  2503. {
  2504. cmRC_t rc = cmOkRC;
  2505. // if the midi buffer is full
  2506. if( p->mii >= p->mn )
  2507. return cmCtxRtCondition( &p->obj, cmEofRC, "The MIDI buffer is full.");
  2508. int n_mii = cmInvalidIdx;
  2509. // locate the MIDI event assoc'd with 'mni' ...
  2510. if( p->mii>0 && mni <= p->midiBuf[p->mii-1].mni )
  2511. {
  2512. if( locIdx != cmInvalidIdx )
  2513. {
  2514. for(n_mii=p->mii-1; n_mii>=0; --n_mii)
  2515. if( p->midiBuf[n_mii].mni == mni )
  2516. break;
  2517. if( n_mii<0 )
  2518. n_mii = cmInvalidIdx;
  2519. }
  2520. }
  2521. else // ... or push a new record onto p->midiBuf[]
  2522. {
  2523. n_mii = p->mii;
  2524. ++p->mii;
  2525. }
  2526. // store the MIDI event
  2527. p->midiBuf[n_mii].mni = mni;
  2528. p->midiBuf[n_mii].locIdx = locIdx;
  2529. p->midiBuf[n_mii].scEvtIdx = scEvtIdx;
  2530. p->midiBuf[n_mii].smpIdx = smpIdx;
  2531. p->midiBuf[n_mii].pitch = pitch;
  2532. p->midiBuf[n_mii].vel = vel;
  2533. // setting vsi=nsi and vsli=nsli will indicate to the calling
  2534. // program that no new sets are ready.
  2535. p->vsi = p->nsi;
  2536. p->vsli = p->nsli;
  2537. if( locIdx == cmInvalidIdx )
  2538. return cmOkRC;
  2539. //
  2540. unsigned scLocIdx = p->mp->loc[ locIdx ].scLocIdx;
  2541. unsigned maxScLocIdx = cmScoreLocCount(p->mp->scH)-1;
  2542. // if this cmScMeas object has not yet synchronized to the cmScMatcher
  2543. // (if p->nsli is not valid)
  2544. if( p->nsli == cmInvalidIdx )
  2545. {
  2546. unsigned i;
  2547. for(i=0; i<p->sn; ++i)
  2548. if( p->set[i].esli+1 == scLocIdx )
  2549. {
  2550. p->nsli = scLocIdx;
  2551. p->nsi = i;
  2552. break;
  2553. }
  2554. if(i==p->sn)
  2555. return rc;
  2556. }
  2557. p->vsi = p->nsi;
  2558. p->vsli = p->nsli;
  2559. // for each cmScore location between p->nsli and scLocIdx
  2560. for(; p->nsli<=scLocIdx && p->nsi < p->sn; ++p->nsli)
  2561. {
  2562. // if this score location index (p->nsli) is one score location
  2563. // ahead of the next sets ending location.
  2564. while( cmMin(maxScLocIdx,p->set[p->nsi].esli+1) == p->nsli )
  2565. {
  2566. // calculate the value assoc'd with p->set[p->nsi]
  2567. _cmScMeasCalcVal(p, p->set + p->nsi, n_mii );
  2568. // advance the set index
  2569. ++p->nsi;
  2570. }
  2571. }
  2572. return rc;
  2573. }
  2574. //=======================================================================================================================
  2575. cmRC_t cmScAlignScanToTimeLineEvent( cmScMatcher* p, cmTlH_t tlH, cmTlObj_t* top, unsigned endSmpIdx )
  2576. {
  2577. assert( top != NULL );
  2578. cmTlMidiEvt_t* mep = NULL;
  2579. cmRC_t rc = cmOkRC;
  2580. // as long as more MIDI events are available get the next MIDI msg
  2581. while( rc==cmOkRC && (mep = cmTlNextMidiEvtObjPtr(tlH, top, top->seqId )) != NULL )
  2582. {
  2583. top = &mep->obj;
  2584. // if the msg falls after the end of the marker then we are through
  2585. if( mep->obj.seqSmpIdx != cmInvalidIdx && mep->obj.seqSmpIdx > endSmpIdx )
  2586. break;
  2587. // if the time line MIDI msg a note-on
  2588. if( (mep->msg->status&0xf0) == kNoteOnMdId )
  2589. {
  2590. rc = cmScMatcherExec(p, mep->obj.seqSmpIdx, mep->msg->status, mep->msg->u.chMsgPtr->d0, mep->msg->u.chMsgPtr->d1, NULL );
  2591. switch( rc )
  2592. {
  2593. case cmOkRC: // continue processing MIDI events
  2594. break;
  2595. case cmEofRC: // end of the score was encountered
  2596. break;
  2597. case cmInvalidArgRC: // p->eli was not set correctly
  2598. break;
  2599. case cmSubSysFailRC: // scan resync failed
  2600. break;
  2601. default:
  2602. { assert(0); }
  2603. }
  2604. }
  2605. }
  2606. if( rc == cmEofRC )
  2607. rc = cmOkRC;
  2608. return rc;
  2609. }
  2610. // This callback connects/feeds the cmScMeas object from the cmScMatcher object.
  2611. // (See _cmScMatcherStoreResult().)
  2612. void cmScMatcherCb( cmScMatcher* p, void* arg, cmScMatcherResult_t* rp )
  2613. {
  2614. cmScMeas* mp = (cmScMeas*)arg;
  2615. cmScMeasExec(mp, rp->mni, rp->locIdx, rp->scEvtIdx, rp->flags, rp->smpIdx, rp->pitch, rp->vel );
  2616. }
  2617. void cmScAlignScanMarkers( cmRpt_t* rpt, cmTlH_t tlH, cmScH_t scH )
  2618. {
  2619. unsigned i;
  2620. double srate = cmTimeLineSampleRate(tlH);
  2621. unsigned midiN = 7;
  2622. unsigned scWndN = 10;
  2623. unsigned markN = 291;
  2624. unsigned dynRefArray[] = { 14, 28, 42, 56, 71, 85, 99, 113,128 };
  2625. unsigned dynRefCnt = sizeof(dynRefArray)/sizeof(dynRefArray[0]);
  2626. cmCtx* ctx = cmCtxAlloc(NULL, rpt, cmLHeapNullHandle, cmSymTblNullHandle );
  2627. cmScMeas* mp = cmScMeasAlloc(ctx,NULL,scH,srate,dynRefArray,dynRefCnt);
  2628. cmScMatcher* p = cmScMatcherAlloc(ctx,NULL,srate,scH,scWndN,midiN,cmScMatcherCb,mp);
  2629. double scoreThresh = 0.5;
  2630. unsigned candCnt = 0;
  2631. unsigned initFailCnt = 0;
  2632. unsigned otherFailCnt = 0;
  2633. unsigned scoreFailCnt = 0;
  2634. bool printFl = false;
  2635. unsigned markCharCnt = 31;
  2636. cmChar_t markText[ markCharCnt+1 ];
  2637. cmTimeSpec_t t0,t1;
  2638. cmTimeGet(&t0);
  2639. // for each marker
  2640. for(i=0; i<markN; ++i)
  2641. {
  2642. // form the marker text
  2643. snprintf(markText,markCharCnt,"Mark %i",i);
  2644. // locate the marker
  2645. cmTlMarker_t* tlmp = cmTimeLineMarkerFind( tlH, markText );
  2646. if( tlmp == NULL )
  2647. {
  2648. if( printFl )
  2649. printf("The marker '%s' was not found.\n\n",markText);
  2650. continue;
  2651. }
  2652. // skip markers which do not contain text
  2653. if( cmTextIsEmpty(tlmp->text) )
  2654. {
  2655. if( printFl )
  2656. printf("The marker '%s' is being skipped because it has no text.\n\n",markText);
  2657. continue;
  2658. }
  2659. printf("=================== MARKER:%s ===================\n",markText);
  2660. cmScMatcherReset(p,0); // reset the score follower to the beginnig of the score
  2661. cmScMeasReset(mp);
  2662. ++candCnt;
  2663. // scan to the beginning of the marker
  2664. cmRC_t rc = cmScAlignScanToTimeLineEvent(p,tlH,&tlmp->obj,tlmp->obj.seqSmpIdx+tlmp->obj.durSmpCnt);
  2665. bool pfl = true;
  2666. if( rc != cmOkRC || p->begSyncLocIdx==cmInvalidIdx)
  2667. {
  2668. bool fl = printFl;
  2669. printFl = true;
  2670. // if a no alignment was found
  2671. if( p->begSyncLocIdx == cmInvalidIdx )
  2672. rc = cmInvalidArgRC;
  2673. if( p->mni == 0 )
  2674. {
  2675. if( printFl )
  2676. printf("mark:%i midi:%i Not enough MIDI notes to fill the scan buffer.\n",i,p->mni);
  2677. pfl = false;
  2678. }
  2679. else
  2680. {
  2681. switch(rc)
  2682. {
  2683. case cmInvalidArgRC:
  2684. if( printFl )
  2685. printf("mark:%i INITIAL SYNC FAIL\n",i);
  2686. ++initFailCnt;
  2687. pfl = false;
  2688. break;
  2689. case cmSubSysFailRC:
  2690. if( printFl )
  2691. printf("mark:%i SCAN RESYNC FAIL\n",i);
  2692. ++otherFailCnt;
  2693. break;
  2694. default:
  2695. if( printFl )
  2696. printf("mark:%i UNKNOWN FAIL\n",i);
  2697. ++otherFailCnt;
  2698. }
  2699. }
  2700. printFl = fl;
  2701. }
  2702. if( pfl )
  2703. {
  2704. double fmeas = cmScMatcherFMeas(p);
  2705. if( printFl )
  2706. printf("mark:%i midi:%i loc:%i bar:%i cost:%f f-meas:%f text:%s\n",i,p->mni,p->begSyncLocIdx,p->mp->loc[p->begSyncLocIdx].barNumb,p->s_opt,fmeas,tlmp->text);
  2707. if( fmeas < scoreThresh )
  2708. ++scoreFailCnt;
  2709. }
  2710. //print score and match for entire marker
  2711. //cmScMatcherPrint(p);
  2712. // ONLY USE ONE MARKER DURING TESTING
  2713. // break;
  2714. if( printFl )
  2715. printf("\n");
  2716. }
  2717. printf("cand:%i fail:%i - init:%i score:%i other:%i\n\n",candCnt,initFailCnt+scoreFailCnt+otherFailCnt,initFailCnt,scoreFailCnt,otherFailCnt);
  2718. cmTimeGet(&t1);
  2719. printf("elapsed:%f\n", (double)cmTimeElapsedMicros(&t0,&t1)/1000000.0 );
  2720. cmScMatcherFree(&p);
  2721. cmScMeasFree(&mp);
  2722. cmCtxFree(&ctx);
  2723. }
  2724. //=======================================================================================================================
  2725. cmScModulator* cmScModulatorAlloc( cmCtx* c, cmScModulator* p, cmCtx_t* ctx, cmSymTblH_t stH, double srate, unsigned samplesPerCycle, const cmChar_t* fn, const cmChar_t* modLabel, cmScModCb_t cbFunc, void* cbArg )
  2726. {
  2727. cmScModulator* op = cmObjAlloc(cmScModulator,c,p);
  2728. if( ctx != NULL )
  2729. if( cmScModulatorInit(op,ctx,stH,srate,samplesPerCycle,fn,modLabel,cbFunc,cbArg) != cmOkRC )
  2730. cmScModulatorFree(&op);
  2731. return op;
  2732. }
  2733. cmRC_t cmScModulatorFree( cmScModulator** pp )
  2734. {
  2735. cmRC_t rc = cmOkRC;
  2736. if( pp==NULL || *pp==NULL )
  2737. return rc;
  2738. cmScModulator* p = *pp;
  2739. if((rc = cmScModulatorFinal(p)) != cmOkRC )
  2740. return rc;
  2741. cmMemFree(p->earray);
  2742. cmObjFree(pp);
  2743. return rc;
  2744. }
  2745. typedef struct
  2746. {
  2747. unsigned typeId;
  2748. unsigned minArgCnt;
  2749. const cmChar_t* label;
  2750. } _cmScModTypeMap_t;
  2751. _cmScModTypeMap_t _cmScModTypeArray[] =
  2752. {
  2753. { kSetModTId, 1, "set" },
  2754. { kLineModTId, 2, "line" },
  2755. { kSetLineModTId, 3, "sline" },
  2756. { kPostModTId, 4, "post" },
  2757. { kInvalidModTId, 0, "<invalid>"}
  2758. };
  2759. const _cmScModTypeMap_t* _cmScModTypeLabelToMap( const cmChar_t* label )
  2760. {
  2761. unsigned i;
  2762. for(i=0; _cmScModTypeArray[i].typeId!=kInvalidModTId; ++i)
  2763. if( strcmp(_cmScModTypeArray[i].label,label) == 0 )
  2764. return _cmScModTypeArray + i;
  2765. return NULL;
  2766. }
  2767. cmScModVar_t* _cmScModSymToVar( cmScModulator* p, unsigned varSymId )
  2768. {
  2769. cmScModVar_t* vp = p->vlist;
  2770. for(; vp!=NULL; vp=vp->vlink)
  2771. if( varSymId == vp->varSymId )
  2772. return vp;
  2773. return NULL;
  2774. }
  2775. cmScModVar_t* _cmScModulatorInsertVar( cmScModulator* p, unsigned varSymId, unsigned flags )
  2776. {
  2777. cmScModVar_t* vp = _cmScModSymToVar(p,varSymId);
  2778. if( vp == NULL )
  2779. {
  2780. vp = cmMemAllocZ(cmScModVar_t,1);
  2781. vp->varSymId = varSymId;
  2782. vp->outVarId = cmInvalidId;
  2783. vp->vlink = p->vlist;
  2784. p->vlist = vp;
  2785. }
  2786. vp->flags = flags;
  2787. vp->value = DBL_MAX;
  2788. vp->min = DBL_MAX;
  2789. vp->max = DBL_MAX;
  2790. vp->rate = DBL_MAX;
  2791. vp->phase = 0;
  2792. vp->entry = NULL;
  2793. vp->alink = NULL;
  2794. return vp;
  2795. }
  2796. cmScModEntry_t* _cmScModulatorInsertEntry(cmScModulator* p, unsigned idx, unsigned scLocIdx, unsigned modSymId, unsigned varSymId, unsigned typeId, unsigned paramCnt )
  2797. {
  2798. assert( idx < p->en );
  2799. p->earray[idx].scLocIdx = scLocIdx;
  2800. p->earray[idx].typeId = typeId;
  2801. p->earray[idx].varPtr = _cmScModulatorInsertVar(p,varSymId,0);
  2802. if( p->earray[idx].varPtr->outVarId == cmInvalidIdx )
  2803. p->earray[idx].varPtr->outVarId = p->outVarCnt++;
  2804. return p->earray + idx;
  2805. }
  2806. /*
  2807. {
  2808. [
  2809. { loc:123, mod:modlabel, var:varlabel, param:[ ] }
  2810. ]
  2811. }
  2812. */
  2813. // Parameter values are found as values of the 'data','min' or 'max' fields.
  2814. // A parameter value may be either a symbol identifier (mapped to a variable)
  2815. // or a literal number. This function determines which form the paramter
  2816. // value takes and parses it accordingly.
  2817. cmRC_t _cmScModulatorParseParam( cmScModulator* p, cmSymTblH_t stH, cmJsonNode_t* np, cmScModParam_t* pp )
  2818. {
  2819. cmRC_t rc = cmOkRC;
  2820. switch( np->typeId )
  2821. {
  2822. case kIntTId:
  2823. case kRealTId:
  2824. if( cmJsonRealValue(np, &pp->val ) != kOkJsRC )
  2825. {
  2826. rc = cmCtxRtCondition( &p->obj, cmInvalidArgRC, "Error parsing in Modulator literal value." );
  2827. goto errLabel;
  2828. }
  2829. pp->pid = kLiteralModPId;
  2830. break;
  2831. case kStringTId:
  2832. {
  2833. const cmChar_t* label = NULL;
  2834. if( cmJsonStringValue(np, &label) != kOkJsRC )
  2835. {
  2836. rc = cmCtxRtCondition( &p->obj, cmInvalidArgRC, "Error parsing in Modulator symbol label." );
  2837. goto errLabel;
  2838. }
  2839. pp->symId = cmSymTblRegisterSymbol(stH,label);
  2840. pp->pid = kSymbolModPId;
  2841. }
  2842. break;
  2843. default:
  2844. rc = cmCtxRtCondition( &p->obj, cmInvalidArgRC, "Parameter value is not a number or identifier." );
  2845. goto errLabel;
  2846. break;
  2847. }
  2848. errLabel:
  2849. return rc;
  2850. }
  2851. cmRC_t _cmScModulatorParse( cmScModulator* p, cmCtx_t* ctx, cmSymTblH_t stH, const cmChar_t* fn )
  2852. {
  2853. cmRC_t rc = cmOkRC;
  2854. cmJsonNode_t* jnp = NULL;
  2855. cmJsonH_t jsH = cmJsonNullHandle;
  2856. unsigned i = cmInvalidIdx;
  2857. unsigned j = cmInvalidIdx;
  2858. // read the JSON file
  2859. if( cmJsonInitializeFromFile(&jsH, fn, ctx ) != kOkJsRC )
  2860. return cmCtxRtCondition( &p->obj, cmInvalidArgRC, "JSON file parse failed on the modulator file: %s.",cmStringNullGuard(fn) );
  2861. jnp = cmJsonRoot(jsH);
  2862. // validate that the first child as an array
  2863. if( jnp==NULL || ((jnp = cmJsonNodeMemberValue(jnp,"array")) == NULL) || cmJsonIsArray(jnp)==false )
  2864. {
  2865. rc = cmCtxRtCondition( &p->obj, cmInvalidArgRC, "Modulator file header syntax error in file:%s",cmStringNullGuard(fn) );
  2866. goto errLabel;
  2867. }
  2868. // allocate the entry array
  2869. unsigned entryCnt = cmJsonChildCount(jnp);
  2870. p->earray = cmMemResizeZ(cmScModEntry_t,p->earray,entryCnt);
  2871. p->en = entryCnt;
  2872. unsigned prvScLocIdx = cmInvalidIdx;
  2873. const cmChar_t* prvModLabel = NULL;
  2874. const cmChar_t* prvVarLabel = NULL;
  2875. const cmChar_t* prvTypeLabel = NULL;
  2876. for(i=0; i<entryCnt; ++i)
  2877. {
  2878. cmJsRC_t jsRC;
  2879. const char* errLabelPtr = NULL;
  2880. unsigned scLocIdx = cmInvalidIdx;
  2881. const cmChar_t* modLabel = NULL;
  2882. const cmChar_t* varLabel = NULL;
  2883. const cmChar_t* typeLabel = NULL;
  2884. cmJsonNode_t* onp = cmJsonArrayElement(jnp,i);
  2885. cmJsonNode_t* dnp = NULL;
  2886. const _cmScModTypeMap_t* map = NULL;
  2887. if((jsRC = cmJsonMemberValues( onp, &errLabelPtr,
  2888. "loc", kIntTId | kOptArgJsFl, &scLocIdx,
  2889. "mod", kStringTId | kOptArgJsFl, &modLabel,
  2890. "var", kStringTId | kOptArgJsFl, &varLabel,
  2891. "type",kStringTId | kOptArgJsFl, &typeLabel,
  2892. NULL )) != kOkJsRC )
  2893. {
  2894. if( errLabelPtr == NULL )
  2895. rc = cmCtxRtCondition( &p->obj, cmInvalidArgRC, "Error:%s on record at index %i in file:%s",errLabelPtr,i,cmStringNullGuard(fn) );
  2896. else
  2897. rc = cmCtxRtCondition( &p->obj, cmInvalidArgRC, "Synax error in Modulator record at index %i in file:%s",i,cmStringNullGuard(fn) );
  2898. goto errLabel;
  2899. }
  2900. // if the score location was not given use the previous score location
  2901. if( scLocIdx == cmInvalidIdx )
  2902. scLocIdx = prvScLocIdx;
  2903. else
  2904. prvScLocIdx = scLocIdx;
  2905. // if the mod label was not given use the previous one
  2906. if( modLabel == NULL )
  2907. modLabel = prvModLabel;
  2908. else
  2909. prvModLabel = modLabel;
  2910. if( modLabel == NULL )
  2911. {
  2912. rc = cmCtxRtCondition(&p->obj, cmInvalidArgRC, "No 'mod' label has been set in mod file '%s'.",cmStringNullGuard(fn));
  2913. goto errLabel;
  2914. }
  2915. // if the var label was not given use the previous one
  2916. if( varLabel == NULL )
  2917. varLabel = prvVarLabel;
  2918. else
  2919. prvVarLabel = varLabel;
  2920. if( varLabel == NULL )
  2921. {
  2922. rc = cmCtxRtCondition(&p->obj, cmInvalidArgRC, "No 'var' label has been set in mod file '%s'.",cmStringNullGuard(fn));
  2923. goto errLabel;
  2924. }
  2925. // if the type label was not given use the previous one
  2926. if( typeLabel == NULL )
  2927. typeLabel = prvTypeLabel;
  2928. else
  2929. prvTypeLabel = typeLabel;
  2930. if( typeLabel == NULL )
  2931. {
  2932. rc = cmCtxRtCondition(&p->obj, cmInvalidArgRC, "No 'type' label has been set in mod file '%s'.",cmStringNullGuard(fn));
  2933. goto errLabel;
  2934. }
  2935. // validate the entry type label
  2936. if((map = _cmScModTypeLabelToMap(typeLabel)) == NULL )
  2937. {
  2938. rc = cmCtxRtCondition( &p->obj, cmInvalidArgRC, "Unknown entry type '%s' in Modulator record at index %i in file:%s",cmStringNullGuard(typeLabel),i,cmStringNullGuard(fn) );
  2939. goto errLabel;
  2940. }
  2941. unsigned modSymId = cmSymTblRegisterSymbol(stH,modLabel);
  2942. unsigned varSymId = cmSymTblRegisterSymbol(stH,varLabel);
  2943. // the mod entry label must match the modulators label
  2944. if( p->modSymId != modSymId )
  2945. {
  2946. --p->en;
  2947. continue;
  2948. }
  2949. // get the count of the elmenets in the data array
  2950. unsigned paramCnt = cmJsonChildCount(onp);
  2951. // fill the entry record and find or create the target var
  2952. cmScModEntry_t* ep = _cmScModulatorInsertEntry(p,i,scLocIdx,modSymId,varSymId,map->typeId,paramCnt);
  2953. typedef struct
  2954. {
  2955. const cmChar_t* label;
  2956. cmScModParam_t* param;
  2957. } map_t;
  2958. // parse the var and parameter records
  2959. map_t mapArray[] =
  2960. {
  2961. { "min", &ep->min },
  2962. { "max", &ep->max },
  2963. { "rate",&ep->rate },
  2964. { "val", &ep->beg },
  2965. { "end", &ep->end },
  2966. { "dur", &ep->dur },
  2967. { NULL, NULL }
  2968. };
  2969. unsigned j=0;
  2970. for(j=0; mapArray[j].param!=NULL; ++j)
  2971. if((dnp = cmJsonFindValue(jsH,mapArray[j].label, onp, kInvalidTId )) != NULL )
  2972. if((rc = _cmScModulatorParseParam(p,stH,dnp,mapArray[j].param)) != cmOkRC )
  2973. goto errLabel;
  2974. }
  2975. errLabel:
  2976. if( rc != cmOkRC )
  2977. cmCtxRtCondition( &p->obj, cmInvalidArgRC, "Error parsing in Modulator 'data' record at index %i value index %i in file:%s",i,j,cmStringNullGuard(fn) );
  2978. // release the JSON tree
  2979. if( cmJsonIsValid(jsH) )
  2980. cmJsonFinalize(&jsH);
  2981. return rc;
  2982. }
  2983. cmRC_t _cmScModulatorReset( cmScModulator* p, cmCtx_t* ctx, unsigned scLocIdx )
  2984. {
  2985. cmRC_t rc = cmOkRC;
  2986. p->alist = NULL;
  2987. p->elist = NULL;
  2988. p->nei = 0;
  2989. p->outVarCnt = 0;
  2990. // reload the file
  2991. if((rc = _cmScModulatorParse(p,ctx,p->stH,p->fn)) != cmOkRC )
  2992. goto errLabel;
  2993. // clear the active flag on all variables
  2994. cmScModVar_t* vp = p->vlist;
  2995. for(; vp!=NULL; vp=vp->vlink)
  2996. {
  2997. vp->flags = cmClrFlag(vp->flags,kActiveModFl);
  2998. vp->alink = NULL;
  2999. }
  3000. errLabel:
  3001. return rc;
  3002. }
  3003. cmRC_t cmScModulatorInit( cmScModulator* p, cmCtx_t* ctx, cmSymTblH_t stH, double srate, unsigned samplesPerCycle, const cmChar_t* fn, const cmChar_t* modLabel, cmScModCb_t cbFunc, void* cbArg )
  3004. {
  3005. cmRC_t rc;
  3006. if((rc = cmScModulatorFinal(p)) != cmOkRC )
  3007. return rc;
  3008. p->fn = cmMemAllocStr(fn);
  3009. p->stH = stH;
  3010. p->modSymId = cmSymTblRegisterSymbol(stH,modLabel);
  3011. p->cbFunc = cbFunc;
  3012. p->cbArg = cbArg;
  3013. p->samplesPerCycle = samplesPerCycle;
  3014. p->srate = srate;
  3015. if( rc != cmOkRC )
  3016. cmScModulatorFinal(p);
  3017. else
  3018. _cmScModulatorReset(p,ctx,0);
  3019. return rc;
  3020. }
  3021. cmRC_t cmScModulatorFinal( cmScModulator* p )
  3022. {
  3023. cmMemFree(p->fn);
  3024. // release each var record
  3025. cmScModVar_t* vp = p->vlist;
  3026. while( vp!=NULL )
  3027. {
  3028. cmScModVar_t* np = vp->vlink;
  3029. cmMemFree(vp);
  3030. vp=np;
  3031. }
  3032. return cmOkRC;
  3033. }
  3034. unsigned cmScModulatorOutVarCount( cmScModulator* p )
  3035. { return p->outVarCnt; }
  3036. cmScModVar_t* cmScModulatorOutVar( cmScModulator* p, unsigned idx )
  3037. {
  3038. unsigned i;
  3039. for(i=0; i<p->en; ++i)
  3040. if( p->earray[i].varPtr->outVarId == idx )
  3041. return p->earray[i].varPtr;
  3042. return NULL;
  3043. }
  3044. cmRC_t cmScModulatorSetValue( cmScModulator* p, unsigned varSymId, double value, double min, double max )
  3045. {
  3046. cmScModVar_t* vp;
  3047. // if the var does not exist ....
  3048. if((vp = _cmScModSymToVar(p, varSymId )) == NULL )
  3049. {
  3050. // ... then create it
  3051. vp = _cmScModulatorInsertVar(p,varSymId,kCalcModFl);
  3052. assert(vp!=NULL);
  3053. }
  3054. assert( min <= max);
  3055. vp->min = min;
  3056. vp->max = max;
  3057. vp->value = value;
  3058. return cmOkRC;
  3059. }
  3060. cmRC_t cmScModulatorReset( cmScModulator* p, cmCtx_t* ctx, unsigned scLocIdx )
  3061. {
  3062. _cmScModulatorReset(p,ctx,scLocIdx);
  3063. return cmScModulatorExec(p,scLocIdx);
  3064. }
  3065. void _cmScModUnlinkActive( cmScModulator* p, cmScModVar_t* vp, cmScModVar_t* pp )
  3066. {
  3067. // if vp is the first link on the chain
  3068. if( vp == p->alist )
  3069. p->alist = vp->alink;
  3070. // if vp is the last link on the chain
  3071. if( vp == p->elist )
  3072. p->elist = pp;
  3073. if( pp != NULL )
  3074. pp->alink = vp->alink;
  3075. vp->flags = cmClrFlag(vp->flags,kActiveModFl);
  3076. vp->alink = NULL;
  3077. vp->entry = NULL;
  3078. }
  3079. // If the requested parameter has a value then return it in *valPtr.
  3080. // If it does not then do nothing. This function applies scaling to RHS values.
  3081. cmRC_t _cmScModGetParam( cmScModulator* p, const cmScModParam_t* pp, double* valPtr )
  3082. {
  3083. cmRC_t rc = cmOkRC;
  3084. switch( pp->pid )
  3085. {
  3086. case kInvalidModPId:
  3087. rc = cmCtxRtCondition( &p->obj, cmInvalidArgRC, "An invalid parameter was encountered.");
  3088. goto errLabel;
  3089. break;
  3090. case kLiteralModPId:
  3091. *valPtr = pp->val;
  3092. break;
  3093. case kSymbolModPId:
  3094. {
  3095. cmScModVar_t* vp;
  3096. // get a pointer to the parameter variable
  3097. if((vp = _cmScModSymToVar(p, pp->symId )) == NULL )
  3098. {
  3099. rc = cmCtxRtCondition( &p->obj, cmInvalidArgRC, "Variable '%s' not found.",cmSymTblLabel(p->stH,pp->symId));
  3100. goto errLabel;
  3101. }
  3102. // if this is not a 'calculated' paramter then scale it here.
  3103. if( cmIsFlag(vp->flags,kCalcModFl ) && vp->min!=DBL_MAX && vp->max!=DBL_MAX )
  3104. *valPtr = (vp->value - vp->min)/(vp->max-vp->min);
  3105. else
  3106. *valPtr = vp->value;
  3107. }
  3108. break;
  3109. default:
  3110. { assert(0); }
  3111. }
  3112. errLabel:
  3113. return rc;
  3114. }
  3115. // Type specific variable activation -
  3116. cmRC_t _cmScModActivate(cmScModulator* p, cmScModEntry_t* ep )
  3117. {
  3118. cmRC_t rc = cmOkRC;
  3119. cmScModVar_t* vp = ep->varPtr;
  3120. // optionally update the min/max/rate values in the target var
  3121. if( ep->min.pid != kInvalidModPId )
  3122. if((rc = _cmScModGetParam(p,&ep->min,&vp->min)) != cmOkRC )
  3123. goto errLabel;
  3124. if( ep->max.pid != kInvalidModPId )
  3125. if((rc = _cmScModGetParam(p,&ep->max,&vp->max)) != cmOkRC )
  3126. goto errLabel;
  3127. if( ep->rate.pid != kInvalidModPId )
  3128. if((rc = _cmScModGetParam(p,&ep->rate,&vp->rate)) != cmOkRC )
  3129. goto errLabel;
  3130. switch( ep->typeId )
  3131. {
  3132. case kSetModTId:
  3133. break;
  3134. case kLineModTId:
  3135. vp->v0 = vp->value;
  3136. vp->phase = 0;
  3137. break;
  3138. case kSetLineModTId:
  3139. _cmScModGetParam(p,&ep->beg,&vp->value); // starting value
  3140. vp->v0 = vp->value; // set initial value
  3141. vp->phase = 0; // reset phase
  3142. break;
  3143. case kPostModTId:
  3144. p->postFl = vp->value;
  3145. break;
  3146. default:
  3147. { assert(0); }
  3148. }
  3149. errLabel:
  3150. return rc;
  3151. }
  3152. // Callback the application with a new variable value.
  3153. cmRC_t _cmScModExecSendValue( cmScModulator* p, cmScModVar_t* vp )
  3154. {
  3155. cmRC_t rc = cmOkRC;
  3156. bool sendFl = true;
  3157. double v = vp->value;
  3158. // scale the output value - this is equiv to scaling the LHS
  3159. if( cmIsFlag(vp->flags,kCalcModFl) && vp->min!=DBL_MAX && vp->max!=DBL_MAX )
  3160. v = vp->min + v * (vp->max - vp->min);
  3161. // if an output rate throttle is in effect ....
  3162. if( vp->rate!=DBL_MAX && vp->phase!=0 )
  3163. sendFl = remainder(vp->phase*p->samplesPerCycle, p->srate*vp->rate/1000 ) < p->samplesPerCycle;
  3164. if(sendFl)
  3165. p->cbFunc(p->cbArg,vp->varSymId,v,p->postFl);
  3166. return rc;
  3167. }
  3168. // Return true if vp should be deactivated otherwise return false.
  3169. bool _cmScModExec( cmScModulator* p, cmScModVar_t* vp )
  3170. {
  3171. cmRC_t rc = cmOkRC;
  3172. bool fl = false;
  3173. bool sendFl = true;
  3174. switch( vp->entry->typeId )
  3175. {
  3176. case kSetModTId:
  3177. {
  3178. if((rc = _cmScModGetParam(p,&vp->entry->beg,&vp->value)) != cmOkRC )
  3179. goto errLabel;
  3180. vp->phase = 0; // force the value to be sent
  3181. fl = true;
  3182. }
  3183. break;
  3184. case kSetLineModTId:
  3185. case kLineModTId:
  3186. {
  3187. double v1=0, td=0;
  3188. // get the target value
  3189. if((rc = _cmScModGetParam(p,&vp->entry->end,&v1)) != cmOkRC)
  3190. goto errLabel;
  3191. // get the time duration
  3192. if((rc = _cmScModGetParam(p,&vp->entry->dur,&td)) != cmOkRC)
  3193. goto errLabel;
  3194. double v = vp->v0 + (v1-vp->v0) * (vp->phase * p->samplesPerCycle) / (p->srate * td);
  3195. if((fl = (vp->value <= v1 && v >= v1) || (vp->value >= v1 && v <= v1 )) == true )
  3196. v = v1;
  3197. vp->value = v;
  3198. }
  3199. break;
  3200. case kPostModTId:
  3201. sendFl = false;
  3202. break;
  3203. default:
  3204. { assert(0); }
  3205. }
  3206. // notify the application that a new variable value has been generated
  3207. if(sendFl)
  3208. {
  3209. rc = _cmScModExecSendValue(p,vp);
  3210. // increment the phase - after send because send notices when phase is zero
  3211. vp->phase += 1;
  3212. }
  3213. errLabel:
  3214. if( rc != cmOkRC )
  3215. fl = true;
  3216. return fl;
  3217. }
  3218. cmRC_t cmScModulatorExec( cmScModulator* p, unsigned scLocIdx )
  3219. {
  3220. cmRC_t trc;
  3221. cmRC_t rc = cmOkRC;
  3222. // trigger entries that have expired since the last call to this function
  3223. for(; p->nei<p->en && (p->earray[p->nei].scLocIdx==-1 || p->earray[p->nei].scLocIdx<=scLocIdx); ++p->nei)
  3224. {
  3225. cmScModEntry_t* ep = p->earray + p->nei;
  3226. // if the variable assoc'd with this entry is not on the active list ...
  3227. if( cmIsFlag(ep->varPtr->flags,kActiveModFl) == false )
  3228. {
  3229. // ... then append it to the end of the active list ...
  3230. ep->varPtr->flags |= kActiveModFl;
  3231. if( p->elist == NULL )
  3232. p->elist = ep->varPtr;
  3233. else
  3234. {
  3235. p->elist->alink = ep->varPtr;
  3236. p->elist = ep->varPtr;
  3237. }
  3238. p->elist->alink = NULL;
  3239. if( p->alist == NULL )
  3240. p->alist = ep->varPtr;
  3241. }
  3242. // do type specific activation
  3243. if((trc = _cmScModActivate(p,ep)) != cmOkRC )
  3244. rc = trc;
  3245. ep->varPtr->entry = ep;
  3246. }
  3247. // Update the active variables
  3248. cmScModVar_t* pp = NULL;
  3249. cmScModVar_t* vp = p->alist;
  3250. for(; vp!=NULL; vp=vp->alink)
  3251. {
  3252. if( _cmScModExec(p,vp) )
  3253. _cmScModUnlinkActive(p,vp,pp);
  3254. else
  3255. pp = vp;
  3256. }
  3257. return rc;
  3258. }
  3259. void _cmScModDumpParam( cmScModulator* p, const cmChar_t* label, cmScModParam_t* pp )
  3260. {
  3261. printf("%s: ",label);
  3262. switch( pp->pid )
  3263. {
  3264. case kInvalidModPId:
  3265. printf("<invalid>");
  3266. break;
  3267. case kLiteralModPId:
  3268. if( pp->val == DBL_MAX )
  3269. printf("<max> ");
  3270. else
  3271. printf("%f ",pp->val);
  3272. break;
  3273. case kSymbolModPId:
  3274. printf("%s ",cmSymTblLabel(p->stH,pp->symId));
  3275. break;
  3276. default:
  3277. { assert(0); }
  3278. }
  3279. }
  3280. void _cmScModDumpVal( cmChar_t* label, double val )
  3281. {
  3282. printf("%s:",label);
  3283. if( val == DBL_MAX )
  3284. printf("<max> " );
  3285. else
  3286. printf("%f ",val);
  3287. }
  3288. void _cmScModDumpVar( cmScModulator* p, const cmScModVar_t* vp )
  3289. {
  3290. printf("%7s %3i fl:0x%x entry:%p alink:%p ",cmSymTblLabel(p->stH,vp->varSymId),vp->outVarId,vp->flags,vp->entry,vp->alink);
  3291. _cmScModDumpVal("val",vp->value);
  3292. _cmScModDumpVal("min",vp->min);
  3293. _cmScModDumpVal("max",vp->max);
  3294. _cmScModDumpVal("rate",vp->rate);
  3295. _cmScModDumpVal("v0",vp->v0);
  3296. }
  3297. cmRC_t cmScModulatorDump( cmScModulator* p )
  3298. {
  3299. cmRC_t rc = cmOkRC;
  3300. printf("MOD:\n");
  3301. printf("nei:%i alist:%p outVarCnt:%i\n",p->nei,p->alist,p->outVarCnt);
  3302. printf("ENTRIES:\n");
  3303. unsigned i;
  3304. for(i=0; i<p->en; ++i)
  3305. {
  3306. cmScModEntry_t* ep = p->earray + i;
  3307. printf("%3i %4i %2i %7s ", i, ep->scLocIdx, ep->typeId, cmSymTblLabel(p->stH,ep->varPtr->varSymId));
  3308. _cmScModDumpParam(p," beg", &ep->beg);
  3309. _cmScModDumpParam(p," end", &ep->end);
  3310. _cmScModDumpParam(p," min", &ep->min);
  3311. _cmScModDumpParam(p," max", &ep->max);
  3312. _cmScModDumpParam(p," rate",&ep->rate);
  3313. printf("\n");
  3314. }
  3315. printf("VARIABLES\n");
  3316. cmScModVar_t* vp = p->vlist;
  3317. for(; vp!=NULL; vp=vp->vlink)
  3318. {
  3319. _cmScModDumpVar(p,vp);
  3320. printf("\n");
  3321. }
  3322. return rc;
  3323. }
  3324. //=======================================================================================================================
  3325. cmRecdPlay* cmRecdPlayAlloc( cmCtx* c, cmRecdPlay* p, double srate, unsigned fragCnt, unsigned chCnt, double initFragSecs, double maxLaSecs, double curLaSecs )
  3326. {
  3327. cmRecdPlay* op = cmObjAlloc(cmRecdPlay,c,p);
  3328. if( cmRecdPlayInit(op,srate,fragCnt,chCnt,initFragSecs,maxLaSecs,curLaSecs) != cmOkRC )
  3329. cmRecdPlayFree(&op);
  3330. return op;
  3331. }
  3332. cmRC_t cmRecdPlayFree( cmRecdPlay** pp )
  3333. {
  3334. cmRC_t rc = cmOkRC;
  3335. if( pp==NULL || *pp==NULL )
  3336. return rc;
  3337. cmRecdPlay* p = *pp;
  3338. if((rc = cmRecdPlayFinal(p)) != cmOkRC )
  3339. return rc;
  3340. cmObjFree(pp);
  3341. return rc;
  3342. }
  3343. cmRC_t cmRecdPlayInit( cmRecdPlay* p, double srate, unsigned fragCnt, unsigned chCnt, double initFragSecs, double maxLaSecs, double curLaSecs )
  3344. {
  3345. cmRC_t rc;
  3346. unsigned i;
  3347. if( curLaSecs > maxLaSecs )
  3348. return cmCtxRtCondition( &p->obj, cmInvalidArgRC, "The initial look-ahead time %f is greater than the maximum look-ahead time %f.",curLaSecs,maxLaSecs);
  3349. if((rc = cmRecdPlayFinal(p)) != cmOkRC )
  3350. return rc;
  3351. if( chCnt == 0 )
  3352. return cmOkRC;
  3353. p->frags = cmMemAllocZ(cmRecdPlayFrag,fragCnt);
  3354. p->fragCnt = fragCnt;
  3355. p->srate = srate;
  3356. p->chCnt = chCnt;
  3357. p->initFragSecs = initFragSecs;
  3358. p->maxLaSmpCnt = floor(maxLaSecs*srate);
  3359. p->curLaSmpCnt = floor(curLaSecs*srate);
  3360. p->laChs = cmMemAllocZ(cmSample_t*,chCnt);
  3361. p->laSmpIdx = 0;
  3362. for(i=0; i<chCnt; ++i)
  3363. p->laChs[i] = cmMemAllocZ(cmSample_t,p->maxLaSmpCnt);
  3364. return rc;
  3365. }
  3366. cmRC_t cmRecdPlayFinal( cmRecdPlay* p )
  3367. {
  3368. unsigned i,j;
  3369. // free the fragments
  3370. for(i=0; i<p->fragCnt; ++i)
  3371. {
  3372. for(j=0; j<p->chCnt; ++j)
  3373. cmMemFree(p->frags[i].chArray[j]);
  3374. cmMemFree(p->frags[i].chArray);
  3375. }
  3376. // free the look-ahead buffers
  3377. for(i=0; i<p->chCnt; ++i)
  3378. cmMemFree(p->laChs[i]);
  3379. cmMemPtrFree(&p->laChs);
  3380. cmMemPtrFree(&p->frags);
  3381. p->fragCnt = 0;
  3382. p->chCnt = 0;
  3383. p->rlist = NULL;
  3384. p->plist = NULL;
  3385. return cmOkRC;
  3386. }
  3387. cmRC_t cmRecdPlayRegisterFrag( cmRecdPlay* p, unsigned fragIdx, unsigned labelSymId )
  3388. {
  3389. assert( fragIdx < p->fragCnt );
  3390. unsigned i;
  3391. p->frags[ fragIdx ].labelSymId = labelSymId;
  3392. p->frags[ fragIdx ].chArray = cmMemResizeZ(cmSample_t*,p->frags[fragIdx].chArray,p->chCnt);
  3393. for(i=0; i<p->chCnt; ++i)
  3394. {
  3395. p->frags[ fragIdx ].allocCnt = floor(p->initFragSecs * p->srate);
  3396. p->frags[ fragIdx ].chArray[i] = cmMemResizeZ(cmSample_t,p->frags[ fragIdx ].chArray[i],p->frags[fragIdx].allocCnt);
  3397. }
  3398. return cmOkRC;
  3399. }
  3400. cmRC_t cmRecdPlaySetLaSecs( cmRecdPlay* p, double curLaSecs )
  3401. {
  3402. p->curLaSmpCnt = floor(curLaSecs*p->srate);
  3403. return cmOkRC;
  3404. }
  3405. cmRC_t cmRecdPlayRewind( cmRecdPlay* p )
  3406. {
  3407. unsigned i;
  3408. // zero the look-ahead buffers
  3409. p->laSmpIdx = 0;
  3410. for(i=0; i<p->chCnt; ++i)
  3411. cmVOS_Zero(p->laChs[i],p->maxLaSmpCnt);
  3412. // remove all the active players
  3413. while( p->plist != NULL )
  3414. cmRecdPlayEndPlay(p,p->plist->labelSymId);
  3415. // remove all the active recorders
  3416. while( p->rlist != NULL )
  3417. cmRecdPlayEndRecord(p,p->rlist->labelSymId);
  3418. // rewind all the fragments play posn.
  3419. for(i=0; i<p->fragCnt; ++i)
  3420. p->frags[i].playIdx = 0;
  3421. return cmOkRC;
  3422. }
  3423. cmRC_t cmRecdPlayBeginRecord( cmRecdPlay* p, unsigned labelSymId )
  3424. {
  3425. unsigned i;
  3426. for(i=0; i<p->fragCnt; ++i)
  3427. if( p->frags[i].labelSymId == labelSymId )
  3428. {
  3429. // if the frag is not already on the recd list
  3430. if( p->frags[i].rlink == NULL )
  3431. {
  3432. p->frags[i].recdIdx = 0;
  3433. p->frags[i].playIdx = 0;
  3434. p->frags[i].rlink = p->rlist;
  3435. p->rlist = p->frags + i;
  3436. // handle LA buf longer than frag buf.
  3437. int cpyCnt = cmMin(p->curLaSmpCnt,p->frags[i].allocCnt);
  3438. // go backwards in LA buf from newest sample to find init src offset
  3439. int srcOffs = p->laSmpIdx - cpyCnt;
  3440. // if the src is before the first sample in the LA buf then wrap to end of buf
  3441. if( srcOffs < 0 )
  3442. srcOffs += p->maxLaSmpCnt;
  3443. assert( 0 <= srcOffs && srcOffs < p->maxLaSmpCnt );
  3444. // cnt of samples to copy from LA buf (limited by end of LA buf)
  3445. int n0 = cmMin(cpyCnt,p->maxLaSmpCnt - srcOffs);
  3446. // if necessary wrap to begin of LA buf for remaining samples
  3447. int n1 = cpyCnt>n0 ? n1 = cpyCnt-n0 : 0;
  3448. int j;
  3449. assert(n0+n1 == cpyCnt );
  3450. for(j=0; j<p->chCnt; ++j)
  3451. cmVOS_Copy(p->frags[i].chArray[j],n0,p->laChs[j]+srcOffs);
  3452. if( n1 > 0 )
  3453. {
  3454. for(j=0; j<p->chCnt; ++j)
  3455. cmVOS_Copy(p->frags[i].chArray[j]+n0,n1,p->laChs[j]);
  3456. }
  3457. p->frags[i].recdIdx = cpyCnt;
  3458. p->frags[i].playIdx = 0;
  3459. }
  3460. return cmOkRC;
  3461. }
  3462. return cmCtxRtCondition( &p->obj, cmInvalidArgRC, "The fragment label symbol id '%i' not found for 'begin record'.",labelSymId);
  3463. }
  3464. cmRC_t cmRecdPlayEndRecord( cmRecdPlay* p, unsigned labelSymId )
  3465. {
  3466. cmRecdPlayFrag* fp = p->rlist;
  3467. cmRecdPlayFrag* pp = NULL;
  3468. for(; fp != NULL; fp=fp->rlink )
  3469. {
  3470. if( fp->labelSymId == labelSymId )
  3471. {
  3472. if( pp == NULL )
  3473. p->rlist = fp->rlink;
  3474. else
  3475. pp->rlink = fp->rlink;
  3476. fp->rlink = NULL;
  3477. return cmOkRC;
  3478. }
  3479. pp = fp;
  3480. }
  3481. return cmCtxRtCondition( &p->obj, cmInvalidArgRC, "The fragment label symbol id '%i' not found for 'end record'.",labelSymId);
  3482. }
  3483. cmRC_t cmRecdPlayInsertRecord(cmRecdPlay* p, unsigned labelSymId, const cmChar_t* wavFn )
  3484. {
  3485. cmRC_t rc = cmOkRC;
  3486. unsigned i;
  3487. for(i=0; i<p->fragCnt; ++i)
  3488. if( p->frags[i].labelSymId == labelSymId )
  3489. {
  3490. cmAudioFileH_t afH = cmNullAudioFileH;
  3491. cmAudioFileInfo_t afInfo;
  3492. cmRC_t afRC = kOkAfRC;
  3493. // open the audio file
  3494. if( cmAudioFileIsValid( afH = cmAudioFileNewOpen(wavFn, &afInfo, &afRC, p->obj.err.rpt )) == false )
  3495. return cmCtxRtCondition( &p->obj, cmInvalidArgRC, "The audio file '%s' could not be opened'.",cmStringNullGuard(wavFn));
  3496. // ignore blank
  3497. if( afInfo.frameCnt == 0 )
  3498. return cmOkRC;
  3499. // allocate buffer space
  3500. unsigned j;
  3501. for(j=0; j<p->chCnt; ++j)
  3502. p->frags[i].chArray[j] = cmMemResize(cmSample_t,p->frags[i].chArray[j],afInfo.frameCnt);
  3503. p->frags[i].allocCnt = afInfo.frameCnt;
  3504. // read samples into the buffer space
  3505. unsigned chIdx = 0;
  3506. unsigned chCnt = cmMin(p->chCnt,afInfo.chCnt);
  3507. unsigned actFrmCnt = 0;
  3508. if( cmAudioFileReadSample(afH,afInfo.frameCnt,chIdx,chCnt,p->frags[i].chArray, &actFrmCnt) != kOkAfRC )
  3509. return cmCtxRtCondition(&p->obj, cmSubSysFailRC, "Read failed on the audio file '%s'.",cmStringNullGuard(wavFn));
  3510. p->frags[i].recdIdx = actFrmCnt;
  3511. return rc;
  3512. }
  3513. return cmCtxRtCondition( &p->obj, cmInvalidArgRC, "The fragment label symbol id '%i' not found for 'begin record'.",labelSymId);
  3514. }
  3515. cmRC_t cmRecdPlayBeginPlay( cmRecdPlay* p, unsigned labelSymId )
  3516. {
  3517. unsigned i;
  3518. for(i=0; i<p->fragCnt; ++i)
  3519. if( p->frags[i].labelSymId == labelSymId )
  3520. {
  3521. // if the frag is not already on the play list
  3522. if( p->frags[i].plink == NULL )
  3523. {
  3524. p->frags[i].playIdx = 0;
  3525. p->frags[i].fadeSmpIdx = 0;
  3526. p->frags[i].fadeDbPerSec = 0.0;
  3527. p->frags[i].plink = p->plist;
  3528. p->plist = p->frags + i;
  3529. }
  3530. return cmOkRC;
  3531. }
  3532. return cmCtxRtCondition( &p->obj, cmInvalidArgRC, "The fragment label symbol id '%i' not found for 'begin play'.",labelSymId);
  3533. }
  3534. cmRC_t cmRecdPlayEndPlay( cmRecdPlay* p, unsigned labelSymId )
  3535. {
  3536. cmRecdPlayFrag* fp = p->plist;
  3537. cmRecdPlayFrag* pp = NULL;
  3538. for(; fp != NULL; fp=fp->plink )
  3539. {
  3540. if( fp->labelSymId == labelSymId )
  3541. {
  3542. if( pp == NULL )
  3543. p->plist = fp->plink;
  3544. else
  3545. pp->plink = fp->plink;
  3546. fp->plink = NULL;
  3547. return cmOkRC;
  3548. }
  3549. pp = fp;
  3550. }
  3551. return cmCtxRtCondition( &p->obj, cmInvalidArgRC, "The fragment label symbol id '%i' not found for 'end play'.",labelSymId);
  3552. }
  3553. cmRC_t cmRecdPlayBeginFade( cmRecdPlay* p, unsigned labelSymId, double fadeDbPerSec )
  3554. {
  3555. cmRecdPlayFrag* fp = p->plist;
  3556. for(; fp != NULL; fp=fp->plink )
  3557. if( fp->labelSymId == labelSymId )
  3558. {
  3559. fp->fadeDbPerSec = -fabs(fadeDbPerSec);
  3560. return cmOkRC;
  3561. }
  3562. return cmCtxRtCondition( &p->obj, cmInvalidArgRC, "The fragment label symbol id '%i' not found for 'fade begin'.",labelSymId);
  3563. }
  3564. cmRC_t cmRecdPlayExec( cmRecdPlay* p, const cmSample_t** iChs, cmSample_t** oChs, unsigned chCnt, unsigned smpCnt )
  3565. {
  3566. unsigned i;
  3567. chCnt = cmMin(chCnt, p->chCnt);
  3568. //-------------------------------------------------------------------
  3569. // copy incoming audio into the look-ahead buffers
  3570. //
  3571. // if the number of incoming samples is longer than the look-head buffer
  3572. // then copy exactly maxLaSmpCnt samples from the end of the incoming sample
  3573. // buffer to the look-ahead buffer.
  3574. unsigned srcOffs = 0;
  3575. unsigned srcSmpCnt = smpCnt;
  3576. if( srcSmpCnt > p->maxLaSmpCnt )
  3577. {
  3578. // advance incoming sample buffer so that there are maxLaSmpCnt samples remaining
  3579. srcOffs = srcSmpCnt-p->maxLaSmpCnt;
  3580. srcSmpCnt = p->maxLaSmpCnt; // decrease the total samples to copy
  3581. }
  3582. // count of samples from cur posn to end of the LA buffer.
  3583. unsigned n0 = cmMin(srcSmpCnt, p->maxLaSmpCnt - p->laSmpIdx );
  3584. // count of samples past the end of the LA buffer to be wrapped into begin of buffer
  3585. unsigned n1 = srcSmpCnt>n0 ? srcSmpCnt-n0 : 0;
  3586. assert(n0+n1 == srcSmpCnt);
  3587. // copy first block to end of LA buffer
  3588. for(i=0; i<chCnt; ++i)
  3589. if( iChs[i] == NULL )
  3590. cmVOS_Zero(p->laChs[i]+p->laSmpIdx,n0);
  3591. else
  3592. cmVOS_Copy(p->laChs[i]+p->laSmpIdx,n0,iChs[i] + srcOffs);
  3593. p->laSmpIdx += n0;
  3594. if( n1!=0)
  3595. {
  3596. // copy second block to begin of LA buffer
  3597. for(i=0; i<chCnt; ++i)
  3598. if( iChs[i] == NULL )
  3599. cmVOS_Zero(p->laChs[i],n1);
  3600. else
  3601. cmVOS_Copy(p->laChs[i],n1,iChs[i] + srcOffs + n0);
  3602. p->laSmpIdx = n1;
  3603. }
  3604. //-------------------------------------------------------------------
  3605. // copy incoming audio into the active record buffers
  3606. //
  3607. cmRecdPlayFrag* fp = p->rlist;
  3608. for(; fp!=NULL; fp=fp->rlink)
  3609. {
  3610. assert( fp->recdIdx <= fp->allocCnt);
  3611. unsigned n = cmMin(fp->allocCnt - fp->recdIdx,smpCnt);
  3612. unsigned i;
  3613. for(i=0; i<p->chCnt; ++i)
  3614. if( iChs[i] == NULL )
  3615. cmVOS_Zero(fp->chArray[i] + fp->recdIdx, n );
  3616. else
  3617. cmVOS_Copy(fp->chArray[i] + fp->recdIdx, n, iChs[i] );
  3618. fp->recdIdx += n;
  3619. }
  3620. //-------------------------------------------------------------------
  3621. // copy outgoing audio out of the active play buffers
  3622. //
  3623. fp = p->plist;
  3624. for(; fp!=NULL; fp=fp->rlink)
  3625. {
  3626. assert( fp->playIdx <= fp->recdIdx);
  3627. double gain = pow(10.0,((fp->fadeSmpIdx / p->srate) * fp->fadeDbPerSec)/20.0);
  3628. unsigned n = cmMin(fp->recdIdx - fp->playIdx,smpCnt);
  3629. unsigned i;
  3630. for(i=0; i<p->chCnt; ++i)
  3631. if( oChs[i] != NULL )
  3632. cmVOS_MultVVS(oChs[i],n,fp->chArray[i] + fp->playIdx,gain);
  3633. fp->playIdx += n;
  3634. // if a fade rate has been set then advance the fade phase
  3635. if(fp->fadeDbPerSec!=0.0)
  3636. fp->fadeSmpIdx += smpCnt;
  3637. }
  3638. return cmOkRC;
  3639. }