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

cmProc4.c 119KB

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