libcm is a C development framework with an emphasis on audio signal processing applications.
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

cmProc4.c 94KB

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