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

cmProc3.c 88KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639
  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 "cmSymTbl.h"
  10. #include "cmFloatTypes.h"
  11. #include "cmComplexTypes.h"
  12. #include "cmFileSys.h"
  13. #include "cmJson.h"
  14. #include "cmProcObj.h"
  15. #include "cmProcTemplate.h"
  16. #include "cmAudioFile.h"
  17. #include "cmMath.h"
  18. #include "cmProc.h"
  19. #include "cmVectOps.h"
  20. #include "cmProc3.h"
  21. #include "cmMidi.h" // cmMidiToSciPitch();
  22. cmPitchShift* cmPitchShiftAlloc( cmCtx* c, cmPitchShift* p, unsigned procSmpCnt, cmReal_t srate )
  23. {
  24. cmPitchShift* op = cmObjAlloc(cmPitchShift, c, p );
  25. if( procSmpCnt != 0 )
  26. if( cmPitchShiftInit(op, procSmpCnt,srate) != cmOkRC )
  27. cmPitchShiftFree(&op);
  28. return op;
  29. }
  30. cmRC_t cmPitchShiftFinal(cmPitchShift* p )
  31. { return cmOkRC; }
  32. #define _cube_interp(x,y0,y1,y2,y3) ((y3) - (y2) - (y0) + (y1))*(x)*(x)*(x) + ((y0) - (y1) - ((y3) - (y2) - (y0) + (y1)))*(x)*(x) + ((y2) - (y0))*(x) + (y1)
  33. #define _lin_interp(x,y0,y1) (y0) + (x) * ((y1)-(y0))
  34. /*
  35. cmRC_t cmPitchShiftFree( cmPitchShift** pp )
  36. {
  37. cmRC_t rc = cmOkRC;
  38. if( pp != NULL && *pp != NULL )
  39. {
  40. cmPitchShift* p = *pp;
  41. if(( rc = cmPitchShiftFinal(p)) == cmOkRC )
  42. {
  43. cmMemPtrFree(&p->x);
  44. cmMemPtrFree(&p->y);
  45. cmMemPtrFree(&p->cf);
  46. cmObjFree(pp);
  47. }
  48. }
  49. return rc;
  50. }
  51. cmRC_t cmPitchShiftInit( cmPitchShift* p, unsigned procSmpCnt, double srate )
  52. {
  53. cmRC_t rc;
  54. if((rc = cmPitchShiftFinal(p)) != cmOkRC )
  55. return rc;
  56. p->procSmpCnt = procSmpCnt;
  57. p->srate = srate;
  58. p->wn = 4096;
  59. p->cfn = 1024;
  60. p->outN = p->procSmpCnt;
  61. p->x = cmMemResizeZ(cmSample_t, p->x,procSmpCnt + 3 );
  62. p->y = cmMemResizeZ(cmSample_t, p->y, p->wn );
  63. p->cf = cmMemResizeZ(cmSample_t, p->cf, p->cfn );
  64. p->pii = procSmpCnt + p->cfn;
  65. p->poi = 0;
  66. p->outV = p->y;
  67. p->prv_x0 = 0;
  68. p->prv_x1 = 0;
  69. p->genFl = true;
  70. p->xfi = 3;
  71. p->cfi = 0;
  72. p->cubeFl = true;
  73. p->linCfFl = true;
  74. assert( p->cfn+p->procSmpCnt < p->wn );
  75. unsigned i;
  76. for(i=0; i<p->cfn; ++i)
  77. {
  78. p->cf[i] = (sin(((double)i/p->cfn * M_PI) - (M_PI/2.0)) + 1.0) / 2.0;
  79. p->cf[i] = (double)i/p->cfn;
  80. }
  81. return rc;
  82. }
  83. // Algorithm:
  84. // 1. Generate srate converted values into p->y[] until it is full.
  85. // 2. Playback from y[] ignoring any incoming samples until less than
  86. // p->cfn + p->procSmpCnt samples remain in y[] (i.e. pii < procSmpCnt + cfn).
  87. // 3. At this point begin generating samples from the input and crossfading them
  88. // with the last cfn samples in y[].
  89. // 4. After cfn new samples have been crossfaded proceed to fill the remaining
  90. // space in y[]
  91. // 5. Goto 2.
  92. //
  93. // Note that since we are pitch shifting down (ratio<1.0) the number of samples generated
  94. // will always be greater than the number of input samples.
  95. //
  96. // Notes:
  97. // For small downward shifts there will be large time aliasing because the length of time
  98. // to fill the buffer (step 4) will because only a few extra samples
  99. // are generated on each input cycle. Try decreasing the window length as the pitch ratio increases.
  100. //
  101. // Implement smoothly varying ratio changes.
  102. //
  103. // Change model so that at ratio 1.0 the input is effectively being constantly cross faded to produce
  104. // identity output.
  105. void _cmPitchShiftDown( cmPitchShift* p, double ratio, const cmSample_t* x, unsigned xn )
  106. {
  107. // shift off the expired samples
  108. memmove(p->y,p->y + p->procSmpCnt, (p->pii - p->procSmpCnt) * sizeof(cmSample_t));
  109. p->pii -= p->procSmpCnt;
  110. // if not currently generating and there are less than cfn + procSmpCnt samples remaining ...
  111. if( p->genFl == false && p->pii <= p->procSmpCnt + p->cfn )
  112. {
  113. // ... then setup to begin generating
  114. p->cfi = 0;
  115. p->genFl = true;
  116. p->xfi = 3;
  117. }
  118. if( p->genFl )
  119. {
  120. // setup the incoming samples
  121. p->x[0] = p->prv_x0;
  122. p->x[1] = p->prv_x1;
  123. p->x[2] = p->prv_x2;
  124. memcpy(p->x+2,x,p->procSmpCnt*sizeof(cmSample_t));
  125. int n0 = p->cubeFl ? xn+1 : xn+2;
  126. // as long as there are incoming samples available and space left in the output buffer
  127. for(; p->xfi < n0 && p->pii < p->wn; p->xfi += ratio )
  128. {
  129. unsigned xii = floor(p->xfi);
  130. double frac = p->xfi - xii;
  131. // generate the value of the output sample
  132. cmSample_t value;
  133. if( p->cubeFl )
  134. value = _cube_interp(frac,p->x[xii-1],p->x[xii],p->x[xii+1],p->x[xii+2]);
  135. else
  136. value = p->x[ xii ] + frac * (p->x[ xii+1 ] - p->x[xii]);
  137. // if xfading
  138. if( p->cfi < p->cfn )
  139. {
  140. // calc index into y[] of the sample to crossfade with
  141. int idx = p->pii - p->cfn + p->cfi;
  142. p->y[idx] = (1.0 - p->cf[p->cfi]) * p->y[idx] + p->cf[p->cfi] * value;
  143. ++p->cfi;
  144. }
  145. else
  146. {
  147. // else fill the remaing space in y[]
  148. p->y[p->pii] = value;
  149. ++p->pii;
  150. }
  151. }
  152. // if the output buffer is full then stop generating
  153. if( p->pii == p->wn )
  154. p->genFl = false;
  155. }
  156. // reset the input index to the beginning of the buffer
  157. p->xfi -= xn;
  158. p->prv_x0 = x[xn-3];
  159. p->prv_x1 = x[xn-2];
  160. p->prv_x2 = x[xn-1];
  161. }
  162. cmRC_t cmPitchShiftExec( cmPitchShift* p, const cmSample_t* x, cmSample_t* y, unsigned n, double shiftRatio )
  163. {
  164. assert(n == p->procSmpCnt);
  165. if( shiftRatio >= 1 )
  166. memcpy(y,x,n*sizeof(cmSample_t));
  167. else
  168. {
  169. _cmPitchShiftDown(p,shiftRatio,x,n);
  170. if( y != NULL )
  171. memcpy(y,p->y,n*sizeof(cmSample_t));
  172. }
  173. return cmOkRC;
  174. }
  175. */
  176. cmRC_t cmPitchShiftFree( cmPitchShift** pp )
  177. {
  178. cmRC_t rc = cmOkRC;
  179. if( pp != NULL && *pp != NULL )
  180. {
  181. cmPitchShift* p = *pp;
  182. if(( rc = cmPitchShiftFinal(p)) == cmOkRC )
  183. {
  184. cmMemPtrFree(&p->b);
  185. cmMemPtrFree(&p->outV);
  186. cmMemPtrFree(&p->wnd);
  187. cmMemPtrFree(&p->osc[0].y);
  188. cmMemPtrFree(&p->osc[1].y);
  189. cmObjFree(pp);
  190. }
  191. }
  192. return rc;
  193. }
  194. /*
  195. cmRC_t cmPitchShiftInit( cmPitchShift* p, unsigned procSmpCnt, double srate)
  196. {
  197. cmRC_t rc;
  198. if((rc = cmPitchShiftFinal(p)) != cmOkRC )
  199. return rc;
  200. p->procSmpCnt = procSmpCnt;
  201. p->srate = srate;
  202. p->wn = 4096;
  203. p->in = 2*p->wn + p->procSmpCnt;
  204. p->outN = p->procSmpCnt;
  205. p->m = cmMemResizeZ(cmSample_t, p->m,p->in + 2 );
  206. p->x = p->m + 1;
  207. p->outV = cmMemResizeZ(cmSample_t, p->outV,procSmpCnt );
  208. p->wnd = cmMemResizeZ(cmSample_t, p->wnd, p->wn+1 );
  209. p->ii = 1;
  210. p->cubeFl = true;
  211. p->ei0 = -1;
  212. p->ei1 = -1;
  213. p->osc[0].ratio = 1.0;
  214. p->osc[0].wi = 0;
  215. p->osc[0].xi = 0;
  216. p->osc[0].yN = 2*p->wn;
  217. p->osc[0].y = cmMemResizeZ(cmSample_t, p->osc[0].y, p->osc[0].yN );
  218. p->osc[0].yii = 0;
  219. p->osc[0].yoi = 0;
  220. p->osc[0].ynn = 0;
  221. p->osc[1].ratio = 1.0;
  222. p->osc[1].wi = floor(p->wn/2);
  223. p->osc[1].xi = 0;
  224. p->osc[1].yN = 2*p->wn;
  225. p->osc[1].y = cmMemResizeZ(cmSample_t, p->osc[1].y, p->osc[1].yN );
  226. p->osc[1].yii = 0;
  227. p->osc[1].yoi = 0;
  228. p->osc[1].ynn = 0;
  229. assert( p->in >= p->procSmpCnt + 1 );
  230. cmVOS_Hann( p->wnd, p->wn+1 );
  231. return rc;
  232. }
  233. #define _isInNoGoZone(p,i) ( ((0 <= (i)) && ((i) <= (p)->ei0)) || (((p)->ii <= (i)) && ((i) <= (p)->ei1)) )
  234. #define _isNotInNoGoZone(p,i) (!_isInNoGoZone(p,i))
  235. void _startNewWindow( cmPitchShift* p, cmPitchShiftOsc_t* op, int li, double ratio)
  236. {
  237. op->wi = 0;
  238. if( op->ratio < 1.0 )
  239. op->xi = p->ii - p->procSmpCnt;
  240. else
  241. op->xi = p->ii + (li)*(p->procSmpCnt/ratio);
  242. while( op->xi < 0 )
  243. op->xi += p->in-1;
  244. while( op->xi > (p->in-1) )
  245. op->xi -= (p->in-1);
  246. op->xi = floor(op->xi);
  247. }
  248. void _cmPitchShiftOsc( cmPitchShift* p, cmPitchShiftOsc_t* op, double ratio )
  249. {
  250. int li = 0;
  251. bool contFl = 1;
  252. // if we are waiting to start a new window until the output buffer drains
  253. if( op->wi==-1 )
  254. {
  255. // if the output buffer has enough samples to complete this cycle - return
  256. if(op->ynn >= p->procSmpCnt)
  257. return;
  258. // otherwise start a new window
  259. _startNewWindow(p,op,li,ratio);
  260. }
  261. // iterate until all output samples have been generated
  262. for(li=0; contFl; ++li)
  263. {
  264. // iterate over one window or until output is complete
  265. while( op->wi < p->wn )
  266. {
  267. int wii = floor(op->wi);
  268. double frac = op->wi - wii;
  269. int xii = (op->xi + wii) % (p->in-1);
  270. cmSample_t wnd = p->wnd[ wii ] + frac * (p->wnd[wii+1] - p->wnd[wii]);
  271. cmSample_t val;
  272. // if enough samples have been generated and the next input will not be in the no-go zone
  273. if( (op->ynn >= p->procSmpCnt) && _isNotInNoGoZone(p,xii-1) && _isNotInNoGoZone(p,xii+2) )
  274. {
  275. contFl = false;
  276. break;
  277. }
  278. if( op->ynn >= op->yN )
  279. {
  280. printf("OVER\n");
  281. contFl = false;
  282. break;
  283. }
  284. // generate the value of the output sample
  285. if( p->cubeFl )
  286. val = _cube_interp(frac,p->x[xii-1],p->x[xii],p->x[xii+1],p->x[xii+2]);
  287. else
  288. val = p->x[ xii ] + frac * (p->x[ xii+1 ] - p->x[xii]);
  289. // apply the window function and assign to output
  290. op->y[op->yii] = wnd * val;
  291. // incr the count of samples in y[]
  292. ++op->ynn;
  293. // advance the output buffers input location
  294. op->yii = (op->yii + 1) % op->yN;
  295. op->wi += ratio; // increment the window location
  296. }
  297. // if a window completed
  298. if( op->wi >= p->wn )
  299. {
  300. if( (ratio < 1.0) && (op->ynn >= p->procSmpCnt) )
  301. {
  302. op->wi = -1;
  303. break;
  304. }
  305. _startNewWindow(p,op,li+1,ratio);
  306. }
  307. }
  308. }
  309. // in=5
  310. // m x
  311. // 0 1 2 3 4 5
  312. // 1 x x a b c d e
  313. // 2 c d e f g h i
  314. // 3 g h i j k l m
  315. //
  316. // ratio < 1 - the output oscillators must be able to generate 1 complete window prior to new samples
  317. // overwriting the oscillators location in the input buffer.
  318. cmRC_t cmPitchShiftExec( cmPitchShift* p, const cmSample_t* x, cmSample_t* y, unsigned xn, double ratio )
  319. {
  320. cmRC_t rc = cmOkRC;
  321. //memcpy(y,x,xn*sizeof(cmSample_t));
  322. //return rc;
  323. int i;
  324. // copy in the incoming samples
  325. for(i=0; i<xn; ++i)
  326. {
  327. p->x[p->ii] = x[i];
  328. ++p->ii;
  329. if( p->ii == p->in+1 )
  330. {
  331. p->x[-1] = p->x[p->in-2];
  332. p->x[ 0] = p->x[p->in-1];
  333. p->x[ 1] = p->x[p->in];
  334. p->ii = 2;
  335. }
  336. }
  337. // locate the section of the input buffer which
  338. // will be written over on the next cycle.
  339. // The oscillators have to avoid ending in this area
  340. if( (p->in+1) - p->ii >= p->procSmpCnt )
  341. {
  342. p->ei1 = p->ii + p->procSmpCnt - 1;
  343. p->ei0 = -1;
  344. }
  345. else
  346. {
  347. int n = (p->in+1) - p->ii;
  348. p->ei1 = (p->ii + n) - 1;
  349. p->ei0 = (p->procSmpCnt - n) - 1;
  350. }
  351. //memset(p->outV,0,p->procSmpCnt*sizeof(cmSample_t));
  352. _cmPitchShiftOsc(p, p->osc + 0, ratio );
  353. _cmPitchShiftOsc(p, p->osc + 1, ratio );
  354. // mix the indidual output of the two oscillators to form the final output
  355. if( p->osc[0].ynn < p->procSmpCnt || p->osc[1].ynn < p->procSmpCnt )
  356. printf("UNDER\n");
  357. for(i=0; i<p->procSmpCnt; ++i)
  358. {
  359. p->outV[i] = p->osc[0].y[p->osc[0].yoi] + p->osc[1].y[p->osc[1].yoi];
  360. p->osc[0].yoi = (p->osc[0].yoi + 1) % p->osc[0].yN;
  361. p->osc[1].yoi = (p->osc[1].yoi + 1) % p->osc[1].yN;
  362. }
  363. p->osc[0].ynn -= p->procSmpCnt;
  364. p->osc[1].ynn -= p->procSmpCnt;
  365. if( y != NULL )
  366. memcpy(y,p->outV,p->outN*sizeof(cmSample_t));
  367. return rc;
  368. }
  369. */
  370. cmRC_t cmPitchShiftInit( cmPitchShift* p, unsigned procSmpCnt, double srate)
  371. {
  372. cmRC_t rc;
  373. if((rc = cmPitchShiftFinal(p)) != cmOkRC )
  374. return rc;
  375. p->procSmpCnt = procSmpCnt;
  376. p->outN = procSmpCnt;
  377. p->outV = cmMemAllocZ(cmSample_t,procSmpCnt);
  378. p->wn = 2048;
  379. p->xn = 2*p->wn + procSmpCnt;
  380. p->bn = p->xn + 3;
  381. p->b = cmMemAllocZ(cmSample_t,p->bn);
  382. p->x = p->b + 1;
  383. p->wnd = cmMemAllocZ(cmSample_t,p->wn+1);
  384. p->xni = p->xn - procSmpCnt + 2;
  385. p->cubeFl = true;
  386. int i;
  387. for(i=0; i<2; ++i)
  388. {
  389. cmPitchShiftOsc_t* op = p->osc + i;
  390. op->xi = p->procSmpCnt;
  391. op->yn = p->wn * 2;
  392. op->y = cmMemAllocZ(cmSample_t,op->yn);
  393. op->yii= 0;
  394. op->yoi= 0;
  395. op->ynn= 0;
  396. op->wi = i==0 ? 0 : p->wn/2;
  397. }
  398. cmVOS_Hann(p->wnd,p->wn+1);
  399. return rc;
  400. }
  401. void _cmPitchShiftOscExec( cmPitchShift* p, cmPitchShiftOsc_t* op, double ratio )
  402. {
  403. int k = 0;
  404. // account for right buffer shift on input
  405. op->xi -= p->procSmpCnt;
  406. // pass through code for testing
  407. if(0)
  408. {
  409. int i;
  410. for(i=0; i<p->procSmpCnt; ++i)
  411. {
  412. op->y[op->yii] = p->x[ (int)floor(op->xi) ];
  413. op->yii = (op->yii + 1) % op->yn;
  414. op->ynn += 1;
  415. op->xi += 1.0;
  416. }
  417. return;
  418. }
  419. while(1)
  420. {
  421. int wii = floor(op->wi);
  422. double wfrac = op->wi - wii;
  423. int xii = floor(op->xi);
  424. double vfrac = op->xi - xii;
  425. cmSample_t val;
  426. // if enough output samples have been generated and we are outside the no-land zone
  427. if( (op->ynn >= p->procSmpCnt && op->xi >= p->procSmpCnt) )
  428. break;
  429. if( op->xi >= p->xn )
  430. {
  431. //printf("Wrap %f %f\n",op->xi,op->wi);
  432. }
  433. cmSample_t wnd = p->wnd[ wii ] + wfrac * (p->wnd[wii+1] - p->wnd[wii]);
  434. // generate the value of the output sample
  435. if( p->cubeFl )
  436. val = _cube_interp(vfrac,p->x[xii-1],p->x[xii],p->x[xii+1],p->x[xii+2]);
  437. else
  438. val = p->x[ xii ] + vfrac * (p->x[ xii+1 ] - p->x[xii]);
  439. // apply the window function and assign to output
  440. op->y[op->yii] = wnd * val;
  441. // incr the count of samples in y[]
  442. ++op->ynn;
  443. // advance the output buffers input location
  444. op->yii = (op->yii + 1) % op->yn;
  445. op->wi += ratio<1 ? 1 : ratio; // increment the window location
  446. op->xi += ratio;
  447. if( op->wi >= p->wn )
  448. {
  449. ++k;
  450. op->wi = 0;
  451. if( ratio < 1 )
  452. op->xi = p->xni; // begin of most recent block of procSmpCnt input samples
  453. else
  454. op->xi = k*p->procSmpCnt/ratio;
  455. }
  456. }
  457. //if( op->ynn != p->procSmpCnt )
  458. // printf("wi:%f xi:%f ynn:%i\n",op->wi,op->xi,op->ynn);
  459. }
  460. // b: 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17
  461. // x: -1 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16
  462. //
  463. // On each cycle:
  464. // 1) shift x[] left by procSmpCnt samples.
  465. // 2) add new samples on right side of x[]
  466. // 3) oscillator scans from right to left.
  467. cmRC_t cmPitchShiftExec( cmPitchShift* p, const cmSample_t* x, cmSample_t* y, unsigned xn, double ratio, bool bypassFl )
  468. {
  469. if(0)
  470. {
  471. memcpy(p->outV,x,xn*sizeof(cmSample_t));
  472. if( y != NULL )
  473. memcpy(y,x,xn*sizeof(cmSample_t));
  474. return cmOkRC;
  475. }
  476. if( y == NULL )
  477. return cmOkRC;
  478. if( x == NULL )
  479. {
  480. cmVOS_Zero(y,xn);
  481. return cmOkRC;
  482. }
  483. if( bypassFl )
  484. {
  485. memcpy(p->outV,x,xn*sizeof(cmSample_t));
  486. if( y != NULL )
  487. memcpy(y,x,xn*sizeof(cmSample_t));
  488. return cmOkRC;
  489. }
  490. int i;
  491. memmove(p->x - 1, p->x+p->procSmpCnt-1,(p->xn - p->procSmpCnt + 3)*sizeof(cmSample_t));
  492. memcpy( p->x + p->xni, x, xn * sizeof(cmSample_t) );
  493. //memmove(p->x + p->procSmpCnt -1, p->x - 1, (p->xn - p->procSmpCnt + 3) * sizeof(cmSample_t));
  494. //memcpy( p->x-1, x, xn * sizeof(cmSample_t));
  495. _cmPitchShiftOscExec(p, p->osc + 0, ratio );
  496. _cmPitchShiftOscExec(p, p->osc + 1, ratio );
  497. // mix the indidual output of the two oscillators to form the final output
  498. if( p->osc[0].ynn < p->procSmpCnt || p->osc[1].ynn < p->procSmpCnt )
  499. printf("UNDER\n");
  500. for(i=0; i<p->procSmpCnt; ++i)
  501. {
  502. p->outV[i] = p->osc[0].y[p->osc[0].yoi] + p->osc[1].y[p->osc[1].yoi];
  503. p->osc[0].yoi = (p->osc[0].yoi + 1) % p->osc[0].yn;
  504. p->osc[1].yoi = (p->osc[1].yoi + 1) % p->osc[1].yn;
  505. }
  506. p->osc[0].ynn -= p->procSmpCnt;
  507. p->osc[1].ynn -= p->procSmpCnt;
  508. if( y != NULL )
  509. memcpy(y,p->outV,xn*sizeof(cmSample_t));
  510. return cmOkRC;
  511. }
  512. //=======================================================================================================================
  513. cmLoopRecord* cmLoopRecordAlloc(
  514. cmCtx* c, cmLoopRecord* p, unsigned procSmpCnt, unsigned maxRecdSmpCnt, unsigned xfadeSmpCnt )
  515. {
  516. cmLoopRecord* op = cmObjAlloc(cmLoopRecord, c, p );
  517. if( procSmpCnt != 0 )
  518. if( cmLoopRecordInit(op, procSmpCnt, maxRecdSmpCnt, xfadeSmpCnt) != cmOkRC )
  519. cmLoopRecordFree(&op);
  520. return op;
  521. }
  522. /*
  523. cmRC_t cmLoopRecordFree( cmLoopRecord** pp )
  524. {
  525. cmRC_t rc = cmOkRC;
  526. if( pp != NULL && *pp != NULL )
  527. {
  528. cmLoopRecord* p = *pp;
  529. if(( rc = cmLoopRecordFinal(p)) == cmOkRC )
  530. {
  531. cmMemPtrFree(&p->bufMem);
  532. cmMemPtrFree(&p->bufArray);
  533. cmMemPtrFree(&p->outV);
  534. cmMemPtrFree(&p->xfadeFunc);
  535. cmObjFree(pp);
  536. }
  537. }
  538. return rc;
  539. }
  540. cmRC_t cmLoopRecordInit( cmLoopRecord* p, unsigned procSmpCnt, unsigned maxRecdSmpCnt, unsigned xfadeSmpCnt )
  541. {
  542. cmRC_t rc;
  543. unsigned i;
  544. if((rc = cmLoopRecordFinal(p)) != cmOkRC )
  545. return rc;
  546. assert( xfadeSmpCnt < maxRecdSmpCnt );
  547. p->maxRecdSmpCnt = maxRecdSmpCnt;
  548. p->bufArrayCnt = 2;
  549. p->bufMem = cmMemResizeZ( cmSample_t, p->bufMem, maxRecdSmpCnt * p->bufArrayCnt );
  550. p->bufArray = cmMemResizeZ( cmLoopRecdBuf, p->bufArray, p->bufArrayCnt );
  551. p->outV = cmMemResizeZ( cmSample_t, p->outV, procSmpCnt );
  552. p->xfadeFunc = cmMemResizeZ( cmSample_t, p->xfadeFunc, xfadeSmpCnt+1 );
  553. p->outN = procSmpCnt;
  554. p->procSmpCnt = procSmpCnt;
  555. p->xfadeSmpCnt = xfadeSmpCnt;
  556. p->recdBufIdx = 0;
  557. p->playBufIdx = 1;
  558. p->recdFl = false;
  559. p->playFl = false;
  560. for(i=0; i<p->bufArrayCnt; ++i)
  561. {
  562. p->bufArray[i].bV = p->bufMem + (i * maxRecdSmpCnt);
  563. p->bufArray[i].bN = maxRecdSmpCnt;
  564. p->bufArray[i].xfi = xfadeSmpCnt;
  565. }
  566. for(i=0; i<=p->xfadeSmpCnt; ++i)
  567. p->xfadeFunc[i] = (cmReal_t)i/p->xfadeSmpCnt;
  568. return rc;
  569. }
  570. cmRC_t cmLoopRecordFinal( cmLoopRecord* p )
  571. { return cmOkRC; }
  572. cmRC_t cmLoopRecordExec( cmLoopRecord* p, const cmSample_t* x, cmSample_t* y, unsigned xn, bool recdFl, bool playFl )
  573. {
  574. unsigned i;
  575. // if the recdFl was enabled
  576. if(recdFl==true && p->recdFl==false)
  577. {
  578. p->recdFl = true;
  579. p->bufArray[p->recdBufIdx].bii = 0;
  580. p->bufArray[p->recdBufIdx].boi = 0;
  581. printf("Recd:on %i\n",p->recdBufIdx);
  582. }
  583. else
  584. // if the recdFl was disabled
  585. if( recdFl==false && p->recdFl==true )
  586. {
  587. p->recdFl = false;
  588. playFl = true;
  589. p->playBufIdx = p->recdBufIdx;
  590. p->recdBufIdx = (p->recdBufIdx + 1) % p->bufArrayCnt;
  591. printf("Recd:off\n");
  592. }
  593. // if the playFl triggered on
  594. if( playFl==true && p->playFl==false)
  595. {
  596. p->bufArray[p->playBufIdx].boi = 0;
  597. p->playFl = true;
  598. //printf("Play:on %i %i\n",p->playBufIdx,p->bufArray[p->playBufIdx].bii);
  599. }
  600. // if recording
  601. if( p->recdFl )
  602. {
  603. cmLoopRecdBuf* rp = p->bufArray + p->recdBufIdx;
  604. for(i=0; i<xn && rp->bii < rp->bN; ++i,++rp->bii)
  605. {
  606. rp->bV[ rp->bii ] = x[i];
  607. }
  608. p->recdFl = rp->bii != rp->bN;
  609. }
  610. // if playing
  611. if( p->playFl )
  612. {
  613. cmLoopRecdBuf* rp = p->bufArray + p->playBufIdx;
  614. unsigned xf0n = p->xfadeSmpCnt/2;
  615. unsigned xf1n = rp->bii - p->xfadeSmpCnt/2;
  616. unsigned xfi0 = (rp->boi + p->xfadeSmpCnt/2) % rp->bii;
  617. for(i=0; i<xn; ++i)
  618. {
  619. bool fl = rp->boi < xf0n || rp->boi > xf1n;
  620. cmSample_t env = fl ? p->xfadeFunc[ rp->xfi ] : 1;
  621. p->outV[i] = ((1.0-env) * rp->bV[ rp->boi ]) + (env * rp->bV[ xfi0 ]);
  622. rp->boi = (rp->boi + 1) % rp->bii;
  623. xfi0 = (xfi0 + 1) % rp->bii;
  624. }
  625. }
  626. if( y != NULL )
  627. memcpy(y,p->outV,xn*sizeof(cmSample_t));
  628. return cmOkRC;
  629. }
  630. */
  631. cmRC_t cmLoopRecordFree( cmLoopRecord** pp )
  632. {
  633. cmRC_t rc = cmOkRC;
  634. if( pp != NULL && *pp != NULL )
  635. {
  636. cmLoopRecord* p = *pp;
  637. if(( rc = cmLoopRecordFinal(p)) == cmOkRC )
  638. {
  639. cmMemPtrFree(&p->bufMem);
  640. cmMemPtrFree(&p->bufArray);
  641. cmMemPtrFree(&p->outV);
  642. cmObjFree(pp);
  643. }
  644. }
  645. return rc;
  646. }
  647. cmRC_t cmLoopRecordInit( cmLoopRecord* p, unsigned procSmpCnt, unsigned maxRecdSmpCnt, unsigned xfadeSmpCnt )
  648. {
  649. cmRC_t rc;
  650. unsigned i;
  651. if((rc = cmLoopRecordFinal(p)) != cmOkRC )
  652. return rc;
  653. assert( xfadeSmpCnt < maxRecdSmpCnt );
  654. p->maxRecdSmpCnt = maxRecdSmpCnt;
  655. p->bufArrayCnt = 2;
  656. p->bufMem = cmMemResizeZ( cmSample_t, p->bufMem, (maxRecdSmpCnt+3) * p->bufArrayCnt * 2 );
  657. p->bufArray = cmMemResizeZ( cmLoopRecdBuf, p->bufArray, p->bufArrayCnt );
  658. p->outV = cmMemResizeZ( cmSample_t, p->outV, procSmpCnt );
  659. p->outN = procSmpCnt;
  660. p->procSmpCnt = procSmpCnt;
  661. p->xfadeSmpCnt = xfadeSmpCnt;
  662. p->recdBufIdx = 0;
  663. p->playBufIdx = 1;
  664. p->recdFl = false;
  665. p->playFl = false;
  666. for(i=0; i<p->bufArrayCnt; ++i)
  667. {
  668. p->bufArray[i].xV = p->bufMem + ((2 * i + 0) * (maxRecdSmpCnt+3)) + 1;
  669. p->bufArray[i].xN = maxRecdSmpCnt;
  670. p->bufArray[i].xii = 0;
  671. p->bufArray[i].wV = p->bufMem + ((2 * i + 1) * (maxRecdSmpCnt+3));
  672. }
  673. return rc;
  674. }
  675. cmRC_t cmLoopRecordFinal( cmLoopRecord* p )
  676. { return cmOkRC; }
  677. void _cmLoopRecordOscExec( cmLoopRecord* p, cmLoopRecdBuf* rp, cmLoopRecdOsc* op, double ratio )
  678. {
  679. unsigned i;
  680. for(i=0; i<p->outN; ++i)
  681. {
  682. int xi = floor(op->xi);
  683. double vfrac = op->xi - xi;
  684. cmSample_t val = _cube_interp(vfrac,rp->xV[xi-1],rp->xV[xi],rp->xV[xi+1],rp->xV[xi+2]);
  685. int wi = floor(op->wi);
  686. double wfrac = op->wi - wi;
  687. cmSample_t wnd = rp->wV[ wi ] + wfrac * (rp->wV[wi+1] - rp->wV[wi]);
  688. wnd = (wnd - 0.5) * op->u + 0.5;
  689. p->outV[i] += wnd * val;
  690. op->wi += ratio;
  691. if( op->wi >= rp->xii )
  692. {
  693. op->wi -= rp->xii;
  694. op->u *= -1.0;
  695. }
  696. op->xi += ratio;
  697. if( op->xi >= rp->xii )
  698. op->xi -= rp->xii;
  699. }
  700. }
  701. //
  702. // a b c d e f g h i - osc 0 sample value
  703. // 0.0 .25 0.5 .75 1.0 1.0 .75 0.5 .25 - osc 0 window value
  704. //
  705. // e f g h i a b c d - osc 1 sample value
  706. // 1.0 .75 0.5 .25 0.0 0.0 .25 0.5 .75 - osc 1 window value
  707. //
  708. // Notes:
  709. // 1) The window values transition through zero
  710. // at the loop point.
  711. // 2)
  712. cmRC_t cmLoopRecordExec( cmLoopRecord* p, const cmSample_t* x, cmSample_t* y, unsigned xn, bool bypassFl, bool recdFl, bool playFl, double ratio, double pgain, double rgain )
  713. {
  714. int i,j;
  715. assert( xn <= p->outN );
  716. if( bypassFl )
  717. {
  718. memcpy(p->outV,x,xn*sizeof(cmSample_t));
  719. if( y != NULL )
  720. {
  721. //memcpy(y,x,xn*sizeof(cmSample_t));
  722. cmVOS_MultVVS(y,xn,x,pgain);
  723. }
  724. return cmOkRC;
  725. }
  726. // if the recdFl was enabled
  727. if(recdFl==true && p->recdFl==false)
  728. {
  729. p->recdFl = true;
  730. p->bufArray[p->recdBufIdx].xii = 0;
  731. //printf("Recd:on %i\n",p->recdBufIdx);
  732. }
  733. else
  734. // if the recdFl was disabled
  735. if( recdFl==false && p->recdFl==true )
  736. {
  737. cmLoopRecdBuf* rp = p->bufArray + p->recdBufIdx;
  738. // arrange the 'wrap-around' samples
  739. rp->xV[-1] = rp->xV[rp->xii-1];
  740. rp->xV[rp->xii ] = rp->xV[0];
  741. rp->xV[rp->xii+1] = rp->xV[1];
  742. // calc the length of the cross-fade
  743. if( rp->xii < p->xfadeSmpCnt * 2)
  744. rp->xfN = rp->xii/2;
  745. else
  746. rp->xfN = p->xfadeSmpCnt;
  747. assert( rp->xfN > 0 );
  748. // fill the crossfade window with zeros
  749. cmVOS_Zero(rp->wV,rp->xii);
  750. // fill the last xfN samples in the xfade window vector with a fade-in slope
  751. int xfi = rp->xii - rp->xfN;
  752. for(j=0; j<rp->xfN; ++j)
  753. rp->wV[xfi+j] = (cmSample_t)j/rp->xfN;
  754. // initialize the oscillators
  755. for(j=0; j<2; ++j)
  756. {
  757. //
  758. rp->osc[j].xi = j==0 ? 0.0 : rp->xfN; // oscillators are p->xfN samples out of phase
  759. rp->osc[j].u = j==0 ? 1.0 : -1.0; // set windows to have opposite polarity
  760. rp->osc[j].wi = xfi; // begin window at cross-fade
  761. }
  762. p->recdFl = false;
  763. p->playFl = true;
  764. p->playBufIdx = p->recdBufIdx;
  765. p->recdBufIdx = (p->recdBufIdx + 1) % p->bufArrayCnt;
  766. //printf("Recd:off\n");
  767. }
  768. // if recording
  769. if( p->recdFl )
  770. {
  771. cmLoopRecdBuf* rp = p->bufArray + p->recdBufIdx;
  772. for(i=0; i<xn && rp->xii < rp->xN; ++i,++rp->xii)
  773. {
  774. rp->xV[ rp->xii ] = x[i];
  775. }
  776. }
  777. if( playFl && p->bufArray[p->playBufIdx].xii > 0 )
  778. {
  779. p->playFl = !p->playFl;
  780. if( p->playFl )
  781. {
  782. // reset oscillators to start at the begin of loop
  783. }
  784. }
  785. if( p->playFl )
  786. {
  787. cmLoopRecdBuf* rp = p->bufArray + p->playBufIdx;
  788. cmVOS_Zero(p->outV,p->outN);
  789. _cmLoopRecordOscExec(p,rp, rp->osc + 0, ratio );
  790. _cmLoopRecordOscExec(p,rp, rp->osc + 1, ratio );
  791. }
  792. if( y != NULL )
  793. {
  794. //memcpy(y,p->outV,xn*sizeof(cmSample_t));
  795. for(i=0; i<p->outN; ++i)
  796. y[i] = (pgain * x[i]) + (rgain * p->outV[i]);
  797. }
  798. return cmOkRC;
  799. }
  800. //=======================================================================================================================
  801. cmGateDetect* cmGateDetectAlloc( cmCtx* c, cmGateDetect* p, unsigned procSmpCnt, cmReal_t onThreshPct, cmReal_t onThreshDb, cmReal_t offThreshDb )
  802. {
  803. cmGateDetect* op = cmObjAlloc(cmGateDetect, c, p );
  804. if( procSmpCnt != 0 )
  805. if( cmGateDetectInit(op, procSmpCnt, onThreshPct, onThreshDb, offThreshDb) != cmOkRC )
  806. cmGateDetectFree(&op);
  807. return op;
  808. }
  809. cmRC_t cmGateDetectFree( cmGateDetect** pp )
  810. {
  811. cmRC_t rc;
  812. if( pp==NULL || *pp == NULL )
  813. return cmOkRC;
  814. cmGateDetect* p = *pp;
  815. if((rc = cmGateDetectFinal(p)) != cmOkRC )
  816. return rc;
  817. cmMemPtrFree(&p->rmsV);
  818. cmMemPtrFree(&p->wndV);
  819. cmObjFree(pp);
  820. return cmOkRC;
  821. }
  822. cmRC_t cmGateDetectInit( cmGateDetect* p, unsigned procSmpCnt, cmReal_t onThreshPct, cmReal_t onThreshDb, cmReal_t offThreshDb )
  823. {
  824. cmRC_t rc;
  825. if((rc = cmGateDetectFinal(p)) != cmOkRC )
  826. return rc;
  827. p->rmsN = 3;
  828. p->rmsV = cmMemResizeZ(cmSample_t,p->rmsV,p->rmsN);
  829. p->wndN = 9;
  830. p->wndV = cmMemResizeZ(cmSample_t,p->wndV,p->wndN);
  831. p->rms = 0;
  832. p->durSmpCnt = 0;
  833. p->gateFl = false;
  834. p->deltaFl = false;
  835. p->onThreshPct = onThreshPct;
  836. p->onThreshDb = onThreshDb;
  837. p->offThreshDb = offThreshDb;
  838. return rc;
  839. }
  840. cmRC_t cmGateDetectFinal(cmGateDetect* p )
  841. {
  842. return cmOkRC;
  843. }
  844. cmRC_t cmGateDetectExec22( cmGateDetect* p, const cmSample_t* x, unsigned xn )
  845. {
  846. p->deltaFl = false;
  847. p->rms = cmVOS_RMS(x,xn,xn);
  848. cmReal_t db = p->rms==0 ? -100 : 20*log10(p->rms);
  849. //cmSample_t b0 = 0;
  850. cmSample_t b1 = 0;
  851. cmVOS_Shift(p->rmsV,p->rmsN,-1,p->rms);
  852. // if gate is on
  853. if( p->gateFl )
  854. {
  855. p->deltaFl = db < p->offThreshDb;
  856. }
  857. else
  858. {
  859. //cmVOS_Lsq1(NULL,p->rmsV,p->rmsN,&b0,&b1);
  860. // p->deltaFl = b1 > p->onThreshPct && db > p->onThreshDb;
  861. unsigned i;
  862. for(i=0; i<p->rmsN-1; ++i)
  863. b1 += p->rmsV[i+1] - p->rmsV[i];
  864. b1 /= p->rmsN;
  865. p->deltaFl = b1 > p->onThreshPct && db > p->onThreshDb;
  866. }
  867. if( p->deltaFl )
  868. {
  869. p->gateFl = !p->gateFl;
  870. p->durSmpCnt = xn;
  871. }
  872. else
  873. {
  874. p->durSmpCnt += xn;
  875. }
  876. //p->rms = b1;
  877. //printf("%f %f %i %f;\n",db,p->rms,p->deltaFl,b1);
  878. return cmOkRC;
  879. }
  880. cmRC_t cmGateDetectExec( cmGateDetect* p, const cmSample_t* x, unsigned xn )
  881. {
  882. p->deltaFl = false;
  883. p->rms = cmVOS_RMS(x,xn,xn);
  884. cmReal_t db = p->rms==0 ? -100 : 20*log10(p->rms);
  885. unsigned i;
  886. cmSample_t d = 0;
  887. // update the rms window
  888. cmVOS_Shift(p->rmsV,p->rmsN,-1,p->rms);
  889. // calc. derr of RMS
  890. for(i=0; i<p->rmsN-1; ++i)
  891. d += p->rmsV[i+1] - p->rmsV[i];
  892. d /= p->rmsN;
  893. // zero negative derr's
  894. d = d<0 ? 0 : d;
  895. // update the peak window
  896. cmVOS_Shift(p->wndV,p->wndN,-1,d);
  897. p->mean = cmVOS_Mean(p->wndV,p->wndN);
  898. // if this is an offset
  899. if( p->gateFl && db < p->offThreshDb )
  900. {
  901. p->gateFl = false;
  902. p->deltaFl = true;
  903. }
  904. else
  905. // if this may be an onset.
  906. if( db > p->onThreshDb )
  907. {
  908. i = p->wndN - 2;
  909. // if previous derr was a peak
  910. if( p->wndV[i]>0 && p->wndV[i-1] < p->wndV[i] && p->wndV[i] > p->wndV[i+1] )
  911. {
  912. // and the peak is the largest value in the exteneded window
  913. if( p->wndV[i] > p->mean )
  914. {
  915. p->deltaFl = true;
  916. p->gateFl = true;
  917. p->durSmpCnt = 0;
  918. }
  919. }
  920. }
  921. if( p->gateFl )
  922. p->durSmpCnt += xn;
  923. p->rms = p->d0;
  924. p->d0 = d;
  925. return cmOkRC;
  926. }
  927. //=======================================================================================================================
  928. cmGateDetect2* cmGateDetectAlloc2( cmCtx* c, cmGateDetect2* p, unsigned procSmpCnt, const cmGateDetectParams* args )
  929. {
  930. cmGateDetect2* op = cmObjAlloc(cmGateDetect2, c, p );
  931. if( procSmpCnt != 0 )
  932. if( cmGateDetectInit2(op, procSmpCnt, args) != cmOkRC )
  933. cmGateDetectFree2(&op);
  934. return op;
  935. }
  936. cmRC_t cmGateDetectFree2( cmGateDetect2** pp )
  937. {
  938. cmRC_t rc;
  939. if( pp==NULL || *pp == NULL )
  940. return cmOkRC;
  941. cmGateDetect2* p = *pp;
  942. if((rc = cmGateDetectFinal2(p)) != cmOkRC )
  943. return rc;
  944. cmMemPtrFree(&p->medV);
  945. cmObjFree(pp);
  946. return cmOkRC;
  947. }
  948. cmRC_t cmGateDetectInit2( cmGateDetect2* p, unsigned procSmpCnt, const cmGateDetectParams* args )
  949. {
  950. cmRC_t rc;
  951. if((rc = cmGateDetectFinal2(p)) != cmOkRC )
  952. return rc;
  953. unsigned pkCnt = 3;
  954. unsigned eleCnt = 3*args->medCnt + args->avgCnt + args->suprCnt + args->offCnt + pkCnt;
  955. unsigned i;
  956. p->args = *args;
  957. p->medV = cmMemResizeZ(cmSample_t,p->medV,eleCnt);
  958. p->fcofV = p->medV + args->medCnt;
  959. p->fdlyV = p->fcofV + args->medCnt;
  960. p->avgV = p->fdlyV + args->medCnt;
  961. p->suprV = p->avgV + args->avgCnt;
  962. p->offV = p->suprV + args->suprCnt;
  963. p->pkV = p->offV + args->offCnt;
  964. assert( p->medV + eleCnt == p->pkV + pkCnt );
  965. p->medIdx = 0;
  966. p->avgIdx = 0;
  967. p->suprIdx = args->suprCnt;
  968. p->offIdx = 0;
  969. p->pkFl = false;
  970. p->gateFl = false;
  971. p->onFl = false;
  972. p->offFl = false;
  973. cmGateDetectSetOnThreshDb2(p,args->onThreshDb);
  974. cmGateDetectSetOnThreshDb2(p,args->offThreshDb);
  975. p->fcofV[0] = 1.0;
  976. for(i=1; i<args->medCnt; ++i)
  977. {
  978. p->fcofV[i] = (1.0 - 1.0/args->medCnt) / ( pow(2.0,i-1) );
  979. //printf("%i %f ",i,p->fcofV[i]);
  980. }
  981. for(i=0; i<args->suprCnt; ++i)
  982. {
  983. p->suprV[i] = 1.0/pow(args->suprCoeff,i + 1.0);
  984. //printf("%i %f ",i,p->suprV[i]);
  985. }
  986. return rc;
  987. }
  988. cmRC_t cmGateDetectFinal2(cmGateDetect2* p )
  989. { return cmOkRC; }
  990. void _cmGateDetectPickPeak( cmGateDetect2* p, cmSample_t input )
  991. {
  992. p->pkV[0] = p->pkV[1];
  993. p->pkV[1] = p->pkV[2];
  994. p->pkV[2] = input;
  995. // if supression is active - apply it to the center pkV[]
  996. if( p->suprIdx < p->args.suprCnt )
  997. {
  998. p->pkV[1] -= p->pkV[1] * p->suprV[p->suprIdx];
  999. p->suprIdx = (p->suprIdx + 1) % p->args.suprCnt;
  1000. }
  1001. p->sup = p->pkV[1];
  1002. // if the center value in pkV[] is a local peak and above the onset threshold
  1003. if( p->pkV[1] > p->onThresh && p->pkV[0] < p->pkV[1] && p->pkV[1] > p->pkV[2] )
  1004. {
  1005. p->suprIdx = 0;
  1006. p->gateFl = true;
  1007. p->onFl = true;
  1008. }
  1009. // update the offset buffer
  1010. p->offV[p->offIdx] = fabs(p->pkV[2]);
  1011. p->offIdx = (p->offIdx + 1) % p->args.offCnt;
  1012. // if this is an offset
  1013. if( p->gateFl==true && cmVOS_Mean(p->offV,p->args.offCnt) < p->offThresh )
  1014. {
  1015. p->gateFl = false;
  1016. p->offFl = true;
  1017. }
  1018. }
  1019. void _cmGateDetectPickPeak2( cmGateDetect2* p, cmSample_t input )
  1020. {
  1021. // if supression is active - apply it to the input
  1022. if( p->suprIdx < p->args.suprCnt )
  1023. {
  1024. input -= input * p->suprV[p->suprIdx];
  1025. ++p->suprIdx;// = (p->suprIdx + 1) % p->args.suprCnt;
  1026. }
  1027. // update the peak buffer
  1028. p->pkV[0] = p->pkV[1];
  1029. p->pkV[1] = p->pkV[2];
  1030. p->pkV[2] = input;
  1031. p->sup = input;
  1032. // if the signal increased above the threshold and is not already waiting for a peak
  1033. if( p->pkV[1] < input && input > p->onThresh && p->pkFl == false )
  1034. {
  1035. p->pkFl = true;
  1036. p->gateFl = true;
  1037. p->onFl = true;
  1038. }
  1039. // if the center value in pkV[] is a local peak and above the onset threshold ...
  1040. if( p->gateFl && p->pkFl && p->pkV[0] < p->pkV[1] && p->pkV[1] > p->pkV[2] )
  1041. {
  1042. p->suprIdx = 0; // ... turn on supression
  1043. p->pkFl = false; // ... not longer waiting for the peak
  1044. }
  1045. // update the offset buffer
  1046. p->offV[p->offIdx] = fabs(input);
  1047. p->offIdx = (p->offIdx + 1) % p->args.offCnt;
  1048. // if this is an offset
  1049. if( p->gateFl==true && cmVOS_Mean(p->offV,p->args.offCnt) < p->offThresh )
  1050. {
  1051. p->gateFl = false;
  1052. p->offFl = true;
  1053. p->pkFl = false;
  1054. }
  1055. }
  1056. cmRC_t cmGateDetectExec2( cmGateDetect2* p, const cmSample_t* x, unsigned xn )
  1057. {
  1058. p->rms = cmVOS_RMS(x,xn,xn); // take RMS of incoming window
  1059. p->medV[ p->medIdx ] = p->rms; // input RMS to median filter
  1060. p->medIdx = (p->medIdx + 1) % p->args.medCnt;
  1061. p->med = cmVOS_Median(p->medV,p->args.medCnt); // calc the median
  1062. p->dif = cmMax(0,p->rms - p->med); // dif = half_rect( rms - med )
  1063. p->avgV[ p->avgIdx ] = p->dif; // input dif to avg filter
  1064. p->avgIdx = (p->avgIdx + 1) % p->args.avgCnt;
  1065. p->avg = cmVOS_Mean(p->avgV,p->args.avgCnt); // calc the avg
  1066. p->ons = p->dif - p->avg; // ons = dif - avg
  1067. cmVOS_Shift(p->fdlyV,p->args.medCnt,1,p->ons);
  1068. p->flt = cmVOS_MultSumVV(p->fdlyV,p->fcofV,p->args.medCnt);
  1069. p->offFl = false;
  1070. p->onFl = false;
  1071. _cmGateDetectPickPeak2(p,p->flt);
  1072. return cmOkRC;
  1073. }
  1074. void _cmGateDetectSetDb2( cmGateDetect2* p, cmReal_t db, cmReal_t* dbPtr )
  1075. {
  1076. *dbPtr = pow(10.0, db/20.0 );
  1077. }
  1078. void cmGateDetectSetOnThreshDb2( cmGateDetect2* p, cmReal_t db )
  1079. { _cmGateDetectSetDb2(p,db,&p->onThresh); }
  1080. void cmGateDetectSetOffThreshDb2( cmGateDetect2* p, cmReal_t db )
  1081. { _cmGateDetectSetDb2(p,db,&p->offThresh); }
  1082. //=======================================================================================================================
  1083. cmAutoGain* cmAutoGainAlloc( cmCtx* c, cmAutoGain* p, unsigned procSmpCnt, cmReal_t srate, cmReal_t hopMs, unsigned chCnt, const cmGateDetectParams* gd_args )
  1084. {
  1085. cmAutoGain* op = cmObjAlloc(cmAutoGain, c, p );
  1086. op->sbp = cmShiftBufAlloc(c,NULL,0,0,0);
  1087. op->gdp = cmGateDetectAlloc2(c,NULL,0,NULL);
  1088. if( procSmpCnt != 0 )
  1089. if( cmAutoGainInit(op, procSmpCnt, srate, hopMs, chCnt, gd_args) != cmOkRC )
  1090. cmAutoGainFree(&op);
  1091. return op;
  1092. }
  1093. cmRC_t cmAutoGainFree( cmAutoGain** pp )
  1094. {
  1095. cmRC_t rc;
  1096. if( pp==NULL || *pp == NULL )
  1097. return cmOkRC;
  1098. cmAutoGain* p = *pp;
  1099. if((rc = cmAutoGainFinal(p)) != cmOkRC )
  1100. return rc;
  1101. cmMemPtrFree(&p->chArray);
  1102. p->chCnt = 0;
  1103. cmShiftBufFree(&p->sbp);
  1104. cmGateDetectFree2(&p->gdp);
  1105. cmObjFree(pp);
  1106. return cmOkRC;
  1107. }
  1108. cmRC_t cmAutoGainInit( cmAutoGain* p, unsigned procSmpCnt, cmReal_t srate, cmReal_t hopMs, unsigned chCnt, const cmGateDetectParams* gd_args )
  1109. {
  1110. unsigned i;
  1111. cmRC_t rc;
  1112. if((rc = cmAutoGainFinal(p)) != cmOkRC )
  1113. return rc;
  1114. unsigned hopSmpCnt = (unsigned)floor(srate * hopMs / 1000.0);
  1115. unsigned wndSmpCnt = hopSmpCnt * gd_args->medCnt;
  1116. cmShiftBufInit(p->sbp,procSmpCnt,wndSmpCnt,hopSmpCnt);
  1117. cmGateDetectInit2(p->gdp,procSmpCnt,gd_args);
  1118. p->chCnt = chCnt;
  1119. p->chArray = cmMemResizeZ(cmAutoGainCh,p->chArray,p->chCnt);
  1120. p->chp = NULL;
  1121. for(i=0; i<p->chCnt; ++i)
  1122. p->chArray[i].id = cmInvalidIdx;
  1123. return rc;
  1124. }
  1125. cmRC_t cmAutoGainFinal( cmAutoGain* p )
  1126. { return cmOkRC;}
  1127. void _cmAutoGainChannelFinish( cmAutoGain* p )
  1128. {
  1129. if( p->chp != NULL )
  1130. {
  1131. if( p->gateMax != 0 )
  1132. {
  1133. p->gateSum += p->gateMax;
  1134. p->gateCnt += 1;
  1135. }
  1136. p->chp->gateMaxAvg = p->gateCnt == 0 ? 0.0 : p->gateSum / p->gateCnt;
  1137. }
  1138. }
  1139. cmRC_t cmAutoGainStartCh( cmAutoGain* p, unsigned id )
  1140. {
  1141. cmReal_t rmsMax = 1.0;
  1142. unsigned i;
  1143. if( id == cmInvalidIdx )
  1144. return cmOkRC;
  1145. // do intermediate channel calculations on the last selected channel
  1146. if( p->chp != NULL )
  1147. _cmAutoGainChannelFinish( p );
  1148. // if 'id' has already been used
  1149. // then select the associated channel as the current channel
  1150. // otherwise select the next avail channel as the current channel
  1151. for(i=0; i<p->chCnt; ++i)
  1152. if( p->chArray[i].id == id || p->chArray[i].id == cmInvalidId )
  1153. {
  1154. p->chp = p->chArray + i;
  1155. break;
  1156. }
  1157. if( p->chp == NULL )
  1158. return cmCtxRtCondition( &p->obj, cmArgAssertRC, "All channels are in use.");
  1159. p->chp->id = id;
  1160. p->gateCnt = 0;
  1161. p->gateSum = 0;
  1162. p->gateMax = 0;
  1163. p->minRms = rmsMax;
  1164. return cmOkRC;
  1165. }
  1166. // The goal of this process is to locate the max RMS value during
  1167. // the duration of each note. When all the notes have been processed for
  1168. // a given channel the average maximum value for all of the notes is
  1169. // then calculated.
  1170. cmRC_t cmAutoGainProcCh( cmAutoGain* p, const cmSample_t* x, unsigned xn )
  1171. {
  1172. // shift the new samples into the shift buffer
  1173. while(cmShiftBufExec(p->sbp,x,xn))
  1174. {
  1175. // update the gate detector
  1176. cmGateDetectExec2(p->gdp,p->sbp->outV,p->sbp->outN);
  1177. // write the output matrix file
  1178. //if( _cmPuWriteMtxFile(p,segFl) != kOkPuRC )
  1179. // goto errLabel;
  1180. // if this frame is an RMS minimum or onset or offset
  1181. // then select it as a possible segment end.
  1182. // Note that for onsets this will effectively force the end to
  1183. // come after the onset because the onset will not be an energy minimum
  1184. // relative to subsequent frames.
  1185. if( p->gdp->rms < p->minRms || p->gdp->onFl || p->gdp->offFl )
  1186. {
  1187. p->minRms = p->gdp->rms;
  1188. // count onsets
  1189. if( p->gdp->onFl )
  1190. ++p->chp->onCnt;
  1191. // count offsets
  1192. if( p->gdp->offFl )
  1193. {
  1194. ++p->chp->offCnt;
  1195. // update the gate sum and count
  1196. p->gateSum += p->gateMax;
  1197. p->gateCnt += 1;
  1198. p->gateMax = 0;
  1199. }
  1200. }
  1201. // track the max RMS value during this gate
  1202. if( p->gdp->gateFl && p->gdp->rms > p->gateMax )
  1203. p->gateMax = p->gdp->rms;
  1204. }
  1205. return cmOkRC;
  1206. }
  1207. cmRC_t cmAutoGainCalcGains( cmAutoGain* p )
  1208. {
  1209. unsigned i;
  1210. cmReal_t avg = 0;
  1211. if( p->chCnt == 0 )
  1212. return cmOkRC;
  1213. // verify that all channels were input
  1214. for(i=0; i<p->chCnt; ++i)
  1215. if( p->chArray[i].id == cmInvalidId )
  1216. break;
  1217. if( i != p->chCnt )
  1218. return cmCtxRtCondition( &p->obj, cmArgAssertRC, "All channels must be set prior to calculating gains.");
  1219. // process the last channel
  1220. _cmAutoGainChannelFinish(p);
  1221. // p->chp isn't used again unless we restart the indidual channel processing
  1222. p->chp = NULL;
  1223. for(i=0; i<p->chCnt; ++i)
  1224. avg += p->chArray[i].gateMaxAvg;
  1225. avg /= p->chCnt;
  1226. for(i=0; i<p->chCnt; ++i)
  1227. {
  1228. cmReal_t d = p->chArray[i].gateMaxAvg==0 ? 1.0 : p->chArray[i].gateMaxAvg;
  1229. p->chArray[i].gain = avg / d;
  1230. }
  1231. return cmOkRC;
  1232. }
  1233. void cmAutoGainPrint( cmAutoGain* p, cmRpt_t* rpt )
  1234. {
  1235. unsigned i=0;
  1236. for(i=0; i<p->chCnt; ++i)
  1237. {
  1238. cmAutoGainCh* chp = p->chArray + i;
  1239. cmRptPrintf(rpt,"midi:%3i %4s on:%i off:%i avg:%5.5f gain:%5.5f\n",
  1240. chp->id,
  1241. cmStringNullGuard(cmMidiToSciPitch(chp->id,NULL,0)),
  1242. chp->onCnt, chp->offCnt, chp->gateMaxAvg, chp->gain );
  1243. }
  1244. }
  1245. //==========================================================================================================================================
  1246. cmChCfg* cmChCfgAlloc( cmCtx* c, cmChCfg* p, cmCtx_t* ctx, const cmChar_t* fn )
  1247. {
  1248. cmChCfg* op = cmObjAlloc(cmChCfg, c, p );
  1249. if( fn != NULL )
  1250. if( cmChCfgInit( op, ctx, fn ) != cmOkRC )
  1251. cmChCfgFree(&op);
  1252. return op;
  1253. }
  1254. cmRC_t cmChCfgFree( cmChCfg** pp )
  1255. {
  1256. cmRC_t rc = cmOkRC;
  1257. if( pp == NULL || *pp == NULL )
  1258. return cmOkRC;
  1259. cmChCfg* p = *pp;
  1260. if((rc = cmChCfgFinal(p)) != cmOkRC )
  1261. return rc;
  1262. cmMemPtrFree(&p->chArray);
  1263. cmFsFreeFn(p->fn);
  1264. cmObjFree(pp);
  1265. return cmOkRC;
  1266. }
  1267. enum { kChColIdx, kSsiColIdx, kPitchColIdx, kMidiColIdx, kGainColIdx, kNsFlColIdx, kCdFlColIdx, kColCnt };
  1268. cmRC_t cmChCfgInit( cmChCfg* p, cmCtx_t* ctx, const cmChar_t* fn )
  1269. {
  1270. cmRC_t rc = cmOkRC;
  1271. unsigned i,j;
  1272. const cmChar_t* ch_array_label = "ch_array";
  1273. typedef struct
  1274. {
  1275. unsigned id;
  1276. const char* label;
  1277. } map_t;
  1278. map_t map[ kColCnt ] =
  1279. {
  1280. { kChColIdx, "ch" },
  1281. { kSsiColIdx, "ssi" },
  1282. { kPitchColIdx, "pitch" },
  1283. { kMidiColIdx, "midi" },
  1284. { kGainColIdx, "gain" },
  1285. { kNsFlColIdx, "ns_fl"},
  1286. { kCdFlColIdx, "cd_fl"}
  1287. };
  1288. if((rc = cmChCfgFinal(p)) != cmOkRC )
  1289. return rc;
  1290. p->fn = cmFsMakeFn(cmFsPrefsDir(),fn,NULL,NULL);
  1291. // read the channel cfg JSON file
  1292. if( cmJsonInitializeFromFile(&p->jsH, p->fn, ctx ) != kOkJsRC )
  1293. {
  1294. rc = cmCtxRtCondition( &p->obj, cmSubSysFailRC, "JSON initialize failed on '%s'.",cmStringNullGuard(p->fn));
  1295. goto errLabel;
  1296. }
  1297. // locate the 'ch_array' node
  1298. if((p->cap = cmJsonFindValue( p->jsH, ch_array_label, cmJsonRoot(p->jsH), kArrayTId )) == NULL )
  1299. {
  1300. rc = cmCtxRtCondition( &p->obj, cmSubSysFailRC, "Unable to locate the JSON element '%s'.",ch_array_label);
  1301. goto errLabel;
  1302. }
  1303. unsigned rowCnt = cmJsonChildCount(p->cap);
  1304. // there must be at least 1 label row and 1 ch row
  1305. if( rowCnt < 2 )
  1306. {
  1307. rc = cmCtxRtCondition( &p->obj, cmSubSysFailRC, "The 'ch_array' appears to be empty.");
  1308. goto errLabel;
  1309. }
  1310. // allocate the ch array
  1311. p->chCnt = rowCnt - 1;
  1312. p->chArray = cmMemResizeZ( cmChCfgCh, p->chArray, p->chCnt );
  1313. p->nsChCnt = 0;
  1314. // read each row
  1315. for(i=0; i<rowCnt; ++i)
  1316. {
  1317. // get the array on row i
  1318. const cmJsonNode_t* np = cmJsonArrayElementC(p->cap,i);
  1319. // all row arrays contain 'kColCnt' elements
  1320. if( cmJsonChildCount(np) != kColCnt )
  1321. {
  1322. rc = cmCtxRtCondition( &p->obj, cmSubSysFailRC, "All 'ch_array' element at index %i does not contain %i values.",i,kColCnt);
  1323. goto errLabel;
  1324. }
  1325. // for each columns
  1326. for(j=0; j<kColCnt; ++j)
  1327. {
  1328. const cmJsonNode_t* cp = cmJsonArrayElementC(np,j);
  1329. // the first row contains the labels ....
  1330. if( i == 0 )
  1331. {
  1332. // verify that the column format is as expected
  1333. if( cmJsonIsString(cp)==false || strcmp(cp->u.stringVal,map[j].label) != 0 )
  1334. {
  1335. rc = cmCtxRtCondition( &p->obj, cmSubSysFailRC, "The first row column at index %i of 'ch_array' should be the label '%s'.",map[j].label);
  1336. goto errLabel;
  1337. }
  1338. }
  1339. else // ... other rows contain Ch Cfg's.
  1340. {
  1341. cmChCfgCh* chp = p->chArray + (i-1);
  1342. switch(j)
  1343. {
  1344. case kChColIdx: rc = cmJsonUIntValue( cp, &chp->ch ); break;
  1345. case kSsiColIdx: rc = cmJsonUIntValue( cp, &chp->ssi ); break;
  1346. case kPitchColIdx: rc = cmJsonStringValue( cp, &chp->pitchStr ); break;
  1347. case kMidiColIdx: rc = cmJsonUIntValue( cp, &chp->midi ); break;
  1348. case kGainColIdx: rc = cmJsonRealValue( cp, &chp->gain ); break;
  1349. case kNsFlColIdx:
  1350. rc = cmJsonBoolValue( cp, &chp->nsFl );
  1351. if( chp->nsFl )
  1352. ++p->nsChCnt;
  1353. break;
  1354. case kCdFlColIdx: rc = cmJsonBoolValue( cp, &chp->cdFl ); break;
  1355. default:
  1356. { assert(0); }
  1357. }
  1358. if( rc != kOkJsRC )
  1359. {
  1360. rc = cmCtxRtCondition( &p->obj, cmSubSysFailRC, "An error occurred while reading the '%s' column on row index:%i .", map[j].label,i);
  1361. goto errLabel;
  1362. }
  1363. }
  1364. }
  1365. }
  1366. errLabel:
  1367. return rc;
  1368. }
  1369. cmRC_t cmChCfgFinal( cmChCfg* p )
  1370. {
  1371. cmRC_t rc = cmOkRC;
  1372. if( cmJsonIsValid(p->jsH) )
  1373. if( cmJsonFinalize(&p->jsH) != kOkJsRC )
  1374. rc = cmCtxRtCondition( &p->obj, cmSubSysFailRC, "JSON finalize failed.");
  1375. return rc;
  1376. }
  1377. cmRC_t cmChCfgWrite( cmChCfg* p )
  1378. {
  1379. cmRC_t rc = cmOkRC;
  1380. unsigned i;
  1381. for(i=0; i<p->chCnt; ++i)
  1382. {
  1383. // get the array on row i+1
  1384. cmJsonNode_t* np = cmJsonArrayElement(p->cap,i+1);
  1385. // get the ele in the 'gainColIdx' column
  1386. np = cmJsonArrayElement(np,kGainColIdx);
  1387. assert( cmJsonIsReal(np) );
  1388. np->u.realVal = p->chArray[i].gain;
  1389. }
  1390. if( cmJsonWrite( p->jsH, cmJsonRoot(p->jsH), p->fn ) != kOkJsRC )
  1391. rc = cmCtxRtCondition( &p->obj, cmSubSysFailRC, "The JSON Channel Cfg file write failed on '%s'.",cmStringNullGuard(p->fn));
  1392. return rc;
  1393. }
  1394. void cmChCfgPrint( cmChCfg* p, cmRpt_t* rpt )
  1395. {
  1396. unsigned i;
  1397. for(i=0; i<p->chCnt; ++i)
  1398. {
  1399. const cmChCfgCh* chp = p->chArray + i;
  1400. cmRptPrintf(rpt,"%3i %3i %4s %3i %5.5f\n",chp->ch,chp->ssi,chp->pitchStr,chp->midi,chp->gain);
  1401. }
  1402. }
  1403. unsigned cmChCfgChannelCount( cmCtx_t* ctx, const cmChar_t* fn, unsigned* nsChCntPtr )
  1404. {
  1405. cmChCfg* ccp;
  1406. unsigned chCnt = 0;
  1407. cmCtx* c = cmCtxAlloc(NULL, &ctx->rpt, cmLHeapNullHandle, cmSymTblNullHandle );
  1408. if((ccp = cmChCfgAlloc(c, NULL, ctx, fn )) == NULL )
  1409. goto errLabel;
  1410. chCnt = ccp->chCnt;
  1411. if( nsChCntPtr != NULL )
  1412. *nsChCntPtr = ccp->nsChCnt;
  1413. cmChCfgFree(&ccp);
  1414. errLabel:
  1415. cmCtxFree(&c);
  1416. return chCnt;
  1417. }
  1418. unsigned cmChCfgChannelIndex( cmCtx_t* ctx, const cmChar_t* fn, unsigned chIdx )
  1419. {
  1420. cmChCfg* ccp;
  1421. unsigned retChIdx = -1;
  1422. cmCtx* c = cmCtxAlloc(NULL, &ctx->rpt, cmLHeapNullHandle, cmSymTblNullHandle );
  1423. if((ccp = cmChCfgAlloc(c, NULL, ctx, fn )) == NULL )
  1424. goto errLabel;
  1425. if( chIdx >= ccp->chCnt )
  1426. cmCtxRtCondition( &ccp->obj, cmArgAssertRC, "The channel index %i is not less than the channel count %i when querying '%s'.",chIdx,ccp->chCnt,cmStringNullGuard(ccp->fn));
  1427. else
  1428. retChIdx = ccp->chArray[chIdx].ch;
  1429. cmChCfgFree(&ccp);
  1430. errLabel:
  1431. cmCtxFree(&c);
  1432. return retChIdx;
  1433. }
  1434. //==========================================================================================================================================
  1435. cmChordDetect* cmChordDetectAlloc( cmCtx*c, cmChordDetect* p, cmReal_t srate, unsigned chCnt, cmReal_t maxTimeSpanMs, unsigned minNotesPerChord )
  1436. {
  1437. cmChordDetect* op = cmObjAlloc(cmChordDetect, c, p );
  1438. if( srate != 0 )
  1439. if( cmChordDetectInit( op, srate, chCnt, maxTimeSpanMs, minNotesPerChord ) != cmOkRC )
  1440. cmChordDetectFree(&op);
  1441. return op;
  1442. }
  1443. cmRC_t cmChordDetectFree( cmChordDetect** pp )
  1444. {
  1445. cmRC_t rc = cmOkRC;
  1446. if( pp == NULL || *pp == NULL )
  1447. return cmOkRC;
  1448. cmChordDetect* p = *pp;
  1449. if((rc = cmChordDetectFinal(p)) != cmOkRC )
  1450. return rc;
  1451. cmMemPtrFree(&p->chArray);
  1452. cmObjFree(pp);
  1453. return cmOkRC;
  1454. }
  1455. cmRC_t cmChordDetectInit( cmChordDetect* p, cmReal_t srate, unsigned chCnt, cmReal_t maxTimeSpanMs, unsigned minNotesPerChord )
  1456. {
  1457. cmRC_t rc;
  1458. if((rc = cmChordDetectFinal(p)) != cmOkRC )
  1459. return rc;
  1460. p->chArray = cmMemResizeZ(cmChordDetectCh, p->chArray, chCnt );
  1461. p->chCnt = chCnt;
  1462. p->minNotesPerChord = minNotesPerChord;
  1463. p->detectFl = false;
  1464. p->timeSmp = 0;
  1465. p->srate = srate;
  1466. cmChordDetectSetSpanMs(p,maxTimeSpanMs);
  1467. unsigned i;
  1468. for(i=0; i<p->chCnt; ++i)
  1469. p->chArray[i].readyFl = true;
  1470. return rc;
  1471. }
  1472. cmRC_t cmChordDetectFinal( cmChordDetect* P )
  1473. { return cmOkRC; }
  1474. cmRC_t cmChordDetectExec( cmChordDetect* p, unsigned procSmpCnt, const bool* gateV, const cmReal_t* rmsV, unsigned chCnt )
  1475. {
  1476. assert( chCnt == p->chCnt );
  1477. chCnt = cmMin(chCnt,p->chCnt);
  1478. cmRC_t rc = cmOkRC;
  1479. unsigned candCnt = 0;
  1480. cmChordDetectCh* oldCand = NULL;
  1481. unsigned i;
  1482. p->detectFl = false;
  1483. p->timeSmp += procSmpCnt;
  1484. // update the readyFl's and candFl's based on onset and offsets
  1485. for(i=0; i<chCnt; ++i)
  1486. {
  1487. cmChordDetectCh* cp = p->chArray + i;
  1488. // if onset and the channel is ready
  1489. if( gateV[i] && cp->gateFl==false && cp->readyFl )
  1490. {
  1491. cp->candSmpTime = p->timeSmp;
  1492. cp->candRMS = rmsV[i];
  1493. cp->candFl = true;
  1494. }
  1495. // if offset then this channel is again ready to be a candidate
  1496. if( gateV[i]==false && cp->gateFl )
  1497. {
  1498. cp->readyFl = true;
  1499. }
  1500. cp->gateFl = gateV[i];
  1501. cp->chordFl = false;
  1502. }
  1503. // check if we have enough channels to form a chord and
  1504. // expire channels that have passed the max time out value
  1505. for(i=0; i<chCnt; ++i)
  1506. {
  1507. cmChordDetectCh* cp = p->chArray + i;
  1508. unsigned ageSmpCnt = p->timeSmp - cp->candSmpTime;
  1509. // if this is a candiate ...
  1510. if( cp->candFl )
  1511. {
  1512. // ... that has not expired
  1513. if( ageSmpCnt <= p->maxTimeSpanSmpCnt )
  1514. {
  1515. // track the oldest candidate
  1516. if( oldCand==NULL || cp->candSmpTime < oldCand->candSmpTime )
  1517. oldCand = cp;
  1518. ++candCnt;
  1519. }
  1520. else // ... that has expired
  1521. {
  1522. cp->candFl = false;
  1523. }
  1524. }
  1525. }
  1526. // If we have enough notes and the oldest candiate will expire on the next cycle.
  1527. // (By waiting for the oldest note to almost expire we gather the maximum number of
  1528. // possible notes given the time duration. If we remove this condition then
  1529. // we will tend to trigger chord detection with fewer notes.)
  1530. if( oldCand != NULL )
  1531. {
  1532. unsigned nextAge = p->timeSmp + procSmpCnt - oldCand->candSmpTime;
  1533. if( candCnt >= p->minNotesPerChord && nextAge >= p->maxTimeSpanSmpCnt )
  1534. {
  1535. for(i=0; i<chCnt; ++i)
  1536. {
  1537. cmChordDetectCh* cp = p->chArray + i;
  1538. if( cp->candFl )
  1539. {
  1540. cp->chordFl = true;
  1541. cp->candFl = false;
  1542. }
  1543. }
  1544. p->detectFl = true;
  1545. }
  1546. }
  1547. return rc;
  1548. }
  1549. cmRC_t cmChordDetectSetSpanMs( cmChordDetect* p, cmReal_t maxTimeSpanMs )
  1550. {
  1551. p->maxTimeSpanSmpCnt = floor( maxTimeSpanMs * p->srate / 1000.0 );
  1552. return cmOkRC;
  1553. }
  1554. //==========================================================================================================================================
  1555. cmXfader* cmXfaderAlloc( cmCtx*c, cmXfader* p, cmReal_t srate, unsigned chCnt, cmReal_t fadeTimeMs )
  1556. {
  1557. cmXfader* op = cmObjAlloc(cmXfader, c, p );
  1558. if( srate != 0 )
  1559. if( cmXfaderInit( op, srate, chCnt, fadeTimeMs ) != cmOkRC )
  1560. cmXfaderFree(&op);
  1561. return op;
  1562. }
  1563. cmRC_t cmXfaderFree( cmXfader** pp )
  1564. {
  1565. cmRC_t rc = cmOkRC;
  1566. if( pp == NULL || *pp == NULL )
  1567. return cmOkRC;
  1568. cmXfader* p = *pp;
  1569. if((rc = cmXfaderFinal(p)) != cmOkRC )
  1570. return rc;
  1571. cmMemPtrFree(&p->chArray);
  1572. cmObjFree(pp);
  1573. return cmOkRC;
  1574. }
  1575. cmRC_t cmXfaderInit( cmXfader* p, cmReal_t srate, unsigned chCnt, cmReal_t fadeTimeMs )
  1576. {
  1577. cmRC_t rc;
  1578. if((rc = cmXfaderFinal(p)) != cmOkRC )
  1579. return rc;
  1580. p->chCnt = chCnt;
  1581. p->chArray = cmMemResizeZ(cmXfaderCh,p->chArray,p->chCnt);
  1582. p->srate = srate;
  1583. p->gateFl = false;
  1584. p->onFl = false;
  1585. p->offFl = false;
  1586. cmXfaderSetXfadeTime(p,fadeTimeMs);
  1587. return rc;
  1588. }
  1589. cmRC_t cmXfaderFinal( cmXfader* p )
  1590. { return cmOkRC; }
  1591. cmRC_t cmXfaderExec( cmXfader* p, unsigned procSmpCnt, const bool* chGateV, unsigned chCnt )
  1592. {
  1593. assert( chCnt == p->chCnt);
  1594. chCnt = cmMin(chCnt,p->chCnt);
  1595. bool gateFl = false;
  1596. // gain change associated with procSmpCnt
  1597. cmReal_t dgain = (cmReal_t)procSmpCnt / p->fadeSmpCnt;
  1598. unsigned i;
  1599. // for each channel
  1600. for(i=0; i<chCnt; ++i)
  1601. {
  1602. cmXfaderCh* cp = p->chArray + i;
  1603. cp->onFl = false;
  1604. cp->offFl = false;
  1605. if( chGateV != NULL )
  1606. {
  1607. cp->onFl = chGateV[i] && !cp->gateFl; // notice fade-in transition begin
  1608. cp->gateFl = chGateV[i];
  1609. }
  1610. cmReal_t g = cp->gain;
  1611. if( cp->gateFl )
  1612. cp->gain = cmMin(cp->gain + dgain,1.0);
  1613. else
  1614. {
  1615. cp->gain = cmMax(cp->gain - dgain,0.0);
  1616. cp->offFl = g>0.0 && cp->gain==0.0; // notice fade-out transition end
  1617. }
  1618. if( cp->gain != 0.0 )
  1619. gateFl = true;
  1620. }
  1621. p->onFl = false;
  1622. p->offFl = false;
  1623. if( p->gateFl==false && gateFl==true )
  1624. p->onFl = true;
  1625. else
  1626. if( p->gateFl==true && gateFl==false )
  1627. p->offFl = true;
  1628. p->gateFl = gateFl;
  1629. return cmOkRC;
  1630. }
  1631. cmRC_t cmXfaderExecAudio( cmXfader* p, unsigned procSmpCnt, const bool* gateV, unsigned chCnt, const cmSample_t* x[], cmSample_t* y )
  1632. {
  1633. cmRC_t rc;
  1634. assert( chCnt == p->chCnt);
  1635. chCnt = cmMin(chCnt,p->chCnt);
  1636. if((rc = cmXfaderExec(p,procSmpCnt,gateV,chCnt)) != cmOkRC )
  1637. return rc;
  1638. unsigned i;
  1639. for(i=0; i<chCnt; ++i)
  1640. if( x[i] != NULL )
  1641. cmVOS_MultVaVS(y,procSmpCnt,x[i],p->chArray[i].gain);
  1642. return rc;
  1643. }
  1644. void cmXfaderSetXfadeTime( cmXfader* p, cmReal_t fadeTimeMs )
  1645. {
  1646. p->fadeSmpCnt = floor(fadeTimeMs * p->srate /1000.0);
  1647. }
  1648. void cmXfaderSelectOne( cmXfader* p, unsigned chIdx )
  1649. {
  1650. unsigned i = 0;
  1651. for(i=0; i<p->chCnt; ++i)
  1652. p->chArray[i].gateFl = i == chIdx;
  1653. }
  1654. void cmXfaderAllOff( cmXfader* p )
  1655. {
  1656. unsigned i = 0;
  1657. for(i=0; i<p->chCnt; ++i)
  1658. p->chArray[i].gateFl = false;
  1659. }
  1660. //==========================================================================================================================================
  1661. cmFader* cmFaderAlloc( cmCtx*c, cmFader* p, cmReal_t srate, cmReal_t fadeTimeMs )
  1662. {
  1663. cmFader* op = cmObjAlloc(cmFader, c, p );
  1664. if( srate != 0 )
  1665. if( cmFaderInit( op, srate, fadeTimeMs ) != cmOkRC )
  1666. cmFaderFree(&op);
  1667. return op;
  1668. }
  1669. cmRC_t cmFaderFree( cmFader** pp )
  1670. {
  1671. cmRC_t rc = cmOkRC;
  1672. if( pp == NULL || *pp == NULL )
  1673. return cmOkRC;
  1674. cmFader* p = *pp;
  1675. if((rc = cmFaderFinal(p)) != cmOkRC )
  1676. return rc;
  1677. cmObjFree(pp);
  1678. return cmOkRC;
  1679. }
  1680. cmRC_t cmFaderInit( cmFader* p, cmReal_t srate, cmReal_t fadeTimeMs )
  1681. {
  1682. cmRC_t rc;
  1683. if((rc = cmFaderFinal(p)) != cmOkRC )
  1684. return rc;
  1685. p->srate = srate;
  1686. p->gain = 0.0;
  1687. cmFaderSetFadeTime(p,fadeTimeMs);
  1688. return rc;
  1689. }
  1690. cmRC_t cmFaderFinal( cmFader* p )
  1691. { return cmOkRC; }
  1692. cmRC_t cmFaderExec( cmFader* p, unsigned procSmpCnt, bool gateFl, bool mixFl, const cmSample_t* x, cmSample_t* y )
  1693. {
  1694. cmReal_t d = (gateFl ? 1.0 : -1.0) * procSmpCnt / p->fadeSmpCnt;
  1695. // TODO: add fade curves
  1696. p->gain = cmMin(1.0,cmMax(0.0,p->gain + d));
  1697. if( x!=NULL && y!=NULL )
  1698. {
  1699. if( mixFl )
  1700. cmVOS_MultVaVS(y, procSmpCnt, x, 1.0/* p->gain*/);
  1701. else
  1702. cmVOS_MultVVS(y,procSmpCnt,x,p->gain);
  1703. }
  1704. return cmOkRC;
  1705. }
  1706. void cmFaderSetFadeTime( cmFader* p, cmReal_t fadeTimeMs )
  1707. {
  1708. p->fadeSmpCnt = (unsigned)floor( fadeTimeMs * p->srate / 1000.0 );
  1709. }
  1710. //=======================================================================================================================
  1711. cmCombFilt* cmCombFiltAlloc( cmCtx* c, cmCombFilt* p, cmReal_t srate, bool feedbackFl, cmReal_t minHz, cmReal_t alpha, cmReal_t hz, bool bypassFl )
  1712. {
  1713. cmCombFilt* op = cmObjAlloc(cmCombFilt, c, p );
  1714. op->idp = cmIDelayAlloc(c, NULL, 0, 0, NULL, NULL, NULL, 0 );
  1715. if( srate != 0 )
  1716. if( cmCombFiltInit( op, srate, feedbackFl, minHz, alpha, hz, bypassFl ) != cmOkRC )
  1717. cmCombFiltFree(&op);
  1718. return op;
  1719. }
  1720. cmRC_t cmCombFiltFree( cmCombFilt** pp)
  1721. {
  1722. cmRC_t rc = cmOkRC;
  1723. if( pp == NULL || *pp == NULL )
  1724. return cmOkRC;
  1725. cmCombFilt* p = *pp;
  1726. if((rc = cmCombFiltFinal(p)) != cmOkRC )
  1727. return rc;
  1728. cmMemFree(p->a);
  1729. cmMemFree(p->b);
  1730. cmMemFree(p->d);
  1731. cmIDelayFree(&p->idp);
  1732. cmObjFree(pp);
  1733. return cmOkRC;
  1734. }
  1735. cmRC_t cmCombFiltInit( cmCombFilt* p, cmReal_t srate, bool feedbackFl, cmReal_t minHz, cmReal_t alpha, cmReal_t hz, bool bypassFl )
  1736. {
  1737. cmRC_t rc;
  1738. if((rc = cmCombFiltFinal(p)) != cmOkRC )
  1739. return rc;
  1740. p->feedbackFl = feedbackFl;
  1741. p->dN = cmMax(1,floor(srate / minHz ));
  1742. p->d = cmMemResizeZ( cmReal_t, p->d, p->dN+1 );
  1743. p->a = cmMemResizeZ( cmReal_t, p->a, p->dN );
  1744. p->b = cmMemResizeZ( cmReal_t, p->b, p->dN );
  1745. p->dn = 1;
  1746. p->alpha = alpha;
  1747. p->srate = srate;
  1748. p->bypassFl = bypassFl;
  1749. cmReal_t tapMs = p->dn * 1000.0 / srate;
  1750. cmReal_t tapFf = 1.0;
  1751. cmReal_t tapFb = 1.0;
  1752. cmIDelayInit(p->idp, srate, p->dN * 1000.0 / srate, &tapMs, &tapFf, &tapFb, 1 );
  1753. cmCombFiltSetHz(p,hz);
  1754. return rc;
  1755. }
  1756. cmRC_t cmCombFiltFinal( cmCombFilt* p )
  1757. { return cmOkRC; }
  1758. cmRC_t cmCombFiltExec( cmCombFilt* p, const cmSample_t* x, cmSample_t* y, unsigned n )
  1759. {
  1760. if( y == NULL )
  1761. return cmOkRC;
  1762. if( x == NULL )
  1763. {
  1764. cmVOS_Zero(y,n);
  1765. return cmOkRC;
  1766. }
  1767. if( p->bypassFl )
  1768. cmVOS_Copy(y,n,x);
  1769. else
  1770. cmIDelayExec(p->idp,x,y,n);
  1771. return cmOkRC;
  1772. }
  1773. void cmCombFiltSetAlpha( cmCombFilt* p, cmReal_t alpha )
  1774. {
  1775. p->b0 = 1.0 - fabs(alpha); // normalization coeff (could be applied directly to the input or output)
  1776. p->a[p->dn-1] = -alpha;
  1777. p->alpha = alpha;
  1778. p->idp->tff[0] = p->b0;
  1779. p->idp->tfb[0] = -alpha;
  1780. }
  1781. cmRC_t cmCombFiltSetHz( cmCombFilt* p, cmReal_t hz )
  1782. {
  1783. if( hz < p->minHz )
  1784. return cmCtxRtCondition( &p->obj, cmInvalidArgRC, "The comb filter frequency %f Hz is invalid given the minimum frequency setting of %f Hz.",hz,p->minHz );
  1785. // clear the current alpha
  1786. p->a[p->dn-1] = 0;
  1787. // change location of alpha in p->a[]
  1788. p->dn = cmMin(p->dN-1,cmMax(1,floor(p->srate / hz )));
  1789. p->hz = hz;
  1790. cmCombFiltSetAlpha(p,p->alpha); // the location of filter coeff changed - reset it here
  1791. cmIDelaySetTapMs(p->idp, 0,p->dn * 1000.0 / p->srate );
  1792. return cmOkRC;
  1793. }
  1794. //=======================================================================================================================
  1795. cmDcFilt* cmDcFiltAlloc( cmCtx* c, cmDcFilt* p, bool bypassFl )
  1796. {
  1797. cmDcFilt* op = cmObjAlloc(cmDcFilt, c, p );
  1798. if( cmDcFiltInit( op, bypassFl ) != cmOkRC )
  1799. cmDcFiltFree(&op);
  1800. return op;
  1801. }
  1802. cmRC_t cmDcFiltFree( cmDcFilt** pp)
  1803. {
  1804. cmRC_t rc = cmOkRC;
  1805. if( pp == NULL || *pp == NULL )
  1806. return cmOkRC;
  1807. cmDcFilt* p = *pp;
  1808. if((rc = cmDcFiltFinal(p)) != cmOkRC )
  1809. return rc;
  1810. cmObjFree(pp);
  1811. return cmOkRC;
  1812. }
  1813. cmRC_t cmDcFiltInit( cmDcFilt* p, bool bypassFl )
  1814. {
  1815. cmRC_t rc;
  1816. if((rc = cmDcFiltFinal(p)) != cmOkRC )
  1817. return rc;
  1818. p->b0 = 1;
  1819. p->b[0] = -1;
  1820. p->a[0] = -0.999;
  1821. p->d[0] = 0;
  1822. p->d[1] = 0;
  1823. p->bypassFl = bypassFl;
  1824. return rc;
  1825. }
  1826. cmRC_t cmDcFiltFinal( cmDcFilt* p )
  1827. { return cmOkRC; }
  1828. cmRC_t cmDcFiltExec( cmDcFilt* p, const cmSample_t* x, cmSample_t* y, unsigned n )
  1829. {
  1830. if( p->bypassFl )
  1831. cmVOS_Copy(y,n,x);
  1832. else
  1833. cmVOS_Filter(y,n,x,n,p->b0, p->b, p->a, p->d, 1 );
  1834. return cmOkRC;
  1835. }
  1836. //=======================================================================================================================
  1837. cmIDelay* cmIDelayAlloc( cmCtx* c, cmIDelay* p, cmReal_t srate, cmReal_t maxDelayMs, const cmReal_t* tapMs, const cmReal_t* tapFfGain, const cmReal_t* tapFbGain, unsigned tapCnt )
  1838. {
  1839. cmIDelay* op = cmObjAlloc(cmIDelay, c, p );
  1840. if( srate != 0 )
  1841. if( cmIDelayInit( op, srate, maxDelayMs, tapMs, tapFfGain, tapFbGain, tapCnt ) != cmOkRC )
  1842. cmIDelayFree(&op);
  1843. return op;
  1844. }
  1845. cmRC_t cmIDelayFree( cmIDelay** pp )
  1846. {
  1847. cmRC_t rc = cmOkRC;
  1848. if( pp == NULL || *pp == NULL )
  1849. return cmOkRC;
  1850. cmIDelay* p = *pp;
  1851. if((rc = cmIDelayFinal(p)) != cmOkRC )
  1852. return rc;
  1853. cmMemFree(p->m);
  1854. cmMemFree(p->ti);
  1855. cmMemFree(p->tff);
  1856. cmMemFree(p->tfb);
  1857. cmObjFree(pp);
  1858. return cmOkRC;
  1859. }
  1860. cmRC_t cmIDelayInit( cmIDelay* p, cmReal_t srate, cmReal_t maxDelayMs, const cmReal_t* tapMs, const cmReal_t* tapFfGain, const cmReal_t* tapFbGain, unsigned tapCnt )
  1861. {
  1862. cmRC_t rc;
  1863. if(( rc = cmIDelayFinal(p)) != cmOkRC )
  1864. return rc;
  1865. p->dn = (unsigned)floor( maxDelayMs * srate / 1000.0 );
  1866. p->mn = p->dn + 3;
  1867. p->m = cmMemResizeZ(cmSample_t,p->m,p->mn);
  1868. p->d = p->m + 1;
  1869. p->tn = tapCnt;
  1870. p->ti = cmMemResize(cmReal_t,p->ti,tapCnt);
  1871. p->tff = cmMemResize(cmReal_t,p->tff,tapCnt);
  1872. p->tfb = cmMemResize(cmReal_t,p->tfb,tapCnt);
  1873. p->srate = srate;
  1874. unsigned i;
  1875. for(i=0; i<tapCnt; ++i)
  1876. {
  1877. cmIDelaySetTapMs(p,i,tapMs[i]);
  1878. p->tff[i] = tapFfGain[i];
  1879. p->tfb[i] = tapFbGain[i];
  1880. }
  1881. return rc;
  1882. }
  1883. cmRC_t cmIDelayFinal(cmIDelay* p )
  1884. { return cmOkRC; }
  1885. cmRC_t cmIDelayExec( cmIDelay* p, const cmSample_t* x, cmSample_t* y, unsigned n )
  1886. {
  1887. unsigned i,j;
  1888. for(i=0; i<n; ++i)
  1889. {
  1890. cmSample_t fb = 0;
  1891. y[i] = 0;
  1892. // calculate the output sample
  1893. for(j=0; j<p->tn; ++j)
  1894. {
  1895. // get tap_j
  1896. cmReal_t tfi = p->ii - p->ti[j];
  1897. // mod it into 0:dn-1
  1898. while( tfi < 0 )
  1899. tfi += p->dn;
  1900. int ti = floor(tfi);
  1901. cmReal_t tf = tfi - ti;
  1902. cmSample_t v = _lin_interp(tf,p->d[ti],p->d[ti+1]); // _cube_interp(tf,p->d[ti-1],p->d[ti],p->d[ti+1],p->d[ti+2]);
  1903. y[i] += p->tff[j] * v;
  1904. fb += p->tfb[j] * v;
  1905. }
  1906. // insert incoming sample
  1907. p->d[p->ii] = x[i] + fb;
  1908. // advance the delay line
  1909. ++p->ii;
  1910. // handle beg/end delay sample duplication
  1911. // -1 0 1 2 .... dn-1 dn dn+1
  1912. // a b c a b c
  1913. // The samples at position -1 0 1 must be duplicated
  1914. // at positions dn-1,dn,dn+1 so that output sample calculation
  1915. // does not need to deal with buffer wrap-around issues.
  1916. if( p->ii == 1 )
  1917. p->d[p->dn] = x[i];
  1918. else
  1919. if( p->ii == 2 )
  1920. p->d[p->dn+1] = x[i];
  1921. else
  1922. if( p->ii == p->dn )
  1923. {
  1924. p->d[-1] = x[i];
  1925. p->ii = 0;
  1926. }
  1927. }
  1928. return cmOkRC;
  1929. }
  1930. cmRC_t cmIDelaySetTapMs( cmIDelay* p, unsigned tapIdx, cmReal_t tapMs )
  1931. {
  1932. cmRC_t rc = cmOkRC;
  1933. if( tapIdx < p->tn )
  1934. p->ti[tapIdx] = tapMs * p->srate / 1000.0;
  1935. else
  1936. rc = cmCtxRtCondition( &p->obj, cmInvalidArgRC, "Tap index %i is out of range 0 - %i.",tapIdx,p->tn-1 );
  1937. return rc;
  1938. }
  1939. //=======================================================================================================================
  1940. cmGroupSel* cmGroupSelAlloc( cmCtx* c, cmGroupSel* p, unsigned chCnt, unsigned groupCnt, unsigned chsPerGroup )
  1941. {
  1942. cmGroupSel* op = cmObjAlloc(cmGroupSel, c, p );
  1943. if( chCnt != 0 )
  1944. if( cmGroupSelInit( op, chCnt, groupCnt, chsPerGroup ) != cmOkRC )
  1945. cmGroupSelFree(&op);
  1946. return op;
  1947. }
  1948. cmRC_t cmGroupSelFree( cmGroupSel** pp )
  1949. {
  1950. cmRC_t rc = cmOkRC;
  1951. if( pp == NULL || *pp == NULL )
  1952. return cmOkRC;
  1953. cmGroupSel* p = *pp;
  1954. if((rc = cmGroupSelFinal(p)) != cmOkRC )
  1955. return rc;
  1956. cmMemFree(p->groupArray);
  1957. cmMemFree(p->chArray);
  1958. cmObjFree(pp);
  1959. return cmOkRC;
  1960. }
  1961. cmRC_t cmGroupSelInit( cmGroupSel* p, unsigned chCnt, unsigned groupCnt, unsigned chsPerGroup )
  1962. {
  1963. cmRC_t rc;
  1964. if((rc = cmGroupSelFinal(p)) != cmOkRC )
  1965. return rc;
  1966. p->chArray = cmMemResizeZ(cmGroupSelCh,p->chArray,chCnt);
  1967. p->groupArray = cmMemResizeZ(cmGroupSelGrp,p->groupArray,chCnt);
  1968. p->chCnt = chCnt;
  1969. p->groupCnt = groupCnt;
  1970. p->chsPerGroup = chsPerGroup;
  1971. unsigned i;
  1972. for(i=0; i<p->chCnt; ++i)
  1973. p->chArray[i].groupIdx = cmInvalidIdx;
  1974. for(i=0; i<p->groupCnt; ++i)
  1975. {
  1976. p->groupArray[i].chIdxArray = cmMemAllocZ(unsigned, p->chCnt);
  1977. p->groupArray[i].chIdxCnt = 0;
  1978. }
  1979. return rc;
  1980. }
  1981. cmRC_t cmGroupSelFinal( cmGroupSel* p )
  1982. {
  1983. unsigned i;
  1984. for(i=0; i<p->groupCnt; ++i)
  1985. cmMemFree(p->groupArray[i].chIdxArray);
  1986. return cmOkRC;
  1987. }
  1988. cmRC_t cmGroupSetChannelGate( cmGroupSel* p, unsigned chIdx, bool gateFl )
  1989. {
  1990. assert(chIdx <p->chCnt);
  1991. cmGroupSelCh* cp = p->chArray + chIdx;
  1992. if( gateFl==true && cp->gateFl==false )
  1993. {
  1994. cp->readyFl = true;
  1995. }
  1996. if( gateFl==false && cp->gateFl==true )
  1997. {
  1998. cp->offsetFl = true;
  1999. cp->readyFl = false;
  2000. }
  2001. cp->gateFl = gateFl;
  2002. //printf("ch:%i gate:%i ready:%i offset:%i grp:%i\n",chIdx,cp->gateFl,cp->readyFl,cp->offsetFl,cp->groupIdx);
  2003. return cmOkRC;
  2004. }
  2005. cmRC_t cmGroupSetChannelRMS( cmGroupSel* p, unsigned chIdx, cmReal_t rms )
  2006. {
  2007. assert(chIdx <p->chCnt);
  2008. cmGroupSelCh* cp = p->chArray + chIdx;
  2009. cp->rms = rms;
  2010. return cmOkRC;
  2011. }
  2012. cmRC_t cmGroupSelExec( cmGroupSel* p )
  2013. {
  2014. unsigned i,j;
  2015. unsigned availGroupCnt = 0;
  2016. p->chsPerGroup = cmMin( p->chsPerGroup, p->chCnt );
  2017. p->updateFl = false;
  2018. // clear the create and release flags on each group
  2019. // and get the count of available groups
  2020. for(i=0; i<p->groupCnt; ++i)
  2021. {
  2022. cmGroupSelGrp* gp = p->groupArray + i;
  2023. gp->createFl = false;
  2024. if( gp->releaseFl )
  2025. {
  2026. // clear the groupIdx from the channels assigned to this released group
  2027. for(j=0; j<gp->chIdxCnt; ++j)
  2028. p->chArray[ gp->chIdxArray[j] ].groupIdx = cmInvalidIdx;
  2029. gp->releaseFl = false;
  2030. gp->chIdxCnt = 0;
  2031. }
  2032. if( gp->chIdxCnt == 0 )
  2033. ++availGroupCnt;
  2034. }
  2035. // count the number of ready but unassigned ch's and
  2036. // release any groups which contain a channel with a gate offset
  2037. unsigned readyChCnt = 0;
  2038. for(i=0; i<p->chCnt; ++i)
  2039. {
  2040. cmGroupSelCh* cp = p->chArray + i;
  2041. // count the number of channels that are ready to be assigned
  2042. if( cp->readyFl )
  2043. ++readyChCnt;
  2044. // if this channel offset and it had been assigned to a group
  2045. // then mark its group for release
  2046. if( cp->offsetFl && cp->groupIdx != cmInvalidIdx )
  2047. {
  2048. p->groupArray[cp->groupIdx].releaseFl = true;
  2049. p->updateFl = true;
  2050. }
  2051. }
  2052. // assign ready ch's to available groups
  2053. while( readyChCnt > p->chsPerGroup && availGroupCnt > 0 )
  2054. {
  2055. unsigned groupIdx;
  2056. // locate an available group
  2057. for(groupIdx=0; groupIdx<p->groupCnt; ++groupIdx)
  2058. if( p->groupArray[groupIdx].chIdxCnt == 0 )
  2059. break;
  2060. if( groupIdx == p->groupCnt )
  2061. break;
  2062. --availGroupCnt;
  2063. cmGroupSelGrp* gp = p->groupArray + groupIdx;
  2064. printf("gs - group:%i chs: ",groupIdx);
  2065. // assign chsPerGroup ch's to this group
  2066. for(i=0; i<p->chCnt && gp->chIdxCnt < p->chsPerGroup; ++i)
  2067. if(p->chArray[i].readyFl )
  2068. {
  2069. p->chArray[i].readyFl = false; // this ch is no longer ready because it is assigned
  2070. p->chArray[i].groupIdx = groupIdx; // set this ch's group idx
  2071. gp->chIdxArray[ gp->chIdxCnt ] = i; // assign channel to group
  2072. gp->chIdxCnt += 1; // update the group ch count
  2073. gp->createFl = true;
  2074. p->updateFl = true;
  2075. --readyChCnt;
  2076. printf("%i ",i);
  2077. }
  2078. printf("\n");
  2079. }
  2080. return cmOkRC;
  2081. }
  2082. //=======================================================================================================================
  2083. cmAudioNofM* cmAudioNofMAlloc( cmCtx* c, cmAudioNofM* p, cmReal_t srate, unsigned inChCnt, unsigned outChCnt, cmReal_t fadeTimeMs )
  2084. {
  2085. cmAudioNofM* op = cmObjAlloc(cmAudioNofM, c, p );
  2086. if( srate != 0 )
  2087. if( cmAudioNofMInit( op, srate, inChCnt, outChCnt, fadeTimeMs ) != cmOkRC )
  2088. cmAudioNofMFree(&op);
  2089. return op;
  2090. }
  2091. cmRC_t cmAudioNofMFree( cmAudioNofM** pp )
  2092. {
  2093. cmRC_t rc = cmOkRC;
  2094. if( pp == NULL || *pp == NULL )
  2095. return cmOkRC;
  2096. cmAudioNofM* p = *pp;
  2097. if((rc = cmAudioNofMFinal(p)) != cmOkRC )
  2098. return rc;
  2099. cmMemFree(p->outArray);
  2100. cmMemFree(p->inArray);
  2101. cmObjFree(pp);
  2102. return cmOkRC;
  2103. }
  2104. cmRC_t cmAudioNofMInit( cmAudioNofM* p, cmReal_t srate, unsigned iChCnt, unsigned oChCnt, cmReal_t fadeTimeMs )
  2105. {
  2106. cmRC_t rc;
  2107. if((rc = cmAudioNofMFinal(p)) != cmOkRC )
  2108. return rc;
  2109. p->iChCnt = iChCnt;
  2110. p->inArray = cmMemResizeZ(cmAudioNofM_In,p->inArray,iChCnt);
  2111. p->oChCnt = oChCnt;
  2112. p->outArray = cmMemResizeZ(cmAudioNofM_Out,p->outArray,oChCnt);
  2113. p->nxtOutChIdx = 0;
  2114. unsigned i;
  2115. for(i=0; i<p->iChCnt; ++i)
  2116. {
  2117. p->inArray[i].fader = cmFaderAlloc(p->obj.ctx, NULL, srate, fadeTimeMs );
  2118. p->inArray[i].outChIdx = cmInvalidIdx;
  2119. }
  2120. cmAudioNofMSetFadeMs( p, fadeTimeMs );
  2121. return rc;
  2122. }
  2123. cmRC_t cmAudioNofMFinal( cmAudioNofM* p )
  2124. {
  2125. unsigned i;
  2126. for(i=0; i<p->iChCnt; ++i)
  2127. cmFaderFree(&p->inArray[i].fader);
  2128. return cmOkRC;
  2129. }
  2130. cmRC_t cmAudioNofMSetChannelGate( cmAudioNofM* p, unsigned inChIdx, bool gateFl )
  2131. {
  2132. assert( inChIdx < p->iChCnt );
  2133. cmAudioNofM_In* ip = p->inArray + inChIdx;
  2134. if( ip->gateFl && gateFl == false )
  2135. ip->offsetFl = true;
  2136. if( ip->gateFl == false && gateFl )
  2137. ip->onsetFl = true;
  2138. ip->gateFl = gateFl;
  2139. printf("nom: %p ch:%i gate:%i on:%i off:%i\n",p,inChIdx,ip->gateFl,ip->offsetFl,ip->onsetFl);
  2140. return cmOkRC;
  2141. }
  2142. cmRC_t cmAudioNofMExec( cmAudioNofM* p, const cmSample_t* x[], unsigned inChCnt, cmSample_t* y[], unsigned outChCnt, unsigned n )
  2143. {
  2144. assert( inChCnt == p->iChCnt && outChCnt == p->oChCnt );
  2145. unsigned i;
  2146. // for each output channel
  2147. for(i=0; i<p->oChCnt; ++i)
  2148. {
  2149. cmAudioNofM_Out* op = p->outArray + i;
  2150. cmAudioNofM_In* ip = op->list;
  2151. cmAudioNofM_In* pp = NULL;
  2152. // for each input assigned to this output chanenl
  2153. while( ip != NULL )
  2154. {
  2155. // if the channel is no longer active
  2156. if( ip->offsetFl && ip->fader->gain == 0.0 )
  2157. {
  2158. printf("nom: off - out:%i\n",ip->outChIdx);
  2159. // remove it from the output channels list
  2160. ip->offsetFl = false;
  2161. ip->outChIdx = cmInvalidIdx;
  2162. if( pp == NULL )
  2163. op->list = ip->link;
  2164. else
  2165. pp->link = ip->link;
  2166. }
  2167. pp = ip;
  2168. ip = ip->link;
  2169. }
  2170. }
  2171. // for each input channel
  2172. for(i=0; i<inChCnt; ++i)
  2173. {
  2174. cmAudioNofM_In* ip = p->inArray + i;
  2175. // if this channel is starting
  2176. if( ip->onsetFl == true && ip->offsetFl == false )
  2177. {
  2178. // assign it to the next output channel
  2179. ip->onsetFl = false;
  2180. ip->outChIdx = p->nxtOutChIdx;
  2181. ip->link = p->outArray[ ip->outChIdx ].list;
  2182. p->outArray[ ip->outChIdx ].list = ip;
  2183. p->nxtOutChIdx = (p->nxtOutChIdx + 1) % p->oChCnt;
  2184. printf("nom: on - in:%i out:%i\n",i,ip->outChIdx);
  2185. }
  2186. // if this channel is active - then mix its input
  2187. if( ip->outChIdx != cmInvalidIdx )
  2188. {
  2189. cmFaderExec( ip->fader, n, ip->gateFl, true, x[i], y[ ip->outChIdx ] );
  2190. }
  2191. }
  2192. return cmOkRC;
  2193. }
  2194. cmRC_t cmAudioNofMSetFadeMs( cmAudioNofM* p, cmReal_t fadeTimeMs )
  2195. {
  2196. unsigned i;
  2197. for(i=0; i<p->iChCnt; ++i)
  2198. cmFaderSetFadeTime(p->inArray[i].fader,fadeTimeMs);
  2199. return cmOkRC;
  2200. }
  2201. //=======================================================================================================================
  2202. cmAdsr* cmAdsrAlloc( cmCtx* c, cmAdsr* p, cmReal_t srate, bool trigFl, cmReal_t minL, cmReal_t dlyMs, cmReal_t atkMs, cmReal_t atkL, cmReal_t dcyMs, cmReal_t susMs, cmReal_t susL, cmReal_t rlsMs )
  2203. {
  2204. cmAdsr* op = cmObjAlloc(cmAdsr, c, p );
  2205. if( srate != 0 )
  2206. if( cmAdsrInit( op, srate, trigFl, minL, dlyMs, atkMs, atkL, dcyMs, susMs, susL, rlsMs ) != cmOkRC )
  2207. cmAdsrFree(&op);
  2208. return op;
  2209. }
  2210. cmRC_t cmAdsrFree( cmAdsr** pp )
  2211. {
  2212. cmRC_t rc = cmOkRC;
  2213. if( pp == NULL || *pp == NULL )
  2214. return cmOkRC;
  2215. cmAdsr* p = *pp;
  2216. if((rc = cmAdsrFinal(p)) != cmOkRC )
  2217. return rc;
  2218. cmObjFree(pp);
  2219. return cmOkRC;
  2220. }
  2221. cmRC_t cmAdsrInit( cmAdsr* p, cmReal_t srate, bool trigFl, cmReal_t minL, cmReal_t dlyMs, cmReal_t atkMs, cmReal_t atkL, cmReal_t dcyMs, cmReal_t susMs, cmReal_t susL, cmReal_t rlsMs )
  2222. {
  2223. cmRC_t rc;
  2224. if((rc = cmAdsrFinal(p)) != cmOkRC )
  2225. return rc;
  2226. // this is a limitation of the design - the design should be replaced with one
  2227. // which increments/decrements the level until it reaches a limit instead of calculating
  2228. // durations
  2229. //assert(atkL>=0 && minL>=0);
  2230. p->srate = srate;
  2231. p->trigModeFl = trigFl;
  2232. p->levelMin = minL;
  2233. p->scaleDur = 1.0;
  2234. cmAdsrSetTime(p,dlyMs,kDlyAdsrId);
  2235. cmAdsrSetTime(p,atkMs,kAtkAdsrId);
  2236. cmAdsrSetTime(p,dcyMs,kDcyAdsrId);
  2237. cmAdsrSetTime(p,susMs,kSusAdsrId);
  2238. cmAdsrSetTime(p,rlsMs,kRlsAdsrId);
  2239. cmAdsrSetLevel(p,atkL,kAtkAdsrId);
  2240. cmAdsrSetLevel(p,susL,kSusAdsrId);
  2241. p->state = kDoneAdsrId;
  2242. p->durSmp = 0;
  2243. p->level = p->levelMin;
  2244. p->gateFl = false;
  2245. p->atkDurSmp = 0;
  2246. p->rlsDurSmp = 0;
  2247. return cmOkRC;
  2248. }
  2249. cmRC_t cmAdsrFinal( cmAdsr* p )
  2250. { return cmOkRC; }
  2251. cmReal_t cmAdsrExec( cmAdsr* p, unsigned procSmpCnt, bool gateFl, cmReal_t tscale, cmReal_t ascale )
  2252. {
  2253. double scaleAmp = ascale;
  2254. double scaleDur = tscale;
  2255. // if onset
  2256. if( p->gateFl == false && gateFl==true )
  2257. {
  2258. p->scaleDur = scaleDur==0 ? 1.0 : fabs(scaleDur);
  2259. //printf("sd:%f %f\n",scaleDur,scaleAmp);
  2260. switch( p->state )
  2261. {
  2262. case kDlyAdsrId:
  2263. // if in delay mode when the re-attack occurs don't do anything
  2264. break;
  2265. case kAtkAdsrId:
  2266. case kDcyAdsrId:
  2267. case kSusAdsrId:
  2268. case kRlsAdsrId:
  2269. // if the atk level == 0 then fall through to kDoneAdsrId
  2270. if( p->actAtkLevel != 0 )
  2271. {
  2272. // re-attak mode:
  2273. // Scale the attack time to the current level relative to the attack level.
  2274. // In general this will result in a decrease in the attack duration.
  2275. p->atkDurSmp = cmMax(1,floor(p->atkSmp * (p->actAtkLevel - p->level) / p->actAtkLevel));
  2276. p->atkBegLevel = p->level;
  2277. p->durSmp = 0;
  2278. p->state = kAtkAdsrId;
  2279. p->actAtkLevel = p->atkLevel * scaleAmp;
  2280. p->actSusLevel = p->susLevel * scaleAmp;
  2281. break;
  2282. }
  2283. case kDoneAdsrId:
  2284. p->atkBegLevel = p->levelMin;
  2285. p->atkDurSmp = p->atkSmp;
  2286. p->state = p->dlySmp == 0 ? kAtkAdsrId : kDlyAdsrId;
  2287. p->durSmp = 0;
  2288. p->actAtkLevel = p->atkLevel * scaleAmp;
  2289. p->actSusLevel = p->susLevel * scaleAmp;
  2290. break;
  2291. default:
  2292. { assert(0); }
  2293. }
  2294. }
  2295. // if an offset occurred and we are not in trigger mode - then go into release mode
  2296. if( p->trigModeFl==false && p->gateFl == true && gateFl == false )
  2297. {
  2298. switch( p->state )
  2299. {
  2300. case kDlyAdsrId:
  2301. case kAtkAdsrId:
  2302. case kDcyAdsrId:
  2303. case kSusAdsrId:
  2304. if( p->actSusLevel == 0 )
  2305. p->state = kDoneAdsrId;
  2306. else
  2307. {
  2308. // scale the release time to the current level relative to the sustain level
  2309. p->rlsDurSmp = cmMax(1,floor(p->rlsSmp * p->level / p->actSusLevel));
  2310. p->rlsLevel = p->level;
  2311. p->durSmp = 0;
  2312. }
  2313. break;
  2314. case kRlsAdsrId:
  2315. case kDoneAdsrId:
  2316. // nothing to do
  2317. break;
  2318. default:
  2319. { assert(0); }
  2320. }
  2321. p->state = kRlsAdsrId;
  2322. }
  2323. p->gateFl = gateFl;
  2324. switch( p->state )
  2325. {
  2326. case kDlyAdsrId:
  2327. p->level = p->levelMin;
  2328. if( p->durSmp >= p->dlySmp )
  2329. {
  2330. p->state = kAtkAdsrId;
  2331. p->durSmp = 0;
  2332. if( p->trigModeFl )
  2333. {
  2334. p->atkBegLevel = p->level;
  2335. p->atkDurSmp = p->atkSmp;
  2336. }
  2337. }
  2338. break;
  2339. case kAtkAdsrId:
  2340. if( p->atkDurSmp != 0 )
  2341. p->level = p->atkBegLevel + (p->actAtkLevel - p->atkBegLevel) * cmMin(p->durSmp,p->atkDurSmp) / p->atkDurSmp;
  2342. if( p->durSmp >= p->atkDurSmp || p->atkDurSmp == 0 )
  2343. {
  2344. p->state = kDcyAdsrId;
  2345. p->durSmp = 0;
  2346. }
  2347. break;
  2348. case kDcyAdsrId:
  2349. if( p->dcySmp != 0 )
  2350. p->level = p->actAtkLevel - ((p->actAtkLevel - p->actSusLevel) * cmMin(p->durSmp,p->dcySmp) / p->dcySmp );
  2351. if( p->durSmp >= p->dcySmp || p->dcySmp==0 )
  2352. {
  2353. p->state = kSusAdsrId;
  2354. p->durSmp = 0;
  2355. }
  2356. break;
  2357. case kSusAdsrId:
  2358. p->level = p->actSusLevel;
  2359. if( p->trigModeFl==true && p->durSmp >= p->susSmp )
  2360. {
  2361. p->state = kRlsAdsrId;
  2362. p->durSmp = 0;
  2363. p->rlsLevel = p->level;
  2364. p->rlsDurSmp = p->rlsSmp;
  2365. }
  2366. break;
  2367. case kRlsAdsrId:
  2368. if( p->rlsDurSmp != 0 )
  2369. p->level = p->rlsLevel - ((p->rlsLevel - p->levelMin) * cmMin(p->durSmp,p->rlsDurSmp) / p->rlsDurSmp);
  2370. if( p->durSmp >= p->rlsDurSmp || p->rlsDurSmp==0 )
  2371. {
  2372. p->state = kDoneAdsrId;
  2373. p->durSmp = 0;
  2374. }
  2375. break;
  2376. case kDoneAdsrId:
  2377. p->level = p->levelMin;
  2378. break;
  2379. default:
  2380. { assert(0); }
  2381. }
  2382. p->durSmp += floor(procSmpCnt/p->scaleDur);
  2383. return p->level;
  2384. }
  2385. void _cmAdsrSetTime( cmAdsr* p, cmReal_t ms, int* smpPtr )
  2386. {
  2387. *smpPtr = cmMax(1,floor(p->srate * ms / 1000.0 ));
  2388. }
  2389. void cmAdsrSetTime( cmAdsr* p, cmReal_t ms, unsigned id )
  2390. {
  2391. switch( id )
  2392. {
  2393. case kDlyAdsrId:
  2394. _cmAdsrSetTime(p,ms,&p->dlySmp);
  2395. break;
  2396. case kAtkAdsrId:
  2397. _cmAdsrSetTime(p,ms,&p->atkSmp);
  2398. break;
  2399. case kDcyAdsrId:
  2400. _cmAdsrSetTime(p,ms,&p->dcySmp);
  2401. break;
  2402. case kSusAdsrId:
  2403. _cmAdsrSetTime(p,ms,&p->susSmp);
  2404. break;
  2405. case kRlsAdsrId:
  2406. _cmAdsrSetTime(p,ms,&p->rlsSmp);
  2407. break;
  2408. default:
  2409. { assert(0); }
  2410. }
  2411. }
  2412. void cmAdsrSetLevel( cmAdsr* p, cmReal_t level, unsigned id )
  2413. {
  2414. switch( id )
  2415. {
  2416. case kDlyAdsrId:
  2417. p->levelMin = level;
  2418. break;
  2419. case kAtkAdsrId:
  2420. p->atkLevel = level;
  2421. p->actAtkLevel = p->atkLevel;
  2422. break;
  2423. case kSusAdsrId:
  2424. p->susLevel = level;
  2425. p->actSusLevel = p->susLevel;
  2426. break;
  2427. default:
  2428. { assert(0); }
  2429. }
  2430. }
  2431. void cmAdsrReport( cmAdsr* p, cmRpt_t* rpt )
  2432. {
  2433. cmRptPrintf(rpt,"state:%i gate:%i phs:%i d:%i a:%i (%i) d:%i s:%i r:%i (%i) - min:%f atk:%f\n",p->state,p->gateFl,p->durSmp,p->dlySmp,p->atkSmp,p->atkDurSmp,p->dcySmp,p->susSmp,p->rlsSmp,p->rlsDurSmp, p->levelMin, p->atkLevel);
  2434. }
  2435. //=======================================================================================================================
  2436. cmCompressor* cmCompressorAlloc( cmCtx* c, cmCompressor* p, cmReal_t srate, unsigned procSmpCnt, cmReal_t inGain, cmReal_t rmsWndMaxMs, cmReal_t rmsWndMs, cmReal_t threshDb, cmReal_t ratio_num, cmReal_t atkMs, cmReal_t rlsMs, cmReal_t outGain, bool bypassFl )
  2437. {
  2438. cmCompressor* op = cmObjAlloc(cmCompressor, c, p );
  2439. if( srate != 0 )
  2440. if( cmCompressorInit( op, srate, procSmpCnt, inGain, rmsWndMaxMs, rmsWndMs, threshDb, ratio_num, atkMs, rlsMs, outGain, bypassFl ) != cmOkRC )
  2441. cmCompressorFree(&op);
  2442. return op;
  2443. }
  2444. cmRC_t cmCompressorFree( cmCompressor** pp )
  2445. {
  2446. cmRC_t rc = cmOkRC;
  2447. if( pp == NULL || *pp == NULL )
  2448. return cmOkRC;
  2449. cmCompressor* p = *pp;
  2450. if((rc = cmCompressorFinal(p)) != cmOkRC )
  2451. return rc;
  2452. cmMemFree(p->rmsWnd);
  2453. cmObjFree(pp);
  2454. return cmOkRC;
  2455. }
  2456. cmRC_t cmCompressorInit( cmCompressor* p, cmReal_t srate, unsigned procSmpCnt, cmReal_t inGain, cmReal_t rmsWndMaxMs, cmReal_t rmsWndMs, cmReal_t threshDb, cmReal_t ratio_num, cmReal_t atkMs, cmReal_t rlsMs, cmReal_t outGain, bool bypassFl )
  2457. {
  2458. cmRC_t rc;
  2459. if((rc = cmCompressorFinal(p)) != cmOkRC )
  2460. return rc;
  2461. p->srate = srate;
  2462. p->procSmpCnt = procSmpCnt;
  2463. p->threshDb = threshDb;
  2464. p->ratio_num = ratio_num;
  2465. cmCompressorSetAttackMs(p,atkMs);
  2466. cmCompressorSetReleaseMs(p,rlsMs);
  2467. p->inGain = inGain;
  2468. p->outGain = outGain;
  2469. p->bypassFl = bypassFl;
  2470. p->rmsWndAllocCnt = cmMax(1,(unsigned)floor(rmsWndMaxMs * srate / (1000.0 * procSmpCnt)));
  2471. p->rmsWnd = cmMemResizeZ(cmSample_t,p->rmsWnd,p->rmsWndAllocCnt);
  2472. cmCompressorSetRmsWndMs(p, rmsWndMs );
  2473. p->rmsWndIdx = 0;
  2474. p->state = kRlsCompId;
  2475. p->timeConstDb = 10.0;
  2476. p->accumDb = p->threshDb;
  2477. return rc;
  2478. }
  2479. cmRC_t cmCompressorFinal( cmCompressor* p )
  2480. { return cmOkRC; }
  2481. /*
  2482. The ratio determines to what degree a signal above the threshold is reduced.
  2483. Given a 2:1 ratio, a signal 2dB above the threshold will be reduced to 1db above the threshold.
  2484. Given a 4:1 ratio, a signal 2dB above the threshold will be reduced to 0.25db above the threshold.
  2485. Gain_reduction_db = (thresh - signal) / ratio_numerator (difference between the threshold and signal level after reduction)
  2486. Gain Coeff = 10^(gain_reduction_db / 20);
  2487. Total_reduction_db = signal - threshold + Gain_reduc_db
  2488. (total change in signal level)
  2489. The attack can be viewed as beginning at the threshold and moving to the peak
  2490. over some period of time. In linear terms this will go from 1.0 to the max gain
  2491. reductions. In this case we step from thresh to peak at a fixed rate in dB
  2492. based on the attack time.
  2493. Db: thresh - [thesh:peak] / ratio_num
  2494. Linear: pow(10, (thresh - [thesh:peak] / ratio_num)/20 );
  2495. During attacks p->accumDb increments toward the p->pkDb.
  2496. During release p->accumDb decrements toward the threshold.
  2497. (thresh - accumDb) / ratio_num gives the signal level which will be achieved
  2498. if this value is converted to linear form and applied as a gain coeff.
  2499. See compressor.m
  2500. */
  2501. cmRC_t cmCompressorExec( cmCompressor* p, const cmSample_t* x, cmSample_t* y, unsigned n )
  2502. {
  2503. cmSample_t xx[n];
  2504. cmVOS_MultVVS(xx,n,x,p->inGain); // apply input gain
  2505. p->rmsWnd[ p->rmsWndIdx ] = cmVOS_RMS(xx, n, n ); // calc and store signal RMS
  2506. p->rmsWndIdx = (p->rmsWndIdx + 1) % p->rmsWndCnt; // advance the RMS storage buffer
  2507. cmReal_t rmsLin = cmVOS_Sum(p->rmsWnd,p->rmsWndCnt) / p->rmsWndCnt; // calc avg RMS
  2508. cmReal_t rmsDb = cmMax(-100.0,20 * log10(cmMax(0.00001,rmsLin))); // convert avg RMS to dB
  2509. rmsDb += 100.0;
  2510. // if the compressor is bypassed
  2511. if( p->bypassFl )
  2512. {
  2513. cmVOS_Copy(y,n,x); // copy through - with no input gain
  2514. return cmOkRC;
  2515. }
  2516. // if the signal is above the threshold
  2517. if( rmsDb <= p->threshDb )
  2518. p->state = kRlsCompId;
  2519. else
  2520. {
  2521. if( rmsDb > p->pkDb )
  2522. p->pkDb = rmsDb;
  2523. p->state = kAtkCompId;
  2524. }
  2525. switch( p->state )
  2526. {
  2527. case kAtkCompId:
  2528. p->accumDb = cmMin(p->pkDb, p->accumDb + p->timeConstDb * n / p->atkSmp );
  2529. break;
  2530. case kRlsCompId:
  2531. p->accumDb = cmMax(p->threshDb, p->accumDb - p->timeConstDb * n / p->rlsSmp );
  2532. break;
  2533. }
  2534. p->gain = pow(10.0,(p->threshDb - p->accumDb) / (p->ratio_num * 20.0));
  2535. cmVOS_MultVVS(y,n,xx,p->gain * p->outGain);
  2536. return cmOkRC;
  2537. }
  2538. void _cmCompressorSetMs( cmCompressor* p, cmReal_t ms, unsigned* smpPtr )
  2539. { *smpPtr = cmMax(1,(unsigned)floor(ms * p->srate / 1000.0)); }
  2540. void cmCompressorSetAttackMs( cmCompressor* p, cmReal_t ms )
  2541. { _cmCompressorSetMs(p,ms,&p->atkSmp); }
  2542. void cmCompressorSetReleaseMs( cmCompressor* p, cmReal_t ms )
  2543. { _cmCompressorSetMs(p,ms,&p->rlsSmp); }
  2544. void cmCompressorSetThreshDb( cmCompressor* p, cmReal_t threshDb )
  2545. { p->threshDb = cmMax(0.0,100 + threshDb); }
  2546. void cmCompressorSetRmsWndMs( cmCompressor* p, cmReal_t ms )
  2547. {
  2548. p->rmsWndCnt = cmMax(1,(unsigned)floor(ms * p->srate / (1000.0 * p->procSmpCnt)));
  2549. // do not allow rmsWndCnt to exceed rmsWndAllocCnt
  2550. if( p->rmsWndCnt > p->rmsWndAllocCnt )
  2551. p->rmsWndCnt = p->rmsWndAllocCnt;
  2552. }
  2553. //=======================================================================================================================
  2554. cmBiQuadEq* cmBiQuadEqAlloc( cmCtx* c, cmBiQuadEq* p, cmReal_t srate, unsigned mode, cmReal_t f0Hz, cmReal_t Q, cmReal_t gainDb, bool bypassFl )
  2555. {
  2556. cmBiQuadEq* op = cmObjAlloc(cmBiQuadEq, c, p );
  2557. if( srate != 0 )
  2558. if( cmBiQuadEqInit( op, srate, mode, f0Hz, Q, gainDb, bypassFl ) != cmOkRC )
  2559. cmBiQuadEqFree(&op);
  2560. return op;
  2561. }
  2562. cmRC_t cmBiQuadEqFree( cmBiQuadEq** pp )
  2563. {
  2564. cmRC_t rc = cmOkRC;
  2565. if( pp == NULL || *pp == NULL )
  2566. return cmOkRC;
  2567. cmBiQuadEq* p = *pp;
  2568. if((rc = cmBiQuadEqFinal(p)) != cmOkRC )
  2569. return rc;
  2570. cmObjFree(pp);
  2571. return cmOkRC;
  2572. }
  2573. void _cmBiQuadEqInit( cmBiQuadEq* p )
  2574. {
  2575. cmReal_t w0 = 2*M_PI*p->f0Hz/p->srate;
  2576. cmReal_t cos_w0 = cos(w0);
  2577. cmReal_t alpha = sin(w0)/(2*p->Q);
  2578. if( p->mode==kLowShelfBqId || p->mode==kHighShelfBqId )
  2579. {
  2580. cmReal_t c = p->mode==kLowShelfBqId ? 1.0 : -1.0;
  2581. cmReal_t A = pow(10.0,p->gainDb/40.0);
  2582. cmReal_t B = 2*sqrt(A)*alpha;
  2583. p->b[0] = A*( (A+1) - c * (A-1)*cos_w0 + B );
  2584. p->b[1] = c*2*A*( (A-1) - c * (A+1)*cos_w0);
  2585. p->b[2] = A*( (A+1) - c * (A-1)*cos_w0 - B );
  2586. p->a[0] = (A+1) + c * (A-1)*cos_w0 + B;
  2587. p->a[1] = -c*2*( (A-1) + c * (A+1)*cos_w0);
  2588. p->a[2] = (A+1) + c * (A-1)*cos_w0 - B;
  2589. }
  2590. else
  2591. {
  2592. if( p->mode != kPeakBqId )
  2593. {
  2594. p->a[0] = 1 + alpha;
  2595. p->a[1] = -2*cos_w0;
  2596. p->a[2] = 1 - alpha;
  2597. }
  2598. switch(p->mode)
  2599. {
  2600. case kLpfBqId:
  2601. case kHpFBqId:
  2602. {
  2603. cmReal_t c = p->mode==kLpfBqId ? 1.0 : -1.0;
  2604. p->b[0] = (1 - c * cos_w0)/2;
  2605. p->b[1] = c * (1 - c * cos_w0);
  2606. p->b[2] = (1 - c * cos_w0)/2;
  2607. }
  2608. break;
  2609. case kBpfBqId:
  2610. p->b[0] = p->Q*alpha;
  2611. p->b[1] = 0;
  2612. p->b[2] = -p->Q*alpha;
  2613. break;
  2614. case kNotchBqId:
  2615. p->b[0] = 1;
  2616. p->b[1] = -2*cos_w0;
  2617. p->b[2] = 1;
  2618. break;
  2619. case kAllpassBqId:
  2620. p->b[0] = 1 - alpha;
  2621. p->b[1] = -2*cos_w0;
  2622. p->b[2] = 1 + alpha;
  2623. break;
  2624. case kPeakBqId:
  2625. {
  2626. cmReal_t A = pow(10.0,p->gainDb/40.0);
  2627. p->b[0] = 1 + alpha*A;
  2628. p->b[1] = -2*cos_w0;
  2629. p->b[2] = 1 - alpha*A;
  2630. p->a[0] = 1 + alpha/A;
  2631. p->a[1] = -2*cos_w0;
  2632. p->a[2] = 1 - alpha/A;
  2633. }
  2634. break;
  2635. }
  2636. }
  2637. cmReal_t a0 = p->a[0];
  2638. unsigned i=0;
  2639. for(; i<3; ++i)
  2640. {
  2641. p->b[i]/=a0;
  2642. p->a[i]/=a0;
  2643. }
  2644. if(0)
  2645. {
  2646. printf("sr:%f mode:%i f0:%f q:%f gain:%f\n", p->srate,p->mode,p->f0Hz,p->Q,p->gainDb);
  2647. for(i=0; i<3; ++i)
  2648. printf("a[%i]=%f b[%i]=%f ",i,p->a[i],i,p->b[i]);
  2649. printf("\n");
  2650. }
  2651. }
  2652. cmRC_t cmBiQuadEqInit( cmBiQuadEq* p, cmReal_t srate, unsigned mode, cmReal_t f0Hz, cmReal_t Q, cmReal_t gainDb, bool bypassFl )
  2653. {
  2654. cmRC_t rc;
  2655. if((rc = cmBiQuadEqFinal(p)) != cmOkRC )
  2656. return rc;
  2657. memset(p->d,0,sizeof(p->d));
  2658. p->srate = srate;
  2659. cmBiQuadEqSet(p, mode, f0Hz, Q, gainDb );
  2660. _cmBiQuadEqInit(p);
  2661. return rc;
  2662. }
  2663. cmRC_t cmBiQuadEqFinal( cmBiQuadEq* p )
  2664. { return cmOkRC;}
  2665. cmRC_t cmBiQuadEqExec( cmBiQuadEq* p, const cmSample_t* x, cmSample_t* y, unsigned n )
  2666. {
  2667. if( y == NULL )
  2668. return cmOkRC;
  2669. if( x == NULL )
  2670. {
  2671. cmVOS_Zero(y,n);
  2672. return cmOkRC;
  2673. }
  2674. if( p->bypassFl )
  2675. {
  2676. cmVOS_Copy(y,n,x);
  2677. return cmOkRC;
  2678. }
  2679. // Direct Form I implementation
  2680. unsigned i=0;
  2681. for(; i<n; ++i)
  2682. {
  2683. y[i] = p->b[0]*x[i] + p->b[1]*p->d[0] + p->b[2]*p->d[1] - p->a[1]*p->d[2] - p->a[2]*p->d[3];
  2684. p->d[1] = p->d[0];
  2685. p->d[0] = x[i];
  2686. p->d[3] = p->d[2];
  2687. p->d[2] = y[i];
  2688. }
  2689. return cmOkRC;
  2690. }
  2691. void cmBiQuadEqSet( cmBiQuadEq* p, unsigned mode, cmReal_t f0Hz, cmReal_t Q, cmReal_t gainDb )
  2692. {
  2693. p->mode = mode;
  2694. p->f0Hz = f0Hz;
  2695. p->Q = Q;
  2696. p->gainDb= gainDb;
  2697. _cmBiQuadEqInit(p);
  2698. }
  2699. //=======================================================================================================================
  2700. cmDistDs* cmDistDsAlloc( cmCtx* c, cmDistDs* p, cmReal_t srate, cmReal_t inGain, cmReal_t downSrate, cmReal_t bits, bool rectFl, bool fullFl, cmReal_t clipDb, cmReal_t outGain, bool bypassFl )
  2701. {
  2702. cmDistDs* op = cmObjAlloc(cmDistDs, c, p );
  2703. if( srate != 0 )
  2704. if( cmDistDsInit( op, srate, inGain, downSrate, bits, rectFl, fullFl, clipDb, outGain, bypassFl ) != cmOkRC )
  2705. cmDistDsFree(&op);
  2706. return op;
  2707. }
  2708. cmRC_t cmDistDsFree( cmDistDs** pp )
  2709. {
  2710. cmRC_t rc = cmOkRC;
  2711. if( pp == NULL || *pp == NULL )
  2712. return cmOkRC;
  2713. cmDistDs* p = *pp;
  2714. if((rc = cmDistDsFinal(p)) != cmOkRC )
  2715. return rc;
  2716. cmObjFree(pp);
  2717. return cmOkRC;
  2718. }
  2719. cmRC_t cmDistDsInit( cmDistDs* p, cmReal_t srate, cmReal_t inGain, cmReal_t downSrate, cmReal_t bits, bool rectFl, bool fullFl, cmReal_t clipDb, cmReal_t outGain, bool bypassFl )
  2720. {
  2721. cmRC_t rc;
  2722. if((rc = cmDistDsFinal(p)) != cmOkRC )
  2723. return rc;
  2724. p->srate = srate;
  2725. p->downSrate = downSrate;
  2726. p->bits = bits;
  2727. p->rectFl = rectFl;
  2728. p->fullFl = fullFl;
  2729. p->clipDb = clipDb;
  2730. p->inGain = inGain;
  2731. p->outGain = outGain;
  2732. p->bypassFl = bypassFl;
  2733. p->fracIdx = 0;
  2734. p->lastVal = 0;
  2735. p->lastY = 0;
  2736. p->lastX = 0;
  2737. return rc;
  2738. }
  2739. cmRC_t cmDistDsFinal( cmDistDs* p )
  2740. { return cmOkRC; }
  2741. void _cmDistDsExpr0( cmDistDs* p, const cmSample_t* x, cmSample_t* y, unsigned n )
  2742. {
  2743. unsigned i= 0;
  2744. for(i=0; i<n; ++i)
  2745. {
  2746. p->lastY = fmod(p->lastY + fabs(x[i] - p->lastX),2.0);
  2747. y[i] = cmVOS_RMS(x,n,n) * x[i] * (p->lastY - 1.0);
  2748. p->lastX = x[i];
  2749. }
  2750. }
  2751. void _cmDistDsExpr1( cmDistDs* p, cmSample_t* x, cmSample_t* y, unsigned n )
  2752. {
  2753. unsigned i= 0;
  2754. for(i=0; i<n; ++i)
  2755. {
  2756. p->lastY = fmod(p->lastY + fabs(x[i] - p->lastX),2.0*M_PI);
  2757. y[i] = x[i] * sin(p->lastY);
  2758. p->lastX = x[i];
  2759. }
  2760. }
  2761. cmRC_t cmDistDsExec( cmDistDs* p, const cmSample_t* x, cmSample_t* y, unsigned n )
  2762. {
  2763. if( x == NULL )
  2764. {
  2765. if( y != NULL )
  2766. cmVOS_Zero(y,n);
  2767. return cmOkRC;
  2768. }
  2769. if( p->bypassFl )
  2770. {
  2771. cmVOS_Copy(y,n,x);
  2772. return cmOkRC;
  2773. }
  2774. unsigned maxVal = cmMax(2,(unsigned)round(pow(2.0,p->bits)));
  2775. double incr = 1.0; // p->downSrate / p->srate;
  2776. unsigned i;
  2777. enum { kNoRectId, kFullRectId, kHalfRectId };
  2778. unsigned rectCode = kNoRectId;
  2779. //cmSample_t t[n];
  2780. //_cmDistDsExpr0(p,x,t,n);
  2781. //x = t;
  2782. if( p->rectFl )
  2783. {
  2784. if( p->fullFl )
  2785. rectCode = kFullRectId;
  2786. else
  2787. rectCode = kHalfRectId;
  2788. }
  2789. double clipLevel = p->clipDb < -100.0 ? 0.0 : pow(10.0,p->clipDb/20.0);
  2790. for(i=0; i<n; ++i)
  2791. {
  2792. double ii = floor(p->fracIdx);
  2793. p->fracIdx += incr;
  2794. // if it is time to sample again
  2795. if( floor(p->fracIdx) != ii )
  2796. {
  2797. cmSample_t v = p->inGain * floor(x[i] * maxVal) / maxVal;
  2798. switch( rectCode )
  2799. {
  2800. case kFullRectId:
  2801. v = (cmSample_t)fabs(v);
  2802. break;
  2803. case kHalfRectId:
  2804. if( v < 0.0 )
  2805. v = 0.0;
  2806. break;
  2807. }
  2808. if( fabs(v) > clipLevel )
  2809. v = v<0.0 ? -clipLevel : clipLevel;
  2810. p->lastVal = v * p->outGain;
  2811. }
  2812. y[i] = p->lastVal;
  2813. }
  2814. return cmOkRC;
  2815. }