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

cmProc4.c 104KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192
  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. 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);
  1033. // if the size of the mtx is not changing then there is nothing to do
  1034. if( rn == p->rn && cn == p->cn )
  1035. return cmOkRC;
  1036. // update the mtx size
  1037. p->rn = rn;
  1038. p->cn = cn;
  1039. // fill in the default values for the first row
  1040. // and column of the DP matrix
  1041. unsigned i,j,k;
  1042. for(i=0; i<rn; ++i)
  1043. for(j=0; j<cn; ++j)
  1044. {
  1045. unsigned v[] = {0,0,0,0};
  1046. if( i == 0 )
  1047. {
  1048. v[kSmMinIdx] = j;
  1049. v[kSmInsIdx] = j;
  1050. }
  1051. else
  1052. if( j == 0 )
  1053. {
  1054. v[kSmMinIdx] = i;
  1055. v[kSmDelIdx] = i;
  1056. }
  1057. // zero the value field
  1058. for(k=0; k<kSmCnt; ++k)
  1059. p->m[ i + (j*rn) ].v[k] = v[k];
  1060. }
  1061. return cmOkRC;
  1062. }
  1063. cmScMatchVal_t* _cmScMatchValPtr( cmScMatch* p, unsigned i, unsigned j, unsigned rn, unsigned cn )
  1064. {
  1065. assert( i < rn && j < cn );
  1066. return p->m + i + (j*rn);
  1067. }
  1068. unsigned _cmScMatchIsMatchIndex( const cmScMatchLoc_t* loc, unsigned pitch )
  1069. {
  1070. unsigned i;
  1071. for(i=0; i<loc->evtCnt; ++i)
  1072. if( loc->evtV[i].pitch == pitch )
  1073. return i;
  1074. return cmInvalidIdx;
  1075. }
  1076. bool _cmScMatchIsMatch( const cmScMatchLoc_t* loc, unsigned pitch )
  1077. { return _cmScMatchIsMatchIndex(loc,pitch) != cmInvalidIdx; }
  1078. bool _cmScMatchIsTrans( cmScMatch* p, const cmScMatchMidi_t* midiV, const cmScMatchVal_t* v1p, unsigned bsi, unsigned i, unsigned j, unsigned rn, unsigned cn )
  1079. {
  1080. bool fl = false;
  1081. cmScMatchVal_t* v0p = _cmScMatchValPtr(p,i,j,rn,cn);
  1082. if( i>=1 && j>=1
  1083. && v1p->v[kSmMinIdx] == v1p->v[kSmSubIdx]
  1084. && cmIsNotFlag(v1p->flags,kSmMatchFl)
  1085. && v0p->v[kSmMinIdx] == v0p->v[kSmSubIdx]
  1086. && cmIsNotFlag(v0p->flags,kSmMatchFl)
  1087. )
  1088. {
  1089. unsigned c00 = midiV[i-1].pitch;
  1090. unsigned c01 = midiV[i ].pitch;
  1091. cmScMatchLoc_t* c10 = p->loc + bsi + j - 1;
  1092. cmScMatchLoc_t* c11 = p->loc + bsi + j;
  1093. fl = _cmScMatchIsMatch(c11,c00) && _cmScMatchIsMatch(c10,c01);
  1094. }
  1095. return fl;
  1096. }
  1097. unsigned _cmScMatchMin( cmScMatch* p, unsigned i, unsigned j, unsigned rn, unsigned cn )
  1098. {
  1099. return _cmScMatchValPtr(p,i,j,rn,cn)->v[kSmMinIdx];
  1100. }
  1101. // Return false if bsi + cn > p->locN
  1102. // pitchV[rn-1]
  1103. bool _cmScMatchCalcMtx( cmScMatch* p, unsigned bsi, const cmScMatchMidi_t* midiV, unsigned rn, unsigned cn )
  1104. {
  1105. // loc[begScanLocIdx:begScanLocIdx+cn-1] must be valid
  1106. if( bsi + cn > p->locN )
  1107. return false;
  1108. unsigned i,j;
  1109. for(j=1; j<cn; ++j)
  1110. for(i=1; i<rn; ++i)
  1111. {
  1112. cmScMatchLoc_t* loc = p->loc + bsi + j - 1;
  1113. unsigned pitch = midiV[i-1].pitch;
  1114. cmScMatchVal_t* vp = _cmScMatchValPtr(p,i,j,rn,cn);
  1115. unsigned idx = _cmScMatchIsMatchIndex(loc,pitch);
  1116. vp->flags = idx==cmInvalidIdx ? 0 : kSmMatchFl;
  1117. vp->scEvtIdx = idx==cmInvalidIdx ? cmInvalidIdx : loc->evtV[idx].scEvtIdx;
  1118. unsigned cost = cmIsFlag(vp->flags,kSmMatchFl) ? 0 : 1;
  1119. vp->v[kSmSubIdx] = _cmScMatchMin(p,i-1,j-1, rn, cn) + cost;
  1120. vp->v[kSmDelIdx] = _cmScMatchMin(p,i-1,j , rn, cn) + 1;
  1121. vp->v[kSmInsIdx] = _cmScMatchMin(p,i, j-1, rn, cn) + 1;
  1122. vp->v[kSmMinIdx] = cmMin( vp->v[kSmSubIdx], cmMin(vp->v[kSmDelIdx],vp->v[kSmInsIdx]));
  1123. vp->flags |= _cmScMatchIsTrans(p,midiV,vp,bsi,i-1,j-1,rn,cn) ? kSmTransFl : 0;
  1124. }
  1125. return true;
  1126. }
  1127. void _cmScMatchPrintMtx( cmScMatch* r, unsigned rn, unsigned cn)
  1128. {
  1129. unsigned i,j,k;
  1130. for(i=0; i<rn; ++i)
  1131. {
  1132. for(j=0; j<cn; ++j)
  1133. {
  1134. printf("(");
  1135. const cmScMatchVal_t* vp = _cmScMatchValPtr(r,i,j,rn,cn);
  1136. for(k=0; k<kSmCnt; ++k)
  1137. {
  1138. printf("%i",vp->v[k]);
  1139. if( k<kSmCnt-1)
  1140. printf(", ");
  1141. else
  1142. printf(" ");
  1143. }
  1144. printf("%c%c)",cmIsFlag(vp->flags,kSmMatchFl)?'m':' ',cmIsFlag(vp->flags,kSmTransFl)?'t':' ');
  1145. }
  1146. printf("\n");
  1147. }
  1148. }
  1149. void _cmScMatchPathPush( cmScMatch* r, unsigned code, unsigned ri, unsigned ci, unsigned flags, unsigned scEvtIdx )
  1150. {
  1151. assert(r->p_avl != NULL );
  1152. cmScMatchPath_t* p = r->p_avl;
  1153. r->p_avl = r->p_avl->next;
  1154. p->code = code;
  1155. p->ri = ri;
  1156. p->ci = ci;
  1157. p->flags = code==kSmSubIdx && cmIsFlag(flags,kSmMatchFl) ? kSmMatchFl : 0;
  1158. p->flags |= cmIsFlag(flags,kSmTransFl) ? kSmTransFl : 0;
  1159. p->scEvtIdx= scEvtIdx;
  1160. p->next = r->p_cur;
  1161. r->p_cur = p;
  1162. }
  1163. void _cmScMatchPathPop( cmScMatch* r )
  1164. {
  1165. assert( r->p_cur != NULL );
  1166. cmScMatchPath_t* tp = r->p_cur->next;
  1167. r->p_cur->next = r->p_avl;
  1168. r->p_avl = r->p_cur;
  1169. r->p_cur = tp;
  1170. }
  1171. double _cmScMatchCalcCandidateCost( cmScMatch* r )
  1172. {
  1173. cmScMatchPath_t* cp = r->p_cur;
  1174. cmScMatchPath_t* bp = r->p_cur;
  1175. cmScMatchPath_t* ep = NULL;
  1176. // skip leading inserts
  1177. for(; cp!=NULL; cp=cp->next)
  1178. if( cp->code != kSmInsIdx )
  1179. {
  1180. bp = cp;
  1181. break;
  1182. }
  1183. // skip to trailing inserts
  1184. for(; cp!=NULL; cp=cp->next)
  1185. if( cp->code!=kSmInsIdx )
  1186. ep = cp;
  1187. // count remaining path length
  1188. assert( ep!=NULL );
  1189. unsigned n=1;
  1190. for(cp=bp; cp!=ep; cp=cp->next)
  1191. ++n;
  1192. double gapCnt = 0;
  1193. double penalty = 0;
  1194. bool pfl = cmIsFlag(bp->flags,kSmMatchFl);
  1195. unsigned i;
  1196. cp = bp;
  1197. for(i=0; i<n; ++i,cp=cp->next)
  1198. {
  1199. // a gap is a transition from a matching subst. to an insert or deletion
  1200. //if( pc != cp->code && cp->code != kSmSubIdx && pc==kSmSubIdx && pfl==true )
  1201. if( pfl==true && cmIsFlag(cp->flags,kSmMatchFl)==false )
  1202. ++gapCnt;
  1203. //
  1204. switch( cp->code )
  1205. {
  1206. case kSmSubIdx:
  1207. penalty += cmIsFlag(cp->flags,kSmMatchFl) ? 0 : 1;
  1208. penalty -= cmIsFlag(cp->flags,kSmTransFl) ? 1 : 0;
  1209. break;
  1210. case kSmDelIdx:
  1211. penalty += 1;
  1212. break;
  1213. case kSmInsIdx:
  1214. penalty += 1;
  1215. break;
  1216. }
  1217. pfl = cmIsFlag(cp->flags,kSmMatchFl);
  1218. }
  1219. double cost = gapCnt/n + penalty;
  1220. //printf("n:%i gaps:%f gap_score:%f penalty:%f score:%f\n",n,gapCnt,gapCnt/n,penalty,score);
  1221. return cost;
  1222. }
  1223. double _cmScMatchEvalCandidate( cmScMatch* r, double min_cost, double cost )
  1224. {
  1225. if( min_cost == DBL_MAX || cost < min_cost)
  1226. {
  1227. // copy the p_cur to p_opt[]
  1228. cmScMatchPath_t* cp = r->p_cur;
  1229. unsigned i;
  1230. for(i=0; cp!=NULL && i<r->pn; cp=cp->next,++i)
  1231. {
  1232. r->p_opt[i].code = cp->code;
  1233. r->p_opt[i].ri = cp->ri;
  1234. r->p_opt[i].ci = cp->ci;
  1235. r->p_opt[i].flags = cp->flags;
  1236. r->p_opt[i].scEvtIdx= cp->scEvtIdx;
  1237. r->p_opt[i].next = cp->next==NULL ? NULL : r->p_opt + i + 1;
  1238. }
  1239. assert( i < r->pn );
  1240. r->p_opt[i].code = 0; // terminate with code=0
  1241. min_cost = cost;
  1242. }
  1243. return min_cost;
  1244. }
  1245. // NOTE: IF THE COST CALCULATION WAS BUILT INTO THE RECURSION THEN
  1246. // THIS FUNCTION COULD BE MADE MORE EFFICIENT BECAUSE PATHS WHICH
  1247. // EXCEEDED THE min_cost COULD BE SHORT CIRCUITED.
  1248. //
  1249. // traverse the solution matrix from the lower-right to
  1250. // the upper-left.
  1251. double _cmScMatchGenPaths( cmScMatch* r, int i, int j, unsigned rn, unsigned cn, double min_cost )
  1252. {
  1253. unsigned m;
  1254. // stop when the upper-right is encountered
  1255. if( i==0 && j==0 )
  1256. return _cmScMatchEvalCandidate(r, min_cost, _cmScMatchCalcCandidateCost(r) );
  1257. cmScMatchVal_t* vp = _cmScMatchValPtr(r,i,j,rn,cn);
  1258. // for each possible dir: up,left,up-left
  1259. for(m=1; m<kSmCnt; ++m)
  1260. if( vp->v[m] == vp->v[kSmMinIdx] )
  1261. {
  1262. // prepend to the current candidate path: r->p_cur
  1263. _cmScMatchPathPush(r,m,i,j,vp->flags,vp->scEvtIdx);
  1264. int ii = i-1;
  1265. int jj = j-1;
  1266. switch(m)
  1267. {
  1268. case kSmSubIdx:
  1269. break;
  1270. case kSmDelIdx:
  1271. jj = j;
  1272. break;
  1273. case kSmInsIdx:
  1274. ii = i;
  1275. break;
  1276. default:
  1277. { assert(0); }
  1278. }
  1279. // recurse!
  1280. min_cost = _cmScMatchGenPaths(r,ii,jj,rn,cn,min_cost);
  1281. // remove the first element from the current path
  1282. _cmScMatchPathPop(r);
  1283. }
  1284. return min_cost;
  1285. }
  1286. double _cmScMatchAlign( cmScMatch* p, unsigned rn, unsigned cn, double min_cost )
  1287. {
  1288. int i = rn-1;
  1289. int j = cn-1;
  1290. unsigned m = _cmScMatchMin(p,i,j,rn,cn);
  1291. if( m==cmMax(rn,cn) )
  1292. printf("Edit distance is at max: %i. No Match.\n",m);
  1293. else
  1294. min_cost = _cmScMatchGenPaths(p,i,j,rn,cn,min_cost);
  1295. return min_cost;
  1296. }
  1297. cmRC_t cmScMatchExec( cmScMatch* p, unsigned locIdx, unsigned locN, const cmScMatchMidi_t* midiV, unsigned midiN, double min_cost )
  1298. {
  1299. cmRC_t rc;
  1300. unsigned rn = midiN + 1;
  1301. unsigned cn = locN + 1;
  1302. // set the DP matrix default values
  1303. if((rc = _cmScMatchInitMtx(p, rn, cn )) != cmOkRC )
  1304. return rc;
  1305. // _cmScMatchCalcMtx() returns false if the score window exceeds the length of the score
  1306. if(!_cmScMatchCalcMtx(p,locIdx, midiV, rn, cn) )
  1307. return cmEofRC;
  1308. //_cmScMatchPrintMtx(p,rn,cn);
  1309. // locate the path through the DP matrix with the lowest edit distance (cost)
  1310. p->opt_cost = _cmScMatchAlign(p, rn, cn, min_cost);
  1311. return rc;
  1312. }
  1313. // Traverse the least cost path and:
  1314. // 1) Return, esi, the score location index of the last MIDI note
  1315. // which has a positive match with the score and assign
  1316. // the internal score index to cp->locIdx.
  1317. //
  1318. // 2) Set cmScAlignPath_t.locIdx - index into p->loc[] associated
  1319. // with each path element that is a 'substitute' or an 'insert'.
  1320. //
  1321. // 3) Set *missCnPtr: the count of trailing non-positive matches.
  1322. //
  1323. // i_opt is index into p->loc[] of p->p_opt.
  1324. unsigned cmScMatchDoSync( cmScMatch* p, unsigned i_opt, cmScMatchMidi_t* midiBuf, unsigned midiN, unsigned* missCntPtr )
  1325. {
  1326. cmScMatchPath_t* cp = p->p_opt;
  1327. unsigned missCnt = 0;
  1328. unsigned esi = cmInvalidIdx;
  1329. unsigned i;
  1330. for(i=0; cp!=NULL; cp=cp->next)
  1331. {
  1332. // there is no MIDI note associated with 'inserts'
  1333. if( cp->code != kSmInsIdx )
  1334. {
  1335. assert( cp->ri > 0 );
  1336. midiBuf[ cp->ri-1 ].locIdx = cmInvalidIdx;
  1337. }
  1338. switch( cp->code )
  1339. {
  1340. case kSmSubIdx:
  1341. midiBuf[ cp->ri-1 ].locIdx = i_opt + i;
  1342. midiBuf[ cp->ri-1 ].scEvtIdx = cp->scEvtIdx;
  1343. if( cmIsFlag(cp->flags,kSmMatchFl) )
  1344. {
  1345. esi = i_opt + i;
  1346. missCnt = 0;
  1347. }
  1348. else
  1349. {
  1350. ++missCnt;
  1351. }
  1352. // fall through
  1353. case kSmInsIdx:
  1354. cp->locIdx = i_opt + i;
  1355. ++i;
  1356. break;
  1357. case kSmDelIdx:
  1358. cp->locIdx = cmInvalidIdx;
  1359. ++missCnt;
  1360. break;
  1361. }
  1362. }
  1363. if( missCntPtr != NULL )
  1364. *missCntPtr = missCnt;
  1365. return esi;
  1366. }
  1367. void _cmScMatchMidiEvtFlags( cmScMatch* p, const cmScMatchLoc_t* lp, unsigned evtIdx, char* s, unsigned sn )
  1368. {
  1369. const cmScoreLoc_t* slp = cmScoreLoc(p->scH,lp->scLocIdx);
  1370. assert( evtIdx < slp->evtCnt );
  1371. const cmScoreEvt_t* ep = slp->evtArray[evtIdx];
  1372. unsigned i = 0;
  1373. s[0] = 0;
  1374. if( cmIsFlag(ep->flags,kEvenScFl) )
  1375. s[i++] = 'e';
  1376. if( cmIsFlag(ep->flags,kTempoScFl) )
  1377. s[i++] = 't';
  1378. if( cmIsFlag(ep->flags,kDynScFl) )
  1379. s[i++] = 'd';
  1380. if( cmIsFlag(ep->flags,kGraceScFl) )
  1381. s[i++] = 'g';
  1382. s[i++] = 0;
  1383. assert( i <= sn );
  1384. }
  1385. void _cmScMatchPrintPath( cmScMatch* p, cmScMatchPath_t* cp, unsigned bsi, const cmScMatchMidi_t* midiV )
  1386. {
  1387. assert( bsi != cmInvalidIdx );
  1388. cmScMatchPath_t* pp = cp;
  1389. int polyN = 0;
  1390. int i;
  1391. printf("loc: ");
  1392. // get the polyphony count for the score window
  1393. for(i=0; pp!=NULL; pp=pp->next)
  1394. {
  1395. cmScMatchLoc_t* lp = p->loc + bsi + pp->ci;
  1396. if( pp->code!=kSmDelIdx )
  1397. {
  1398. if(lp->evtCnt > polyN)
  1399. polyN = lp->evtCnt;
  1400. printf("%4i%4s ",bsi+i," ");
  1401. ++i;
  1402. }
  1403. else
  1404. printf("%4s%4s "," "," ");
  1405. }
  1406. printf("\n");
  1407. // print the score notes
  1408. for(i=polyN; i>0; --i)
  1409. {
  1410. printf("%3i: ",i);
  1411. for(pp=cp; pp!=NULL; pp=pp->next)
  1412. {
  1413. if( pp->code!=kSmDelIdx )
  1414. {
  1415. int locIdx = bsi + pp->ci - 1;
  1416. assert(0 <= locIdx && locIdx <= p->locN);
  1417. cmScMatchLoc_t* lp = p->loc + locIdx;
  1418. if( lp->evtCnt >= i )
  1419. {
  1420. unsigned sn = 6;
  1421. char s[sn];
  1422. _cmScMatchMidiEvtFlags(p,lp,i-1,s,sn );
  1423. printf("%4s%-4s ",cmMidiToSciPitch(lp->evtV[i-1].pitch,NULL,0),s);
  1424. }
  1425. else
  1426. printf("%4s%4s "," "," ");
  1427. }
  1428. else
  1429. printf("%4s%4s ", (pp->code==kSmDelIdx? "-" : " ")," ");
  1430. /*
  1431. int locIdx = bsi + pp->ci - 1;
  1432. assert(0 <= locIdx && locIdx <= p->locN);
  1433. cmScMatchLoc_t* lp = p->loc + locIdx;
  1434. if( pp->code!=kSmDelIdx && lp->evtCnt >= i )
  1435. printf("%4s ",cmMidiToSciPitch(lp->evtV[i-1].pitch,NULL,0));
  1436. else
  1437. printf("%4s ", pp->code==kSmDelIdx? "-" : " ");
  1438. */
  1439. }
  1440. printf("\n");
  1441. }
  1442. printf("mid: ");
  1443. // print the MIDI buffer
  1444. for(pp=cp; pp!=NULL; pp=pp->next)
  1445. {
  1446. if( pp->code!=kSmInsIdx )
  1447. printf("%4s%4s ",cmMidiToSciPitch(midiV[pp->ri-1].pitch,NULL,0)," ");
  1448. else
  1449. printf("%4s%4s ",pp->code==kSmInsIdx?"-":" "," ");
  1450. }
  1451. printf("\nvel: ");
  1452. // print the MIDI velocity
  1453. for(pp=cp; pp!=NULL; pp=pp->next)
  1454. {
  1455. if( pp->code!=kSmInsIdx )
  1456. printf("%4i%4s ",midiV[pp->ri-1].vel," ");
  1457. else
  1458. printf("%4s%4s ",pp->code==kSmInsIdx?"-":" "," ");
  1459. }
  1460. printf("\nmni: ");
  1461. // print the MIDI buffer index (mni)
  1462. for(pp=cp; pp!=NULL; pp=pp->next)
  1463. {
  1464. if( pp->code!=kSmInsIdx )
  1465. printf("%4i%4s ",midiV[pp->ri-1].mni," ");
  1466. else
  1467. printf("%4s%4s ",pp->code==kSmInsIdx?"-":" "," ");
  1468. }
  1469. printf("\n op: ");
  1470. // print the substitute/insert/delete operation
  1471. for(pp=cp; pp!=NULL; pp=pp->next)
  1472. {
  1473. char c = ' ';
  1474. switch( pp->code )
  1475. {
  1476. case kSmSubIdx: c = 's'; break;
  1477. case kSmDelIdx: c = 'd'; break;
  1478. case kSmInsIdx: c = 'i'; break;
  1479. default:
  1480. { assert(0); }
  1481. }
  1482. printf("%4c%4s ",c," ");
  1483. }
  1484. printf("\n ");
  1485. // give substitute attribute (match or transpose)
  1486. for(pp=cp; pp!=NULL; pp=pp->next)
  1487. {
  1488. cmChar_t s[3];
  1489. int k = 0;
  1490. if( cmIsFlag(pp->flags,kSmMatchFl) )
  1491. s[k++] = 'm';
  1492. if( cmIsFlag(pp->flags,kSmTransFl) )
  1493. s[k++] = 't';
  1494. s[k] = 0;
  1495. printf("%4s%4s ",s," ");
  1496. }
  1497. printf("\nscl: ");
  1498. // print the stored location index
  1499. for(pp=cp; pp!=NULL; pp=pp->next)
  1500. {
  1501. if( pp->locIdx == cmInvalidIdx )
  1502. printf("%4s%4s "," "," ");
  1503. else
  1504. printf("%4i%4s ",p->loc[pp->locIdx].scLocIdx," ");
  1505. }
  1506. printf("\nbar: ");
  1507. // print the stored location index
  1508. for(pp=cp; pp!=NULL; pp=pp->next)
  1509. {
  1510. if( pp->locIdx==cmInvalidIdx || pp->scEvtIdx==cmInvalidIdx )
  1511. printf("%4s%4s "," "," ");
  1512. else
  1513. {
  1514. const cmScoreEvt_t* ep = cmScoreEvt(p->scH, pp->scEvtIdx );
  1515. printf("%4i%4s ",ep->barNumb," ");
  1516. }
  1517. }
  1518. printf("\nsec: ");
  1519. // print seconds
  1520. unsigned begSmpIdx = cmInvalidIdx;
  1521. for(pp=cp; pp!=NULL; pp=pp->next)
  1522. {
  1523. if( pp->code!=kSmInsIdx )
  1524. {
  1525. if( begSmpIdx == cmInvalidIdx )
  1526. begSmpIdx = midiV[pp->ri-1].smpIdx;
  1527. printf("%2.2f%4s ", (double)(midiV[pp->ri-1].smpIdx - begSmpIdx)/96000.0," ");
  1528. }
  1529. else
  1530. printf("%4s%4s ",pp->code==kSmInsIdx?"-":" "," ");
  1531. }
  1532. printf("\n\n");
  1533. }
  1534. //=======================================================================================================================
  1535. cmScMatcher* cmScMatcherAlloc( cmCtx* c, cmScMatcher* p, double srate, cmScH_t scH, unsigned scWndN, unsigned midiWndN, cmScMatcherCb_t cbFunc, void* cbArg )
  1536. {
  1537. cmScMatcher* op = cmObjAlloc(cmScMatcher,c,p);
  1538. if( op != NULL )
  1539. op->mp = cmScMatchAlloc(c,NULL,cmScNullHandle,0,0);
  1540. if( srate != 0 )
  1541. {
  1542. if( cmScMatcherInit(op,srate,scH,scWndN,midiWndN,cbFunc,cbArg) != cmOkRC )
  1543. cmScMatcherFree(&op);
  1544. }
  1545. return op;
  1546. }
  1547. cmRC_t cmScMatcherFree( cmScMatcher** pp )
  1548. {
  1549. cmRC_t rc = cmOkRC;
  1550. if( pp==NULL || *pp==NULL )
  1551. return rc;
  1552. cmScMatcher* p = *pp;
  1553. if((rc = cmScMatcherFinal(p)) != cmOkRC )
  1554. return rc;
  1555. cmScMatchFree(&p->mp);
  1556. cmMemFree(p->midiBuf);
  1557. cmMemFree(p->res);
  1558. cmObjFree(pp);
  1559. return rc;
  1560. }
  1561. cmRC_t cmScMatcherInit( cmScMatcher* p, double srate, cmScH_t scH, unsigned scWndN, unsigned midiWndN, cmScMatcherCb_t cbFunc, void* cbArg )
  1562. {
  1563. cmRC_t rc;
  1564. if((rc = cmScMatcherFinal(p)) != cmOkRC )
  1565. return rc;
  1566. if( midiWndN > scWndN )
  1567. return cmCtxRtCondition( &p->obj, cmInvalidArgRC, "The score alignment MIDI event buffer length (%i) must be less than the score window length (%i).",midiWndN,scWndN);
  1568. if(( rc = cmScMatchInit(p->mp,scH,scWndN,midiWndN)) != cmOkRC )
  1569. return rc;
  1570. p->cbFunc = cbFunc;
  1571. p->cbArg = cbArg;
  1572. p->mn = midiWndN;
  1573. p->midiBuf = cmMemResizeZ(cmScMatchMidi_t,p->midiBuf,p->mn);
  1574. p->initHopCnt = 50;
  1575. p->stepCnt = 3;
  1576. p->maxMissCnt = p->stepCnt+1;
  1577. p->rn = 2 * cmScoreEvtCount(scH);
  1578. p->res = cmMemResizeZ(cmScMatcherResult_t,p->res,p->rn);
  1579. p->printFl = false;
  1580. cmScMatcherReset(p,0);
  1581. return rc;
  1582. }
  1583. cmRC_t cmScMatcherFinal( cmScMatcher* p )
  1584. {
  1585. return cmScMatchFinal(p->mp);
  1586. }
  1587. cmRC_t cmScMatcherReset( cmScMatcher* p, unsigned scLocIdx )
  1588. {
  1589. p->mbi = p->mp->mmn;
  1590. p->mni = 0;
  1591. p->begSyncLocIdx = cmInvalidIdx;
  1592. p->s_opt = DBL_MAX;
  1593. p->missCnt = 0;
  1594. p->scanCnt = 0;
  1595. p->ri = 0;
  1596. p->eli = cmInvalidIdx;
  1597. p->ili = 0;
  1598. // convert scLocIdx to an index into p->mp->loc[]
  1599. unsigned i;
  1600. for(i=0; i<p->mp->locN; ++i)
  1601. if( p->mp->loc[i].scLocIdx == scLocIdx )
  1602. p->ili = i;
  1603. return cmOkRC;
  1604. }
  1605. bool cmScMatcherInputMidi( cmScMatcher* p, unsigned smpIdx, unsigned status, cmMidiByte_t d0, cmMidiByte_t d1 )
  1606. {
  1607. if( status != kNoteOnMdId )
  1608. return false;
  1609. unsigned mi = p->mn-1;
  1610. //printf("%3i %5.2f %4s\n",p->mni,(double)smpIdx/p->srate,cmMidiToSciPitch(d0,NULL,0));
  1611. // shift the new MIDI event onto the end of the MIDI buffer
  1612. memmove(p->midiBuf, p->midiBuf+1, sizeof(cmScMatchMidi_t)*mi);
  1613. p->midiBuf[mi].locIdx = cmInvalidIdx;
  1614. p->midiBuf[mi].scEvtIdx = cmInvalidIdx;
  1615. p->midiBuf[mi].mni = p->mni++;
  1616. p->midiBuf[mi].smpIdx = smpIdx;
  1617. p->midiBuf[mi].pitch = d0;
  1618. p->midiBuf[mi].vel = d1;
  1619. if( p->mbi > 0 )
  1620. --p->mbi;
  1621. return true;
  1622. }
  1623. void _cmScMatcherStoreResult( cmScMatcher* p, unsigned locIdx, unsigned scEvtIdx, unsigned flags, const cmScMatchMidi_t* mp )
  1624. {
  1625. // don't store missed score note results
  1626. assert( mp != NULL );
  1627. bool matchFl = cmIsFlag(flags,kSmMatchFl);
  1628. bool tpFl = locIdx!=cmInvalidIdx && matchFl;
  1629. bool fpFl = locIdx==cmInvalidIdx || matchFl==false;
  1630. cmScMatcherResult_t * rp = NULL;
  1631. unsigned i;
  1632. cmScMatcherResult_t r;
  1633. assert( tpFl==false || (tpFl==true && locIdx != cmInvalidIdx ) );
  1634. // it is possible that the same MIDI event is reported more than once
  1635. // (due to step->scan back tracking) - try to find previous result records
  1636. // associated with this MIDI event
  1637. for(i=0; i<p->ri; ++i)
  1638. if( p->res[i].mni == mp->mni )
  1639. {
  1640. // if this is not the first time this note was reported and it is a true positive
  1641. if( tpFl )
  1642. {
  1643. rp = p->res + i;
  1644. break;
  1645. }
  1646. // a match was found but this was not a true-pos so ignore it
  1647. return;
  1648. }
  1649. if( rp == NULL )
  1650. {
  1651. if( p->ri >= p->rn )
  1652. {
  1653. rp = &r;
  1654. memset(rp,0,sizeof(r));
  1655. }
  1656. else
  1657. {
  1658. rp = p->res + p->ri;
  1659. ++p->ri;
  1660. }
  1661. }
  1662. rp->locIdx = locIdx;
  1663. rp->scEvtIdx = scEvtIdx;
  1664. rp->mni = mp->mni;
  1665. rp->smpIdx = mp->smpIdx;
  1666. rp->pitch = mp->pitch;
  1667. rp->vel = mp->vel;
  1668. rp->flags = flags | (tpFl ? kSmTruePosFl : 0) | (fpFl ? kSmFalsePosFl : 0);
  1669. if( p->cbFunc != NULL )
  1670. p->cbFunc(p,p->cbArg,rp);
  1671. }
  1672. void cmScMatcherPrintPath( cmScMatcher* p )
  1673. {
  1674. _cmScMatchPrintPath(p->mp, p->mp->p_opt, p->begSyncLocIdx, p->midiBuf );
  1675. }
  1676. unsigned cmScMatcherScan( cmScMatcher* p, unsigned bli, unsigned hopCnt )
  1677. {
  1678. assert( p->mp != NULL && p->mp->mmn > 0 );
  1679. unsigned i_opt = cmInvalidIdx;
  1680. double s_opt = DBL_MAX;
  1681. cmRC_t rc = cmOkRC;
  1682. unsigned i;
  1683. // initialize the internal values set by this function
  1684. p->missCnt = 0;
  1685. p->eli = cmInvalidIdx;
  1686. p->s_opt = DBL_MAX;
  1687. // if the MIDI buf is not full
  1688. if( p->mbi != 0 )
  1689. return cmInvalidIdx;
  1690. // calc the edit distance from pitchV[] to a sliding score window
  1691. for(i=0; rc==cmOkRC && (hopCnt==cmInvalidCnt || i<hopCnt); ++i)
  1692. {
  1693. rc = cmScMatchExec(p->mp, bli + i, p->mp->msn, p->midiBuf, p->mp->mmn, s_opt );
  1694. switch(rc)
  1695. {
  1696. case cmOkRC: // normal result
  1697. if( p->mp->opt_cost < s_opt )
  1698. {
  1699. s_opt = p->mp->opt_cost;
  1700. i_opt = bli + i;
  1701. }
  1702. break;
  1703. case cmEofRC: // score window encountered the end of the score
  1704. break;
  1705. default: // error state
  1706. return cmInvalidIdx;
  1707. }
  1708. }
  1709. // store the cost assoc'd with i_opt
  1710. p->s_opt = s_opt;
  1711. if( i_opt == cmInvalidIdx )
  1712. return cmInvalidIdx;
  1713. // set the locIdx field in midiBuf[], trailing miss count and
  1714. // return the latest positive-match locIdx
  1715. p->eli = cmScMatchDoSync(p->mp,i_opt,p->midiBuf,p->mp->mmn,&p->missCnt);
  1716. // if no positive matches were found
  1717. if( p->eli == cmInvalidIdx )
  1718. i_opt = cmInvalidIdx;
  1719. else
  1720. {
  1721. cmScMatchPath_t* cp;
  1722. // record result
  1723. for(cp=p->mp->p_opt; cp!=NULL; cp=cp->next)
  1724. if( cp->code != kSmInsIdx )
  1725. _cmScMatcherStoreResult(p, cp->locIdx, cp->scEvtIdx, cp->flags, p->midiBuf + cp->ri - 1);
  1726. }
  1727. return i_opt;
  1728. }
  1729. cmRC_t cmScMatcherStep( cmScMatcher* p )
  1730. {
  1731. int i;
  1732. unsigned pitch = p->midiBuf[ p->mn-1 ].pitch;
  1733. unsigned locIdx = cmInvalidIdx;
  1734. unsigned pidx = cmInvalidIdx;
  1735. // the tracker must be sync'd to step
  1736. if( p->eli == cmInvalidIdx )
  1737. return cmCtxRtCondition( &p->obj, cmInvalidArgRC, "The p->eli value must be valid to perform a step operation.");
  1738. // if the end of the score has been reached
  1739. if( p->eli + 1 >= p->mp->locN )
  1740. return cmEofRC;
  1741. // attempt to match to next location first
  1742. if( (pidx = _cmScMatchIsMatchIndex(p->mp->loc + p->eli + 1, pitch)) != cmInvalidIdx )
  1743. {
  1744. locIdx = p->eli + 1;
  1745. }
  1746. else
  1747. {
  1748. //
  1749. for(i=2; i<p->stepCnt; ++i)
  1750. {
  1751. // go forward
  1752. if( p->eli+i < p->mp->locN && (pidx=_cmScMatchIsMatchIndex(p->mp->loc + p->eli + i, pitch))!=cmInvalidIdx )
  1753. {
  1754. locIdx = p->eli + i;
  1755. break;
  1756. }
  1757. // go backward
  1758. if( p->eli >= (i-1) && (pidx=_cmScMatchIsMatchIndex(p->mp->loc + p->eli - (i-1), pitch))!=cmInvalidIdx )
  1759. {
  1760. locIdx = p->eli - (i-1);
  1761. break;
  1762. }
  1763. }
  1764. }
  1765. unsigned scEvtIdx = locIdx==cmInvalidIdx ? cmInvalidIdx : p->mp->loc[locIdx].evtV[pidx].scEvtIdx;
  1766. p->midiBuf[ p->mn-1 ].locIdx = locIdx;
  1767. p->midiBuf[ p->mn-1 ].scEvtIdx = scEvtIdx;
  1768. if( locIdx == cmInvalidIdx )
  1769. ++p->missCnt;
  1770. else
  1771. {
  1772. p->missCnt = 0;
  1773. p->eli = locIdx;
  1774. }
  1775. // store the result
  1776. _cmScMatcherStoreResult(p, locIdx, scEvtIdx, locIdx!=cmInvalidIdx ? kSmMatchFl : 0, p->midiBuf + p->mn - 1);
  1777. if( p->missCnt >= p->maxMissCnt )
  1778. {
  1779. unsigned begScanLocIdx = p->eli > p->mn ? p->eli - p->mn : 0;
  1780. p->s_opt = DBL_MAX;
  1781. unsigned bli = cmScMatcherScan(p,begScanLocIdx,p->mn*2);
  1782. ++p->scanCnt;
  1783. // if the scan failed find a match
  1784. if( bli == cmInvalidIdx )
  1785. return cmCtxRtCondition( &p->obj, cmSubSysFailRC, "Scan resync. failed.");
  1786. }
  1787. return cmOkRC;
  1788. }
  1789. cmRC_t cmScMatcherExec( cmScMatcher* p, unsigned smpIdx, unsigned status, cmMidiByte_t d0, cmMidiByte_t d1, unsigned* scLocIdxPtr )
  1790. {
  1791. bool fl = p->mbi > 0;
  1792. cmRC_t rc = cmOkRC;
  1793. unsigned org_eli = p->eli;
  1794. if( scLocIdxPtr != NULL )
  1795. *scLocIdxPtr = cmInvalidIdx;
  1796. // update the MIDI buffer with the incoming note
  1797. if( cmScMatcherInputMidi(p,smpIdx,status,d0,d1) == false )
  1798. return rc;
  1799. // if the MIDI buffer transitioned to full then perform an initial scan sync.
  1800. if( fl && p->mbi == 0 )
  1801. {
  1802. if( (p->begSyncLocIdx = cmScMatcherScan(p,p->ili,p->initHopCnt)) == cmInvalidIdx )
  1803. rc = cmInvalidArgRC; // signal init. scan sync. fail
  1804. else
  1805. {
  1806. //cmScMatcherPrintPath(p);
  1807. }
  1808. }
  1809. else
  1810. {
  1811. // if the MIDI buffer is full then perform a step sync.
  1812. if( !fl && p->mbi == 0 )
  1813. rc = cmScMatcherStep(p);
  1814. }
  1815. // if we lost sync
  1816. if( p->eli == cmInvalidIdx )
  1817. {
  1818. // IF WE LOST SYNC THEN WE BETTER DO SOMETHING - LIKE INCREASE THE SCAN HOPS
  1819. // ON THE NEXT EVENT.
  1820. p->eli = org_eli;
  1821. }
  1822. else
  1823. {
  1824. if( scLocIdxPtr!=NULL && p->eli != org_eli )
  1825. {
  1826. //printf("LOC:%i bar:%i\n",p->eli,p->mp->loc[p->eli].barNumb);
  1827. *scLocIdxPtr = p->mp->loc[p->eli].scLocIdx;
  1828. }
  1829. }
  1830. return rc;
  1831. }
  1832. double cmScMatcherFMeas( cmScMatcher* p )
  1833. {
  1834. unsigned bli = p->mp->locN;
  1835. unsigned eli = 0;
  1836. unsigned scNoteCnt = 0; // total count of score notes
  1837. unsigned matchCnt = 0; // count of matched notes (true positives)
  1838. unsigned wrongCnt = 0; // count of incorrect notes (false positives)
  1839. unsigned missCnt = 0; // count of missed score notes (false negatives)
  1840. unsigned i;
  1841. for(i=0; i<p->ri; ++i)
  1842. if( p->res[i].locIdx != cmInvalidIdx )
  1843. {
  1844. bli = cmMin(bli,p->res[i].locIdx);
  1845. eli = cmMax(eli,p->res[i].locIdx);
  1846. if( cmIsFlag(p->res[i].flags,kSmTruePosFl) )
  1847. ++matchCnt;
  1848. if( cmIsFlag(p->res[i].flags,kSmFalsePosFl) )
  1849. ++wrongCnt;
  1850. }
  1851. scNoteCnt = eli - bli + 1;
  1852. missCnt = scNoteCnt - matchCnt;
  1853. double prec = (double)2.0 * matchCnt / (matchCnt + wrongCnt);
  1854. double rcal = (double)2.0 * matchCnt / (matchCnt + missCnt);
  1855. double fmeas = prec * rcal / (prec + rcal);
  1856. //printf("total:%i match:%i wrong:%i miss:%i\n",scNoteCnt,matchCnt,wrongCnt,missCnt);
  1857. return fmeas;
  1858. }
  1859. typedef struct cmScMatcherPrint_str
  1860. {
  1861. unsigned flags;
  1862. unsigned scLocIdx;
  1863. unsigned mni;
  1864. unsigned pitch;
  1865. unsigned vel;
  1866. } cmScMatcherPrint_t;
  1867. void _cmScMatcherInsertPrint(cmScMatcherPrint_t* a, unsigned i, unsigned* anp, unsigned aan, const cmScMatcherResult_t* rp, unsigned scLocIdx )
  1868. {
  1869. assert( *anp + 1 <= aan );
  1870. memmove(a + i + 1, a + i, (*anp-i)*sizeof(cmScMatcherPrint_t));
  1871. memset( a + i, 0, sizeof(cmScMatcherPrint_t));
  1872. *anp += 1;
  1873. a[i].flags = rp->flags;
  1874. a[i].scLocIdx = scLocIdx;
  1875. a[i].mni = rp->mni;
  1876. a[i].pitch = rp->pitch;
  1877. a[i].vel = rp->vel;
  1878. }
  1879. void cmScMatcherPrint( cmScMatcher* p )
  1880. {
  1881. unsigned bsli = cmScoreEvtCount(p->mp->scH);
  1882. unsigned esli = 0;
  1883. unsigned i,j,k;
  1884. // get first/last scLocIdx from res[]
  1885. for(i=0; i<p->ri; ++i)
  1886. if( p->res[i].locIdx != cmInvalidIdx )
  1887. {
  1888. bsli = cmMin(bsli,p->mp->loc[p->res[i].locIdx].scLocIdx);
  1889. esli = cmMax(esli,p->mp->loc[p->res[i].locIdx].scLocIdx);
  1890. }
  1891. unsigned an = 0;
  1892. unsigned aan = p->ri;
  1893. // calc the count of score events between bsli and esli.
  1894. for(i=bsli; i<=esli; ++i)
  1895. {
  1896. cmScoreLoc_t* lp = cmScoreLoc(p->mp->scH, i);
  1897. assert(lp != NULL);
  1898. aan += lp->evtCnt;
  1899. }
  1900. // allocate an array off 'aan' print records
  1901. cmScMatcherPrint_t* a = cmMemAllocZ(cmScMatcherPrint_t,aan);
  1902. // fill a[] note and bar events from cmScoreLoc()
  1903. for(i=bsli; i<=esli; ++i)
  1904. {
  1905. unsigned scLocIdx = i;
  1906. cmScoreLoc_t* lp = cmScoreLoc(p->mp->scH, scLocIdx );
  1907. for(j=0; j<lp->evtCnt; ++j)
  1908. {
  1909. assert( an < aan );
  1910. cmScoreEvt_t* ep = lp->evtArray[j];
  1911. cmScMatcherPrint_t* pp = a + an;
  1912. an += 1;
  1913. switch( ep->type )
  1914. {
  1915. case kBarEvtScId:
  1916. pp->flags = kSmBarFl;
  1917. break;
  1918. case kNonEvtScId:
  1919. pp->flags = kSmNoteFl;
  1920. break;
  1921. }
  1922. pp->scLocIdx = scLocIdx;
  1923. pp->mni = cmInvalidIdx;
  1924. pp->pitch = ep->pitch;
  1925. pp->vel = kInvalidMidiVelocity;
  1926. }
  1927. }
  1928. // for each result record
  1929. for(i=0; i<p->ri; ++i)
  1930. {
  1931. cmScMatcherResult_t* rp = p->res + i;
  1932. // if this result recd matched a score event
  1933. if( cmIsFlag(rp->flags,kSmTruePosFl) )
  1934. {
  1935. // locate the matching score event
  1936. for(k=0; k<an; ++k)
  1937. if( a[k].scLocIdx==p->mp->loc[rp->locIdx].scLocIdx && a[k].pitch==rp->pitch )
  1938. {
  1939. a[k].mni = rp->mni;
  1940. a[k].vel = rp->vel;
  1941. a[k].flags |= kSmMatchFl;
  1942. break;
  1943. }
  1944. }
  1945. // if this result did not match a score event
  1946. if( cmIsFlag(rp->flags,kSmFalsePosFl) )
  1947. {
  1948. unsigned d_min;
  1949. cmScMatcherPrint_t* dp = NULL;
  1950. unsigned scLocIdx = cmInvalidIdx;
  1951. // if this result does not have a valid locIdx
  1952. // (e.g. errant MIDI notes: scan:'delete' note or a step:mis-match note)
  1953. if( rp->locIdx == cmInvalidIdx )
  1954. {
  1955. // find the print recd with the closet 'mni'
  1956. for(k=0; k<an; ++k)
  1957. if( a[k].mni != cmInvalidIdx )
  1958. {
  1959. unsigned d;
  1960. if( a[k].mni > rp->mni )
  1961. d = a[k].mni - rp->mni;
  1962. else
  1963. d = rp->mni - a[k].mni;
  1964. if( dp==NULL || d < d_min )
  1965. {
  1966. dp = a + k;
  1967. d_min = d;
  1968. }
  1969. }
  1970. k = dp - a;
  1971. assert( k < an );
  1972. scLocIdx = p->mp->loc[k].scLocIdx;
  1973. if( a[k].mni < rp->mni )
  1974. ++k;
  1975. }
  1976. else // result w/ a valid locIdx (e.g. scan 'substitute' with no match)
  1977. {
  1978. scLocIdx = p->mp->loc[rp->locIdx].scLocIdx;
  1979. // find the print recd with the closest scIdx
  1980. for(k=0; k<an; ++k)
  1981. if( a[k].scLocIdx != cmInvalidIdx )
  1982. {
  1983. unsigned d;
  1984. if( a[k].scLocIdx > scLocIdx )
  1985. d = a[k].scLocIdx - scLocIdx;
  1986. else
  1987. d = scLocIdx - a[k].scLocIdx;
  1988. if( dp==NULL || d < d_min )
  1989. {
  1990. dp = a + k;
  1991. d_min = d;
  1992. }
  1993. }
  1994. k = dp - a;
  1995. assert( k < an );
  1996. if( a[k].scLocIdx < scLocIdx )
  1997. ++k;
  1998. }
  1999. // create a new print recd to represent the false-positive result recd
  2000. assert( dp != NULL );
  2001. _cmScMatcherInsertPrint(a, k, &an,aan,rp,scLocIdx);
  2002. }
  2003. }
  2004. for(i=0; i<an; ++i)
  2005. {
  2006. printf("%4i %4i %4s %c%c%c\n",a[i].scLocIdx,a[i].mni,
  2007. cmIsFlag(a[i].flags,kSmBarFl) ? "|" : cmMidiToSciPitch(a[i].pitch,NULL,0),
  2008. cmIsFlag(a[i].flags,kSmNoteFl) ? 'n' : ' ',
  2009. cmIsFlag(a[i].flags,kSmMatchFl) ? 'm' : (cmIsFlag(a[i].flags,kSmTransFl) ? 't' : ' '),
  2010. cmIsFlag(a[i].flags,kSmFalsePosFl) ? '*' : ' '
  2011. );
  2012. }
  2013. }
  2014. //=======================================================================================================================
  2015. cmScMeas* cmScMeasAlloc( cmCtx* c, cmScMeas* p, cmScH_t scH, double srate, const unsigned* dynRefArray, unsigned dynRefCnt )
  2016. {
  2017. cmScMeas* op = cmObjAlloc(cmScMeas,c,p);
  2018. op->mp = cmScMatchAlloc( c, NULL, cmScNullHandle, 0, 0 );
  2019. if( cmScoreIsValid(scH) )
  2020. if( cmScMeasInit(op,scH,srate,dynRefArray,dynRefCnt) != cmOkRC )
  2021. cmScMeasFree(&op);
  2022. return op;
  2023. }
  2024. cmRC_t cmScMeasFree( cmScMeas** pp )
  2025. {
  2026. cmRC_t rc = cmOkRC;
  2027. if( pp==NULL || *pp==NULL )
  2028. return rc;
  2029. cmScMeas* p = *pp;
  2030. if((rc = cmScMeasFinal(p)) != cmOkRC )
  2031. return rc;
  2032. cmScMatchFree(&p->mp);
  2033. cmMemFree(p->midiBuf);
  2034. cmMemFree(p->set);
  2035. cmMemFree(p->dynRef);
  2036. cmObjFree(pp);
  2037. return rc;
  2038. }
  2039. void _cmScMeasPrint( cmScMeas* p )
  2040. {
  2041. unsigned i;
  2042. for(i=0; i<p->sn; ++i)
  2043. {
  2044. cmScMeasSet_t* sp = p->set + i;
  2045. printf("%4i: sli:%4i %4i li:%4i %4i\n", i, sp->bsli, sp->esli, sp->bli, sp->eli );
  2046. }
  2047. }
  2048. int _cmScMeasSortFunc( const void* p0, const void* p1 )
  2049. {
  2050. const cmScMeasSet_t* s0 = (const cmScMeasSet_t*)p0;
  2051. const cmScMeasSet_t* s1 = (const cmScMeasSet_t*)p1;
  2052. return s0->esli - s1->esli;
  2053. }
  2054. cmRC_t cmScMeasInit( cmScMeas* p, cmScH_t scH, double srate, const unsigned* dynRefArray, unsigned dynRefCnt )
  2055. {
  2056. cmRC_t rc;
  2057. unsigned i,j;
  2058. unsigned si;
  2059. unsigned maxScWndN = 0;
  2060. if((rc = cmScMeasFinal(p)) != cmOkRC )
  2061. return rc;
  2062. p->mii = 0;
  2063. p->mn = 2 * cmScoreEvtCount(scH);
  2064. p->midiBuf = cmMemResizeZ(cmScMatchMidi_t,p->midiBuf,p->mn);
  2065. p->sn = cmScoreSetCount(scH);
  2066. p->set = cmMemResizeZ(cmScMeasSet_t,p->set,p->sn);
  2067. p->dynRef = cmMemResizeZ(unsigned,p->dynRef,dynRefCnt);
  2068. p->dn = dynRefCnt;
  2069. p->srate = srate;
  2070. memcpy(p->dynRef,dynRefArray,sizeof(dynRefArray[0])*dynRefCnt);
  2071. unsigned n = cmScoreLocCount(scH);
  2072. // for each score location
  2073. for(i=0,si=0; i<n; ++i)
  2074. {
  2075. cmScoreLoc_t* lp = cmScoreLoc(scH,i);
  2076. cmScoreSet_t* sp = lp->setList;
  2077. // for each set that ends on this score location
  2078. for(; sp!=NULL; sp=sp->llink,++si)
  2079. {
  2080. assert(si < p->sn);
  2081. cmScMeasSet_t* msp = p->set + si;
  2082. msp->sp = sp;
  2083. msp->bsli = cmScoreLocCount(scH);
  2084. msp->esli = 0;
  2085. msp->bsei = cmScoreEvtCount(scH);
  2086. msp->esei = 0;
  2087. msp->bli = cmInvalidIdx;
  2088. msp->eli = cmInvalidIdx;
  2089. for(j=0; j<sp->eleCnt; ++j)
  2090. {
  2091. msp->bsli = cmMin(msp->bsli,sp->eleArray[j]->locIdx);
  2092. msp->esli = cmMax(msp->esli,sp->eleArray[j]->locIdx);
  2093. msp->bsei = cmMin(msp->bsei,sp->eleArray[j]->index);
  2094. msp->esei = cmMax(msp->esei,sp->eleArray[j]->index);
  2095. }
  2096. }
  2097. }
  2098. // initialize p->mp so that mp->loc[] is loaded - use dummy scWndN and midiN
  2099. if((rc = cmScMatchInit(p->mp, scH, 11, 10 )) != cmOkRC )
  2100. return rc;
  2101. // assign set[].bli and set[].eli
  2102. for(j=0; j<p->sn; ++j)
  2103. {
  2104. cmScMeasSet_t* msp = p->set + j;
  2105. for(i=0; i<p->mp->locN; ++i)
  2106. {
  2107. if( msp->bli==cmInvalidIdx && msp->bsli==p->mp->loc[i].scLocIdx )
  2108. msp->bli = i;
  2109. if( msp->esli==p->mp->loc[i].scLocIdx )
  2110. msp->eli = i;
  2111. }
  2112. assert( msp->eli > msp->bli );
  2113. maxScWndN = cmMax( maxScWndN, msp->eli - msp->bli + 1 );
  2114. }
  2115. // setup the match
  2116. if((rc = cmScMatchInit(p->mp, scH, 2*maxScWndN+1, 2*maxScWndN )) != cmOkRC )
  2117. return rc;
  2118. // sort set[] on cmScMeasSet_t.esli
  2119. qsort(p->set, p->sn, sizeof(cmScMeasSet_t), _cmScMeasSortFunc );
  2120. //_cmScMeasPrint(p);
  2121. cmScMeasReset(p);
  2122. return rc;
  2123. }
  2124. cmRC_t cmScMeasFinal( cmScMeas* p )
  2125. { return cmScMatchFinal(p->mp); }
  2126. cmRC_t cmScMeasReset( cmScMeas* p )
  2127. {
  2128. cmRC_t rc = cmOkRC;
  2129. p->mii = 0;
  2130. p->nsi = cmInvalidIdx;
  2131. p->vsi = cmInvalidIdx;
  2132. p->nsli = cmInvalidIdx;
  2133. unsigned i;
  2134. for(i=0; i<p->sn; ++i)
  2135. {
  2136. p->set[i].value = DBL_MAX;
  2137. p->set[i].tempo = 0;
  2138. p->set[i].match_cost = 0;
  2139. }
  2140. return rc;
  2141. }
  2142. typedef struct
  2143. {
  2144. unsigned scLocIdx; // score loc index
  2145. double frac; // score based fraction of beat
  2146. unsigned smpIdx; // time of assoc'd MIDI event
  2147. unsigned cnt; //
  2148. double val; //
  2149. } _cmScMeasTimeEle_t;
  2150. typedef struct
  2151. {
  2152. unsigned setN; // set length
  2153. unsigned midiN; // count of MIDI events to match to score
  2154. unsigned alignN; // count of score events in the alignment (<= setN)
  2155. unsigned matchN; // count of positive matches
  2156. double tempo;
  2157. double value;
  2158. } _cmScMeasResult_t;
  2159. double _cmScMeasCalcTempo( const _cmScMeasTimeEle_t* b, unsigned bn, double srate )
  2160. {
  2161. assert( bn >= 2 );
  2162. assert( b[bn-1].smpIdx != cmInvalidIdx );
  2163. assert( b[0].smpIdx != cmInvalidIdx );
  2164. double durSmpCnt = b[bn-1].smpIdx - b[0].smpIdx;
  2165. double beats = 0;
  2166. unsigned i;
  2167. for(i=0; i<bn; ++i)
  2168. beats += b[i].frac;
  2169. assert(beats != 0);
  2170. return beats / (durSmpCnt / (srate * 60.0));
  2171. }
  2172. // Note: On successful completion (return!=0) the first
  2173. // and last record returned in c[cn] will be matched records.
  2174. unsigned _cmScMeasTimeAlign( cmScMeas* p, cmScMeasSet_t* sp, cmScMatchMidi_t* m, unsigned mn, _cmScMeasTimeEle_t* c, unsigned cn, _cmScMeasResult_t* rp )
  2175. {
  2176. int i,j,k;
  2177. int an = sp->sp->eleCnt;
  2178. _cmScMeasTimeEle_t* b = NULL;
  2179. int bn = 0;
  2180. bool tempoFl = false;
  2181. unsigned matchN = 0;
  2182. assert( an!=0);
  2183. // alloc a 'score set' element array
  2184. _cmScMeasTimeEle_t a[an];
  2185. // get the scLocIdx of each set element from the score
  2186. for(i=0,j=0; i<an; ++i)
  2187. if( i==0 || sp->sp->eleArray[i-1]->locIdx != sp->sp->eleArray[i]->locIdx )
  2188. {
  2189. assert( sp->sp->eleArray[i]->locIdx != cmInvalidIdx );
  2190. a[j].scLocIdx = sp->sp->eleArray[i]->locIdx;
  2191. a[j].frac = sp->sp->eleArray[i]->frac;
  2192. a[j].smpIdx = cmInvalidIdx;
  2193. a[j].cnt = 0;
  2194. ++j;
  2195. }
  2196. an = j; // set the count of unique score locations (new length of a[])
  2197. // collect the 'smpIdx' for each MIDI event which matches a set element
  2198. for(i=0; i<mn; ++i)
  2199. if( m[i].locIdx != cmInvalidIdx )
  2200. {
  2201. for(j=0; j<an; ++j)
  2202. if( p->mp->loc[m[i].locIdx].scLocIdx == a[j].scLocIdx )
  2203. {
  2204. a[j].smpIdx += m[i].smpIdx;
  2205. a[j].cnt += 1;
  2206. if( a[j].cnt == 1 )
  2207. matchN += 1; // only cnt one match per sc loc.
  2208. break;
  2209. }
  2210. }
  2211. // remove leading missing values
  2212. for(i=0; i<an; ++i)
  2213. if( a[i].smpIdx != cmInvalidIdx )
  2214. {
  2215. b = a + i;
  2216. bn = an - i;
  2217. break;
  2218. }
  2219. // remove trailing missing values
  2220. for(i=bn-1; i>=0; --i,--bn)
  2221. if( b[i].smpIdx != cmInvalidIdx )
  2222. break;
  2223. // can't measure evenness against less than 2 values
  2224. if( bn < 2 )
  2225. {
  2226. return 0;
  2227. }
  2228. assert(b[0].smpIdx != cmInvalidIdx && b[bn-1].smpIdx != cmInvalidIdx);
  2229. // calc avg. smpIdx, insert missing values, and convert b[].smpIdx to delta smp index
  2230. for(i=0,j=0; i<bn; ++i)
  2231. {
  2232. if( b[i].cnt > 1 )
  2233. b[i].smpIdx /= b[i].cnt;
  2234. if( b[i].smpIdx == cmInvalidIdx )
  2235. ++j; // incr missing value count
  2236. else
  2237. {
  2238. if( i > 0 )
  2239. {
  2240. // fill in missing values
  2241. ++j;
  2242. unsigned d = (b[i].smpIdx - b[i-j].smpIdx)/j;
  2243. for(k=0; k<j; ++k)
  2244. b[i-j+k].val = d;
  2245. }
  2246. j=0;
  2247. }
  2248. if( b[i].frac != 0 )
  2249. tempoFl = true;
  2250. }
  2251. rp->setN = an;
  2252. rp->midiN = mn;
  2253. rp->alignN = bn;
  2254. rp->matchN = matchN;
  2255. rp->tempo = 0;
  2256. rp->value = 0;
  2257. // calculate tempo
  2258. if( tempoFl )
  2259. rp->tempo = _cmScMeasCalcTempo(b,bn,p->srate);
  2260. assert(bn<=cn);
  2261. // TODO: this copy should be eliminated
  2262. // copy to output
  2263. for(i=0; i<bn && i<cn; ++i)
  2264. c[i] = b[i];
  2265. return bn;
  2266. }
  2267. double _cmScMeasEven( cmScMeas* p, cmScMeasSet_t* sp, cmScMatchMidi_t* m, unsigned mn, _cmScMeasResult_t* rp )
  2268. {
  2269. unsigned bn = sp->sp->eleCnt;
  2270. _cmScMeasTimeEle_t b[bn];
  2271. unsigned i;
  2272. if((bn = _cmScMeasTimeAlign(p,sp,m,mn,b,bn,rp)) == 0 )
  2273. return DBL_MAX;
  2274. // calc avg. delta time
  2275. double d_avg = 0;
  2276. for(i=0; i<bn-1; ++i)
  2277. d_avg += b[i].val;
  2278. d_avg /= (bn-1);
  2279. // calc std-dev of delta time
  2280. double d_sd = 0;
  2281. for(i=0; i<bn-1; ++i)
  2282. d_sd += (b[i].val-d_avg) * (b[i].val-d_avg);
  2283. // if there is no deviation then we can't compute a z-score
  2284. // (this will happen if we fill in all the missing values based on 2 values)
  2285. if( d_sd == 0 )
  2286. return 1.0;
  2287. d_sd = sqrt(d_sd/(bn-1));
  2288. // calc avg. z-score
  2289. double z = 0;
  2290. for(i=0; i<bn-1; ++i)
  2291. z += fabs(b[i].val - d_avg)/d_sd;
  2292. double val = z / (bn-1);
  2293. rp->value = val;
  2294. return val;
  2295. }
  2296. // return Tempo estimation in BPM
  2297. double _cmScMeasTempo( cmScMeas* p, cmScMeasSet_t* sp, cmScMatchMidi_t* m, unsigned mn, _cmScMeasResult_t* rp )
  2298. {
  2299. unsigned bn = sp->sp->eleCnt;
  2300. _cmScMeasTimeEle_t b[bn];
  2301. if((bn= _cmScMeasTimeAlign(p,sp,m,mn,b,bn,rp)) == 0 )
  2302. return DBL_MAX;
  2303. return rp->tempo;
  2304. }
  2305. double _cmScMeasDyn( cmScMeas* p, cmScMeasSet_t* sp, cmScMatchMidi_t* m, unsigned mn, _cmScMeasResult_t* rp )
  2306. {
  2307. typedef struct
  2308. {
  2309. unsigned scEvtIdx;
  2310. unsigned vel;
  2311. double val;
  2312. } ele_t;
  2313. int i,j;
  2314. int n = sp->sp->eleCnt;
  2315. double vv = 0;
  2316. unsigned vn = 0;
  2317. unsigned matchN = 0;
  2318. unsigned alignN = 0;
  2319. assert( n!=0);
  2320. ele_t a[n];
  2321. // get the scEvtIdx of each set element
  2322. for(i=0; i<n; ++i)
  2323. {
  2324. cmScoreEvt_t* ep = cmScoreEvt( p->mp->scH, sp->sp->eleArray[i]->index );
  2325. assert( ep != NULL );
  2326. a[i].scEvtIdx = sp->sp->eleArray[i]->index;
  2327. a[i].vel = 0;
  2328. a[i].val = ep->dynVal;
  2329. }
  2330. // set the performed vel. of each note in the set
  2331. // (if a note was not played it's a[].vel is left at 0)
  2332. for(i=0; i<mn; ++i)
  2333. if( m[i].scEvtIdx != cmInvalidIdx )
  2334. {
  2335. alignN += 1;
  2336. for(j=0; j<n; ++j)
  2337. if( m[i].scEvtIdx == a[j].scEvtIdx )
  2338. {
  2339. matchN += 1;
  2340. a[j].vel = m[i].vel;
  2341. break;
  2342. }
  2343. }
  2344. // assign a dynamics category to each note in the set
  2345. for(i=0; i<n; ++i)
  2346. if( a[i].vel > 0 )
  2347. {
  2348. unsigned mnv = 0; // lower bound for first dyn's category
  2349. for(j=0; j<p->dn; ++j)
  2350. {
  2351. if( mnv <= a[i].vel && a[i].vel < p->dynRef[j] )
  2352. {
  2353. // accum. the diff. between the ref. and performed dyn. category
  2354. vv += fabs(a[i].val - j);
  2355. vn += 1;
  2356. break;
  2357. }
  2358. mnv = p->dynRef[j];
  2359. }
  2360. assert(j<p->dn);
  2361. }
  2362. rp->setN = n;
  2363. rp->midiN = mn;
  2364. rp->alignN = alignN;
  2365. rp->matchN = matchN;
  2366. rp->tempo = 0;
  2367. rp->value = vn == 0 ? DBL_MAX : vv/vn;
  2368. return rp->value;
  2369. }
  2370. unsigned MEAS_MATCH_CNT = 0;
  2371. void _cmScMeasPrintResult( cmScMeas* p, cmScMeasSet_t* sp, _cmScMeasResult_t* rp, unsigned bli, const cmScMatchMidi_t* mb )
  2372. {
  2373. const char* label = "<none>";
  2374. switch( sp->sp->varId )
  2375. {
  2376. case kEvenVarScId:
  2377. label = "even";
  2378. break;
  2379. case kDynVarScId:
  2380. label = "dyn";
  2381. break;
  2382. case kTempoVarScId:
  2383. label = "tempo";
  2384. break;
  2385. }
  2386. const cmChar_t* msg = "";
  2387. if( rp->value == DBL_MAX )
  2388. {
  2389. msg = "Measure FAILED.";
  2390. sp->value = 0;
  2391. }
  2392. 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);
  2393. if( rp->tempo != 0 )
  2394. printf(" tempo:%f ",rp->tempo);
  2395. printf("\n");
  2396. _cmScMatchPrintPath(p->mp, p->mp->p_opt, bli, mb );
  2397. }
  2398. void _cmScMeasCalcVal( cmScMeas* p, cmScMeasSet_t* sp, int n_mii )
  2399. {
  2400. unsigned mn = 0;
  2401. int i;
  2402. if( n_mii == 0 )
  2403. return;
  2404. // Determine the count of MIDI notes to match to the set score
  2405. // by searching from the MIDI note just recieved (midiBuf[n_mii]
  2406. // back toward the beginning until a MIDI event which occurs just
  2407. // prior to the set's begScLocIdx.
  2408. for(i=n_mii; i>=0; --i)
  2409. {
  2410. ++mn;
  2411. if( p->midiBuf[i].locIdx != cmInvalidIdx )
  2412. {
  2413. unsigned scLocIdx = p->mp->loc[ p->midiBuf[i].locIdx ].scLocIdx;
  2414. if( scLocIdx < sp->bsli )
  2415. break;
  2416. }
  2417. }
  2418. i = cmMax(0,i);
  2419. assert(mn>0);
  2420. // Create a copy of the the MIDI buffer to prevent the
  2421. // p->midiBuf[].locIdx from being overwritten by cmScMatchDoSync().
  2422. cmScMatchMidi_t mb[ mn ];
  2423. unsigned j;
  2424. for(j=0; j<mn; ++j)
  2425. {
  2426. mb[j] = p->midiBuf[i+j];
  2427. mb[j].locIdx = cmInvalidIdx;
  2428. }
  2429. // In general the first and last MIDI event should be assigned
  2430. // to a score location - it's possible however that no MIDI
  2431. // event's prior to the one at p->midiBuf[n_mii] were assigned.
  2432. assert( (i==0 || p->midiBuf[i].locIdx!=cmInvalidIdx) && p->midiBuf[i+mn-1].locIdx != cmInvalidIdx);
  2433. unsigned bli = p->midiBuf[i].locIdx;
  2434. unsigned ln = p->midiBuf[i+mn-1].locIdx - bli + 1;
  2435. double min_cost = DBL_MAX;
  2436. _cmScMeasResult_t r;
  2437. memset(&r,0,sizeof(r));
  2438. // match MIDI to score
  2439. if( cmScMatchExec(p->mp, bli, ln, mb, mn, min_cost ) != cmOkRC )
  2440. return;
  2441. // sync the score and MIDI based on the match information
  2442. if( cmScMatchDoSync(p->mp, bli, mb, mn, NULL ) == cmInvalidIdx )
  2443. return;
  2444. if( p->mp->opt_cost != DBL_MAX )
  2445. sp->match_cost = p->mp->opt_cost / sp->sp->eleCnt;
  2446. switch( sp->sp->varId )
  2447. {
  2448. case kEvenVarScId:
  2449. sp->value = _cmScMeasEven(p, sp, mb, mn, &r );
  2450. break;
  2451. case kDynVarScId:
  2452. sp->value = _cmScMeasDyn(p, sp, mb, mn, &r );
  2453. break;
  2454. case kTempoVarScId:
  2455. sp->value = _cmScMeasTempo(p, sp, mb, mn, &r );
  2456. break;
  2457. default:
  2458. { assert(0); }
  2459. }
  2460. sp->tempo = r.tempo;
  2461. // print the result
  2462. //_cmScMeasPrintResult(p, sp, &r, bli, mb );
  2463. MEAS_MATCH_CNT++;
  2464. }
  2465. cmRC_t cmScMeasExec( cmScMeas* p, unsigned mni, unsigned locIdx, unsigned scEvtIdx, unsigned flags, unsigned smpIdx, unsigned pitch, unsigned vel )
  2466. {
  2467. cmRC_t rc = cmOkRC;
  2468. // if the midi buffer is full
  2469. if( p->mii >= p->mn )
  2470. return cmCtxRtCondition( &p->obj, cmEofRC, "The MIDI buffer is full.");
  2471. int n_mii = cmInvalidIdx;
  2472. // locate the MIDI event assoc'd with 'mni' ...
  2473. if( p->mii>0 && mni <= p->midiBuf[p->mii-1].mni )
  2474. {
  2475. if( locIdx != cmInvalidIdx )
  2476. {
  2477. for(n_mii=p->mii-1; n_mii>=0; --n_mii)
  2478. if( p->midiBuf[n_mii].mni == mni )
  2479. break;
  2480. if( n_mii<0 )
  2481. n_mii = cmInvalidIdx;
  2482. }
  2483. }
  2484. else // ... or push a new record onto p->midiBuf[]
  2485. {
  2486. n_mii = p->mii;
  2487. ++p->mii;
  2488. }
  2489. // store the MIDI event
  2490. p->midiBuf[n_mii].mni = mni;
  2491. p->midiBuf[n_mii].locIdx = locIdx;
  2492. p->midiBuf[n_mii].scEvtIdx = scEvtIdx;
  2493. p->midiBuf[n_mii].smpIdx = smpIdx;
  2494. p->midiBuf[n_mii].pitch = pitch;
  2495. p->midiBuf[n_mii].vel = vel;
  2496. if( locIdx == cmInvalidIdx )
  2497. return cmOkRC;
  2498. //
  2499. unsigned scLocIdx = p->mp->loc[ locIdx ].scLocIdx;
  2500. unsigned maxScLocIdx = cmScoreLocCount(p->mp->scH)-1;
  2501. // if this cmScMeas object has not yet synchronized to the cmScMatcher
  2502. // (if p->nsli is not valid)
  2503. if( p->nsli == cmInvalidIdx )
  2504. {
  2505. unsigned i;
  2506. for(i=0; i<p->sn; ++i)
  2507. if( p->set[i].esli+1 == scLocIdx )
  2508. {
  2509. p->nsli = scLocIdx;
  2510. p->nsi = i;
  2511. break;
  2512. }
  2513. if(i==p->sn)
  2514. return rc;
  2515. }
  2516. p->vsi = p->nsi;
  2517. p->vsli = p->nsli;
  2518. // for each cmScore location between p->nsli and scLocIdx
  2519. for(; p->nsli<=scLocIdx && p->nsi < p->sn; ++p->nsli)
  2520. {
  2521. // if this score location index (p->nsli) is one score location
  2522. // ahead of the next sets ending location.
  2523. while( cmMin(maxScLocIdx,p->set[p->nsi].esli+1) == p->nsli )
  2524. {
  2525. // calculate the value assoc'd with p->set[p->nsi]
  2526. _cmScMeasCalcVal(p, p->set + p->nsi, n_mii );
  2527. // advance the set index
  2528. ++p->nsi;
  2529. }
  2530. }
  2531. return rc;
  2532. }
  2533. //=======================================================================================================================
  2534. cmRC_t cmScAlignScanToTimeLineEvent( cmScMatcher* p, cmTlH_t tlH, cmTlObj_t* top, unsigned endSmpIdx )
  2535. {
  2536. assert( top != NULL );
  2537. cmTlMidiEvt_t* mep = NULL;
  2538. cmRC_t rc = cmOkRC;
  2539. // as long as more MIDI events are available get the next MIDI msg
  2540. while( rc==cmOkRC && (mep = cmTlNextMidiEvtObjPtr(tlH, top, top->seqId )) != NULL )
  2541. {
  2542. top = &mep->obj;
  2543. // if the msg falls after the end of the marker then we are through
  2544. if( mep->obj.seqSmpIdx != cmInvalidIdx && mep->obj.seqSmpIdx > endSmpIdx )
  2545. break;
  2546. // if the time line MIDI msg a note-on
  2547. if( mep->msg->status == kNoteOnMdId )
  2548. {
  2549. rc = cmScMatcherExec(p, mep->obj.seqSmpIdx, mep->msg->status, mep->msg->u.chMsgPtr->d0, mep->msg->u.chMsgPtr->d1, NULL );
  2550. switch( rc )
  2551. {
  2552. case cmOkRC: // continue processing MIDI events
  2553. break;
  2554. case cmEofRC: // end of the score was encountered
  2555. break;
  2556. case cmInvalidArgRC: // p->eli was not set correctly
  2557. break;
  2558. case cmSubSysFailRC: // scan resync failed
  2559. break;
  2560. default:
  2561. { assert(0); }
  2562. }
  2563. }
  2564. }
  2565. if( rc == cmEofRC )
  2566. rc = cmOkRC;
  2567. return rc;
  2568. }
  2569. // This callback connects/feeds the cmScMeas object from the cmScMatcher object.
  2570. // (See _cmScMatcherStoreResult().)
  2571. void cmScMatcherCb( cmScMatcher* p, void* arg, cmScMatcherResult_t* rp )
  2572. {
  2573. cmScMeas* mp = (cmScMeas*)arg;
  2574. cmScMeasExec(mp, rp->mni, rp->locIdx, rp->scEvtIdx, rp->flags, rp->smpIdx, rp->pitch, rp->vel );
  2575. }
  2576. void cmScAlignScanMarkers( cmRpt_t* rpt, cmTlH_t tlH, cmScH_t scH )
  2577. {
  2578. unsigned i;
  2579. double srate = cmTimeLineSampleRate(tlH);
  2580. unsigned midiN = 7;
  2581. unsigned scWndN = 10;
  2582. unsigned markN = 291;
  2583. unsigned dynRefArray[] = { 14, 28, 42, 56, 71, 85, 99, 113,128 };
  2584. unsigned dynRefCnt = sizeof(dynRefArray)/sizeof(dynRefArray[0]);
  2585. cmCtx* ctx = cmCtxAlloc(NULL, rpt, cmLHeapNullHandle, cmSymTblNullHandle );
  2586. cmScMeas* mp = cmScMeasAlloc(ctx,NULL,scH,srate,dynRefArray,dynRefCnt);
  2587. cmScMatcher* p = cmScMatcherAlloc(ctx,NULL,srate,scH,scWndN,midiN,cmScMatcherCb,mp);
  2588. double scoreThresh = 0.5;
  2589. unsigned candCnt = 0;
  2590. unsigned initFailCnt = 0;
  2591. unsigned otherFailCnt = 0;
  2592. unsigned scoreFailCnt = 0;
  2593. bool printFl = false;
  2594. unsigned markCharCnt = 31;
  2595. cmChar_t markText[ markCharCnt+1 ];
  2596. cmTimeSpec_t t0,t1;
  2597. cmTimeGet(&t0);
  2598. // for each marker
  2599. for(i=0; i<markN; ++i)
  2600. {
  2601. // form the marker text
  2602. snprintf(markText,markCharCnt,"Mark %i",i);
  2603. // locate the marker
  2604. cmTlMarker_t* tlmp = cmTimeLineMarkerFind( tlH, markText );
  2605. if( tlmp == NULL )
  2606. {
  2607. if( printFl )
  2608. printf("The marker '%s' was not found.\n\n",markText);
  2609. continue;
  2610. }
  2611. // skip markers which do not contain text
  2612. if( cmTextIsEmpty(tlmp->text) )
  2613. {
  2614. if( printFl )
  2615. printf("The marker '%s' is being skipped because it has no text.\n\n",markText);
  2616. continue;
  2617. }
  2618. printf("=================== MARKER:%s ===================\n",markText);
  2619. cmScMatcherReset(p,0); // reset the score follower to the beginnig of the score
  2620. cmScMeasReset(mp);
  2621. ++candCnt;
  2622. // scan to the beginning of the marker
  2623. cmRC_t rc = cmScAlignScanToTimeLineEvent(p,tlH,&tlmp->obj,tlmp->obj.seqSmpIdx+tlmp->obj.durSmpCnt);
  2624. bool pfl = true;
  2625. if( rc != cmOkRC || p->begSyncLocIdx==cmInvalidIdx)
  2626. {
  2627. bool fl = printFl;
  2628. printFl = true;
  2629. // if a no alignment was found
  2630. if( p->begSyncLocIdx == cmInvalidIdx )
  2631. rc = cmInvalidArgRC;
  2632. if( p->mni == 0 )
  2633. {
  2634. if( printFl )
  2635. printf("mark:%i midi:%i Not enough MIDI notes to fill the scan buffer.\n",i,p->mni);
  2636. pfl = false;
  2637. }
  2638. else
  2639. {
  2640. switch(rc)
  2641. {
  2642. case cmInvalidArgRC:
  2643. if( printFl )
  2644. printf("mark:%i INITIAL SYNC FAIL\n",i);
  2645. ++initFailCnt;
  2646. pfl = false;
  2647. break;
  2648. case cmSubSysFailRC:
  2649. if( printFl )
  2650. printf("mark:%i SCAN RESYNC FAIL\n",i);
  2651. ++otherFailCnt;
  2652. break;
  2653. default:
  2654. if( printFl )
  2655. printf("mark:%i UNKNOWN FAIL\n",i);
  2656. ++otherFailCnt;
  2657. }
  2658. }
  2659. printFl = fl;
  2660. }
  2661. if( pfl )
  2662. {
  2663. double fmeas = cmScMatcherFMeas(p);
  2664. if( printFl )
  2665. 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);
  2666. if( fmeas < scoreThresh )
  2667. ++scoreFailCnt;
  2668. }
  2669. //print score and match for entire marker
  2670. //cmScMatcherPrint(p);
  2671. // ONLY USE ONE MARKER DURING TESTING
  2672. // break;
  2673. if( printFl )
  2674. printf("\n");
  2675. }
  2676. printf("cand:%i fail:%i - init:%i score:%i other:%i\n\n",candCnt,initFailCnt+scoreFailCnt+otherFailCnt,initFailCnt,scoreFailCnt,otherFailCnt);
  2677. cmTimeGet(&t1);
  2678. printf("elapsed:%f\n", (double)cmTimeElapsedMicros(&t0,&t1)/1000000.0 );
  2679. cmScMatcherFree(&p);
  2680. cmScMeasFree(&mp);
  2681. cmCtxFree(&ctx);
  2682. }
  2683. //=======================================================================================================================
  2684. 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 )
  2685. {
  2686. cmScModulator* op = cmObjAlloc(cmScModulator,c,p);
  2687. if( ctx != NULL )
  2688. if( cmScModulatorInit(op,ctx,stH,srate,samplesPerCycle,fn,modLabel,cbFunc,cbArg) != cmOkRC )
  2689. cmScModulatorFree(&op);
  2690. return op;
  2691. }
  2692. cmRC_t cmScModulatorFree( cmScModulator** pp )
  2693. {
  2694. cmRC_t rc = cmOkRC;
  2695. if( pp==NULL || *pp==NULL )
  2696. return rc;
  2697. cmScModulator* p = *pp;
  2698. if((rc = cmScModulatorFinal(p)) != cmOkRC )
  2699. return rc;
  2700. cmMemFree(p->earray);
  2701. cmObjFree(pp);
  2702. return rc;
  2703. }
  2704. typedef struct
  2705. {
  2706. unsigned typeId;
  2707. unsigned minArgCnt;
  2708. const cmChar_t* label;
  2709. } _cmScModTypeMap_t;
  2710. _cmScModTypeMap_t _cmScModTypeArray[] =
  2711. {
  2712. { kSetModTId, 1, "set" },
  2713. { kLineModTId, 2, "line" },
  2714. { kSetLineModTId, 3, "sline" },
  2715. { kInvalidModTId, 0, "<invalid>"}
  2716. };
  2717. const _cmScModTypeMap_t* _cmScModTypeLabelToMap( const cmChar_t* label )
  2718. {
  2719. unsigned i;
  2720. for(i=0; _cmScModTypeArray[i].typeId!=kInvalidModTId; ++i)
  2721. if( strcmp(_cmScModTypeArray[i].label,label) == 0 )
  2722. return _cmScModTypeArray + i;
  2723. return NULL;
  2724. }
  2725. cmScModVar_t* _cmScModSymToVar( cmScModulator* p, unsigned varSymId )
  2726. {
  2727. cmScModVar_t* vp = p->vlist;
  2728. for(; vp!=NULL; vp=vp->vlink)
  2729. if( varSymId == vp->varSymId )
  2730. return vp;
  2731. return NULL;
  2732. }
  2733. cmScModVar_t* _cmScModulatorInsertVar( cmScModulator* p, unsigned varSymId, unsigned flags )
  2734. {
  2735. cmScModVar_t* vp = _cmScModSymToVar(p,varSymId);
  2736. if( vp == NULL )
  2737. {
  2738. vp = cmMemAllocZ(cmScModVar_t,1);
  2739. vp->varSymId = varSymId;
  2740. vp->outVarId = cmInvalidId;
  2741. vp->vlink = p->vlist;
  2742. p->vlist = vp;
  2743. }
  2744. vp->flags = flags;
  2745. vp->value = DBL_MAX;
  2746. vp->min = DBL_MAX;
  2747. vp->max = DBL_MAX;
  2748. vp->rate = DBL_MAX;
  2749. vp->phase = 0;
  2750. vp->entry = NULL;
  2751. vp->alink = NULL;
  2752. return vp;
  2753. }
  2754. cmScModEntry_t* _cmScModulatorInsertEntry(cmScModulator* p, unsigned idx, unsigned scLocIdx, unsigned modSymId, unsigned varSymId, unsigned typeId, unsigned paramCnt )
  2755. {
  2756. assert( idx < p->en );
  2757. p->earray[idx].scLocIdx = scLocIdx;
  2758. p->earray[idx].typeId = typeId;
  2759. p->earray[idx].varPtr = _cmScModulatorInsertVar(p,varSymId,0);
  2760. if( p->earray[idx].varPtr->outVarId == cmInvalidIdx )
  2761. p->earray[idx].varPtr->outVarId = p->outVarCnt++;
  2762. return p->earray + idx;
  2763. }
  2764. /*
  2765. {
  2766. [
  2767. { loc:123, mod:modlabel, var:varlabel, param:[ ] }
  2768. ]
  2769. }
  2770. */
  2771. // Parameter values are found as values of the 'data','min' or 'max' fields.
  2772. // A parameter value may be either a symbol identifier (mapped to a variable)
  2773. // or a literal number. This function determines which form the paramter
  2774. // value takes and parses it accordingly.
  2775. cmRC_t _cmScModulatorParseParam( cmScModulator* p, cmSymTblH_t stH, cmJsonNode_t* np, cmScModParam_t* pp )
  2776. {
  2777. cmRC_t rc = cmOkRC;
  2778. switch( np->typeId )
  2779. {
  2780. case kIntTId:
  2781. case kRealTId:
  2782. if( cmJsonRealValue(np, &pp->val ) != kOkJsRC )
  2783. {
  2784. rc = cmCtxRtCondition( &p->obj, cmInvalidArgRC, "Error parsing in Modulator literal value." );
  2785. goto errLabel;
  2786. }
  2787. pp->pid = kLiteralModPId;
  2788. break;
  2789. case kStringTId:
  2790. {
  2791. const cmChar_t* label = NULL;
  2792. if( cmJsonStringValue(np, &label) != kOkJsRC )
  2793. {
  2794. rc = cmCtxRtCondition( &p->obj, cmInvalidArgRC, "Error parsing in Modulator symbol label." );
  2795. goto errLabel;
  2796. }
  2797. pp->symId = cmSymTblRegisterSymbol(stH,label);
  2798. pp->pid = kSymbolModPId;
  2799. }
  2800. break;
  2801. default:
  2802. rc = cmCtxRtCondition( &p->obj, cmInvalidArgRC, "Parameter value is not a number or identifier." );
  2803. goto errLabel;
  2804. break;
  2805. }
  2806. errLabel:
  2807. return rc;
  2808. }
  2809. cmRC_t _cmScModulatorParse2( cmScModulator* p, cmCtx_t* ctx, cmSymTblH_t stH, const cmChar_t* fn )
  2810. {
  2811. cmRC_t rc = cmOkRC;
  2812. cmJsonNode_t* jnp = NULL;
  2813. cmJsonH_t jsH = cmJsonNullHandle;
  2814. unsigned i = cmInvalidIdx;
  2815. unsigned j = cmInvalidIdx;
  2816. // read the JSON file
  2817. if( cmJsonInitializeFromFile(&jsH, fn, ctx ) != kOkJsRC )
  2818. return cmCtxRtCondition( &p->obj, cmInvalidArgRC, "JSON file parse failed on the modulator file: %s.",cmStringNullGuard(fn) );
  2819. jnp = cmJsonRoot(jsH);
  2820. // validate that the first child as an array
  2821. if( jnp==NULL || ((jnp = cmJsonNodeMemberValue(jnp,"array")) == NULL) || cmJsonIsArray(jnp)==false )
  2822. {
  2823. rc = cmCtxRtCondition( &p->obj, cmInvalidArgRC, "Modulator file header syntax error in file:%s",cmStringNullGuard(fn) );
  2824. goto errLabel;
  2825. }
  2826. // allocate the entry array
  2827. unsigned entryCnt = cmJsonChildCount(jnp);
  2828. p->earray = cmMemResizeZ(cmScModEntry_t,p->earray,entryCnt);
  2829. p->en = entryCnt;
  2830. for(i=0; i<entryCnt; ++i)
  2831. {
  2832. cmJsRC_t jsRC;
  2833. const char* errLabelPtr = NULL;
  2834. unsigned scLocIdx = cmInvalidIdx;
  2835. const cmChar_t* modLabel = NULL;
  2836. const cmChar_t* varLabel = NULL;
  2837. const cmChar_t* typeLabel = NULL;
  2838. cmJsonNode_t* onp = cmJsonArrayElement(jnp,i);
  2839. cmJsonNode_t* dnp = NULL;
  2840. const _cmScModTypeMap_t* map = NULL;
  2841. if((jsRC = cmJsonMemberValues( onp, &errLabelPtr,
  2842. "loc", kIntTId, &scLocIdx,
  2843. "mod", kStringTId, &modLabel,
  2844. "var", kStringTId, &varLabel,
  2845. "type",kStringTId, &typeLabel,
  2846. NULL )) != kOkJsRC )
  2847. {
  2848. if( errLabelPtr == NULL )
  2849. rc = cmCtxRtCondition( &p->obj, cmInvalidArgRC, "Error:%s on record at index %i in file:%s",errLabelPtr,i,cmStringNullGuard(fn) );
  2850. else
  2851. rc = cmCtxRtCondition( &p->obj, cmInvalidArgRC, "Synax error in Modulator record at index %i in file:%s",i,cmStringNullGuard(fn) );
  2852. goto errLabel;
  2853. }
  2854. // validate the entry type label
  2855. if((map = _cmScModTypeLabelToMap(typeLabel)) == NULL )
  2856. {
  2857. rc = cmCtxRtCondition( &p->obj, cmInvalidArgRC, "Unknown entry type '%s' in Modulator record at index %i in file:%s",cmStringNullGuard(typeLabel),i,cmStringNullGuard(fn) );
  2858. goto errLabel;
  2859. }
  2860. unsigned modSymId = cmSymTblRegisterSymbol(stH,modLabel);
  2861. unsigned varSymId = cmSymTblRegisterSymbol(stH,varLabel);
  2862. // the mod entry label must match the modulators label
  2863. if( p->modSymId != modSymId )
  2864. {
  2865. --p->en;
  2866. continue;
  2867. }
  2868. // get the count of the elmenets in the data array
  2869. unsigned paramCnt = cmJsonChildCount(onp);
  2870. // fill the entry record and find or create the target var
  2871. cmScModEntry_t* ep = _cmScModulatorInsertEntry(p,i,scLocIdx,modSymId,varSymId,map->typeId,paramCnt);
  2872. typedef struct
  2873. {
  2874. const cmChar_t* label;
  2875. cmScModParam_t* param;
  2876. } map_t;
  2877. // parse the var and parameter records
  2878. map_t mapArray[] =
  2879. {
  2880. { "min", &ep->min },
  2881. { "max", &ep->max },
  2882. { "rate",&ep->rate },
  2883. { "val", &ep->beg },
  2884. { "end", &ep->end },
  2885. { "dur", &ep->dur },
  2886. { NULL, NULL }
  2887. };
  2888. unsigned j=0;
  2889. for(j=0; mapArray[j].param!=NULL; ++j)
  2890. if((dnp = cmJsonFindValue(jsH,mapArray[j].label, onp, kInvalidTId )) != NULL )
  2891. if((rc = _cmScModulatorParseParam(p,stH,dnp,mapArray[j].param)) != cmOkRC )
  2892. goto errLabel;
  2893. }
  2894. errLabel:
  2895. if( rc != cmOkRC )
  2896. cmCtxRtCondition( &p->obj, cmInvalidArgRC, "Error parsing in Modulator 'data' record at index %i value index %i in file:%s",i,j,cmStringNullGuard(fn) );
  2897. // release the JSON tree
  2898. if( cmJsonIsValid(jsH) )
  2899. cmJsonFinalize(&jsH);
  2900. return rc;
  2901. }
  2902. cmRC_t _cmScModulatorParse( cmScModulator* p, cmCtx_t* ctx, cmSymTblH_t stH, const cmChar_t* fn )
  2903. {
  2904. cmRC_t rc = cmOkRC;
  2905. cmJsonNode_t* jnp = NULL;
  2906. cmJsonH_t jsH = cmJsonNullHandle;
  2907. unsigned i = cmInvalidIdx;
  2908. unsigned j = cmInvalidIdx;
  2909. // read the JSON file
  2910. if( cmJsonInitializeFromFile(&jsH, fn, ctx ) != kOkJsRC )
  2911. return cmCtxRtCondition( &p->obj, cmInvalidArgRC, "JSON file parse failed on the modulator file: %s.",cmStringNullGuard(fn) );
  2912. jnp = cmJsonRoot(jsH);
  2913. // validate that the first child as an array
  2914. if( jnp==NULL || ((jnp = cmJsonNodeMemberValue(jnp,"array")) == NULL) || cmJsonIsArray(jnp)==false )
  2915. {
  2916. rc = cmCtxRtCondition( &p->obj, cmInvalidArgRC, "Modulator file header syntax error in file:%s",cmStringNullGuard(fn) );
  2917. goto errLabel;
  2918. }
  2919. // allocate the entry array
  2920. unsigned entryCnt = cmJsonChildCount(jnp);
  2921. p->earray = cmMemResizeZ(cmScModEntry_t,p->earray,entryCnt);
  2922. p->en = entryCnt;
  2923. unsigned prvScLocIdx = cmInvalidIdx;
  2924. const cmChar_t* prvModLabel = NULL;
  2925. const cmChar_t* prvVarLabel = NULL;
  2926. const cmChar_t* prvTypeLabel = NULL;
  2927. for(i=0; i<entryCnt; ++i)
  2928. {
  2929. cmJsRC_t jsRC;
  2930. const char* errLabelPtr = NULL;
  2931. unsigned scLocIdx = cmInvalidIdx;
  2932. const cmChar_t* modLabel = NULL;
  2933. const cmChar_t* varLabel = NULL;
  2934. const cmChar_t* typeLabel = NULL;
  2935. cmJsonNode_t* onp = cmJsonArrayElement(jnp,i);
  2936. cmJsonNode_t* dnp = NULL;
  2937. const _cmScModTypeMap_t* map = NULL;
  2938. if((jsRC = cmJsonMemberValues( onp, &errLabelPtr,
  2939. "loc", kIntTId | kOptArgJsFl, &scLocIdx,
  2940. "mod", kStringTId | kOptArgJsFl, &modLabel,
  2941. "var", kStringTId | kOptArgJsFl, &varLabel,
  2942. "type",kStringTId | kOptArgJsFl, &typeLabel,
  2943. NULL )) != kOkJsRC )
  2944. {
  2945. if( errLabelPtr == NULL )
  2946. rc = cmCtxRtCondition( &p->obj, cmInvalidArgRC, "Error:%s on record at index %i in file:%s",errLabelPtr,i,cmStringNullGuard(fn) );
  2947. else
  2948. rc = cmCtxRtCondition( &p->obj, cmInvalidArgRC, "Synax error in Modulator record at index %i in file:%s",i,cmStringNullGuard(fn) );
  2949. goto errLabel;
  2950. }
  2951. // if the score location was not given use the previous score location
  2952. if( scLocIdx == cmInvalidIdx )
  2953. scLocIdx = prvScLocIdx;
  2954. else
  2955. prvScLocIdx = scLocIdx;
  2956. // if the mod label was not given use the previous one
  2957. if( modLabel == NULL )
  2958. modLabel = prvModLabel;
  2959. else
  2960. prvModLabel = modLabel;
  2961. if( modLabel == NULL )
  2962. {
  2963. rc = cmCtxRtCondition(&p->obj, cmInvalidArgRC, "No 'mod' label has been set in mod file '%s'.",cmStringNullGuard(fn));
  2964. goto errLabel;
  2965. }
  2966. // if the var label was not given use the previous one
  2967. if( varLabel == NULL )
  2968. varLabel = prvVarLabel;
  2969. else
  2970. prvVarLabel = varLabel;
  2971. if( varLabel == NULL )
  2972. {
  2973. rc = cmCtxRtCondition(&p->obj, cmInvalidArgRC, "No 'var' label has been set in mod file '%s'.",cmStringNullGuard(fn));
  2974. goto errLabel;
  2975. }
  2976. // if the type label was not given use the previous one
  2977. if( typeLabel == NULL )
  2978. typeLabel = prvTypeLabel;
  2979. else
  2980. prvTypeLabel = typeLabel;
  2981. if( typeLabel == NULL )
  2982. {
  2983. rc = cmCtxRtCondition(&p->obj, cmInvalidArgRC, "No 'type' label has been set in mod file '%s'.",cmStringNullGuard(fn));
  2984. goto errLabel;
  2985. }
  2986. // validate the entry type label
  2987. if((map = _cmScModTypeLabelToMap(typeLabel)) == NULL )
  2988. {
  2989. rc = cmCtxRtCondition( &p->obj, cmInvalidArgRC, "Unknown entry type '%s' in Modulator record at index %i in file:%s",cmStringNullGuard(typeLabel),i,cmStringNullGuard(fn) );
  2990. goto errLabel;
  2991. }
  2992. unsigned modSymId = cmSymTblRegisterSymbol(stH,modLabel);
  2993. unsigned varSymId = cmSymTblRegisterSymbol(stH,varLabel);
  2994. // the mod entry label must match the modulators label
  2995. if( p->modSymId != modSymId )
  2996. {
  2997. --p->en;
  2998. continue;
  2999. }
  3000. // get the count of the elmenets in the data array
  3001. unsigned paramCnt = cmJsonChildCount(onp);
  3002. // fill the entry record and find or create the target var
  3003. cmScModEntry_t* ep = _cmScModulatorInsertEntry(p,i,scLocIdx,modSymId,varSymId,map->typeId,paramCnt);
  3004. typedef struct
  3005. {
  3006. const cmChar_t* label;
  3007. cmScModParam_t* param;
  3008. } map_t;
  3009. // parse the var and parameter records
  3010. map_t mapArray[] =
  3011. {
  3012. { "min", &ep->min },
  3013. { "max", &ep->max },
  3014. { "rate",&ep->rate },
  3015. { "val", &ep->beg },
  3016. { "end", &ep->end },
  3017. { "dur", &ep->dur },
  3018. { NULL, NULL }
  3019. };
  3020. unsigned j=0;
  3021. for(j=0; mapArray[j].param!=NULL; ++j)
  3022. if((dnp = cmJsonFindValue(jsH,mapArray[j].label, onp, kInvalidTId )) != NULL )
  3023. if((rc = _cmScModulatorParseParam(p,stH,dnp,mapArray[j].param)) != cmOkRC )
  3024. goto errLabel;
  3025. }
  3026. errLabel:
  3027. if( rc != cmOkRC )
  3028. cmCtxRtCondition( &p->obj, cmInvalidArgRC, "Error parsing in Modulator 'data' record at index %i value index %i in file:%s",i,j,cmStringNullGuard(fn) );
  3029. // release the JSON tree
  3030. if( cmJsonIsValid(jsH) )
  3031. cmJsonFinalize(&jsH);
  3032. return rc;
  3033. }
  3034. cmRC_t _cmScModulatorReset( cmScModulator* p, cmCtx_t* ctx, unsigned scLocIdx )
  3035. {
  3036. cmRC_t rc = cmOkRC;
  3037. p->alist = NULL;
  3038. p->elist = NULL;
  3039. p->nei = 0;
  3040. p->outVarCnt = 0;
  3041. // reload the file
  3042. if((rc = _cmScModulatorParse(p,ctx,p->stH,p->fn)) != cmOkRC )
  3043. goto errLabel;
  3044. // clear the active flag on all variables
  3045. cmScModVar_t* vp = p->vlist;
  3046. for(; vp!=NULL; vp=vp->vlink)
  3047. {
  3048. vp->flags = cmClrFlag(vp->flags,kActiveModFl);
  3049. vp->alink = NULL;
  3050. }
  3051. errLabel:
  3052. return rc;
  3053. }
  3054. 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 )
  3055. {
  3056. cmRC_t rc;
  3057. if((rc = cmScModulatorFinal(p)) != cmOkRC )
  3058. return rc;
  3059. p->fn = cmMemAllocStr(fn);
  3060. p->stH = stH;
  3061. p->modSymId = cmSymTblRegisterSymbol(stH,modLabel);
  3062. p->cbFunc = cbFunc;
  3063. p->cbArg = cbArg;
  3064. p->samplesPerCycle = samplesPerCycle;
  3065. p->srate = srate;
  3066. if( rc != cmOkRC )
  3067. cmScModulatorFinal(p);
  3068. else
  3069. _cmScModulatorReset(p,ctx,0);
  3070. return rc;
  3071. }
  3072. cmRC_t cmScModulatorFinal( cmScModulator* p )
  3073. {
  3074. cmMemFree(p->fn);
  3075. // release each var record
  3076. cmScModVar_t* vp = p->vlist;
  3077. while( vp!=NULL )
  3078. {
  3079. cmScModVar_t* np = vp->vlink;
  3080. cmMemFree(vp);
  3081. vp=np;
  3082. }
  3083. return cmOkRC;
  3084. }
  3085. unsigned cmScModulatorOutVarCount( cmScModulator* p )
  3086. { return p->outVarCnt; }
  3087. cmScModVar_t* cmScModulatorOutVar( cmScModulator* p, unsigned idx )
  3088. {
  3089. unsigned i;
  3090. for(i=0; i<p->en; ++i)
  3091. if( p->earray[i].varPtr->outVarId == idx )
  3092. return p->earray[i].varPtr;
  3093. return NULL;
  3094. }
  3095. cmRC_t cmScModulatorSetValue( cmScModulator* p, unsigned varSymId, double value, double min, double max )
  3096. {
  3097. cmScModVar_t* vp;
  3098. // if the var does not exist ....
  3099. if((vp = _cmScModSymToVar(p, varSymId )) == NULL )
  3100. {
  3101. // ... then create it
  3102. vp = _cmScModulatorInsertVar(p,varSymId,kCalcModFl);
  3103. assert(vp!=NULL);
  3104. }
  3105. assert( min <= max);
  3106. vp->min = min;
  3107. vp->max = max;
  3108. vp->value = value;
  3109. return cmOkRC;
  3110. }
  3111. cmRC_t cmScModulatorReset( cmScModulator* p, cmCtx_t* ctx, unsigned scLocIdx )
  3112. {
  3113. _cmScModulatorReset(p,ctx,scLocIdx);
  3114. return cmScModulatorExec(p,scLocIdx);
  3115. }
  3116. void _cmScModUnlinkActive( cmScModulator* p, cmScModVar_t* vp, cmScModVar_t* pp )
  3117. {
  3118. // if vp is the first link on the chain
  3119. if( vp == p->alist )
  3120. p->alist = vp->alink;
  3121. // if vp is the last link on the chain
  3122. if( vp == p->elist )
  3123. p->elist = pp;
  3124. if( pp != NULL )
  3125. pp->alink = vp->alink;
  3126. vp->flags = cmClrFlag(vp->flags,kActiveModFl);
  3127. vp->alink = NULL;
  3128. vp->entry = NULL;
  3129. }
  3130. // If the requested parameter has a value then return it in *valPtr.
  3131. // If it does not then do nothing. This function applies scaling to RHS values.
  3132. cmRC_t _cmScModGetParam( cmScModulator* p, const cmScModParam_t* pp, double* valPtr )
  3133. {
  3134. cmRC_t rc = cmOkRC;
  3135. switch( pp->pid )
  3136. {
  3137. case kInvalidModPId:
  3138. break;
  3139. case kLiteralModPId:
  3140. *valPtr = pp->val;
  3141. break;
  3142. case kSymbolModPId:
  3143. {
  3144. cmScModVar_t* vp;
  3145. // get a pointer to the parameter variable
  3146. if((vp = _cmScModSymToVar(p, pp->symId )) == NULL )
  3147. {
  3148. rc = cmCtxRtCondition( &p->obj, cmInvalidArgRC, "Variable '%s' not found.",cmSymTblLabel(p->stH,pp->symId));
  3149. goto errLabel;
  3150. }
  3151. // if this is not a 'calculated' paramter then scale it here.
  3152. if( cmIsFlag(vp->flags,kCalcModFl ) && vp->min!=DBL_MAX && vp->max!=DBL_MAX )
  3153. *valPtr = (vp->value - vp->min)/(vp->max-vp->min);
  3154. else
  3155. *valPtr = vp->value;
  3156. }
  3157. break;
  3158. default:
  3159. { assert(0); }
  3160. }
  3161. errLabel:
  3162. return rc;
  3163. }
  3164. // Type specific variable activation -
  3165. cmRC_t _cmScModActivate(cmScModulator* p, cmScModEntry_t* ep )
  3166. {
  3167. cmRC_t rc = cmOkRC;
  3168. cmScModVar_t* vp = ep->varPtr;
  3169. // optionally update the min/max/rate values in the target var
  3170. if((rc = _cmScModGetParam(p,&ep->min,&vp->min)) != cmOkRC )
  3171. goto errLabel;
  3172. if((rc = _cmScModGetParam(p,&ep->max,&vp->max)) != cmOkRC )
  3173. goto errLabel;
  3174. if((rc = _cmScModGetParam(p,&ep->rate,&vp->rate)) != cmOkRC )
  3175. goto errLabel;
  3176. switch( ep->typeId )
  3177. {
  3178. case kSetModTId:
  3179. break;
  3180. case kLineModTId:
  3181. vp->v0 = vp->value;
  3182. vp->phase = 0;
  3183. break;
  3184. case kSetLineModTId:
  3185. _cmScModGetParam(p,&ep->beg,&vp->value); // starting value
  3186. vp->v0 = vp->value; // set initial value
  3187. vp->phase = 0; // reset phase
  3188. break;
  3189. default:
  3190. { assert(0); }
  3191. }
  3192. errLabel:
  3193. return rc;
  3194. }
  3195. // Callback the application with a new variable value.
  3196. cmRC_t _cmScModExecSendValue( cmScModulator* p, cmScModVar_t* vp )
  3197. {
  3198. cmRC_t rc = cmOkRC;
  3199. bool sendFl = true;
  3200. double v = vp->value;
  3201. // scale the output value - this is equiv to scaling the LHS
  3202. if( cmIsFlag(vp->flags,kCalcModFl) && vp->min!=DBL_MAX && vp->max!=DBL_MAX )
  3203. v = vp->min + v * (vp->max - vp->min);
  3204. // if an output rate throttle is in effect ....
  3205. if( vp->rate!=DBL_MAX && vp->phase!=0 )
  3206. sendFl = remainder(vp->phase*p->samplesPerCycle, p->srate*vp->rate/1000 ) < p->samplesPerCycle;
  3207. if(sendFl)
  3208. p->cbFunc(p->cbArg,vp->varSymId,v);
  3209. return rc;
  3210. }
  3211. // Return true if vp should be deactivated otherwise return false.
  3212. bool _cmScModExec( cmScModulator* p, cmScModVar_t* vp )
  3213. {
  3214. cmRC_t rc = cmOkRC;
  3215. bool fl = false;
  3216. switch( vp->entry->typeId )
  3217. {
  3218. case kSetModTId:
  3219. {
  3220. if((rc = _cmScModGetParam(p,&vp->entry->beg,&vp->value)) != cmOkRC )
  3221. goto errLabel;
  3222. vp->phase = 0; // force the value to be sent
  3223. fl = true;
  3224. }
  3225. break;
  3226. case kSetLineModTId:
  3227. case kLineModTId:
  3228. {
  3229. double v1, td;
  3230. // get the target value
  3231. if((rc = _cmScModGetParam(p,&vp->entry->end,&v1)) != cmOkRC)
  3232. goto errLabel;
  3233. // get the time duration
  3234. if((rc = _cmScModGetParam(p,&vp->entry->dur,&td)) != cmOkRC)
  3235. goto errLabel;
  3236. double v = vp->v0 + (v1-vp->v0) * (vp->phase * p->samplesPerCycle) / (p->srate * td);
  3237. if((fl = (vp->value <= v1 && v >= v1) || (vp->value >= v1 && v <= v1 )) == true )
  3238. v = v1;
  3239. vp->value = v;
  3240. }
  3241. break;
  3242. default:
  3243. { assert(0); }
  3244. }
  3245. // notify the application that a new variable value has been generated
  3246. rc = _cmScModExecSendValue(p,vp);
  3247. // increment the phase - after send because send notices when phase is zero
  3248. vp->phase += 1;
  3249. errLabel:
  3250. if( rc != cmOkRC )
  3251. fl = true;
  3252. return fl;
  3253. }
  3254. cmRC_t cmScModulatorExec( cmScModulator* p, unsigned scLocIdx )
  3255. {
  3256. cmRC_t trc;
  3257. cmRC_t rc = cmOkRC;
  3258. // trigger entries that have expired since the last call to this function
  3259. for(; p->nei<p->en && (p->earray[p->nei].scLocIdx==-1 || p->earray[p->nei].scLocIdx<=scLocIdx); ++p->nei)
  3260. {
  3261. cmScModEntry_t* ep = p->earray + p->nei;
  3262. // if the variable assoc'd with this entry is not on the active list ...
  3263. if( cmIsFlag(ep->varPtr->flags,kActiveModFl) == false )
  3264. {
  3265. // ... then append it to the end of the active list ...
  3266. ep->varPtr->flags |= kActiveModFl;
  3267. if( p->elist == NULL )
  3268. p->elist = ep->varPtr;
  3269. else
  3270. {
  3271. p->elist->alink = ep->varPtr;
  3272. p->elist = ep->varPtr;
  3273. }
  3274. p->elist->alink = NULL;
  3275. if( p->alist == NULL )
  3276. p->alist = ep->varPtr;
  3277. }
  3278. // do type specific activation
  3279. if((trc = _cmScModActivate(p,ep)) != cmOkRC )
  3280. rc = trc;
  3281. ep->varPtr->entry = ep;
  3282. }
  3283. cmScModVar_t* pp = NULL;
  3284. cmScModVar_t* vp = p->alist;
  3285. for(; vp!=NULL; vp=vp->alink)
  3286. {
  3287. if( _cmScModExec(p,vp) )
  3288. _cmScModUnlinkActive(p,vp,pp);
  3289. else
  3290. pp = vp;
  3291. }
  3292. return rc;
  3293. }
  3294. void _cmScModDumpParam( cmScModulator* p, const cmChar_t* label, cmScModParam_t* pp )
  3295. {
  3296. printf("%s: ",label);
  3297. switch( pp->pid )
  3298. {
  3299. case kInvalidModPId:
  3300. printf("<invalid>");
  3301. break;
  3302. case kLiteralModPId:
  3303. if( pp->val == DBL_MAX )
  3304. printf("<max> ");
  3305. else
  3306. printf("%f ",pp->val);
  3307. break;
  3308. case kSymbolModPId:
  3309. printf("%s ",cmSymTblLabel(p->stH,pp->symId));
  3310. break;
  3311. default:
  3312. { assert(0); }
  3313. }
  3314. }
  3315. void _cmScModDumpVal( cmChar_t* label, double val )
  3316. {
  3317. printf("%s:",label);
  3318. if( val == DBL_MAX )
  3319. printf("<max> " );
  3320. else
  3321. printf("%f ",val);
  3322. }
  3323. void _cmScModDumpVar( cmScModulator* p, const cmScModVar_t* vp )
  3324. {
  3325. printf("%7s %3i fl:0x%x entry:%p alink:%p ",cmSymTblLabel(p->stH,vp->varSymId),vp->outVarId,vp->flags,vp->entry,vp->alink);
  3326. _cmScModDumpVal("val",vp->value);
  3327. _cmScModDumpVal("min",vp->min);
  3328. _cmScModDumpVal("max",vp->max);
  3329. _cmScModDumpVal("rate",vp->rate);
  3330. _cmScModDumpVal("v0",vp->v0);
  3331. }
  3332. cmRC_t cmScModulatorDump( cmScModulator* p )
  3333. {
  3334. cmRC_t rc = cmOkRC;
  3335. printf("MOD:\n");
  3336. printf("nei:%i alist:%p outVarCnt:%i\n",p->nei,p->alist,p->outVarCnt);
  3337. printf("ENTRIES:\n");
  3338. unsigned i;
  3339. for(i=0; i<p->en; ++i)
  3340. {
  3341. cmScModEntry_t* ep = p->earray + i;
  3342. printf("%3i %4i %2i %7s ", i, ep->scLocIdx, ep->typeId, cmSymTblLabel(p->stH,ep->varPtr->varSymId));
  3343. _cmScModDumpParam(p," beg", &ep->beg);
  3344. _cmScModDumpParam(p," end", &ep->end);
  3345. _cmScModDumpParam(p," min", &ep->min);
  3346. _cmScModDumpParam(p," max", &ep->max);
  3347. _cmScModDumpParam(p," rate",&ep->rate);
  3348. printf("\n");
  3349. }
  3350. printf("VARIABLES\n");
  3351. cmScModVar_t* vp = p->vlist;
  3352. for(; vp!=NULL; vp=vp->vlink)
  3353. {
  3354. _cmScModDumpVar(p,vp);
  3355. printf("\n");
  3356. }
  3357. return rc;
  3358. }