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

cmProc3.c 88KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627
  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. if( chGateV != NULL )
  1604. cp->gateFl = chGateV[i];
  1605. if( cp->gateFl )
  1606. cp->gain = cmMin(cp->gain + dgain,1.0);
  1607. else
  1608. cp->gain = cmMax(cp->gain - dgain,0.0);
  1609. if( cp->gain != 0.0 )
  1610. gateFl = true;
  1611. }
  1612. p->onFl = false;
  1613. p->offFl = false;
  1614. if( p->gateFl==false && gateFl==true )
  1615. p->onFl = true;
  1616. else
  1617. if( p->gateFl==true && gateFl==false )
  1618. p->offFl = true;
  1619. p->gateFl = gateFl;
  1620. return cmOkRC;
  1621. }
  1622. cmRC_t cmXfaderExecAudio( cmXfader* p, unsigned procSmpCnt, const bool* gateV, unsigned chCnt, const cmSample_t* x[], cmSample_t* y )
  1623. {
  1624. cmRC_t rc;
  1625. assert( chCnt == p->chCnt);
  1626. chCnt = cmMin(chCnt,p->chCnt);
  1627. if((rc = cmXfaderExec(p,procSmpCnt,gateV,chCnt)) != cmOkRC )
  1628. return rc;
  1629. unsigned i;
  1630. for(i=0; i<chCnt; ++i)
  1631. if( x[i] != NULL )
  1632. cmVOS_MultVaVS(y,procSmpCnt,x[i],p->chArray[i].gain);
  1633. return rc;
  1634. }
  1635. void cmXfaderSetXfadeTime( cmXfader* p, cmReal_t fadeTimeMs )
  1636. {
  1637. p->fadeSmpCnt = floor(fadeTimeMs * p->srate /1000.0);
  1638. }
  1639. void cmXfaderSelectOne( cmXfader* p, unsigned chIdx )
  1640. {
  1641. unsigned i = 0;
  1642. for(i=0; i<p->chCnt; ++i)
  1643. p->chArray[i].gateFl = i == chIdx;
  1644. }
  1645. void cmXfaderAllOff( cmXfader* p )
  1646. {
  1647. unsigned i = 0;
  1648. for(i=0; i<p->chCnt; ++i)
  1649. p->chArray[i].gateFl = false;
  1650. }
  1651. //==========================================================================================================================================
  1652. cmFader* cmFaderAlloc( cmCtx*c, cmFader* p, cmReal_t srate, cmReal_t fadeTimeMs )
  1653. {
  1654. cmFader* op = cmObjAlloc(cmFader, c, p );
  1655. if( srate != 0 )
  1656. if( cmFaderInit( op, srate, fadeTimeMs ) != cmOkRC )
  1657. cmFaderFree(&op);
  1658. return op;
  1659. }
  1660. cmRC_t cmFaderFree( cmFader** pp )
  1661. {
  1662. cmRC_t rc = cmOkRC;
  1663. if( pp == NULL || *pp == NULL )
  1664. return cmOkRC;
  1665. cmFader* p = *pp;
  1666. if((rc = cmFaderFinal(p)) != cmOkRC )
  1667. return rc;
  1668. cmObjFree(pp);
  1669. return cmOkRC;
  1670. }
  1671. cmRC_t cmFaderInit( cmFader* p, cmReal_t srate, cmReal_t fadeTimeMs )
  1672. {
  1673. cmRC_t rc;
  1674. if((rc = cmFaderFinal(p)) != cmOkRC )
  1675. return rc;
  1676. p->srate = srate;
  1677. p->gain = 0.0;
  1678. cmFaderSetFadeTime(p,fadeTimeMs);
  1679. return rc;
  1680. }
  1681. cmRC_t cmFaderFinal( cmFader* p )
  1682. { return cmOkRC; }
  1683. cmRC_t cmFaderExec( cmFader* p, unsigned procSmpCnt, bool gateFl, bool mixFl, const cmSample_t* x, cmSample_t* y )
  1684. {
  1685. cmReal_t d = (gateFl ? 1.0 : -1.0) * procSmpCnt / p->fadeSmpCnt;
  1686. // TODO: add fade curves
  1687. p->gain = cmMin(1.0,cmMax(0.0,p->gain + d));
  1688. if( x!=NULL && y!=NULL )
  1689. {
  1690. if( mixFl )
  1691. cmVOS_MultVaVS(y, procSmpCnt, x, 1.0/* p->gain*/);
  1692. else
  1693. cmVOS_MultVVS(y,procSmpCnt,x,p->gain);
  1694. }
  1695. return cmOkRC;
  1696. }
  1697. void cmFaderSetFadeTime( cmFader* p, cmReal_t fadeTimeMs )
  1698. {
  1699. p->fadeSmpCnt = (unsigned)floor( fadeTimeMs * p->srate / 1000.0 );
  1700. }
  1701. //=======================================================================================================================
  1702. cmCombFilt* cmCombFiltAlloc( cmCtx* c, cmCombFilt* p, cmReal_t srate, bool feedbackFl, cmReal_t minHz, cmReal_t alpha, cmReal_t hz, bool bypassFl )
  1703. {
  1704. cmCombFilt* op = cmObjAlloc(cmCombFilt, c, p );
  1705. op->idp = cmIDelayAlloc(c, NULL, 0, 0, NULL, NULL, NULL, 0 );
  1706. if( srate != 0 )
  1707. if( cmCombFiltInit( op, srate, feedbackFl, minHz, alpha, hz, bypassFl ) != cmOkRC )
  1708. cmCombFiltFree(&op);
  1709. return op;
  1710. }
  1711. cmRC_t cmCombFiltFree( cmCombFilt** pp)
  1712. {
  1713. cmRC_t rc = cmOkRC;
  1714. if( pp == NULL || *pp == NULL )
  1715. return cmOkRC;
  1716. cmCombFilt* p = *pp;
  1717. if((rc = cmCombFiltFinal(p)) != cmOkRC )
  1718. return rc;
  1719. cmMemFree(p->a);
  1720. cmMemFree(p->b);
  1721. cmMemFree(p->d);
  1722. cmIDelayFree(&p->idp);
  1723. cmObjFree(pp);
  1724. return cmOkRC;
  1725. }
  1726. cmRC_t cmCombFiltInit( cmCombFilt* p, cmReal_t srate, bool feedbackFl, cmReal_t minHz, cmReal_t alpha, cmReal_t hz, bool bypassFl )
  1727. {
  1728. cmRC_t rc;
  1729. if((rc = cmCombFiltFinal(p)) != cmOkRC )
  1730. return rc;
  1731. p->feedbackFl = feedbackFl;
  1732. p->dN = cmMax(1,floor(srate / minHz ));
  1733. p->d = cmMemResizeZ( cmReal_t, p->d, p->dN+1 );
  1734. p->a = cmMemResizeZ( cmReal_t, p->a, p->dN );
  1735. p->b = cmMemResizeZ( cmReal_t, p->b, p->dN );
  1736. p->dn = 1;
  1737. p->alpha = alpha;
  1738. p->srate = srate;
  1739. p->bypassFl = bypassFl;
  1740. cmReal_t tapMs = p->dn * 1000.0 / srate;
  1741. cmReal_t tapFf = 1.0;
  1742. cmReal_t tapFb = 1.0;
  1743. cmIDelayInit(p->idp, srate, p->dN * 1000.0 / srate, &tapMs, &tapFf, &tapFb, 1 );
  1744. cmCombFiltSetHz(p,hz);
  1745. return rc;
  1746. }
  1747. cmRC_t cmCombFiltFinal( cmCombFilt* p )
  1748. { return cmOkRC; }
  1749. cmRC_t cmCombFiltExec( cmCombFilt* p, const cmSample_t* x, cmSample_t* y, unsigned n )
  1750. {
  1751. if( y == NULL )
  1752. return cmOkRC;
  1753. if( x == NULL )
  1754. {
  1755. cmVOS_Zero(y,n);
  1756. return cmOkRC;
  1757. }
  1758. if( p->bypassFl )
  1759. cmVOS_Copy(y,n,x);
  1760. else
  1761. cmIDelayExec(p->idp,x,y,n);
  1762. return cmOkRC;
  1763. }
  1764. void cmCombFiltSetAlpha( cmCombFilt* p, cmReal_t alpha )
  1765. {
  1766. p->b0 = 1.0 - fabs(alpha); // normalization coeff (could be applied directly to the input or output)
  1767. p->a[p->dn-1] = -alpha;
  1768. p->alpha = alpha;
  1769. p->idp->tff[0] = p->b0;
  1770. p->idp->tfb[0] = -alpha;
  1771. }
  1772. cmRC_t cmCombFiltSetHz( cmCombFilt* p, cmReal_t hz )
  1773. {
  1774. if( hz < p->minHz )
  1775. return cmCtxRtCondition( &p->obj, cmInvalidArgRC, "The comb filter frequency %f Hz is invalid given the minimum frequency setting of %f Hz.",hz,p->minHz );
  1776. // clear the current alpha
  1777. p->a[p->dn-1] = 0;
  1778. // change location of alpha in p->a[]
  1779. p->dn = cmMin(p->dN-1,cmMax(1,floor(p->srate / hz )));
  1780. p->hz = hz;
  1781. cmCombFiltSetAlpha(p,p->alpha); // the location of filter coeff changed - reset it here
  1782. cmIDelaySetTapMs(p->idp, 0,p->dn * 1000.0 / p->srate );
  1783. return cmOkRC;
  1784. }
  1785. //=======================================================================================================================
  1786. cmDcFilt* cmDcFiltAlloc( cmCtx* c, cmDcFilt* p, bool bypassFl )
  1787. {
  1788. cmDcFilt* op = cmObjAlloc(cmDcFilt, c, p );
  1789. if( cmDcFiltInit( op, bypassFl ) != cmOkRC )
  1790. cmDcFiltFree(&op);
  1791. return op;
  1792. }
  1793. cmRC_t cmDcFiltFree( cmDcFilt** pp)
  1794. {
  1795. cmRC_t rc = cmOkRC;
  1796. if( pp == NULL || *pp == NULL )
  1797. return cmOkRC;
  1798. cmDcFilt* p = *pp;
  1799. if((rc = cmDcFiltFinal(p)) != cmOkRC )
  1800. return rc;
  1801. cmObjFree(pp);
  1802. return cmOkRC;
  1803. }
  1804. cmRC_t cmDcFiltInit( cmDcFilt* p, bool bypassFl )
  1805. {
  1806. cmRC_t rc;
  1807. if((rc = cmDcFiltFinal(p)) != cmOkRC )
  1808. return rc;
  1809. p->b0 = 1;
  1810. p->b[0] = -1;
  1811. p->a[0] = -0.999;
  1812. p->d[0] = 0;
  1813. p->d[1] = 0;
  1814. p->bypassFl = bypassFl;
  1815. return rc;
  1816. }
  1817. cmRC_t cmDcFiltFinal( cmDcFilt* p )
  1818. { return cmOkRC; }
  1819. cmRC_t cmDcFiltExec( cmDcFilt* p, const cmSample_t* x, cmSample_t* y, unsigned n )
  1820. {
  1821. if( p->bypassFl )
  1822. cmVOS_Copy(y,n,x);
  1823. else
  1824. cmVOS_Filter(y,n,x,n,p->b0, p->b, p->a, p->d, 1 );
  1825. return cmOkRC;
  1826. }
  1827. //=======================================================================================================================
  1828. 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 )
  1829. {
  1830. cmIDelay* op = cmObjAlloc(cmIDelay, c, p );
  1831. if( srate != 0 )
  1832. if( cmIDelayInit( op, srate, maxDelayMs, tapMs, tapFfGain, tapFbGain, tapCnt ) != cmOkRC )
  1833. cmIDelayFree(&op);
  1834. return op;
  1835. }
  1836. cmRC_t cmIDelayFree( cmIDelay** pp )
  1837. {
  1838. cmRC_t rc = cmOkRC;
  1839. if( pp == NULL || *pp == NULL )
  1840. return cmOkRC;
  1841. cmIDelay* p = *pp;
  1842. if((rc = cmIDelayFinal(p)) != cmOkRC )
  1843. return rc;
  1844. cmMemFree(p->m);
  1845. cmMemFree(p->ti);
  1846. cmMemFree(p->tff);
  1847. cmMemFree(p->tfb);
  1848. cmObjFree(pp);
  1849. return cmOkRC;
  1850. }
  1851. 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 )
  1852. {
  1853. cmRC_t rc;
  1854. if(( rc = cmIDelayFinal(p)) != cmOkRC )
  1855. return rc;
  1856. p->dn = (unsigned)floor( maxDelayMs * srate / 1000.0 );
  1857. p->mn = p->dn + 3;
  1858. p->m = cmMemResizeZ(cmSample_t,p->m,p->mn);
  1859. p->d = p->m + 1;
  1860. p->tn = tapCnt;
  1861. p->ti = cmMemResize(cmReal_t,p->ti,tapCnt);
  1862. p->tff = cmMemResize(cmReal_t,p->tff,tapCnt);
  1863. p->tfb = cmMemResize(cmReal_t,p->tfb,tapCnt);
  1864. p->srate = srate;
  1865. unsigned i;
  1866. for(i=0; i<tapCnt; ++i)
  1867. {
  1868. cmIDelaySetTapMs(p,i,tapMs[i]);
  1869. p->tff[i] = tapFfGain[i];
  1870. p->tfb[i] = tapFbGain[i];
  1871. }
  1872. return rc;
  1873. }
  1874. cmRC_t cmIDelayFinal(cmIDelay* p )
  1875. { return cmOkRC; }
  1876. cmRC_t cmIDelayExec( cmIDelay* p, const cmSample_t* x, cmSample_t* y, unsigned n )
  1877. {
  1878. unsigned i,j;
  1879. for(i=0; i<n; ++i)
  1880. {
  1881. cmSample_t fb = 0;
  1882. y[i] = 0;
  1883. // calculate the output sample
  1884. for(j=0; j<p->tn; ++j)
  1885. {
  1886. // get tap_j
  1887. cmReal_t tfi = p->ii - p->ti[j];
  1888. // mod it into 0:dn-1
  1889. while( tfi < 0 )
  1890. tfi += p->dn;
  1891. int ti = floor(tfi);
  1892. cmReal_t tf = tfi - ti;
  1893. 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]);
  1894. y[i] += p->tff[j] * v;
  1895. fb += p->tfb[j] * v;
  1896. }
  1897. // insert incoming sample
  1898. p->d[p->ii] = x[i] + fb;
  1899. // advance the delay line
  1900. ++p->ii;
  1901. // handle beg/end delay sample duplication
  1902. // -1 0 1 2 .... dn-1 dn dn+1
  1903. // a b c a b c
  1904. // The samples at position -1 0 1 must be duplicated
  1905. // at positions dn-1,dn,dn+1 so that output sample calculation
  1906. // does not need to deal with buffer wrap-around issues.
  1907. if( p->ii == 1 )
  1908. p->d[p->dn] = x[i];
  1909. else
  1910. if( p->ii == 2 )
  1911. p->d[p->dn+1] = x[i];
  1912. else
  1913. if( p->ii == p->dn )
  1914. {
  1915. p->d[-1] = x[i];
  1916. p->ii = 0;
  1917. }
  1918. }
  1919. return cmOkRC;
  1920. }
  1921. cmRC_t cmIDelaySetTapMs( cmIDelay* p, unsigned tapIdx, cmReal_t tapMs )
  1922. {
  1923. cmRC_t rc = cmOkRC;
  1924. if( tapIdx < p->tn )
  1925. p->ti[tapIdx] = tapMs * p->srate / 1000.0;
  1926. else
  1927. rc = cmCtxRtCondition( &p->obj, cmInvalidArgRC, "Tap index %i is out of range 0 - %i.",tapIdx,p->tn-1 );
  1928. return rc;
  1929. }
  1930. //=======================================================================================================================
  1931. cmGroupSel* cmGroupSelAlloc( cmCtx* c, cmGroupSel* p, unsigned chCnt, unsigned groupCnt, unsigned chsPerGroup )
  1932. {
  1933. cmGroupSel* op = cmObjAlloc(cmGroupSel, c, p );
  1934. if( chCnt != 0 )
  1935. if( cmGroupSelInit( op, chCnt, groupCnt, chsPerGroup ) != cmOkRC )
  1936. cmGroupSelFree(&op);
  1937. return op;
  1938. }
  1939. cmRC_t cmGroupSelFree( cmGroupSel** pp )
  1940. {
  1941. cmRC_t rc = cmOkRC;
  1942. if( pp == NULL || *pp == NULL )
  1943. return cmOkRC;
  1944. cmGroupSel* p = *pp;
  1945. if((rc = cmGroupSelFinal(p)) != cmOkRC )
  1946. return rc;
  1947. cmMemFree(p->groupArray);
  1948. cmMemFree(p->chArray);
  1949. cmObjFree(pp);
  1950. return cmOkRC;
  1951. }
  1952. cmRC_t cmGroupSelInit( cmGroupSel* p, unsigned chCnt, unsigned groupCnt, unsigned chsPerGroup )
  1953. {
  1954. cmRC_t rc;
  1955. if((rc = cmGroupSelFinal(p)) != cmOkRC )
  1956. return rc;
  1957. p->chArray = cmMemResizeZ(cmGroupSelCh,p->chArray,chCnt);
  1958. p->groupArray = cmMemResizeZ(cmGroupSelGrp,p->groupArray,chCnt);
  1959. p->chCnt = chCnt;
  1960. p->groupCnt = groupCnt;
  1961. p->chsPerGroup = chsPerGroup;
  1962. unsigned i;
  1963. for(i=0; i<p->chCnt; ++i)
  1964. p->chArray[i].groupIdx = cmInvalidIdx;
  1965. for(i=0; i<p->groupCnt; ++i)
  1966. {
  1967. p->groupArray[i].chIdxArray = cmMemAllocZ(unsigned, p->chCnt);
  1968. p->groupArray[i].chIdxCnt = 0;
  1969. }
  1970. return rc;
  1971. }
  1972. cmRC_t cmGroupSelFinal( cmGroupSel* p )
  1973. {
  1974. unsigned i;
  1975. for(i=0; i<p->groupCnt; ++i)
  1976. cmMemFree(p->groupArray[i].chIdxArray);
  1977. return cmOkRC;
  1978. }
  1979. cmRC_t cmGroupSetChannelGate( cmGroupSel* p, unsigned chIdx, bool gateFl )
  1980. {
  1981. assert(chIdx <p->chCnt);
  1982. cmGroupSelCh* cp = p->chArray + chIdx;
  1983. if( gateFl==true && cp->gateFl==false )
  1984. {
  1985. cp->readyFl = true;
  1986. }
  1987. if( gateFl==false && cp->gateFl==true )
  1988. {
  1989. cp->offsetFl = true;
  1990. cp->readyFl = false;
  1991. }
  1992. cp->gateFl = gateFl;
  1993. //printf("ch:%i gate:%i ready:%i offset:%i grp:%i\n",chIdx,cp->gateFl,cp->readyFl,cp->offsetFl,cp->groupIdx);
  1994. return cmOkRC;
  1995. }
  1996. cmRC_t cmGroupSetChannelRMS( cmGroupSel* p, unsigned chIdx, cmReal_t rms )
  1997. {
  1998. assert(chIdx <p->chCnt);
  1999. cmGroupSelCh* cp = p->chArray + chIdx;
  2000. cp->rms = rms;
  2001. return cmOkRC;
  2002. }
  2003. cmRC_t cmGroupSelExec( cmGroupSel* p )
  2004. {
  2005. unsigned i,j;
  2006. unsigned availGroupCnt = 0;
  2007. p->chsPerGroup = cmMin( p->chsPerGroup, p->chCnt );
  2008. p->updateFl = false;
  2009. // clear the create and release flags on each group
  2010. // and get the count of available groups
  2011. for(i=0; i<p->groupCnt; ++i)
  2012. {
  2013. cmGroupSelGrp* gp = p->groupArray + i;
  2014. gp->createFl = false;
  2015. if( gp->releaseFl )
  2016. {
  2017. // clear the groupIdx from the channels assigned to this released group
  2018. for(j=0; j<gp->chIdxCnt; ++j)
  2019. p->chArray[ gp->chIdxArray[j] ].groupIdx = cmInvalidIdx;
  2020. gp->releaseFl = false;
  2021. gp->chIdxCnt = 0;
  2022. }
  2023. if( gp->chIdxCnt == 0 )
  2024. ++availGroupCnt;
  2025. }
  2026. // count the number of ready but unassigned ch's and
  2027. // release any groups which contain a channel with a gate offset
  2028. unsigned readyChCnt = 0;
  2029. for(i=0; i<p->chCnt; ++i)
  2030. {
  2031. cmGroupSelCh* cp = p->chArray + i;
  2032. // count the number of channels that are ready to be assigned
  2033. if( cp->readyFl )
  2034. ++readyChCnt;
  2035. // if this channel offset and it had been assigned to a group
  2036. // then mark its group for release
  2037. if( cp->offsetFl && cp->groupIdx != cmInvalidIdx )
  2038. {
  2039. p->groupArray[cp->groupIdx].releaseFl = true;
  2040. p->updateFl = true;
  2041. }
  2042. }
  2043. // assign ready ch's to available groups
  2044. while( readyChCnt > p->chsPerGroup && availGroupCnt > 0 )
  2045. {
  2046. unsigned groupIdx;
  2047. // locate an available group
  2048. for(groupIdx=0; groupIdx<p->groupCnt; ++groupIdx)
  2049. if( p->groupArray[groupIdx].chIdxCnt == 0 )
  2050. break;
  2051. if( groupIdx == p->groupCnt )
  2052. break;
  2053. --availGroupCnt;
  2054. cmGroupSelGrp* gp = p->groupArray + groupIdx;
  2055. printf("gs - group:%i chs: ",groupIdx);
  2056. // assign chsPerGroup ch's to this group
  2057. for(i=0; i<p->chCnt && gp->chIdxCnt < p->chsPerGroup; ++i)
  2058. if(p->chArray[i].readyFl )
  2059. {
  2060. p->chArray[i].readyFl = false; // this ch is no longer ready because it is assigned
  2061. p->chArray[i].groupIdx = groupIdx; // set this ch's group idx
  2062. gp->chIdxArray[ gp->chIdxCnt ] = i; // assign channel to group
  2063. gp->chIdxCnt += 1; // update the group ch count
  2064. gp->createFl = true;
  2065. p->updateFl = true;
  2066. --readyChCnt;
  2067. printf("%i ",i);
  2068. }
  2069. printf("\n");
  2070. }
  2071. return cmOkRC;
  2072. }
  2073. //=======================================================================================================================
  2074. cmAudioNofM* cmAudioNofMAlloc( cmCtx* c, cmAudioNofM* p, cmReal_t srate, unsigned inChCnt, unsigned outChCnt, cmReal_t fadeTimeMs )
  2075. {
  2076. cmAudioNofM* op = cmObjAlloc(cmAudioNofM, c, p );
  2077. if( srate != 0 )
  2078. if( cmAudioNofMInit( op, srate, inChCnt, outChCnt, fadeTimeMs ) != cmOkRC )
  2079. cmAudioNofMFree(&op);
  2080. return op;
  2081. }
  2082. cmRC_t cmAudioNofMFree( cmAudioNofM** pp )
  2083. {
  2084. cmRC_t rc = cmOkRC;
  2085. if( pp == NULL || *pp == NULL )
  2086. return cmOkRC;
  2087. cmAudioNofM* p = *pp;
  2088. if((rc = cmAudioNofMFinal(p)) != cmOkRC )
  2089. return rc;
  2090. cmMemFree(p->outArray);
  2091. cmMemFree(p->inArray);
  2092. cmObjFree(pp);
  2093. return cmOkRC;
  2094. }
  2095. cmRC_t cmAudioNofMInit( cmAudioNofM* p, cmReal_t srate, unsigned iChCnt, unsigned oChCnt, cmReal_t fadeTimeMs )
  2096. {
  2097. cmRC_t rc;
  2098. if((rc = cmAudioNofMFinal(p)) != cmOkRC )
  2099. return rc;
  2100. p->iChCnt = iChCnt;
  2101. p->inArray = cmMemResizeZ(cmAudioNofM_In,p->inArray,iChCnt);
  2102. p->oChCnt = oChCnt;
  2103. p->outArray = cmMemResizeZ(cmAudioNofM_Out,p->outArray,oChCnt);
  2104. p->nxtOutChIdx = 0;
  2105. unsigned i;
  2106. for(i=0; i<p->iChCnt; ++i)
  2107. {
  2108. p->inArray[i].fader = cmFaderAlloc(p->obj.ctx, NULL, srate, fadeTimeMs );
  2109. p->inArray[i].outChIdx = cmInvalidIdx;
  2110. }
  2111. cmAudioNofMSetFadeMs( p, fadeTimeMs );
  2112. return rc;
  2113. }
  2114. cmRC_t cmAudioNofMFinal( cmAudioNofM* p )
  2115. {
  2116. unsigned i;
  2117. for(i=0; i<p->iChCnt; ++i)
  2118. cmFaderFree(&p->inArray[i].fader);
  2119. return cmOkRC;
  2120. }
  2121. cmRC_t cmAudioNofMSetChannelGate( cmAudioNofM* p, unsigned inChIdx, bool gateFl )
  2122. {
  2123. assert( inChIdx < p->iChCnt );
  2124. cmAudioNofM_In* ip = p->inArray + inChIdx;
  2125. if( ip->gateFl && gateFl == false )
  2126. ip->offsetFl = true;
  2127. if( ip->gateFl == false && gateFl )
  2128. ip->onsetFl = true;
  2129. ip->gateFl = gateFl;
  2130. printf("nom: %p ch:%i gate:%i on:%i off:%i\n",p,inChIdx,ip->gateFl,ip->offsetFl,ip->onsetFl);
  2131. return cmOkRC;
  2132. }
  2133. cmRC_t cmAudioNofMExec( cmAudioNofM* p, const cmSample_t* x[], unsigned inChCnt, cmSample_t* y[], unsigned outChCnt, unsigned n )
  2134. {
  2135. assert( inChCnt == p->iChCnt && outChCnt == p->oChCnt );
  2136. unsigned i;
  2137. // for each output channel
  2138. for(i=0; i<p->oChCnt; ++i)
  2139. {
  2140. cmAudioNofM_Out* op = p->outArray + i;
  2141. cmAudioNofM_In* ip = op->list;
  2142. cmAudioNofM_In* pp = NULL;
  2143. // for each input assigned to this output chanenl
  2144. while( ip != NULL )
  2145. {
  2146. // if the channel is no longer active
  2147. if( ip->offsetFl && ip->fader->gain == 0.0 )
  2148. {
  2149. printf("nom: off - out:%i\n",ip->outChIdx);
  2150. // remove it from the output channels list
  2151. ip->offsetFl = false;
  2152. ip->outChIdx = cmInvalidIdx;
  2153. if( pp == NULL )
  2154. op->list = ip->link;
  2155. else
  2156. pp->link = ip->link;
  2157. }
  2158. pp = ip;
  2159. ip = ip->link;
  2160. }
  2161. }
  2162. // for each input channel
  2163. for(i=0; i<inChCnt; ++i)
  2164. {
  2165. cmAudioNofM_In* ip = p->inArray + i;
  2166. // if this channel is starting
  2167. if( ip->onsetFl == true && ip->offsetFl == false )
  2168. {
  2169. // assign it to the next output channel
  2170. ip->onsetFl = false;
  2171. ip->outChIdx = p->nxtOutChIdx;
  2172. ip->link = p->outArray[ ip->outChIdx ].list;
  2173. p->outArray[ ip->outChIdx ].list = ip;
  2174. p->nxtOutChIdx = (p->nxtOutChIdx + 1) % p->oChCnt;
  2175. printf("nom: on - in:%i out:%i\n",i,ip->outChIdx);
  2176. }
  2177. // if this channel is active - then mix its input
  2178. if( ip->outChIdx != cmInvalidIdx )
  2179. {
  2180. cmFaderExec( ip->fader, n, ip->gateFl, true, x[i], y[ ip->outChIdx ] );
  2181. }
  2182. }
  2183. return cmOkRC;
  2184. }
  2185. cmRC_t cmAudioNofMSetFadeMs( cmAudioNofM* p, cmReal_t fadeTimeMs )
  2186. {
  2187. unsigned i;
  2188. for(i=0; i<p->iChCnt; ++i)
  2189. cmFaderSetFadeTime(p->inArray[i].fader,fadeTimeMs);
  2190. return cmOkRC;
  2191. }
  2192. //=======================================================================================================================
  2193. 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 )
  2194. {
  2195. cmAdsr* op = cmObjAlloc(cmAdsr, c, p );
  2196. if( srate != 0 )
  2197. if( cmAdsrInit( op, srate, trigFl, minL, dlyMs, atkMs, atkL, dcyMs, susMs, susL, rlsMs ) != cmOkRC )
  2198. cmAdsrFree(&op);
  2199. return op;
  2200. }
  2201. cmRC_t cmAdsrFree( cmAdsr** pp )
  2202. {
  2203. cmRC_t rc = cmOkRC;
  2204. if( pp == NULL || *pp == NULL )
  2205. return cmOkRC;
  2206. cmAdsr* p = *pp;
  2207. if((rc = cmAdsrFinal(p)) != cmOkRC )
  2208. return rc;
  2209. cmObjFree(pp);
  2210. return cmOkRC;
  2211. }
  2212. 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 )
  2213. {
  2214. cmRC_t rc;
  2215. if((rc = cmAdsrFinal(p)) != cmOkRC )
  2216. return rc;
  2217. // this is a limitation of the design - the design should be replaced with one
  2218. // which increments/decrements the level until it reaches a limit instead of calculating
  2219. // durations
  2220. //assert(atkL>=0 && minL>=0);
  2221. p->srate = srate;
  2222. p->trigModeFl = trigFl;
  2223. p->levelMin = minL;
  2224. p->scaleDur = 1.0;
  2225. cmAdsrSetTime(p,dlyMs,kDlyAdsrId);
  2226. cmAdsrSetTime(p,atkMs,kAtkAdsrId);
  2227. cmAdsrSetTime(p,dcyMs,kDcyAdsrId);
  2228. cmAdsrSetTime(p,susMs,kSusAdsrId);
  2229. cmAdsrSetTime(p,rlsMs,kRlsAdsrId);
  2230. cmAdsrSetLevel(p,atkL,kAtkAdsrId);
  2231. cmAdsrSetLevel(p,susL,kSusAdsrId);
  2232. p->state = kDoneAdsrId;
  2233. p->durSmp = 0;
  2234. p->level = p->levelMin;
  2235. p->gateFl = false;
  2236. p->atkDurSmp = 0;
  2237. p->rlsDurSmp = 0;
  2238. return cmOkRC;
  2239. }
  2240. cmRC_t cmAdsrFinal( cmAdsr* p )
  2241. { return cmOkRC; }
  2242. cmReal_t cmAdsrExec( cmAdsr* p, unsigned procSmpCnt, bool gateFl, cmReal_t tscale, cmReal_t ascale )
  2243. {
  2244. double scaleAmp = ascale;
  2245. double scaleDur = tscale;
  2246. // if onset
  2247. if( p->gateFl == false && gateFl==true )
  2248. {
  2249. p->scaleDur = scaleDur==0 ? 1.0 : fabs(scaleDur);
  2250. //printf("sd:%f %f\n",scaleDur,scaleAmp);
  2251. switch( p->state )
  2252. {
  2253. case kDlyAdsrId:
  2254. // if in delay mode when the re-attack occurs don't do anything
  2255. break;
  2256. case kAtkAdsrId:
  2257. case kDcyAdsrId:
  2258. case kSusAdsrId:
  2259. case kRlsAdsrId:
  2260. // if the atk level == 0 then fall through to kDoneAdsrId
  2261. if( p->actAtkLevel != 0 )
  2262. {
  2263. // re-attak mode:
  2264. // Scale the attack time to the current level relative to the attack level.
  2265. // In general this will result in a decrease in the attack duration.
  2266. p->atkDurSmp = cmMax(1,floor(p->atkSmp * (p->actAtkLevel - p->level) / p->actAtkLevel));
  2267. p->atkBegLevel = p->level;
  2268. p->durSmp = 0;
  2269. p->state = kAtkAdsrId;
  2270. p->actAtkLevel = p->atkLevel * scaleAmp;
  2271. p->actSusLevel = p->susLevel * scaleAmp;
  2272. break;
  2273. }
  2274. case kDoneAdsrId:
  2275. p->atkBegLevel = p->levelMin;
  2276. p->atkDurSmp = p->atkSmp;
  2277. p->state = p->dlySmp == 0 ? kAtkAdsrId : kDlyAdsrId;
  2278. p->durSmp = 0;
  2279. p->actAtkLevel = p->atkLevel * scaleAmp;
  2280. p->actSusLevel = p->susLevel * scaleAmp;
  2281. break;
  2282. default:
  2283. { assert(0); }
  2284. }
  2285. }
  2286. // if an offset occurred and we are not in trigger mode - then go into release mode
  2287. if( p->trigModeFl==false && p->gateFl == true && gateFl == false )
  2288. {
  2289. switch( p->state )
  2290. {
  2291. case kDlyAdsrId:
  2292. case kAtkAdsrId:
  2293. case kDcyAdsrId:
  2294. case kSusAdsrId:
  2295. if( p->actSusLevel == 0 )
  2296. p->state = kDoneAdsrId;
  2297. else
  2298. {
  2299. // scale the release time to the current level relative to the sustain level
  2300. p->rlsDurSmp = cmMax(1,floor(p->rlsSmp * p->level / p->actSusLevel));
  2301. p->rlsLevel = p->level;
  2302. p->durSmp = 0;
  2303. }
  2304. break;
  2305. case kRlsAdsrId:
  2306. case kDoneAdsrId:
  2307. // nothing to do
  2308. break;
  2309. default:
  2310. { assert(0); }
  2311. }
  2312. p->state = kRlsAdsrId;
  2313. }
  2314. p->gateFl = gateFl;
  2315. switch( p->state )
  2316. {
  2317. case kDlyAdsrId:
  2318. p->level = p->levelMin;
  2319. if( p->durSmp >= p->dlySmp )
  2320. {
  2321. p->state = kAtkAdsrId;
  2322. p->durSmp = 0;
  2323. if( p->trigModeFl )
  2324. {
  2325. p->atkBegLevel = p->level;
  2326. p->atkDurSmp = p->atkSmp;
  2327. }
  2328. }
  2329. break;
  2330. case kAtkAdsrId:
  2331. if( p->atkDurSmp != 0 )
  2332. p->level = p->atkBegLevel + (p->actAtkLevel - p->atkBegLevel) * cmMin(p->durSmp,p->atkDurSmp) / p->atkDurSmp;
  2333. if( p->durSmp >= p->atkDurSmp || p->atkDurSmp == 0 )
  2334. {
  2335. p->state = kDcyAdsrId;
  2336. p->durSmp = 0;
  2337. }
  2338. break;
  2339. case kDcyAdsrId:
  2340. if( p->dcySmp != 0 )
  2341. p->level = p->actAtkLevel - ((p->actAtkLevel - p->actSusLevel) * cmMin(p->durSmp,p->dcySmp) / p->dcySmp );
  2342. if( p->durSmp >= p->dcySmp || p->dcySmp==0 )
  2343. {
  2344. p->state = kSusAdsrId;
  2345. p->durSmp = 0;
  2346. }
  2347. break;
  2348. case kSusAdsrId:
  2349. p->level = p->actSusLevel;
  2350. if( p->trigModeFl==true && p->durSmp >= p->susSmp )
  2351. {
  2352. p->state = kRlsAdsrId;
  2353. p->durSmp = 0;
  2354. p->rlsLevel = p->level;
  2355. p->rlsDurSmp = p->rlsSmp;
  2356. }
  2357. break;
  2358. case kRlsAdsrId:
  2359. if( p->rlsDurSmp != 0 )
  2360. p->level = p->rlsLevel - ((p->rlsLevel - p->levelMin) * cmMin(p->durSmp,p->rlsDurSmp) / p->rlsDurSmp);
  2361. if( p->durSmp >= p->rlsDurSmp || p->rlsDurSmp==0 )
  2362. {
  2363. p->state = kDoneAdsrId;
  2364. p->durSmp = 0;
  2365. }
  2366. break;
  2367. case kDoneAdsrId:
  2368. p->level = p->levelMin;
  2369. break;
  2370. default:
  2371. { assert(0); }
  2372. }
  2373. p->durSmp += floor(procSmpCnt/p->scaleDur);
  2374. return p->level;
  2375. }
  2376. void _cmAdsrSetTime( cmAdsr* p, cmReal_t ms, int* smpPtr )
  2377. {
  2378. *smpPtr = cmMax(1,floor(p->srate * ms / 1000.0 ));
  2379. }
  2380. void cmAdsrSetTime( cmAdsr* p, cmReal_t ms, unsigned id )
  2381. {
  2382. switch( id )
  2383. {
  2384. case kDlyAdsrId:
  2385. _cmAdsrSetTime(p,ms,&p->dlySmp);
  2386. break;
  2387. case kAtkAdsrId:
  2388. _cmAdsrSetTime(p,ms,&p->atkSmp);
  2389. break;
  2390. case kDcyAdsrId:
  2391. _cmAdsrSetTime(p,ms,&p->dcySmp);
  2392. break;
  2393. case kSusAdsrId:
  2394. _cmAdsrSetTime(p,ms,&p->susSmp);
  2395. break;
  2396. case kRlsAdsrId:
  2397. _cmAdsrSetTime(p,ms,&p->rlsSmp);
  2398. break;
  2399. default:
  2400. { assert(0); }
  2401. }
  2402. }
  2403. void cmAdsrSetLevel( cmAdsr* p, cmReal_t level, unsigned id )
  2404. {
  2405. switch( id )
  2406. {
  2407. case kDlyAdsrId:
  2408. p->levelMin = level;
  2409. break;
  2410. case kAtkAdsrId:
  2411. p->atkLevel = level;
  2412. p->actAtkLevel = p->atkLevel;
  2413. break;
  2414. case kSusAdsrId:
  2415. p->susLevel = level;
  2416. p->actSusLevel = p->susLevel;
  2417. break;
  2418. default:
  2419. { assert(0); }
  2420. }
  2421. }
  2422. void cmAdsrReport( cmAdsr* p, cmRpt_t* rpt )
  2423. {
  2424. 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);
  2425. }
  2426. //=======================================================================================================================
  2427. 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 )
  2428. {
  2429. cmCompressor* op = cmObjAlloc(cmCompressor, c, p );
  2430. if( srate != 0 )
  2431. if( cmCompressorInit( op, srate, procSmpCnt, inGain, rmsWndMaxMs, rmsWndMs, threshDb, ratio_num, atkMs, rlsMs, outGain, bypassFl ) != cmOkRC )
  2432. cmCompressorFree(&op);
  2433. return op;
  2434. }
  2435. cmRC_t cmCompressorFree( cmCompressor** pp )
  2436. {
  2437. cmRC_t rc = cmOkRC;
  2438. if( pp == NULL || *pp == NULL )
  2439. return cmOkRC;
  2440. cmCompressor* p = *pp;
  2441. if((rc = cmCompressorFinal(p)) != cmOkRC )
  2442. return rc;
  2443. cmMemFree(p->rmsWnd);
  2444. cmObjFree(pp);
  2445. return cmOkRC;
  2446. }
  2447. 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 )
  2448. {
  2449. cmRC_t rc;
  2450. if((rc = cmCompressorFinal(p)) != cmOkRC )
  2451. return rc;
  2452. p->srate = srate;
  2453. p->procSmpCnt = procSmpCnt;
  2454. p->threshDb = threshDb;
  2455. p->ratio_num = ratio_num;
  2456. cmCompressorSetAttackMs(p,atkMs);
  2457. cmCompressorSetReleaseMs(p,rlsMs);
  2458. p->inGain = inGain;
  2459. p->outGain = outGain;
  2460. p->bypassFl = bypassFl;
  2461. p->rmsWndAllocCnt = cmMax(1,(unsigned)floor(rmsWndMaxMs * srate / (1000.0 * procSmpCnt)));
  2462. p->rmsWnd = cmMemResizeZ(cmSample_t,p->rmsWnd,p->rmsWndAllocCnt);
  2463. cmCompressorSetRmsWndMs(p, rmsWndMs );
  2464. p->rmsWndIdx = 0;
  2465. p->state = kRlsCompId;
  2466. p->timeConstDb = 10.0;
  2467. p->accumDb = p->threshDb;
  2468. return rc;
  2469. }
  2470. cmRC_t cmCompressorFinal( cmCompressor* p )
  2471. { return cmOkRC; }
  2472. /*
  2473. The ratio determines to what degree a signal above the threshold is reduced.
  2474. Given a 2:1 ratio, a signal 2dB above the threshold will be reduced to 1db above the threshold.
  2475. Given a 4:1 ratio, a signal 2dB above the threshold will be reduced to 0.25db above the threshold.
  2476. Gain_reduction_db = (thresh - signal) / ratio_numerator (difference between the threshold and signal level after reduction)
  2477. Gain Coeff = 10^(gain_reduction_db / 20);
  2478. Total_reduction_db = signal - threshold + Gain_reduc_db
  2479. (total change in signal level)
  2480. The attack can be viewed as beginning at the threshold and moving to the peak
  2481. over some period of time. In linear terms this will go from 1.0 to the max gain
  2482. reductions. In this case we step from thresh to peak at a fixed rate in dB
  2483. based on the attack time.
  2484. Db: thresh - [thesh:peak] / ratio_num
  2485. Linear: pow(10, (thresh - [thesh:peak] / ratio_num)/20 );
  2486. During attacks p->accumDb increments toward the p->pkDb.
  2487. During release p->accumDb decrements toward the threshold.
  2488. (thresh - accumDb) / ratio_num gives the signal level which will be achieved
  2489. if this value is converted to linear form and applied as a gain coeff.
  2490. See compressor.m
  2491. */
  2492. cmRC_t cmCompressorExec( cmCompressor* p, const cmSample_t* x, cmSample_t* y, unsigned n )
  2493. {
  2494. cmSample_t xx[n];
  2495. cmVOS_MultVVS(xx,n,x,p->inGain); // apply input gain
  2496. p->rmsWnd[ p->rmsWndIdx ] = cmVOS_RMS(xx, n, n ); // calc and store signal RMS
  2497. p->rmsWndIdx = (p->rmsWndIdx + 1) % p->rmsWndCnt; // advance the RMS storage buffer
  2498. cmReal_t rmsLin = cmVOS_Sum(p->rmsWnd,p->rmsWndCnt) / p->rmsWndCnt; // calc avg RMS
  2499. cmReal_t rmsDb = cmMax(-100.0,20 * log10(cmMax(0.00001,rmsLin))); // convert avg RMS to dB
  2500. rmsDb += 100.0;
  2501. // if the compressor is bypassed
  2502. if( p->bypassFl )
  2503. {
  2504. cmVOS_Copy(y,n,x); // copy through - with no input gain
  2505. return cmOkRC;
  2506. }
  2507. // if the signal is above the threshold
  2508. if( rmsDb <= p->threshDb )
  2509. p->state = kRlsCompId;
  2510. else
  2511. {
  2512. if( rmsDb > p->pkDb )
  2513. p->pkDb = rmsDb;
  2514. p->state = kAtkCompId;
  2515. }
  2516. switch( p->state )
  2517. {
  2518. case kAtkCompId:
  2519. p->accumDb = cmMin(p->pkDb, p->accumDb + p->timeConstDb * n / p->atkSmp );
  2520. break;
  2521. case kRlsCompId:
  2522. p->accumDb = cmMax(p->threshDb, p->accumDb - p->timeConstDb * n / p->rlsSmp );
  2523. break;
  2524. }
  2525. p->gain = pow(10.0,(p->threshDb - p->accumDb) / (p->ratio_num * 20.0));
  2526. cmVOS_MultVVS(y,n,xx,p->gain * p->outGain);
  2527. return cmOkRC;
  2528. }
  2529. void _cmCompressorSetMs( cmCompressor* p, cmReal_t ms, unsigned* smpPtr )
  2530. { *smpPtr = cmMax(1,(unsigned)floor(ms * p->srate / 1000.0)); }
  2531. void cmCompressorSetAttackMs( cmCompressor* p, cmReal_t ms )
  2532. { _cmCompressorSetMs(p,ms,&p->atkSmp); }
  2533. void cmCompressorSetReleaseMs( cmCompressor* p, cmReal_t ms )
  2534. { _cmCompressorSetMs(p,ms,&p->rlsSmp); }
  2535. void cmCompressorSetThreshDb( cmCompressor* p, cmReal_t threshDb )
  2536. { p->threshDb = cmMax(0.0,100 + threshDb); }
  2537. void cmCompressorSetRmsWndMs( cmCompressor* p, cmReal_t ms )
  2538. {
  2539. p->rmsWndCnt = cmMax(1,(unsigned)floor(ms * p->srate / (1000.0 * p->procSmpCnt)));
  2540. // do not allow rmsWndCnt to exceed rmsWndAllocCnt
  2541. if( p->rmsWndCnt > p->rmsWndAllocCnt )
  2542. p->rmsWndCnt = p->rmsWndAllocCnt;
  2543. }
  2544. //=======================================================================================================================
  2545. cmBiQuadEq* cmBiQuadEqAlloc( cmCtx* c, cmBiQuadEq* p, cmReal_t srate, unsigned mode, cmReal_t f0Hz, cmReal_t Q, cmReal_t gainDb, bool bypassFl )
  2546. {
  2547. cmBiQuadEq* op = cmObjAlloc(cmBiQuadEq, c, p );
  2548. if( srate != 0 )
  2549. if( cmBiQuadEqInit( op, srate, mode, f0Hz, Q, gainDb, bypassFl ) != cmOkRC )
  2550. cmBiQuadEqFree(&op);
  2551. return op;
  2552. }
  2553. cmRC_t cmBiQuadEqFree( cmBiQuadEq** pp )
  2554. {
  2555. cmRC_t rc = cmOkRC;
  2556. if( pp == NULL || *pp == NULL )
  2557. return cmOkRC;
  2558. cmBiQuadEq* p = *pp;
  2559. if((rc = cmBiQuadEqFinal(p)) != cmOkRC )
  2560. return rc;
  2561. cmObjFree(pp);
  2562. return cmOkRC;
  2563. }
  2564. void _cmBiQuadEqInit( cmBiQuadEq* p )
  2565. {
  2566. cmReal_t w0 = 2*M_PI*p->f0Hz/p->srate;
  2567. cmReal_t cos_w0 = cos(w0);
  2568. cmReal_t alpha = sin(w0)/(2*p->Q);
  2569. if( p->mode==kLowShelfBqId || p->mode==kHighShelfBqId )
  2570. {
  2571. cmReal_t c = p->mode==kLowShelfBqId ? 1.0 : -1.0;
  2572. cmReal_t A = pow(10.0,p->gainDb/40.0);
  2573. cmReal_t B = 2*sqrt(A)*alpha;
  2574. p->b[0] = A*( (A+1) - c * (A-1)*cos_w0 + B );
  2575. p->b[1] = c*2*A*( (A-1) - c * (A+1)*cos_w0);
  2576. p->b[2] = A*( (A+1) - c * (A-1)*cos_w0 - B );
  2577. p->a[0] = (A+1) + c * (A-1)*cos_w0 + B;
  2578. p->a[1] = -c*2*( (A-1) + c * (A+1)*cos_w0);
  2579. p->a[2] = (A+1) + c * (A-1)*cos_w0 - B;
  2580. }
  2581. else
  2582. {
  2583. if( p->mode != kPeakBqId )
  2584. {
  2585. p->a[0] = 1 + alpha;
  2586. p->a[1] = -2*cos_w0;
  2587. p->a[2] = 1 - alpha;
  2588. }
  2589. switch(p->mode)
  2590. {
  2591. case kLpfBqId:
  2592. case kHpFBqId:
  2593. {
  2594. cmReal_t c = p->mode==kLpfBqId ? 1.0 : -1.0;
  2595. p->b[0] = (1 - c * cos_w0)/2;
  2596. p->b[1] = c * (1 - c * cos_w0);
  2597. p->b[2] = (1 - c * cos_w0)/2;
  2598. }
  2599. break;
  2600. case kBpfBqId:
  2601. p->b[0] = p->Q*alpha;
  2602. p->b[1] = 0;
  2603. p->b[2] = -p->Q*alpha;
  2604. break;
  2605. case kNotchBqId:
  2606. p->b[0] = 1;
  2607. p->b[1] = -2*cos_w0;
  2608. p->b[2] = 1;
  2609. break;
  2610. case kAllpassBqId:
  2611. p->b[0] = 1 - alpha;
  2612. p->b[1] = -2*cos_w0;
  2613. p->b[2] = 1 + alpha;
  2614. break;
  2615. case kPeakBqId:
  2616. {
  2617. cmReal_t A = pow(10.0,p->gainDb/40.0);
  2618. p->b[0] = 1 + alpha*A;
  2619. p->b[1] = -2*cos_w0;
  2620. p->b[2] = 1 - alpha*A;
  2621. p->a[0] = 1 + alpha/A;
  2622. p->a[1] = -2*cos_w0;
  2623. p->a[2] = 1 - alpha/A;
  2624. }
  2625. break;
  2626. }
  2627. }
  2628. cmReal_t a0 = p->a[0];
  2629. unsigned i=0;
  2630. for(; i<3; ++i)
  2631. {
  2632. p->b[i]/=a0;
  2633. p->a[i]/=a0;
  2634. }
  2635. if(0)
  2636. {
  2637. printf("sr:%f mode:%i f0:%f q:%f gain:%f\n", p->srate,p->mode,p->f0Hz,p->Q,p->gainDb);
  2638. for(i=0; i<3; ++i)
  2639. printf("a[%i]=%f b[%i]=%f ",i,p->a[i],i,p->b[i]);
  2640. printf("\n");
  2641. }
  2642. }
  2643. cmRC_t cmBiQuadEqInit( cmBiQuadEq* p, cmReal_t srate, unsigned mode, cmReal_t f0Hz, cmReal_t Q, cmReal_t gainDb, bool bypassFl )
  2644. {
  2645. cmRC_t rc;
  2646. if((rc = cmBiQuadEqFinal(p)) != cmOkRC )
  2647. return rc;
  2648. memset(p->d,0,sizeof(p->d));
  2649. p->srate = srate;
  2650. cmBiQuadEqSet(p, mode, f0Hz, Q, gainDb );
  2651. _cmBiQuadEqInit(p);
  2652. return rc;
  2653. }
  2654. cmRC_t cmBiQuadEqFinal( cmBiQuadEq* p )
  2655. { return cmOkRC;}
  2656. cmRC_t cmBiQuadEqExec( cmBiQuadEq* p, const cmSample_t* x, cmSample_t* y, unsigned n )
  2657. {
  2658. if( y == NULL )
  2659. return cmOkRC;
  2660. if( x == NULL )
  2661. {
  2662. cmVOS_Zero(y,n);
  2663. return cmOkRC;
  2664. }
  2665. if( p->bypassFl )
  2666. {
  2667. cmVOS_Copy(y,n,x);
  2668. return cmOkRC;
  2669. }
  2670. // Direct Form I implementation
  2671. unsigned i=0;
  2672. for(; i<n; ++i)
  2673. {
  2674. 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];
  2675. p->d[1] = p->d[0];
  2676. p->d[0] = x[i];
  2677. p->d[3] = p->d[2];
  2678. p->d[2] = y[i];
  2679. }
  2680. return cmOkRC;
  2681. }
  2682. void cmBiQuadEqSet( cmBiQuadEq* p, unsigned mode, cmReal_t f0Hz, cmReal_t Q, cmReal_t gainDb )
  2683. {
  2684. p->mode = mode;
  2685. p->f0Hz = f0Hz;
  2686. p->Q = Q;
  2687. p->gainDb= gainDb;
  2688. _cmBiQuadEqInit(p);
  2689. }
  2690. //=======================================================================================================================
  2691. 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 )
  2692. {
  2693. cmDistDs* op = cmObjAlloc(cmDistDs, c, p );
  2694. if( srate != 0 )
  2695. if( cmDistDsInit( op, srate, inGain, downSrate, bits, rectFl, fullFl, clipDb, outGain, bypassFl ) != cmOkRC )
  2696. cmDistDsFree(&op);
  2697. return op;
  2698. }
  2699. cmRC_t cmDistDsFree( cmDistDs** pp )
  2700. {
  2701. cmRC_t rc = cmOkRC;
  2702. if( pp == NULL || *pp == NULL )
  2703. return cmOkRC;
  2704. cmDistDs* p = *pp;
  2705. if((rc = cmDistDsFinal(p)) != cmOkRC )
  2706. return rc;
  2707. cmObjFree(pp);
  2708. return cmOkRC;
  2709. }
  2710. 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 )
  2711. {
  2712. cmRC_t rc;
  2713. if((rc = cmDistDsFinal(p)) != cmOkRC )
  2714. return rc;
  2715. p->srate = srate;
  2716. p->downSrate = downSrate;
  2717. p->bits = bits;
  2718. p->rectFl = rectFl;
  2719. p->fullFl = fullFl;
  2720. p->clipDb = clipDb;
  2721. p->inGain = inGain;
  2722. p->outGain = outGain;
  2723. p->bypassFl = bypassFl;
  2724. p->fracIdx = 0;
  2725. p->lastVal = 0;
  2726. p->lastY = 0;
  2727. p->lastX = 0;
  2728. return rc;
  2729. }
  2730. cmRC_t cmDistDsFinal( cmDistDs* p )
  2731. { return cmOkRC; }
  2732. void _cmDistDsExpr0( cmDistDs* p, const cmSample_t* x, cmSample_t* y, unsigned n )
  2733. {
  2734. unsigned i= 0;
  2735. for(i=0; i<n; ++i)
  2736. {
  2737. p->lastY = fmod(p->lastY + fabs(x[i] - p->lastX),2.0);
  2738. y[i] = cmVOS_RMS(x,n,n) * x[i] * (p->lastY - 1.0);
  2739. p->lastX = x[i];
  2740. }
  2741. }
  2742. void _cmDistDsExpr1( cmDistDs* p, cmSample_t* x, cmSample_t* y, unsigned n )
  2743. {
  2744. unsigned i= 0;
  2745. for(i=0; i<n; ++i)
  2746. {
  2747. p->lastY = fmod(p->lastY + fabs(x[i] - p->lastX),2.0*M_PI);
  2748. y[i] = x[i] * sin(p->lastY);
  2749. p->lastX = x[i];
  2750. }
  2751. }
  2752. cmRC_t cmDistDsExec( cmDistDs* p, const cmSample_t* x, cmSample_t* y, unsigned n )
  2753. {
  2754. if( x == NULL )
  2755. {
  2756. if( y != NULL )
  2757. cmVOS_Zero(y,n);
  2758. return cmOkRC;
  2759. }
  2760. if( p->bypassFl )
  2761. {
  2762. cmVOS_Copy(y,n,x);
  2763. return cmOkRC;
  2764. }
  2765. unsigned maxVal = cmMax(2,(unsigned)round(pow(2.0,p->bits)));
  2766. double incr = 1.0; // p->downSrate / p->srate;
  2767. unsigned i;
  2768. enum { kNoRectId, kFullRectId, kHalfRectId };
  2769. unsigned rectCode = kNoRectId;
  2770. //cmSample_t t[n];
  2771. //_cmDistDsExpr0(p,x,t,n);
  2772. //x = t;
  2773. if( p->rectFl )
  2774. {
  2775. if( p->fullFl )
  2776. rectCode = kFullRectId;
  2777. else
  2778. rectCode = kHalfRectId;
  2779. }
  2780. double clipLevel = p->clipDb < -100.0 ? 0.0 : pow(10.0,p->clipDb/20.0);
  2781. for(i=0; i<n; ++i)
  2782. {
  2783. double ii = floor(p->fracIdx);
  2784. p->fracIdx += incr;
  2785. // if it is time to sample again
  2786. if( floor(p->fracIdx) != ii )
  2787. {
  2788. cmSample_t v = p->inGain * floor(x[i] * maxVal) / maxVal;
  2789. switch( rectCode )
  2790. {
  2791. case kFullRectId:
  2792. v = (cmSample_t)fabs(v);
  2793. break;
  2794. case kHalfRectId:
  2795. if( v < 0.0 )
  2796. v = 0.0;
  2797. break;
  2798. }
  2799. if( fabs(v) > clipLevel )
  2800. v = v<0.0 ? -clipLevel : clipLevel;
  2801. p->lastVal = v * p->outGain;
  2802. }
  2803. y[i] = p->lastVal;
  2804. }
  2805. return cmOkRC;
  2806. }