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

cmProc4.c 100KB

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