libcm is a C development framework with an emphasis on audio signal processing applications.
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

cmProc4.c 104KB

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