libcm is a C development framework with an emphasis on audio signal processing applications.
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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