libcm is a C development framework with an emphasis on audio signal processing applications.
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

cmProc4.c 94KB

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