Instruments.cpp 216 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705
  1. #include "core/FruityDance.h"
  2. #include "core/FruitySlicer.h"
  3. #include "core/Instruments.h"
  4. #include "core/HostSlide.h"
  5. #include "core/HostTimelineScope.h"
  6. #include "core/SynthParams.h"
  7. #include "core/FpcInstrument.h"
  8. #include "core/ControlSurface.h"
  9. #include "core/VoltageController.h"
  10. #include "core/Vfx.h"
  11. #include "core/VideoPlayer.h"
  12. #include "core/MidiOut.h"
  13. #include "core/Scheduler.h"
  14. #include "core/ClipOps.h"
  15. #include "core/ClipEnvelope.h"
  16. #include "core/ChannelPoly.h"
  17. #include "core/Simd.h"
  18. #include "core/DirectWave.h"
  19. #include "core/FlSynths.h"
  20. #include "core/FlResampler.h"
  21. #include "core/FlSettings.h"
  22. #include "core/TimeStretch.h"
  23. #include "core/FlVoiceProcessor.h"
  24. #include "core/DrumSynthLive.h"
  25. #include "core/Gms.h"
  26. #include "core/Harmless.h"
  27. #include "core/Morphine.h"
  28. #include "core/SytrusEngine.h"
  29. #include "core/Harmor.h"
  30. #include "core/MiniSynth.h"
  31. #include "core/PocketSuperSaw.h"
  32. #include "core/FmSynth.h"
  33. #include "core/physmod/LynxModel.h"
  34. #include "core/WavetableSynth.h"
  35. #include "core/Braid.h"
  36. #include "core/SimSynth.h"
  37. #include "core/Wasp.h"
  38. #include "core/Plucked.h"
  39. #include "core/SoundFont.h"
  40. #include "core/BeepMap.h"
  41. #include "core/Sawer.h"
  42. #include "core/FlmPad.h"
  43. #include "core/Drumaxx.h"
  44. #include "core/Granulizer.h"
  45. #include "core/WaveTraveller.h"
  46. #include "core/SlicexInstrument.h"
  47. #include "core/Slayer.h"
  48. #include "core/Ogun.h"
  49. #include "core/TransistorBass.h"
  50. #include "core/Dx10.h"
  51. #include "core/Kepler.h"
  52. #include "core/PoiZone.h"
  53. #include "core/BassDrum.h"
  54. #include "core/FruitKick.h"
  55. #include "core/LynxDrums.h"
  56. #include "core/Toxic.h"
  57. #include "core/ThreeOsc.h"
  58. #include "core/PhysicalModels.h"
  59. #include <algorithm>
  60. #include <limits>
  61. #include <utility>
  62. #include <atomic>
  63. #include <cmath>
  64. #include <complex>
  65. namespace lynx
  66. {
  67. namespace
  68. {
  69. // An audio clip voice's fade gain at its position: FL's S curve (shape bits), with its tension, as FL's voices compute it (a
  70. // fade of N samples: x = (i + 1) / (N + 1), REA round 180d), or straight fades (FL's shape 1, and projects from before it).
  71. // A comp crossfade (shape bits 3 / 4, round 177c) is the equal-power curve, which wins over the others and has no tension.
  72. float clipFadeGainOf (float elapsed, float remaining, float in, float out, std::uint8_t shape, float inTension, float outTension) noexcept
  73. {
  74. auto gain = 1.0f;
  75. if (in > 0.0f && elapsed < in && (shape & 8) != 0)
  76. gain *= clipops::equalPowerCurve (elapsed / in);
  77. else if (in > 0.0f && elapsed < in)
  78. {
  79. const auto y = (shape & 1) != 0 ? clipops::crossfadeCurve ((elapsed + 1.0f) / (in + 1.0f)) : elapsed / in;
  80. gain *= inTension != 0.0f ? clipops::fadeTensionCurve (y, inTension) : y;
  81. }
  82. if (out > 0.0f && remaining < out && (shape & 16) != 0)
  83. gain *= clipops::equalPowerCurve (std::max (0.0f, remaining) / out);
  84. else if (out > 0.0f && remaining < out)
  85. {
  86. const auto y = (shape & 2) != 0 ? clipops::crossfadeCurve (std::max (0.0f, remaining) / (out + 1.0f)) : std::max (0.0f, remaining) / out;
  87. gain *= outTension != 0.0f ? clipops::fadeTensionCurve (y, outTension) : y;
  88. }
  89. return gain;
  90. }
  91. // 1 / channelGain at FL's default channel volume (10000 of 12800)
  92. float audioClipUnity() noexcept
  93. {
  94. static const float unity = 1.0f / channelGain (10000.0f / 12800.0f);
  95. return unity;
  96. }
  97. } // namespace
  98. namespace
  99. {
  100. constexpr double twoPi = 6.283185307179586;
  101. // Per-sample factor for an exponential decay that drops 60 dB in `seconds`.
  102. float decayCoefficient (double seconds, double sampleRate) noexcept
  103. {
  104. return (float) std::exp (std::log (0.001) / (seconds * sampleRate));
  105. }
  106. // In-place complex radix-2 FFT (wavetables for the spectral oscillator)
  107. void fftInPlace (std::vector<std::complex<double>>& a, bool inverse)
  108. {
  109. const auto n = a.size();
  110. for (std::size_t i = 1, j = 0; i < n; ++i)
  111. {
  112. auto bit = n >> 1;
  113. for (; j & bit; bit >>= 1)
  114. j ^= bit;
  115. j ^= bit;
  116. if (i < j)
  117. std::swap (a[i], a[j]);
  118. }
  119. for (std::size_t len = 2; len <= n; len <<= 1)
  120. {
  121. const auto w = std::polar (1.0, (inverse ? 2.0 : -2.0) * twoPi / 2.0 / (double) len);
  122. for (std::size_t i = 0; i < n; i += len)
  123. {
  124. std::complex<double> wn (1.0, 0.0);
  125. for (std::size_t k = 0; k < len / 2; ++k)
  126. {
  127. const auto u = a[i + k], v = a[i + k + len / 2] * wn;
  128. a[i + k] = u + v;
  129. a[i + k + len / 2] = u - v;
  130. wn *= w;
  131. }
  132. }
  133. }
  134. }
  135. double midiToHz (int key) noexcept
  136. {
  137. return 440.0 * std::pow (2.0, (key - 69) / 12.0);
  138. }
  139. // ---------------------------------------------------------------------------
  140. // Drums: each hit takes a voice; a few voices allow short overlaps.
  141. struct DrumVoice
  142. {
  143. bool active = false;
  144. float level = 0.0f; // amplitude envelope
  145. float velocity = 0.0f;
  146. double phase = 0.0;
  147. double pitchEnv = 0.0; // kick/snare: pitch envelope
  148. float filterState = 0.0f;
  149. float lastNoise = 0.0f;
  150. float lastHighPass = 0.0f;
  151. int age = 0; // samples since the hit
  152. float panL = 1.0f, panR = 1.0f; // the note's own pan (issue #63)
  153. double pitchRatio = 1.0; // the note's fine pitch
  154. };
  155. void voicePan (float pan, float& left, float& right) noexcept;
  156. class DrumInstrument final : public Instrument
  157. {
  158. public:
  159. // Round 190sy: the numbers below were constants until the drums got an editor; they are the channel's values now
  160. // (core/LynxDrums.h), and their defaults are the old constants, converted exactly (bit-identical renders)
  161. explicit DrumInstrument (InstrumentKind k) : kind (k)
  162. {
  163. for (int i = 0; i < lynxdrums::paramCount; ++i)
  164. values[(std::size_t) i].store (lynxdrums::defaultValue (k, i));
  165. }
  166. void prepare (double sr) noexcept override
  167. {
  168. sampleRate = sr;
  169. taken = 0; // (the coefficients follow the new rate)
  170. take();
  171. allNotesOff();
  172. }
  173. // UI thread: the channel's values; the audio thread takes them at its next call
  174. void configure (const ChannelDef& channel, double) noexcept override
  175. {
  176. bool changed = false;
  177. for (int i = 0; i < lynxdrums::paramCount; ++i)
  178. {
  179. const auto d = lynxdrums::defaultValue (kind, i);
  180. if (! std::isfinite (d))
  181. continue;
  182. const auto v = lynxdrums::value (channel, i);
  183. if (values[(std::size_t) i].exchange (v) != v)
  184. changed = true;
  185. }
  186. if (changed)
  187. version.fetch_add (1);
  188. }
  189. // automation and links (AutomationTargetKind::channelParam with the parameter's index), 0…1 over its range
  190. void setParameter (int index, float value01) noexcept override
  191. {
  192. const auto* p = findEngineParam (lynxdrums::params (kind), index);
  193. if (p == nullptr || ! std::isfinite (value01))
  194. return;
  195. values[(std::size_t) index].store (p->raw (value01));
  196. version.fetch_add (1);
  197. }
  198. void noteOn (int, float velocity) noexcept override
  199. {
  200. take();
  201. // Steals the oldest voice if all are busy.
  202. DrumVoice* target = &voices[0];
  203. for (auto& v : voices)
  204. {
  205. if (! v.active)
  206. {
  207. target = &v;
  208. break;
  209. }
  210. if (v.age > target->age)
  211. target = &v;
  212. }
  213. *target = {};
  214. target->active = true;
  215. target->level = 1.0f;
  216. target->velocity = velocity;
  217. target->pitchEnv = 1.0;
  218. // issue #63: the note's pan and fine pitch (the Channel Rack's graph editor / the piano roll); centred notes
  219. // stay bit for bit as before
  220. if (nextPan != 0.0f)
  221. voicePan (nextPan, target->panL, target->panR);
  222. if (nextCents != 0.0f)
  223. target->pitchRatio = std::pow (2.0, (double) nextCents / 1200.0);
  224. nextPan = nextCents = 0.0f;
  225. }
  226. void setNextNoteExpression (float pan, float cents, bool) noexcept override
  227. {
  228. nextPan = std::isfinite (pan) ? std::clamp (pan, -1.0f, 1.0f) : 0.0f;
  229. nextCents = std::isfinite (cents) ? std::clamp (cents, -4800.0f, 4800.0f) : 0.0f;
  230. }
  231. void noteOff (int) noexcept override {} // drums play until the end of the decay
  232. void allNotesOff() noexcept override
  233. {
  234. for (auto& v : voices)
  235. v.active = false;
  236. }
  237. void render (float* left, float* right, int n, float gl, float gr) noexcept override
  238. {
  239. take();
  240. const auto level = settings.level;
  241. for (auto& v : voices)
  242. {
  243. if (! v.active)
  244. continue;
  245. for (int i = 0; i < n; ++i)
  246. {
  247. const auto s = nextSample (v) * v.velocity * level; // (Level 100 % = × 1: exact)
  248. left[i] += s * gl * v.panL;
  249. right[i] += s * gr * v.panR;
  250. }
  251. if (v.level < 0.0005f)
  252. v.active = false;
  253. }
  254. }
  255. bool idle() const noexcept override
  256. {
  257. return std::none_of (voices.begin(), voices.end(), [] (const auto& v) { return v.active; });
  258. }
  259. private:
  260. float nextSample (DrumVoice& v) noexcept
  261. {
  262. float out = 0.0f;
  263. switch (kind)
  264. {
  265. case InstrumentKind::kick:
  266. {
  267. const auto hz = (settings.minHz + sweepHz * v.pitchEnv) * v.pitchRatio; // sweep Max → Min (155 → 45 Hz)
  268. v.phase += twoPi * hz / sampleRate;
  269. out = (float) std::sin (v.phase) * v.level;
  270. break;
  271. }
  272. case InstrumentKind::snare:
  273. {
  274. const auto hz = (settings.minHz + sweepHz * v.pitchEnv) * v.pitchRatio; // (240 → 180 Hz)
  275. v.phase += twoPi * hz / sampleRate;
  276. const auto tone = (float) std::sin (v.phase) * (float) v.pitchEnv;
  277. const auto noise = highPass (v, noiseGen.next());
  278. out = (settings.body * tone + settings.snap * noise) * v.level; // (Body 50 %, Snap 70 %)
  279. break;
  280. }
  281. case InstrumentKind::hat:
  282. out = 0.8f * highPass (v, noiseGen.next()) * v.level;
  283. break;
  284. case InstrumentKind::clap:
  285. {
  286. // A few short snaps (Snaps, Spread ms apart; 3 × 10 ms) followed by a tail: mimics several hands.
  287. const auto ms = v.age * 1000.0 / sampleRate;
  288. const auto burst = ms < burstMs ? (float) std::exp (-std::fmod (ms, settings.spreadMs) / 2.0) : 1.0f;
  289. out = 0.8f * bandPass (v, noiseGen.next()) * v.level * burst;
  290. break;
  291. }
  292. case InstrumentKind::synth:
  293. case InstrumentKind::sampler:
  294. case InstrumentKind::audioClip:
  295. case InstrumentKind::plugin:
  296. case InstrumentKind::controller:
  297. case InstrumentKind::midiOut:
  298. case InstrumentKind::layer:
  299. case InstrumentKind::dashboard:
  300. case InstrumentKind::voltage:
  301. case InstrumentKind::vfx:
  302. case InstrumentKind::videoplayer:
  303. case InstrumentKind::patcher:
  304. case InstrumentKind::sakura:
  305. case InstrumentKind::drumpad:
  306. case InstrumentKind::boobass:
  307. case InstrumentKind::drumsynth:
  308. case InstrumentKind::harmless:
  309. case InstrumentKind::sytrus:
  310. case InstrumentKind::harmor:
  311. case InstrumentKind::gms:
  312. case InstrumentKind::morphine:
  313. case InstrumentKind::ogun:
  314. case InstrumentKind::minisynth:
  315. case InstrumentKind::dx10:
  316. case InstrumentKind::kepler:
  317. case InstrumentKind::keplerExo:
  318. case InstrumentKind::poizone:
  319. case InstrumentKind::fruitkick:
  320. case InstrumentKind::bassdrum:
  321. case InstrumentKind::toxic:
  322. case InstrumentKind::threeosc:
  323. case InstrumentKind::autogun:
  324. case InstrumentKind::transistorbass:
  325. case InstrumentKind::simsynth:
  326. case InstrumentKind::wasp:
  327. case InstrumentKind::plucked:
  328. case InstrumentKind::beepmap:
  329. case InstrumentKind::sawer:
  330. case InstrumentKind::flkeys:
  331. case InstrumentKind::granulizer:
  332. case InstrumentKind::wavetraveller:
  333. case InstrumentKind::fruityslicer:
  334. case InstrumentKind::slicex:
  335. case InstrumentKind::fpc:
  336. case InstrumentKind::pocketSuperSaw:
  337. case InstrumentKind::tetra:
  338. case InstrumentKind::helix:
  339. case InstrumentKind::braid:
  340. case InstrumentKind::lynxModel:
  341. case InstrumentKind::drumaxx:
  342. case InstrumentKind::slayer:
  343. case InstrumentKind::fruitydance:
  344. case InstrumentKind::directwave:
  345. case InstrumentKind::soundfont:
  346. break;
  347. }
  348. v.level *= decay;
  349. v.pitchEnv *= pitchDecay;
  350. ++v.age;
  351. return out;
  352. }
  353. // Simple 1st-order high-pass (difference), good enough for cymbal noise (Tone: the coefficient, 0.85 by default).
  354. float highPass (DrumVoice& v, float x) const noexcept
  355. {
  356. const auto y = settings.highPass * (v.filterState + x - v.lastNoise);
  357. v.lastNoise = x;
  358. v.filterState = y;
  359. return y;
  360. }
  361. // Cheap band-pass: high-pass followed by a two-point average.
  362. float bandPass (DrumVoice& v, float x) const noexcept
  363. {
  364. const auto hp = highPass (v, x);
  365. const auto y = 0.5f * (hp + v.lastHighPass);
  366. v.lastHighPass = hp;
  367. return y;
  368. }
  369. // (audio thread) the values the UI or automation sent since the last call, and the coefficients they give
  370. void take() noexcept
  371. {
  372. const auto now = version.load();
  373. if (now == taken)
  374. return;
  375. taken = now;
  376. for (int i = 0; i < lynxdrums::paramCount; ++i)
  377. lynxdrums::applyValue (kind, settings, i, values[(std::size_t) i].load());
  378. decay = decayCoefficient (settings.ampDecayMs / 1000.0, sampleRate);
  379. pitchDecay = decayCoefficient (settings.pitchDecayMs / 1000.0, sampleRate);
  380. sweepHz = settings.maxHz - settings.minHz;
  381. burstMs = (double) settings.snaps * settings.spreadMs;
  382. }
  383. InstrumentKind kind;
  384. double sampleRate = 44100.0;
  385. float decay = 0.999f;
  386. double pitchDecay = 0.999;
  387. lynxdrums::Settings settings;
  388. double sweepHz = 110.0, burstMs = 30.0;
  389. std::array<std::atomic<float>, lynxdrums::paramCount> values {};
  390. std::atomic<std::uint32_t> version { 1 };
  391. std::uint32_t taken = 0;
  392. std::array<DrumVoice, 4> voices {};
  393. Noise noiseGen;
  394. float nextPan = 0.0f, nextCents = 0.0f;
  395. };
  396. // Per-voice pan gains (constant power, 1 at center).
  397. void voicePan (float pan, float& left, float& right) noexcept
  398. {
  399. const auto angle = (std::clamp (pan, -1.0f, 1.0f) + 1.0f) * 0.25f * 3.14159265f;
  400. left = std::cos (angle) * 1.41421356f;
  401. right = std::sin (angle) * 1.41421356f;
  402. }
  403. // ---------------------------------------------------------------------------
  404. // Simple polyphonic synth: sawtooth with low-pass and AR envelope.
  405. // ---------------------------------------------------------------------------
  406. // Modulation envelopes (cutoff and pitch), per voice: 0 attack, 1 hold, 2 decay,
  407. // 3 sustain, 4 release. Straight segments (tension 0, the FL default; REA_rodada3 §1.5).
  408. struct ModState
  409. {
  410. float level = 0.0f;
  411. float releaseStep = 0.0f; // fixed on note release: from the current level down to 0
  412. int stage = 0, held = 0;
  413. // Toxic shape: samples left in the current 128-sample block, elapsed time and the block's target/coefficient
  414. int blockLeft = 0;
  415. double elapsed = 0.0;
  416. float target = 0.0f, coefficient = 0.0f;
  417. };
  418. struct ModCoefficients
  419. {
  420. bool active = false, toxic = false;
  421. float amount = 0.0f, attackStep = 1.0f, decayStep = 1.0f, releasePerLevel = 1.0f, sustain = 0.0f;
  422. float toxicAttack = 0.0f, toxicDecay = 0.0f, toxicRelease = 0.0f; // per-sample coefficients
  423. int holdSamples = 0;
  424. static ModCoefficients make (const ModEnvelope& e, double sampleRate) noexcept
  425. {
  426. ModCoefficients c;
  427. c.active = e.amount != 0.0f;
  428. c.amount = e.amount;
  429. if (e.shape == 1)
  430. {
  431. // REA_rodada33 §2.1–2.2: times in seconds (floor 0.001), sustain level as is
  432. auto seconds = [] (float t) { return std::max (t, 0.001f); };
  433. c.toxic = true;
  434. c.attackStep = seconds (e.attack); // the attack stage lasts while elapsed < A
  435. c.sustain = e.sustain;
  436. c.toxicAttack = (float) (8.82 / ((double) seconds (e.attack) * 39.441975 * sampleRate));
  437. c.toxicDecay = (float) (8.82 / ((double) seconds (e.decay) * sampleRate));
  438. c.toxicRelease = (float) (8.82 / ((double) seconds (e.release) * sampleRate));
  439. return c;
  440. }
  441. c.attackStep = (float) (1.0 / (std::max (0.0005, (double) e.attack) * sampleRate));
  442. c.holdSamples = (int) (std::max (0.0f, e.hold) * sampleRate);
  443. c.sustain = std::clamp (e.sustain, 0.0f, 1.0f);
  444. c.decayStep = (float) ((1.0 - c.sustain) / (std::max (0.0005, (double) e.decay) * sampleRate)); // from 1 to sustain
  445. c.releasePerLevel = (float) (1.0 / (std::max (0.002, (double) e.release) * sampleRate));
  446. return c;
  447. }
  448. void advance (ModState& m) const noexcept
  449. {
  450. if (toxic)
  451. {
  452. // stage chosen at each block start (released → 0, attack → 5 while elapsed < A, else decay → S + 1e-7);
  453. // one-pole step every sample, clipped at 1
  454. if (--m.blockLeft < 0)
  455. {
  456. m.blockLeft = 127;
  457. if (m.stage == 4)
  458. m.target = 0.0f, m.coefficient = toxicRelease;
  459. else if ((double) attackStep <= m.elapsed)
  460. m.target = sustain + 1.0e-7f, m.coefficient = toxicDecay;
  461. else
  462. m.target = 5.0f, m.coefficient = toxicAttack;
  463. m.elapsed += 128.0 / 44100.0;
  464. }
  465. m.level = std::min (1.0f, (m.target - m.level) * m.coefficient + m.level);
  466. return;
  467. }
  468. switch (m.stage)
  469. {
  470. case 0:
  471. m.level += attackStep;
  472. if (m.level >= 1.0f) { m.level = 1.0f; m.stage = 1; }
  473. break;
  474. case 1:
  475. if (++m.held >= holdSamples) m.stage = 2;
  476. break;
  477. case 2:
  478. m.level -= decayStep;
  479. if (m.level <= sustain) { m.level = sustain; m.stage = 3; }
  480. break;
  481. case 3: break;
  482. default: m.level = std::max (0.0f, m.level - m.releaseStep); break;
  483. }
  484. }
  485. void release (ModState& m) const noexcept
  486. {
  487. m.stage = 4;
  488. m.releaseStep = m.level * releasePerLevel;
  489. }
  490. };
  491. // Channel LFO, advanced on the control tick.
  492. struct LfoState
  493. {
  494. double phase = 0.0;
  495. float fade = 0.0f;
  496. double delayLeft = 0.0; // samples
  497. };
  498. struct LfoCoefficients
  499. {
  500. bool active = false;
  501. float amount = 0.0f;
  502. double increment = 0.0; // cycles per sample
  503. double delaySamples = 0.0;
  504. float fadeStep = 1.0f; // per sample
  505. int shape = 0;
  506. bool global = false;
  507. double cyclesPerTick = 0.0; // global: phase = song position (ticks) × this
  508. static LfoCoefficients make (const ChannelLfo& l, double sampleRate, double bpm) noexcept
  509. {
  510. LfoCoefficients c;
  511. c.active = l.amount != 0.0f;
  512. c.amount = l.amount;
  513. const auto unit = l.sync ? 60.0 / std::max (1.0, bpm) : 1.0; // beats -> seconds
  514. c.increment = 1.0 / (std::max (0.005, (double) l.period * unit) * sampleRate);
  515. const auto timeUnit = l.secondsTiming ? 1.0 : unit;
  516. c.delaySamples = std::max (0.0, (double) l.delay * timeUnit * sampleRate);
  517. c.fadeStep = l.attack > 0.0f ? (float) (1.0 / ((double) l.attack * timeUnit * sampleRate)) : 1.0f;
  518. c.shape = std::clamp (l.shape, 0, 2);
  519. c.global = l.global;
  520. // period in beats (synced) or in seconds converted via BPM
  521. const auto periodBeats = l.sync ? std::max (0.005, (double) l.period) : std::max (0.005, (double) l.period) * std::max (1.0, bpm) / 60.0;
  522. c.cyclesPerTick = 1.0 / (periodBeats * ppq);
  523. return c;
  524. }
  525. // `songTicks`: song position (a global LFO starts at its phase; delay and fade-in stay per note)
  526. void start (LfoState& s, double songTicks = 0.0) const noexcept
  527. {
  528. s = { 0.0, fadeStep >= 1.0f ? 1.0f : 0.0f, delaySamples };
  529. if (global)
  530. {
  531. s.phase = songTicks * cyclesPerTick;
  532. s.phase -= std::floor (s.phase);
  533. }
  534. }
  535. // advances `n` samples and returns the output (±1, fade-in already applied)
  536. float tick (LfoState& s, int n) const noexcept
  537. {
  538. if (s.delayLeft > 0.0)
  539. {
  540. s.delayLeft -= n;
  541. return 0.0f;
  542. }
  543. s.phase += increment * n;
  544. s.phase -= std::floor (s.phase);
  545. s.fade = std::min (1.0f, s.fade + fadeStep * (float) n);
  546. const auto p = s.phase;
  547. float value = 0.0f;
  548. switch (shape)
  549. {
  550. case 1: value = (float) (p < 0.25 ? 4.0 * p : p < 0.75 ? 2.0 - 4.0 * p : 4.0 * p - 4.0); break;
  551. case 2: value = p < 0.5 ? 1.0f : -1.0f; break;
  552. default: value = (float) std::sin (6.283185307179586 * p); break;
  553. }
  554. return value * s.fade;
  555. }
  556. };
  557. // "TPT" SVF low-pass coefficients (stable at any cutoff), shared by the synth and the sampler.
  558. // The same filter gives all four responses (mode: 0 low-pass, 1 band-pass, 2 high-pass,
  559. // 3 band-stop), like the LP/BP/HP/BS types of FL's channel filter.
  560. struct SvfCoefficients
  561. {
  562. float a1 = 1.0f, a2 = 0.0f, a3 = 0.0f, k = 2.0f;
  563. int mode = 0;
  564. // 4-pole ladder (Toxic Biohazard, REA_rodada26 §2): f = 2fc/fs, k = 3.6f − 1.6f² − 1, p = (k + 1)/2, feedback
  565. // res·R(u) with u = (log2 fc − 5)/9; stages s = (x + x_prev)·p − k·s_prev; input saturated by
  566. // v·(1 − 3a + 4a² − 2a³), a = min(|v|/15, 1). (FL builds its table for 44.1 kHz; LYNX keeps fc in Hz at any rate.)
  567. bool ladder = false;
  568. float lp = 0.0f, lk = 0.0f, feedback = 0.0f;
  569. void setLadder (double cutoffHz, float resonance, double sampleRate, int filterMode) noexcept
  570. {
  571. ladder = true;
  572. mode = std::clamp (filterMode, 0, 2);
  573. const auto fc = std::clamp (cutoffHz, 32.0, 16384.0 * sampleRate / 44100.0);
  574. const auto f = 2.0 * fc / sampleRate;
  575. const auto kk = 3.6 * f - 1.6 * f * f - 1.0, p = (kk + 1.0) / 2.0;
  576. const auto u = std::clamp ((std::log2 (fc) - 5.0) / 9.0, 0.0, 1.0);
  577. const auto r = 1.96 * std::pow (1.0 - u, 1.5)
  578. + 0.98 * (0.95 * std::exp ((1.0 - p) * 1.386249) + (u > 0.7 ? 8.0 / 9.0 * (u - 0.7) * (u - 0.7) : 0.0));
  579. lp = (float) p;
  580. lk = (float) kk;
  581. feedback = (float) (std::clamp (resonance, 0.0f, 1.0f) * r);
  582. }
  583. // state: s1…s4 and the previous input of each stage
  584. float processLadder (float in, std::array<float, 8>& st) const noexcept
  585. {
  586. auto v = in - feedback * st[3];
  587. const auto a = std::min (std::abs (v) / 15.0f, 1.0f);
  588. v *= 1.0f - 3.0f * a + 4.0f * a * a - 2.0f * a * a * a;
  589. auto x = v;
  590. for (int i = 0; i < 4; ++i)
  591. {
  592. const auto s = (x + st[(std::size_t) i + 4]) * lp - lk * st[(std::size_t) i];
  593. st[(std::size_t) i + 4] = x;
  594. st[(std::size_t) i] = s;
  595. x = s;
  596. }
  597. switch (mode)
  598. {
  599. case 1: return st[2] - st[3];
  600. case 2: return v - st[3];
  601. default: return st[3];
  602. }
  603. }
  604. void set (double cutoffHz, float resonance, double sampleRate, int filterMode = 0, bool useLadder = false) noexcept
  605. {
  606. if (useLadder)
  607. {
  608. setLadder (cutoffHz, resonance, sampleRate, filterMode);
  609. return;
  610. }
  611. ladder = false;
  612. const auto fc = std::clamp (cutoffHz, 20.0, sampleRate * 0.45);
  613. const auto g = (float) std::tan (3.14159265358979 * fc / sampleRate);
  614. k = 2.0f - 1.9f * std::clamp (resonance, 0.0f, 1.0f); // 2 = no resonance
  615. a1 = 1.0f / (1.0f + g * (g + k));
  616. a2 = g * a1;
  617. a3 = g * a2;
  618. mode = std::clamp (filterMode, 0, 3);
  619. }
  620. float process (float in, float& low, float& band) const noexcept
  621. {
  622. const auto v3 = in - low;
  623. const auto v1 = a1 * band + a2 * v3;
  624. const auto v2 = low + a2 * band + a3 * v3;
  625. band = 2.0f * v1 - band;
  626. low = 2.0f * v2 - low;
  627. switch (mode)
  628. {
  629. case 1: return v1;
  630. case 2: return in - k * v1 - v2;
  631. case 3: return in - k * v1;
  632. default: return v2;
  633. }
  634. }
  635. };
  636. // Kepler's chorus (REA_rodada26 §3): mono input → high-pass (0.5 Hz) → two RBJ low-passes (7 kHz, Q 0.707) →
  637. // one delay line read by two taps (L and R LFO phases) with Catmull-Rom interpolation → 1-pole low-pass 7 kHz →
  638. // equal-power mix (m → 0.5). Delay = base + depth·w(LFO), smoothed by s = 1 − 0.1^(20/fs). Noise/gate not modelled.
  639. class KeplerChorus
  640. {
  641. public:
  642. void prepare (double sr) noexcept
  643. {
  644. sampleRate = sr;
  645. smooth = 1.0 - std::pow (0.1, 20.0 / sr);
  646. const auto th = std::tan (3.141592653589793 * 0.5 / sr);
  647. hpB = 1.0 / (1.0 + th);
  648. hpA = (1.0 - th) / (1.0 + th);
  649. const auto tl = std::tan (3.141592653589793 * 7000.0 / sr);
  650. lpB = tl / (1.0 + tl);
  651. lpA = (1.0 - tl) / (1.0 + tl);
  652. const auto w0 = 2.0 * 3.141592653589793 * 7000.0 / sr, alpha = std::sin (w0) / (2.0 * 0.707), a0 = 1.0 + alpha;
  653. bq = { (1.0 - std::cos (w0)) / 2.0 / a0, (1.0 - std::cos (w0)) / a0, (1.0 - std::cos (w0)) / 2.0 / a0,
  654. -2.0 * std::cos (w0) / a0, (1.0 - alpha) / a0 };
  655. reset();
  656. }
  657. void reset() noexcept
  658. {
  659. line.fill (0.0f);
  660. write = 0;
  661. phase = 0.0f;
  662. delay = { 0.01, 0.01 };
  663. mix = 0.0;
  664. outputGain = 0.0;
  665. hpX = hpY = 0.0;
  666. biquad = {};
  667. post = {};
  668. }
  669. // in place on a mono-summed signal; left/right receive the stereo result
  670. void process (float* left, float* right, int n, int mode) noexcept
  671. {
  672. const auto rate = mode == 3 ? 8.0 : mode == 2 ? 0.6 : 0.4;
  673. const auto offset = mode == 3 ? 0.0286111f : 0.5f;
  674. const auto base = mode == 3 ? 0.00285 : 0.00108, depth = mode == 3 ? 0.00052 : 0.00415;
  675. const auto increment = (float) (rate / sampleRate);
  676. for (int i = 0; i < n; ++i)
  677. {
  678. const double dry = 0.5 * ((double) left[i] + right[i]);
  679. // pre-filter (high-pass, then two low-pass biquads) into the delay line
  680. const auto hp = hpB * (dry - hpX) + hpA * hpY;
  681. hpX = dry;
  682. hpY = hp;
  683. auto x = hp;
  684. for (auto& st : biquad)
  685. {
  686. const auto y = bq[0] * x + st[0];
  687. st[0] = bq[1] * x - bq[3] * y + st[1];
  688. st[1] = bq[2] * x - bq[4] * y;
  689. x = y;
  690. }
  691. line[(std::size_t) write] = (float) x;
  692. mix += (0.5 - mix) * smooth;
  693. outputGain += (1.0 - outputGain) * smooth; // the unit fades in after it starts (§3.3 step 10)
  694. const auto wetGain = std::sqrt (mix), dryGain = std::sqrt (1.0 - mix);
  695. for (int c = 0; c < 2; ++c)
  696. {
  697. auto ph = phase + (c == 1 ? offset : 0.0f);
  698. ph -= std::floor (ph);
  699. const double w = mode == 3 ? (std::sin (2.0 * 3.141592653589793 * ph) + 1.0) / 2.0
  700. : ph < 0.25f ? 2.0 * ph + 0.5 : ph < 0.75f ? 1.5 - 2.0 * ph : 2.0 * ph - 1.5;
  701. auto& d = delay[(std::size_t) c];
  702. d += (base + depth * w - d) * smooth;
  703. const auto samples = d * sampleRate;
  704. const auto whole = (int) samples;
  705. const auto t = samples - whole;
  706. auto tap = [&] (int back) { return (double) line[(std::size_t) ((write - back) & mask)]; };
  707. const auto y0 = tap (whole - 1), y1 = tap (whole), y2 = tap (whole + 1), y3 = tap (whole + 2);
  708. const auto wet = y1 + 0.5 * t * (y2 - y0 + t * (2.0 * y0 - 5.0 * y1 + 4.0 * y2 - y3 + t * (3.0 * (y1 - y2) + y3 - y0)));
  709. auto& p = post[(std::size_t) c];
  710. const auto filtered = lpB * (wet + p[0]) + lpA * p[1];
  711. p[0] = wet;
  712. p[1] = filtered;
  713. (c == 0 ? left : right)[i] = (float) ((filtered * wetGain + dry * dryGain) * outputGain);
  714. }
  715. phase += increment;
  716. if (phase >= 1.0f)
  717. phase -= 1.0f;
  718. write = (write + 1) & mask;
  719. }
  720. }
  721. private:
  722. static constexpr int size = 32768, mask = size - 1;
  723. double sampleRate = 44100.0, smooth = 0.001;
  724. double hpB = 1.0, hpA = 0.0, lpB = 0.5, lpA = 0.0;
  725. std::array<double, 5> bq {};
  726. std::array<std::array<double, 2>, 2> biquad {}, post {};
  727. double hpX = 0.0, hpY = 0.0, mix = 0.0, outputGain = 0.0;
  728. std::array<double, 2> delay { 0.01, 0.01 };
  729. std::array<float, size> line {};
  730. int write = 0;
  731. float phase = 0.0f; // float32 LFO phase, as in FL (§3.5)
  732. };
  733. // ---------------------------------------------------------------------------
  734. // Round 190gp: four synth voices side by side, in SSE2 registers (core/Simd.h: SSE2 on x86-64, NEON through sse2neon on
  735. // ARM64, with its IEEE-exact division): each lane does a voice's own scalar arithmetic, operation for operation (no
  736. // FMA: -ffp-contract=off; a branch becomes a select of both results, which leaves the chosen one unchanged; a double
  737. // lane pair is two __m128d), and the voices are added to the output one after another in voice order, as the voice
  738. // loop adds them. So the samples are the same, bit for bit (tests: SynthLanes190gpTests.inc). (GCC's own 32-byte
  739. // vector types lower double compares lane by lane through the integer unit on SSE2: slower than the voice loop.)
  740. namespace lanes
  741. {
  742. #define LYNX_LANES_INLINE [[gnu::always_inline]] inline
  743. struct I4
  744. {
  745. union { __m128i v; std::int32_t e[4]; };
  746. LYNX_LANES_INLINE std::int32_t& operator[] (int j) noexcept { return e[j]; }
  747. LYNX_LANES_INLINE std::int32_t operator[] (int j) const noexcept { return e[j]; }
  748. };
  749. struct F4
  750. {
  751. union { __m128 v; float e[4]; };
  752. LYNX_LANES_INLINE float& operator[] (int j) noexcept { return e[j]; }
  753. LYNX_LANES_INLINE float operator[] (int j) const noexcept { return e[j]; }
  754. };
  755. struct D4 // (also the mask of a double compare: each lane all ones or all zeros)
  756. {
  757. union { __m128d p[2]; double e[4]; };
  758. LYNX_LANES_INLINE double& operator[] (int j) noexcept { return e[j]; }
  759. LYNX_LANES_INLINE double operator[] (int j) const noexcept { return e[j]; }
  760. };
  761. using L4 = D4;
  762. LYNX_LANES_INLINE F4 mk (__m128 v) noexcept { F4 r; r.v = v; return r; }
  763. LYNX_LANES_INLINE I4 mk (__m128i v) noexcept { I4 r; r.v = v; return r; }
  764. LYNX_LANES_INLINE D4 mk (__m128d lo, __m128d hi) noexcept { D4 r; r.p[0] = lo; r.p[1] = hi; return r; }
  765. LYNX_LANES_INLINE F4 f4 (float x) noexcept { return mk (_mm_set1_ps (x)); }
  766. LYNX_LANES_INLINE D4 d4 (double x) noexcept { return mk (_mm_set1_pd (x), _mm_set1_pd (x)); }
  767. LYNX_LANES_INLINE I4 i4 (std::int32_t x) noexcept { return mk (_mm_set1_epi32 (x)); }
  768. LYNX_LANES_INLINE F4 operator+ (F4 a, F4 b) noexcept { return mk (_mm_add_ps (a.v, b.v)); }
  769. LYNX_LANES_INLINE F4 operator- (F4 a, F4 b) noexcept { return mk (_mm_sub_ps (a.v, b.v)); }
  770. LYNX_LANES_INLINE F4 operator* (F4 a, F4 b) noexcept { return mk (_mm_mul_ps (a.v, b.v)); }
  771. LYNX_LANES_INLINE F4& operator+= (F4& a, F4 b) noexcept { return a = a + b; }
  772. LYNX_LANES_INLINE F4& operator-= (F4& a, F4 b) noexcept { return a = a - b; }
  773. LYNX_LANES_INLINE F4& operator*= (F4& a, F4 b) noexcept { return a = a * b; }
  774. LYNX_LANES_INLINE I4 operator< (F4 a, F4 b) noexcept { return mk (_mm_castps_si128 (_mm_cmplt_ps (a.v, b.v))); }
  775. LYNX_LANES_INLINE I4 operator>= (F4 a, F4 b) noexcept { return mk (_mm_castps_si128 (_mm_cmpge_ps (a.v, b.v))); }
  776. LYNX_LANES_INLINE D4 operator+ (D4 a, D4 b) noexcept { return mk (_mm_add_pd (a.p[0], b.p[0]), _mm_add_pd (a.p[1], b.p[1])); }
  777. LYNX_LANES_INLINE D4 operator- (D4 a, D4 b) noexcept { return mk (_mm_sub_pd (a.p[0], b.p[0]), _mm_sub_pd (a.p[1], b.p[1])); }
  778. LYNX_LANES_INLINE D4 operator* (D4 a, D4 b) noexcept { return mk (_mm_mul_pd (a.p[0], b.p[0]), _mm_mul_pd (a.p[1], b.p[1])); }
  779. LYNX_LANES_INLINE D4 operator/ (D4 a, D4 b) noexcept { return mk (_mm_div_pd (a.p[0], b.p[0]), _mm_div_pd (a.p[1], b.p[1])); }
  780. LYNX_LANES_INLINE D4& operator+= (D4& a, D4 b) noexcept { return a = a + b; }
  781. LYNX_LANES_INLINE L4 operator< (D4 a, D4 b) noexcept { return mk (_mm_cmplt_pd (a.p[0], b.p[0]), _mm_cmplt_pd (a.p[1], b.p[1])); }
  782. LYNX_LANES_INLINE L4 operator> (D4 a, D4 b) noexcept { return mk (_mm_cmpgt_pd (a.p[0], b.p[0]), _mm_cmpgt_pd (a.p[1], b.p[1])); }
  783. LYNX_LANES_INLINE L4 operator>= (D4 a, D4 b) noexcept { return mk (_mm_cmpge_pd (a.p[0], b.p[0]), _mm_cmpge_pd (a.p[1], b.p[1])); }
  784. LYNX_LANES_INLINE I4 operator- (I4 a, I4 b) noexcept { return mk (_mm_sub_epi32 (a.v, b.v)); }
  785. LYNX_LANES_INLINE I4& operator-= (I4& a, I4 b) noexcept { return a = a - b; }
  786. LYNX_LANES_INLINE I4 operator| (I4 a, I4 b) noexcept { return mk (_mm_or_si128 (a.v, b.v)); }
  787. LYNX_LANES_INLINE I4 operator== (I4 a, I4 b) noexcept { return mk (_mm_cmpeq_epi32 (a.v, b.v)); }
  788. LYNX_LANES_INLINE I4 operator> (I4 a, I4 b) noexcept { return mk (_mm_cmpgt_epi32 (a.v, b.v)); }
  789. LYNX_LANES_INLINE I4 operator<= (I4 a, I4 b) noexcept { return mk (_mm_xor_si128 (_mm_cmpgt_epi32 (a.v, b.v), _mm_set1_epi32 (-1))); }
  790. LYNX_LANES_INLINE F4 select (I4 m, F4 a, F4 b) noexcept
  791. {
  792. const auto k = _mm_castsi128_ps (m.v);
  793. return mk (_mm_or_ps (_mm_and_ps (k, a.v), _mm_andnot_ps (k, b.v)));
  794. }
  795. LYNX_LANES_INLINE I4 select (I4 m, I4 a, I4 b) noexcept { return mk (_mm_or_si128 (_mm_and_si128 (m.v, a.v), _mm_andnot_si128 (m.v, b.v))); }
  796. LYNX_LANES_INLINE D4 select (L4 m, D4 a, D4 b) noexcept
  797. {
  798. return mk (_mm_or_pd (_mm_and_pd (m.p[0], a.p[0]), _mm_andnot_pd (m.p[0], b.p[0])), _mm_or_pd (_mm_and_pd (m.p[1], a.p[1]), _mm_andnot_pd (m.p[1], b.p[1])));
  799. }
  800. // a double compare's lanes as a float / int mask, and back
  801. LYNX_LANES_INLINE I4 narrow (L4 m) noexcept
  802. {
  803. return mk (_mm_castps_si128 (_mm_shuffle_ps (_mm_castpd_ps (m.p[0]), _mm_castpd_ps (m.p[1]), _MM_SHUFFLE (2, 0, 2, 0))));
  804. }
  805. LYNX_LANES_INLINE L4 widen (I4 m) noexcept { return mk (_mm_castsi128_pd (_mm_unpacklo_epi32 (m.v, m.v)), _mm_castsi128_pd (_mm_unpackhi_epi32 (m.v, m.v))); }
  806. LYNX_LANES_INLINE F4 toFloat (D4 x) noexcept { return mk (_mm_movelh_ps (_mm_cvtpd_ps (x.p[0]), _mm_cvtpd_ps (x.p[1]))); }
  807. LYNX_LANES_INLINE F4 abs (F4 x) noexcept { return mk (_mm_and_ps (x.v, _mm_castsi128_ps (_mm_set1_epi32 (0x7fffffff)))); }
  808. LYNX_LANES_INLINE bool any (I4 m) noexcept { return _mm_movemask_ps (_mm_castsi128_ps (m.v)) != 0; }
  809. // SynthInstrument::polyBlep, lane by lane (the divisions only when a lane is next to a discontinuity, as there)
  810. LYNX_LANES_INLINE F4 polyBlep (D4 t, D4 dt) noexcept
  811. {
  812. const auto before = narrow (t < dt), after = narrow (t > d4 (1.0) - dt);
  813. if (! any (before | after))
  814. return f4 (0.0f);
  815. const auto a = t / dt;
  816. const auto b = (t - d4 (1.0)) / dt;
  817. const auto low = toFloat (a + a - a * a - d4 (1.0));
  818. const auto high = toFloat (b * b + b + b + d4 (1.0));
  819. return select (before, low, select (after, high, f4 (0.0f)));
  820. }
  821. // SynthInstrument::oscillator for the shapes without state or tables (sine, triangle, saw, square)
  822. LYNX_LANES_INLINE F4 oscillator (Waveform w, D4 phase, D4 dt) noexcept
  823. {
  824. const auto firstHalf = phase < d4 (0.5);
  825. switch (w)
  826. {
  827. case Waveform::sine:
  828. {
  829. const auto x = toFloat (select (firstHalf, phase, phase - d4 (1.0))) * f4 (2.0f);
  830. const auto y = f4 (4.0f) * x * (f4 (1.0f) - abs (x));
  831. return f4 (0.225f) * (y * abs (y) - y) + y;
  832. }
  833. case Waveform::triangle: return toFloat (select (firstHalf, d4 (4.0) * phase - d4 (1.0), d4 (3.0) - d4 (4.0) * phase));
  834. case Waveform::saw: return toFloat (d4 (2.0) * phase - d4 (1.0)) - polyBlep (phase, dt);
  835. case Waveform::square:
  836. {
  837. auto s = select (narrow (firstHalf), f4 (1.0f), f4 (-1.0f));
  838. s += polyBlep (phase, dt);
  839. s -= polyBlep (select (firstHalf, phase + d4 (0.5), phase - d4 (0.5)), dt);
  840. return s;
  841. }
  842. default: return f4 (0.0f);
  843. }
  844. }
  845. // one oscillator of the voice loop: its phase step (std::min (0.49, …)), its value × its level, the phase advanced and
  846. // wrapped
  847. // (`unit`: every lane's pitch factor and the pitch wheel are exactly 1, so × them changes no bit and is left out)
  848. LYNX_LANES_INLINE F4 advance (Waveform w, float level, D4& phase, D4 phaseDelta, double ratio, D4 pitchMul, D4 bend, bool unit) noexcept
  849. {
  850. auto delta = phaseDelta * d4 (ratio);
  851. if (! unit)
  852. delta = delta * pitchMul * bend;
  853. delta = select (delta < d4 (0.49), delta, d4 (0.49));
  854. const auto value = f4 (level) * oscillator (w, phase, delta);
  855. phase += delta;
  856. phase = select (phase >= d4 (1.0), phase - d4 (1.0), phase);
  857. return value;
  858. }
  859. // SvfCoefficients::process (the four responses)
  860. LYNX_LANES_INLINE F4 svf (int mode, F4 in, F4& lo, F4& bp, F4 a1, F4 a2, F4 a3, F4 k) noexcept
  861. {
  862. const auto v3 = in - lo;
  863. const auto v1 = a1 * bp + a2 * v3;
  864. const auto v2 = lo + a2 * bp + a3 * v3;
  865. bp = f4 (2.0f) * v1 - bp;
  866. lo = f4 (2.0f) * v2 - lo;
  867. switch (mode)
  868. {
  869. case 1: return v1;
  870. case 2: return in - k * v1 - v2;
  871. case 3: return in - k * v1;
  872. default: return v2;
  873. }
  874. }
  875. // the 3-band tone control
  876. LYNX_LANES_INLINE F4 bands (F4 x, F4& st0, F4& st1, F4 c0, F4 c1, F4 g0, F4 g1, F4 g2) noexcept
  877. {
  878. st0 += c0 * (x - st0);
  879. st1 += c1 * (x - st1);
  880. return st0 * g0 + (st1 - st0) * g1 + (x - st1) * g2;
  881. }
  882. #undef LYNX_LANES_INLINE
  883. } // namespace lanes
  884. std::atomic<bool> synthLanesFlag { true };
  885. struct SynthVoice
  886. {
  887. float panL = 1.0f, panR = 1.0f;
  888. double glideRatio = 1.0; // multiplies the frequency every sample during a slide
  889. int glideLeft = 0;
  890. bool active = false;
  891. bool releasing = false;
  892. int key = 0;
  893. float velocity = 0.0f;
  894. float level = 0.0f; // envelope
  895. int stage = 0; // 0 attack, 1 decay, 2 sustain, 3 release
  896. double phaseDelta = 0.0; // of the fundamental (each oscillator multiplies it)
  897. std::array<double, 3> phase {};
  898. float low = 0.0f, band = 0.0f; // filter states
  899. float lowR = 0.0f, bandR = 0.0f; // right-side filter (only with per-oscillator pan)
  900. std::array<std::array<float, 8>, 2> ladder {}; // ladder filter states (left, right)
  901. std::array<ModState, 2> mod {}; // filter, pitch
  902. std::array<LfoState, lfoTargets> lfo {};
  903. float lfoGain = 1.0f, lfoGainStep = 0.0f; // volume LFO, ramped between ticks
  904. float basePan = 0.0f; // note pan (the pan LFO adds to it)
  905. float cents = 0.0f; // the note's fine pitch (a VFX may move it while it sounds)
  906. SvfCoefficients filter; // this voice's (only with a cutoff envelope)
  907. double pitchMul = 1.0;
  908. float fmLevel = 1.0f; // FM index envelope (1 -> fmSustain)
  909. double sweep = 1.0; // s of the pitch sweep (1 -> 0)
  910. float tone[2][2] {}; // states of the two low-passes of the 3-band tone control (per side)
  911. int controlCountdown = 0;
  912. int age = 0;
  913. std::uint32_t noteId = 0; // the note it plays (round 190ej): only that note's end releases it
  914. };
  915. // Settings exchange without blocking the audio thread: the UI writes under a short flag and audio
  916. // only copies when it can grab the flag (if it can't, it uses the old settings for this block).
  917. template <typename T>
  918. class SettingsMailbox
  919. {
  920. public:
  921. void write (const T& value) noexcept
  922. {
  923. while (busy.test_and_set (std::memory_order_acquire)) {}
  924. pending = value;
  925. dirty = true;
  926. busy.clear (std::memory_order_release);
  927. }
  928. bool read (T& out) noexcept
  929. {
  930. if (busy.test_and_set (std::memory_order_acquire))
  931. return false;
  932. const auto changed = dirty;
  933. if (changed)
  934. {
  935. out = pending;
  936. dirty = false;
  937. }
  938. busy.clear (std::memory_order_release);
  939. return changed;
  940. }
  941. private:
  942. std::atomic_flag busy = ATOMIC_FLAG_INIT;
  943. T pending {};
  944. bool dirty = false;
  945. };
  946. class SynthInstrument final : public Instrument
  947. {
  948. public:
  949. SynthInstrument()
  950. {
  951. for (auto& k : automatedKnobs)
  952. k.store (std::numeric_limits<float>::quiet_NaN(), std::memory_order_relaxed);
  953. }
  954. void prepare (double sr) noexcept override
  955. {
  956. sampleRate = sr;
  957. lastPhaseDelta = 0.0;
  958. chorusUnit.prepare (sr);
  959. updateCoefficients();
  960. allNotesOff();
  961. }
  962. void configure (const ChannelDef& channel, double songBpm) noexcept override
  963. {
  964. bpm.store (std::max (1.0, songBpm)); // first: the synced LFO uses it when reading the settings
  965. channelPitch.store (channel.sampler.pitch * 100.0f); // the channel's PITCH knob (issue #14)
  966. updateFrames (channel.synth);
  967. // an automated knob (issue #152, round 190he) keeps the automation's value until its Song value changes (the
  968. // knob turned by hand, a MIDI link), as the Sampler's (issue #12)
  969. for (int k = 0; k < synthparam::count; ++k)
  970. {
  971. const auto now = synthparam::get (channel.synth, k);
  972. if (! (configuredKnobs[(std::size_t) k] == now))
  973. {
  974. configuredKnobs[(std::size_t) k] = now;
  975. automatedKnobs[(std::size_t) k].store (std::numeric_limits<float>::quiet_NaN(), std::memory_order_relaxed);
  976. }
  977. }
  978. if (const auto& l = channel.misc.levels; l.modX != 0.0f || l.modY != 0.0f) // Levels adjustment Mod X / Y (round 190dz)
  979. {
  980. auto adjusted = channel.synth;
  981. adjusted.cutoff = adjustedCutoff (adjusted.cutoff, l.modX);
  982. adjusted.resonance = adjustedResonance (adjusted.resonance, l.modY);
  983. mailbox.write (adjusted);
  984. }
  985. else
  986. mailbox.write (channel.synth);
  987. }
  988. ~SynthInstrument() override
  989. {
  990. delete incomingFrames.exchange (nullptr);
  991. delete retiredFrames.exchange (nullptr);
  992. delete activeFrames;
  993. }
  994. void startModulation (SynthVoice& v, float pan) noexcept
  995. {
  996. v.basePan = pan;
  997. v.lfoGain = 1.0f;
  998. v.lfoGainStep = 0.0f;
  999. v.sweep = 1.0;
  1000. std::fill (&v.tone[0][0], &v.tone[0][0] + 4, 0.0f);
  1001. v.controlCountdown = 0;
  1002. for (std::size_t i = 0; i < lfoTargets; ++i)
  1003. if (lfos[i].active)
  1004. lfos[i].start (v.lfo[i], songTicks);
  1005. }
  1006. void setSongPosition (double ticks) noexcept override { songTicks = ticks; }
  1007. // an automation clip / a modulator on one of LYNX Synth's knobs (core/SynthParams.h, issue #152). Audio thread.
  1008. void setParameter (int index, float value) noexcept override
  1009. {
  1010. if (! synthparam::valid (index) || ! std::isfinite (value))
  1011. return;
  1012. auto& slot = automatedKnobs[(std::size_t) synthparam::indexOf (index)];
  1013. if (slot.load (std::memory_order_relaxed) == value)
  1014. return;
  1015. slot.store (value, std::memory_order_relaxed);
  1016. automatedGeneration.fetch_add (1, std::memory_order_release);
  1017. }
  1018. // the Song's settings (configure's mailbox) with the automated knobs on top; coefficients only when something changed
  1019. void pullSettings() noexcept
  1020. {
  1021. const auto fresh = mailbox.read (settings);
  1022. const auto generation = automatedGeneration.load (std::memory_order_acquire);
  1023. if (! fresh && generation == appliedGeneration)
  1024. return;
  1025. appliedGeneration = generation;
  1026. for (int k = 0; k < synthparam::count; ++k)
  1027. if (const auto v = automatedKnobs[(std::size_t) k].load (std::memory_order_relaxed); ! std::isnan (v))
  1028. synthparam::set (settings, k, v);
  1029. updateCoefficients();
  1030. }
  1031. // portamento: the voice starts at `from` and glides to `to` over the porta time (channel porta,
  1032. // inverted by the note)
  1033. void glide (SynthVoice& v, double from, double to) noexcept
  1034. {
  1035. const auto steps = (int) (settings.portaBeats * 60.0 / bpm.load() * sampleRate);
  1036. const auto on = settings.porta != nextPorta;
  1037. if (! on || settings.portaBeats <= 0.0f || from <= 0.0 || steps < 1)
  1038. {
  1039. v.phaseDelta = to;
  1040. v.glideLeft = 0;
  1041. return;
  1042. }
  1043. v.phaseDelta = from;
  1044. v.glideRatio = std::pow (to / from, 1.0 / steps); // linear in semitones, like FL
  1045. v.glideLeft = steps;
  1046. }
  1047. void noteOn (int key, float velocity) noexcept override
  1048. {
  1049. pullSettings();
  1050. if (settings.mono)
  1051. {
  1052. // mono channel (polyphony 1 in FL): the sounding voice changes note without resetting phase or filter;
  1053. // the envelopes restart from the current level
  1054. SynthVoice* sounding = nullptr;
  1055. for (auto& v : voices)
  1056. if (v.active && (sounding == nullptr || v.age < sounding->age))
  1057. sounding = &v;
  1058. if (sounding != nullptr)
  1059. {
  1060. for (auto& v : voices)
  1061. if (&v != sounding)
  1062. v.active = false;
  1063. auto& v = *sounding;
  1064. v.key = key;
  1065. v.noteId = startingNoteId();
  1066. v.velocity = velocity;
  1067. v.releasing = false;
  1068. v.stage = 0;
  1069. v.age = 0;
  1070. const auto cents = nextCents + channelPitch.load (std::memory_order_relaxed);
  1071. const auto target = midiToHz (key) / sampleRate * std::pow (2.0, cents / 1200.0);
  1072. v.cents = cents;
  1073. glide (v, v.phaseDelta, target);
  1074. lastPhaseDelta = target;
  1075. for (auto& m : v.mod)
  1076. m = { m.level, 0.0f, 0, 0 };
  1077. v.fmLevel = 1.0f;
  1078. voicePan (nextPan, v.panL, v.panR);
  1079. startModulation (v, nextPan);
  1080. nextPan = nextCents = 0.0f;
  1081. nextPorta = false;
  1082. return;
  1083. }
  1084. }
  1085. SynthVoice* target = &voices[0];
  1086. for (auto& v : voices)
  1087. {
  1088. if (! v.active)
  1089. {
  1090. target = &v;
  1091. break;
  1092. }
  1093. if (v.age > target->age)
  1094. target = &v;
  1095. }
  1096. *target = {};
  1097. target->active = true;
  1098. target->key = key;
  1099. target->noteId = startingNoteId();
  1100. target->velocity = velocity;
  1101. const auto cents = nextCents + channelPitch.load (std::memory_order_relaxed);
  1102. const auto delta = midiToHz (key) / sampleRate * std::pow (2.0, cents / 1200.0);
  1103. target->cents = cents;
  1104. glide (*target, lastPhaseDelta, delta); // with porta, starts from the previous note's pitch
  1105. lastPhaseDelta = delta;
  1106. voicePan (nextPan, target->panL, target->panR);
  1107. startModulation (*target, nextPan);
  1108. nextPan = nextCents = 0.0f;
  1109. nextPorta = false;
  1110. }
  1111. void pitchBend (float semitones) noexcept override
  1112. {
  1113. bendMul = std::isfinite (semitones) ? std::exp2 ((double) std::clamp (semitones, -48.0f, 48.0f) / 12.0) : 1.0;
  1114. }
  1115. void setNextNoteExpression (float pan, float cents, bool porta) noexcept override
  1116. {
  1117. nextPan = pan;
  1118. nextCents = cents;
  1119. nextPorta = porta;
  1120. }
  1121. // a VFX changes a sounding note (round 164b): its fine pitch, pan or volume
  1122. void voiceProperty (int key, int prop, float value) noexcept override
  1123. {
  1124. if (! std::isfinite (value))
  1125. return;
  1126. for (auto& v : voices)
  1127. if (v.active && ! v.releasing && v.key == key)
  1128. {
  1129. if (prop == (int) vfx::Prop::pitch && v.phaseDelta > 0.0)
  1130. {
  1131. v.phaseDelta *= std::exp2 ((double) (value - v.cents) / 1200.0);
  1132. v.cents = value;
  1133. }
  1134. else if (prop == (int) vfx::Prop::pan)
  1135. {
  1136. v.basePan = std::clamp (value, -1.0f, 1.0f);
  1137. voicePan (v.basePan, v.panL, v.panR);
  1138. }
  1139. else if (prop == (int) vfx::Prop::velocity)
  1140. v.velocity = std::clamp (value, 0.0f, 1.0f);
  1141. }
  1142. }
  1143. bool followsSlides() const noexcept override { return true; } // (round 168l: a Mono channel's notes)
  1144. void slideTo (int key, float cents, float samples) noexcept override
  1145. {
  1146. const auto target = midiToHz (key) / sampleRate * std::pow (2.0, (cents + channelPitch.load (std::memory_order_relaxed)) / 1200.0);
  1147. const auto steps = std::max (1, (int) samples);
  1148. for (auto& v : voices)
  1149. if (v.active && ! v.releasing && v.phaseDelta > 0.0)
  1150. {
  1151. v.glideRatio = std::pow (target / v.phaseDelta, 1.0 / steps);
  1152. v.glideLeft = steps; // the voice keeps its original key: its "off" is what ends the note
  1153. }
  1154. }
  1155. void noteOff (int key) noexcept override
  1156. {
  1157. // (round 190ej: the note's own voice, as FL's generators end it)
  1158. for (auto& v : voices)
  1159. if (v.active && ! v.releasing && endsVoice (v.key, v.noteId, key))
  1160. {
  1161. v.releasing = true;
  1162. v.stage = 3;
  1163. for (std::size_t e = 0; e < 2; ++e)
  1164. modEnv[e].release (v.mod[e]);
  1165. }
  1166. }
  1167. void allNotesOff() noexcept override
  1168. {
  1169. for (auto& v : voices)
  1170. v.active = false;
  1171. }
  1172. void render (float* left, float* right, int n, float gl, float gr) noexcept override
  1173. {
  1174. pullSettings();
  1175. // new spectrum frames (built in configure): the old set goes back for the other thread to free
  1176. if (retiredFrames.load() == nullptr)
  1177. if (auto* frames = incomingFrames.exchange (nullptr))
  1178. {
  1179. retiredFrames.store (activeFrames); // a set with count 0 stays active as "static spectrum"
  1180. activeFrames = frames;
  1181. evolving = frames->count > 1;
  1182. }
  1183. // Kepler chorus: voices without the channel's volume/pan → chorus (mono in, stereo out) → volume/pan
  1184. if (settings.chorus > 0)
  1185. {
  1186. const auto anyActive = std::any_of (voices.begin(), voices.end(), [] (const SynthVoice& v) { return v.active; });
  1187. if (anyActive)
  1188. chorusTail = (int) (0.05 * sampleRate); // the delay (≤ 5.2 ms) and filters ring a little after the last voice
  1189. for (int done = 0; done < n; done += scratchSize)
  1190. {
  1191. const auto m = std::min (scratchSize, n - done);
  1192. std::fill (scratchL.begin(), scratchL.begin() + m, 0.0f);
  1193. std::fill (scratchR.begin(), scratchR.begin() + m, 0.0f);
  1194. renderVoices (scratchL.data(), scratchR.data(), m, 1.0f, 1.0f);
  1195. chorusUnit.process (scratchL.data(), scratchR.data(), m, settings.chorus);
  1196. for (int i = 0; i < m; ++i)
  1197. {
  1198. left[done + i] += scratchL[(std::size_t) i] * gl;
  1199. right[done + i] += scratchR[(std::size_t) i] * gr;
  1200. }
  1201. }
  1202. if (! anyActive)
  1203. chorusTail = std::max (0, chorusTail - n);
  1204. return;
  1205. }
  1206. renderVoices (left, right, n, gl, gr);
  1207. }
  1208. // the control "tick" of voice `v` at sample `i` of the block (every 16 samples): pitch, filter, volume and pan
  1209. // (round 190gp: one function for the voice loop and the four-lane one, so both run the same code)
  1210. [[gnu::always_inline]] inline void controlTick (SynthVoice& v, int i) noexcept
  1211. {
  1212. v.controlCountdown = 16;
  1213. auto semitones = modEnv[1].active ? modEnv[1].amount * v.mod[1].level : 0.0f;
  1214. auto octaves = modEnv[0].active ? modEnv[0].amount * v.mod[0].level : 0.0f;
  1215. octaves += settings.keyTrack * (float) (v.key - 48) / 12.0f;
  1216. if (lfos[lfoPitch].active)
  1217. semitones += lfos[lfoPitch].amount * lfos[lfoPitch].tick (v.lfo[lfoPitch], 16);
  1218. if (settings.vibratoCents > 0.0f) // 6 Hz global phase, depth × r², r = 3·age/fs ≤ 1
  1219. {
  1220. const auto r = std::min (1.0, 3.0 * (v.age + 1) / sampleRate);
  1221. const auto phase = vibratoPhase + 6.0 * i / sampleRate;
  1222. semitones += (float) (settings.vibratoCents / 100.0 * r * r * std::sin (2.0 * 3.141592653589793 * phase));
  1223. }
  1224. if (lfos[lfoCutoff].active)
  1225. octaves += lfos[lfoCutoff].amount * lfos[lfoCutoff].tick (v.lfo[lfoCutoff], 16);
  1226. if (lfos[lfoVolume].active)
  1227. {
  1228. const auto target = std::max (0.0f, 1.0f + lfos[lfoVolume].amount * lfos[lfoVolume].tick (v.lfo[lfoVolume], 16));
  1229. v.lfoGainStep = (target - v.lfoGain) / 16.0f;
  1230. }
  1231. if (lfos[lfoPan].active)
  1232. voicePan (v.basePan + lfos[lfoPan].amount * lfos[lfoPan].tick (v.lfo[lfoPan], 16), v.panL, v.panR);
  1233. v.pitchMul = semitones != 0.0f ? std::exp2 (semitones / 12.0) : 1.0;
  1234. if (settings.sweep > 0.0f)
  1235. {
  1236. const auto s2 = v.sweep * v.sweep;
  1237. v.pitchMul *= 1.0 + settings.sweep * s2 * s2;
  1238. v.sweep *= sweepCoeff;
  1239. }
  1240. if (filterModulated)
  1241. v.filter.set (settings.cutoff * std::exp2 (octaves), settings.resonance, sampleRate, settings.filterType, settings.ladder);
  1242. }
  1243. // Round 190gp: can the active voices run side by side this block? Not with what keeps state across voices or reads
  1244. // tables (noise, spectral shapes, the evolving spectrum), FM's phase wrap, the ladder filter or Harmless' tremolo:
  1245. // those blocks run voice by voice. (Both ways give the same samples; this one costs about half.)
  1246. bool lanesFit() const noexcept
  1247. {
  1248. if (! synthLanesFlag.load (std::memory_order_relaxed) || evolving || settings.fm > 0.0f || settings.ladder
  1249. || settings.stereoTremolo > 0.0f)
  1250. return false;
  1251. for (const auto& osc : settings.osc)
  1252. if (osc.level > 0.0f && osc.wave != Waveform::sine && osc.wave != Waveform::triangle && osc.wave != Waveform::saw
  1253. && osc.wave != Waveform::square)
  1254. return false;
  1255. if (filterModulated) // (each voice's own filter: one response for all the lanes)
  1256. for (const auto& v : voices)
  1257. if (v.active && (v.filter.ladder || v.filter.mode != sharedFilter.mode))
  1258. return false;
  1259. return sharedFilter.mode >= 0 && sharedFilter.mode <= 3;
  1260. }
  1261. // Up to four voices (`count`, in voice order) through the voice loop's arithmetic side by side, then added to the
  1262. // output in voice order. The voices' state is loaded into lanes and stored back as the voice loop leaves it.
  1263. void renderVoiceGroup (SynthVoice* const* group, int count, float* __restrict left, float* __restrict right, int n, float gl,
  1264. float gr) noexcept
  1265. {
  1266. using namespace lanes;
  1267. F4 level, velocity, lfoGain, lfoGainStep, panL, panR, low, band, lowR, bandR, tone00, tone01, tone10, tone11;
  1268. F4 a1, a2, a3, kk;
  1269. I4 stage, glideLeft, countdown;
  1270. D4 phaseDelta, glideRatio, pitchMul, phase0, phase1, phase2;
  1271. std::array<int, 4> age {};
  1272. for (int j = 0; j < 4; ++j)
  1273. {
  1274. const auto& v = *group[j < count ? j : 0]; // (an unused lane copies the first voice; its results are dropped)
  1275. level[j] = v.level;
  1276. velocity[j] = v.velocity;
  1277. lfoGain[j] = v.lfoGain;
  1278. lfoGainStep[j] = v.lfoGainStep;
  1279. panL[j] = v.panL;
  1280. panR[j] = v.panR;
  1281. low[j] = v.low;
  1282. band[j] = v.band;
  1283. lowR[j] = v.lowR;
  1284. bandR[j] = v.bandR;
  1285. tone00[j] = v.tone[0][0];
  1286. tone01[j] = v.tone[0][1];
  1287. tone10[j] = v.tone[1][0];
  1288. tone11[j] = v.tone[1][1];
  1289. const auto& f = filterModulated ? v.filter : sharedFilter;
  1290. a1[j] = f.a1;
  1291. a2[j] = f.a2;
  1292. a3[j] = f.a3;
  1293. kk[j] = f.k;
  1294. stage[j] = v.stage;
  1295. glideLeft[j] = v.glideLeft;
  1296. countdown[j] = j < count ? v.controlCountdown : std::numeric_limits<std::int32_t>::max() / 2;
  1297. phaseDelta[j] = v.phaseDelta;
  1298. glideRatio[j] = v.glideRatio;
  1299. pitchMul[j] = v.pitchMul;
  1300. phase0[j] = v.phase[0];
  1301. phase1[j] = v.phase[1];
  1302. phase2[j] = v.phase[2];
  1303. age[(std::size_t) j] = v.age;
  1304. }
  1305. const auto sustain = f4 (settings.sustain), attack = f4 (attackStep), decay = f4 (decayCoeff), release = f4 (releaseCoeff);
  1306. const auto bend = d4 (bendMul);
  1307. // (round 190gp: without modulation the voices' pitch factors stay where they are; all 1 and no pitch bend: the
  1308. // phase steps skip two exact × 1 per oscillator. Nothing gliding: the glide is skipped, as it would change nothing)
  1309. auto unitPitch = ! modulated && bendMul == 1.0;
  1310. auto anyGlide = false;
  1311. for (int j = 0; j < count; ++j)
  1312. {
  1313. unitPitch = unitPitch && group[j]->pitchMul == 1.0;
  1314. anyGlide = anyGlide || group[j]->glideLeft > 0;
  1315. }
  1316. const auto& osc = settings.osc;
  1317. const int mode = sharedFilter.mode;
  1318. const auto summed = osc3Modulates ? 2 : 3;
  1319. const auto bandGain0 = f4 (settings.bandGain[0]), bandGain1 = f4 (settings.bandGain[1]), bandGain2 = f4 (settings.bandGain[2]);
  1320. const auto toneC0 = f4 (toneCoeff[0]), toneC1 = f4 (toneCoeff[1]);
  1321. const auto gainL = f4 (gl), gainR = f4 (gr);
  1322. constexpr int chunk = 64;
  1323. alignas (16) float outL[4 * chunk], outR[4 * chunk];
  1324. for (int base = 0; base < n; base += chunk)
  1325. {
  1326. const auto m = std::min (chunk, n - base);
  1327. for (int q = 0; q < m; ++q)
  1328. {
  1329. const auto i = base + q;
  1330. // ADSR envelope (the voice loop's switch: each stage's result, the lane's own stage picked)
  1331. {
  1332. auto attacked = level + attack;
  1333. const auto peaked = attacked >= f4 (1.0f);
  1334. attacked = select (peaked, f4 (1.0f), attacked);
  1335. auto decayed = sustain + (level - sustain) * decay;
  1336. const auto settled = decayed - sustain < f4 (0.001f);
  1337. decayed = select (settled, sustain, decayed);
  1338. const auto released = level * release;
  1339. const auto s0 = stage == i4 (0), s1 = stage == i4 (1), s2 = stage == i4 (2);
  1340. level = select (s0, attacked, select (s1, decayed, select (s2, level, released)));
  1341. stage = select (s0, select (peaked, i4 (1), i4 (0)), select (s1, select (settled, i4 (2), i4 (1)), stage));
  1342. }
  1343. if (anyGlide)
  1344. {
  1345. const auto gliding = glideLeft > i4 (0);
  1346. phaseDelta = select (widen (gliding), phaseDelta * glideRatio, phaseDelta);
  1347. glideLeft = select (gliding, glideLeft - i4 (1), glideLeft);
  1348. }
  1349. if (modulated)
  1350. {
  1351. for (int j = 0; j < count; ++j)
  1352. for (std::size_t e = 0; e < 2; ++e)
  1353. if (modEnv[e].active)
  1354. modEnv[e].advance (group[j]->mod[e]);
  1355. countdown -= i4 (1);
  1356. if (const auto due = countdown <= i4 (0); any (due))
  1357. for (int j = 0; j < count; ++j)
  1358. if (due[j] != 0)
  1359. {
  1360. auto& v = *group[j];
  1361. v.lfoGain = lfoGain[j];
  1362. v.age = age[(std::size_t) j] + i;
  1363. controlTick (v, i);
  1364. countdown[j] = v.controlCountdown;
  1365. pitchMul[j] = v.pitchMul;
  1366. panL[j] = v.panL;
  1367. panR[j] = v.panR;
  1368. lfoGainStep[j] = v.lfoGainStep;
  1369. if (filterModulated)
  1370. {
  1371. a1[j] = v.filter.a1;
  1372. a2[j] = v.filter.a2;
  1373. a3[j] = v.filter.a3;
  1374. kk[j] = v.filter.k;
  1375. }
  1376. }
  1377. lfoGain += lfoGainStep;
  1378. }
  1379. auto sum = f4 (0.0f), sumR = f4 (0.0f), modulator = f4 (0.0f);
  1380. if (osc3Modulates && osc[2].level > 0.0f) // (AM only here: FM blocks run voice by voice)
  1381. modulator = lanes::advance (osc[2].wave, osc[2].level, phase2, phaseDelta, ratios[2], pitchMul, bend, unitPitch);
  1382. if (osc[0].level > 0.0f)
  1383. {
  1384. const auto value = lanes::advance (osc[0].wave, osc[0].level, phase0, phaseDelta, ratios[0], pitchMul, bend, unitPitch);
  1385. sum += value * f4 (oscPanL[0]);
  1386. sumR += value * f4 (oscPanR[0]);
  1387. }
  1388. if (osc[1].level > 0.0f)
  1389. {
  1390. const auto value = lanes::advance (osc[1].wave, osc[1].level, phase1, phaseDelta, ratios[1], pitchMul, bend, unitPitch);
  1391. sum += value * f4 (oscPanL[1]);
  1392. sumR += value * f4 (oscPanR[1]);
  1393. }
  1394. if (summed == 3 && osc[2].level > 0.0f)
  1395. {
  1396. const auto value = lanes::advance (osc[2].wave, osc[2].level, phase2, phaseDelta, ratios[2], pitchMul, bend, unitPitch);
  1397. sum += value * f4 (oscPanL[2]);
  1398. sumR += value * f4 (oscPanR[2]);
  1399. }
  1400. if (settings.am)
  1401. {
  1402. const auto factor = settings.ring ? f4 (1.0f - osc[2].level) + modulator : f4 (1.0f) - modulator;
  1403. sum *= factor;
  1404. sumR *= factor;
  1405. }
  1406. // the SVF (SvfCoefficients::process)
  1407. auto outLeft = lanes::svf (mode, sum, low, band, a1, a2, a3, kk);
  1408. auto outRight = ! stereoOscillators ? outLeft : lanes::svf (mode, sumR, lowR, bandR, a1, a2, a3, kk);
  1409. if (useBands)
  1410. {
  1411. outLeft = lanes::bands (outLeft, tone00, tone01, toneC0, toneC1, bandGain0, bandGain1, bandGain2);
  1412. outRight = stereoOscillators ? lanes::bands (outRight, tone10, tone11, toneC0, toneC1, bandGain0, bandGain1, bandGain2) : outLeft;
  1413. }
  1414. const auto s = f4 (0.3f) * level * velocity * lfoGain;
  1415. const auto contributionL = outLeft * s * gainL * panL * f4 (1.0f); // (× the tremolo's 1)
  1416. const auto contributionR = outRight * s * gainR * panR * f4 (1.0f);
  1417. std::memcpy (outL + 4 * q, &contributionL, sizeof (contributionL));
  1418. std::memcpy (outR + 4 * q, &contributionR, sizeof (contributionR));
  1419. }
  1420. // the voices into the output one after another, in voice order (as the voice loop adds them)
  1421. for (int q = 0; q < m; ++q)
  1422. for (int j = 0; j < count; ++j)
  1423. {
  1424. left[base + q] += outL[4 * q + j];
  1425. right[base + q] += outR[4 * q + j];
  1426. }
  1427. }
  1428. for (int j = 0; j < count; ++j)
  1429. {
  1430. auto& v = *group[j];
  1431. v.level = level[j];
  1432. v.lfoGain = lfoGain[j];
  1433. v.lfoGainStep = lfoGainStep[j];
  1434. v.panL = panL[j];
  1435. v.panR = panR[j];
  1436. v.low = low[j];
  1437. v.band = band[j];
  1438. v.lowR = lowR[j];
  1439. v.bandR = bandR[j];
  1440. v.tone[0][0] = tone00[j];
  1441. v.tone[0][1] = tone01[j];
  1442. v.tone[1][0] = tone10[j];
  1443. v.tone[1][1] = tone11[j];
  1444. v.stage = stage[j];
  1445. v.glideLeft = glideLeft[j];
  1446. if (modulated)
  1447. v.controlCountdown = countdown[j];
  1448. v.phaseDelta = phaseDelta[j];
  1449. v.pitchMul = pitchMul[j];
  1450. v.phase[0] = phase0[j];
  1451. v.phase[1] = phase1[j];
  1452. v.phase[2] = phase2[j];
  1453. v.age = age[(std::size_t) j] + n;
  1454. if (v.stage == 3 && v.level < 0.0005f)
  1455. v.active = false;
  1456. }
  1457. }
  1458. void renderVoiceLanes (float* __restrict left, float* __restrict right, int n, float gl, float gr) noexcept
  1459. {
  1460. std::array<SynthVoice*, 4> group {};
  1461. int count = 0;
  1462. for (auto& v : voices)
  1463. if (v.active)
  1464. {
  1465. group[(std::size_t) count++] = &v;
  1466. if (count == 4)
  1467. {
  1468. renderVoiceGroup (group.data(), 4, left, right, n, gl, gr);
  1469. count = 0;
  1470. }
  1471. }
  1472. if (count == 1) // (one voice: the voice loop is quicker than four lanes with three idle; two already gain)
  1473. renderVoice (*group[0], left, right, n, gl, gr);
  1474. else if (count > 0)
  1475. renderVoiceGroup (group.data(), count, left, right, n, gl, gr);
  1476. // global free-running phases (Harmless tremolo and vibrato), as renderVoices ends
  1477. tremoloPhase += 2.5 * n / sampleRate;
  1478. tremoloPhase -= std::floor (tremoloPhase);
  1479. vibratoPhase += 6.0 * n / sampleRate;
  1480. vibratoPhase -= std::floor (vibratoPhase);
  1481. }
  1482. // (round 190ge: the output buffers never overlap this instrument's state — the scratch ones are written only through
  1483. // these pointers here — so `__restrict` lets the compiler keep the settings in registers through the sample loop
  1484. // instead of reading them again after every store; the same arithmetic, the same samples)
  1485. // one voice over the block, added to the output (round 190gp: on its own, for the voice loop and a lone voice of
  1486. // the four-lane one)
  1487. void renderVoice (SynthVoice& v, float* __restrict left, float* __restrict right, int n, float gl, float gr) noexcept
  1488. {
  1489. for (int i = 0; i < n; ++i)
  1490. {
  1491. if (evolving) // evolving spectrum: the two frames around the note's age
  1492. {
  1493. const auto t = v.age / sampleRate;
  1494. const auto x = std::min ((double) (activeFrames->count - 1), (activeFrames->count - 1) * std::sqrt (t / activeFrames->span));
  1495. const auto k = std::min ((int) x, activeFrames->count - 2);
  1496. frameA = &activeFrames->tables[(std::size_t) k];
  1497. frameB = &activeFrames->tables[(std::size_t) k + 1];
  1498. frameMix = (float) (x - k);
  1499. }
  1500. // ADSR envelope
  1501. switch (v.stage)
  1502. {
  1503. case 0:
  1504. v.level += attackStep;
  1505. if (v.level >= 1.0f) { v.level = 1.0f; v.stage = 1; }
  1506. break;
  1507. case 1:
  1508. v.level = settings.sustain + (v.level - settings.sustain) * decayCoeff;
  1509. if (v.level - settings.sustain < 0.001f) { v.level = settings.sustain; v.stage = 2; }
  1510. break;
  1511. case 2: break;
  1512. default: v.level *= releaseCoeff; break;
  1513. }
  1514. if (v.glideLeft > 0)
  1515. {
  1516. v.phaseDelta *= v.glideRatio;
  1517. --v.glideLeft;
  1518. }
  1519. if (modulated)
  1520. {
  1521. for (std::size_t e = 0; e < 2; ++e)
  1522. if (modEnv[e].active)
  1523. modEnv[e].advance (v.mod[e]);
  1524. // every 16 samples (the control "tick"): pitch, filter, volume and pan
  1525. if (--v.controlCountdown <= 0)
  1526. controlTick (v, i);
  1527. v.lfoGain += v.lfoGainStep;
  1528. }
  1529. float sum = 0.0f, sumR = 0.0f, modulator = 0.0f;
  1530. double fmShift = 0.0;
  1531. // AM/FM: osc 3 is not summed, it modulates (first, so FM shifts the phase of osc 1 + 2)
  1532. if (osc3Modulates)
  1533. {
  1534. const auto& osc = settings.osc[2];
  1535. if (osc.level > 0.0f)
  1536. {
  1537. const auto delta = std::min (0.49, v.phaseDelta * ratios[2] * v.pitchMul * bendMul);
  1538. modulator = osc.level * oscillator (osc.wave, v.phase[2], delta);
  1539. v.phase[2] += delta;
  1540. if (v.phase[2] >= 1.0)
  1541. v.phase[2] -= 1.0;
  1542. }
  1543. if (settings.fm > 0.0f)
  1544. {
  1545. v.fmLevel = settings.fmSustain + (v.fmLevel - settings.fmSustain) * fmDecayCoeff;
  1546. fmShift = (double) (settings.fm * v.fmLevel * modulator);
  1547. }
  1548. }
  1549. for (std::size_t o = 0; o < (osc3Modulates ? 2u : 3u); ++o)
  1550. {
  1551. const auto& osc = settings.osc[o];
  1552. if (osc.level <= 0.0f)
  1553. continue;
  1554. const auto delta = std::min (0.49, v.phaseDelta * ratios[o] * v.pitchMul * bendMul);
  1555. auto phase = v.phase[o];
  1556. if (fmShift != 0.0)
  1557. {
  1558. phase += fmShift;
  1559. phase -= std::floor (phase);
  1560. }
  1561. const auto value = osc.level * oscillator (osc.wave, phase, delta);
  1562. sum += value * oscPanL[o];
  1563. sumR += value * oscPanR[o];
  1564. v.phase[o] += delta;
  1565. if (v.phase[o] >= 1.0) // delta < 0.5: at most one wrap (no floor, which is a function call on CPUs without SSE4)
  1566. v.phase[o] -= 1.0;
  1567. }
  1568. if (settings.am) // (o1·g1 + o2·g2)·(1 − g3·o3), REA_rodada6 §3; ring (Sytrus): 1 − g3 + g3·o3, rodada18 §2
  1569. {
  1570. const auto factor = settings.ring ? 1.0f - settings.osc[2].level + modulator : 1.0f - modulator;
  1571. sum *= factor;
  1572. sumR *= factor;
  1573. }
  1574. // resonant low-pass filter (state variable "TPT": stable at any cutoff)
  1575. const auto& f = filterModulated ? v.filter : sharedFilter;
  1576. auto outL = f.ladder ? f.processLadder (sum, v.ladder[0]) : f.process (sum, v.low, v.band);
  1577. auto outR = ! stereoOscillators ? outL : f.ladder ? f.processLadder (sumR, v.ladder[1]) : f.process (sumR, v.lowR, v.bandR);
  1578. if (useBands)
  1579. {
  1580. auto bands = [&] (float x, float* st) {
  1581. st[0] += toneCoeff[0] * (x - st[0]);
  1582. st[1] += toneCoeff[1] * (x - st[1]);
  1583. return st[0] * settings.bandGain[0] + (st[1] - st[0]) * settings.bandGain[1] + (x - st[1]) * settings.bandGain[2];
  1584. };
  1585. outL = bands (outL, v.tone[0]);
  1586. outR = stereoOscillators ? bands (outR, v.tone[1]) : outL;
  1587. }
  1588. const auto s = 0.3f * v.level * v.velocity * v.lfoGain;
  1589. auto tl = 1.0f, tr = 1.0f;
  1590. if (settings.stereoTremolo > 0.0f) // rectified 2.5 Hz, L/R a quarter period apart; 0.1 s fade-in per voice
  1591. {
  1592. const auto theta = 2.0 * 3.141592653589793 * (tremoloPhase + 2.5 * i / sampleRate);
  1593. const auto d = (double) settings.stereoTremolo;
  1594. const auto r = std::min (1.0, v.age / std::max (1.0, std::round (0.1 * sampleRate)));
  1595. tl = (float) (1.0 + r * d * (std::abs (1.25 * std::cos (theta)) - 1.0));
  1596. tr = (float) (1.0 + r * d * (std::abs (1.25 * std::sin (theta)) - 1.0));
  1597. }
  1598. left[i] += outL * s * gl * v.panL * tl;
  1599. right[i] += outR * s * gr * v.panR * tr;
  1600. ++v.age;
  1601. }
  1602. if (v.stage == 3 && v.level < 0.0005f)
  1603. v.active = false;
  1604. }
  1605. void renderVoices (float* __restrict left, float* __restrict right, int n, float gl, float gr) noexcept
  1606. {
  1607. if (lanesFit())
  1608. return renderVoiceLanes (left, right, n, gl, gr);
  1609. for (auto& v : voices)
  1610. if (v.active)
  1611. renderVoice (v, left, right, n, gl, gr);
  1612. // global free-running phases (Harmless tremolo and vibrato)
  1613. tremoloPhase += 2.5 * n / sampleRate;
  1614. tremoloPhase -= std::floor (tremoloPhase);
  1615. vibratoPhase += 6.0 * n / sampleRate;
  1616. vibratoPhase -= std::floor (vibratoPhase);
  1617. }
  1618. bool idle() const noexcept override
  1619. {
  1620. return chorusTail <= 0 && std::none_of (voices.begin(), voices.end(), [] (const auto& v) { return v.active; });
  1621. }
  1622. private:
  1623. static constexpr int scratchSize = 1024;
  1624. std::array<float, scratchSize> scratchL {}, scratchR {};
  1625. KeplerChorus chorusUnit;
  1626. int chorusTail = 0;
  1627. double tremoloPhase = 0.0, vibratoPhase = 0.0;
  1628. // sine of a 0..1 phase via a refined parabola (error < 0.1%), much cheaper than std::sin
  1629. static float fastSine (double phase) noexcept
  1630. {
  1631. auto x = (float) (phase < 0.5 ? phase : phase - 1.0) * 2.0f; // -1..1 (half cycle = 1)
  1632. const auto y = 4.0f * x * (1.0f - std::abs (x)); // parabola
  1633. return 0.225f * (y * std::abs (y) - y) + y; // refinement
  1634. }
  1635. // aliasing correction at discontinuities (polyBLEP)
  1636. static float polyBlep (double t, double dt) noexcept
  1637. {
  1638. if (t < dt)
  1639. {
  1640. t /= dt;
  1641. return (float) (t + t - t * t - 1.0);
  1642. }
  1643. if (t > 1.0 - dt)
  1644. {
  1645. t = (t - 1.0) / dt;
  1646. return (float) (t * t + t + t + 1.0);
  1647. }
  1648. return 0.0f;
  1649. }
  1650. [[gnu::always_inline]] inline float oscillator (Waveform w, double phase, double dt) noexcept // (round 190ge: in the sample loop, not a call per oscillator per sample)
  1651. {
  1652. switch (w)
  1653. {
  1654. case Waveform::sine: return fastSine (phase);
  1655. case Waveform::triangle: return (float) (phase < 0.5 ? 4.0 * phase - 1.0 : 3.0 - 4.0 * phase);
  1656. case Waveform::saw: return (float) (2.0 * phase - 1.0) - polyBlep (phase, dt);
  1657. case Waveform::square:
  1658. {
  1659. auto s = phase < 0.5 ? 1.0f : -1.0f;
  1660. s += polyBlep (phase, dt);
  1661. s -= polyBlep (phase < 0.5 ? phase + 0.5 : phase - 0.5, dt);
  1662. return s;
  1663. }
  1664. case Waveform::noise: return noise.next();
  1665. case Waveform::spectral:
  1666. {
  1667. // the table with harmonics up to 1024 >> j stays below Nyquist: j = lowest level that fits
  1668. int level = 0;
  1669. while (level < wavetableLevels - 1 && (double) (1024 >> level) * dt > 0.5)
  1670. ++level;
  1671. const auto pos = phase * wavetableSize;
  1672. const auto i = std::min ((int) pos, wavetableSize - 1);
  1673. const auto f = (float) (pos - i);
  1674. auto read = [&] (const Tables& tables) {
  1675. const auto& t = tables[(std::size_t) level];
  1676. return t[(std::size_t) i] + f * (t[(std::size_t) i + 1] - t[(std::size_t) i]);
  1677. };
  1678. if (evolving)
  1679. {
  1680. const auto a = read (*frameA);
  1681. return a + frameMix * (read (*frameB) - a);
  1682. }
  1683. return read (wavetables);
  1684. }
  1685. }
  1686. return 0.0f;
  1687. }
  1688. // band-limited wavetables of the spectrum (IFFT per level; level j holds harmonics ≤ 1024 >> j)
  1689. static constexpr int wavetableSize = 2048, wavetableLevels = 10;
  1690. using Tables = std::array<std::array<float, wavetableSize + 1>, wavetableLevels>;
  1691. Tables wavetables {};
  1692. // evolving spectrum: `count` snapshots at t_f = span·(f/(count − 1))², harmonic h scaled by 10^(−3t/decay_h)
  1693. struct Frames
  1694. {
  1695. int count = 0;
  1696. double span = 1.0;
  1697. std::vector<Tables> tables;
  1698. };
  1699. static constexpr int frameCount = 8;
  1700. std::atomic<Frames*> incomingFrames { nullptr }, retiredFrames { nullptr };
  1701. Frames* activeFrames = nullptr; // audio thread only
  1702. bool evolving = false;
  1703. const Tables* frameA = nullptr;
  1704. const Tables* frameB = nullptr;
  1705. float frameMix = 0.0f;
  1706. // configure() side: what the last frames were built from
  1707. std::array<float, SynthSettings::spectrumSize> framedSpectrum {}, framedPhase {}, framedDecay {}, framedTarget {};
  1708. static void fillTables (Tables& tables, const std::array<float, SynthSettings::spectrumSize>& amplitude,
  1709. const std::array<float, SynthSettings::spectrumSize>& phase, std::vector<std::complex<double>>& bins)
  1710. {
  1711. for (int level = 0; level < wavetableLevels; ++level)
  1712. {
  1713. std::fill (bins.begin(), bins.end(), std::complex<double> {});
  1714. const auto top = std::min (SynthSettings::spectrumSize, 1024 >> level);
  1715. for (int h = 1; h <= top; ++h)
  1716. {
  1717. // a·sin(2π(h·t + φ)) = Im: coefficient −i·a/2·e^(i2πφ) at +h and its conjugate at −h
  1718. const auto a = (double) amplitude[(std::size_t) h - 1] * (2.0 / 3.141592653589793); // 1/n saw = LYNX's ±1 saw
  1719. const auto c = std::polar (a / 2.0, twoPi * phase[(std::size_t) h - 1] - twoPi / 4.0);
  1720. bins[(std::size_t) h] = c;
  1721. bins[(std::size_t) (wavetableSize - h)] = std::conj (c);
  1722. }
  1723. fftInPlace (bins, true);
  1724. auto& t = tables[(std::size_t) level];
  1725. for (int i = 0; i < wavetableSize; ++i)
  1726. t[(std::size_t) i] = (float) bins[(std::size_t) i].real();
  1727. t[(std::size_t) wavetableSize] = t[0];
  1728. }
  1729. }
  1730. // called from configure() (off the audio thread): builds the frames when the evolving spectrum changes
  1731. void updateFrames (const SynthSettings& s)
  1732. {
  1733. delete retiredFrames.exchange (nullptr);
  1734. const auto spectral = std::any_of (s.osc.begin(), s.osc.end(), [] (const SynthOscillator& o) { return o.wave == Waveform::spectral; });
  1735. const auto evolving = spectral && std::any_of (s.spectrumDecay.begin(), s.spectrumDecay.end(), [] (float t) { return t > 0.0f; });
  1736. const auto wasEvolving = std::any_of (framedDecay.begin(), framedDecay.end(), [] (float t) { return t > 0.0f; });
  1737. if (! evolving && ! wasEvolving)
  1738. return;
  1739. if (evolving && framedSpectrum == s.spectrum && framedPhase == s.spectrumPhase && framedDecay == s.spectrumDecay
  1740. && framedTarget == s.spectrumTarget)
  1741. return;
  1742. framedTarget = s.spectrumTarget;
  1743. framedSpectrum = s.spectrum;
  1744. framedPhase = s.spectrumPhase;
  1745. framedDecay = evolving ? s.spectrumDecay : std::array<float, SynthSettings::spectrumSize> {};
  1746. auto* frames = new Frames; // count 0 = back to the static spectrum
  1747. if (evolving)
  1748. {
  1749. frames->count = frameCount;
  1750. frames->span = std::min (60.0, (double) *std::max_element (s.spectrumDecay.begin(), s.spectrumDecay.end()));
  1751. frames->tables.resize ((std::size_t) frameCount);
  1752. std::vector<std::complex<double>> bins ((std::size_t) wavetableSize);
  1753. for (int f = 0; f < frameCount; ++f)
  1754. {
  1755. const auto t = frames->span * std::pow ((double) f / (frameCount - 1), 2.0);
  1756. auto amplitude = s.spectrum;
  1757. for (std::size_t h = 0; h < amplitude.size(); ++h)
  1758. if (s.spectrumDecay[h] > 0.0f)
  1759. amplitude[h] = s.spectrumTarget[h]
  1760. + (amplitude[h] - s.spectrumTarget[h]) * (float) std::pow (10.0, -3.0 * t / s.spectrumDecay[h]);
  1761. fillTables (frames->tables[(std::size_t) f], amplitude, s.spectrumPhase, bins);
  1762. }
  1763. }
  1764. delete incomingFrames.exchange (frames);
  1765. }
  1766. std::array<float, SynthSettings::spectrumSize> builtSpectrum {}, builtPhase {};
  1767. bool wavetablesBuilt = false;
  1768. std::vector<std::complex<double>> fftBins = std::vector<std::complex<double>> ((std::size_t) wavetableSize);
  1769. void buildWavetables()
  1770. {
  1771. if (wavetablesBuilt && builtSpectrum == settings.spectrum && builtPhase == settings.spectrumPhase)
  1772. return;
  1773. builtSpectrum = settings.spectrum;
  1774. builtPhase = settings.spectrumPhase;
  1775. wavetablesBuilt = true;
  1776. fillTables (wavetables, settings.spectrum, settings.spectrumPhase, fftBins); // bins allocated with the instrument
  1777. }
  1778. void updateCoefficients() noexcept
  1779. {
  1780. if (std::any_of (settings.osc.begin(), settings.osc.end(), [] (const SynthOscillator& o) { return o.wave == Waveform::spectral; }))
  1781. buildWavetables(); // only when the spectrum changes
  1782. attackStep = (float) (1.0 / (std::max (0.0005, (double) settings.attack) * sampleRate));
  1783. decayCoeff = decayCoefficient (std::max (0.001, (double) settings.decay), sampleRate);
  1784. releaseCoeff = decayCoefficient (std::max (0.005, (double) settings.release), sampleRate);
  1785. for (std::size_t o = 0; o < 3; ++o)
  1786. {
  1787. const auto& osc = settings.osc[o];
  1788. ratios[o] = std::pow (2.0, osc.octave + (osc.semitones * 100.0 + osc.detune) / 1200.0);
  1789. const auto p = std::clamp (osc.pan, -1.0f, 1.0f);
  1790. oscPanL[o] = p > 0.0f ? 1.0f - p : 1.0f;
  1791. oscPanR[o] = p < 0.0f ? 1.0f + p : 1.0f;
  1792. }
  1793. stereoOscillators = std::any_of (settings.osc.begin(), settings.osc.end(), [] (const SynthOscillator& o) { return o.pan != 0.0f; });
  1794. osc3Modulates = settings.am || settings.fm > 0.0f;
  1795. fmDecayCoeff = settings.fmDecay > 0.0f ? decayCoefficient (std::max (0.001, (double) settings.fmDecay), sampleRate) : 1.0f;
  1796. sharedFilter.set (settings.cutoff, settings.resonance, sampleRate, settings.filterType, settings.ladder);
  1797. modEnv[0] = ModCoefficients::make (settings.filterEnv, sampleRate);
  1798. modEnv[1] = ModCoefficients::make (settings.pitchEnv, sampleRate);
  1799. auto anyLfo = false;
  1800. for (std::size_t i = 0; i < lfoTargets; ++i)
  1801. {
  1802. lfos[i] = LfoCoefficients::make (settings.lfo[i], sampleRate, bpm.load());
  1803. anyLfo = anyLfo || lfos[i].active;
  1804. }
  1805. filterModulated = modEnv[0].active || lfos[lfoCutoff].active || settings.keyTrack != 0.0f;
  1806. modulated = modEnv[0].active || modEnv[1].active || anyLfo || settings.keyTrack != 0.0f || settings.sweep > 0.0f
  1807. || settings.vibratoCents > 0.0f;
  1808. sweepCoeff = std::exp (-16.0 / (std::max (0.0005, (double) settings.sweepTime) * sampleRate)); // per 16-sample tick
  1809. useBands = settings.bandGain != std::array<float, 3> { 1.0f, 1.0f, 1.0f };
  1810. toneCoeff[0] = (float) std::min (1.0, 0.025 * 44100.0 / sampleRate); // ≈ 178 Hz (REA_rodada18 §11)
  1811. toneCoeff[1] = (float) std::min (1.0, 0.155 * 44100.0 / sampleRate); // ≈ 1.18 kHz
  1812. }
  1813. double sampleRate = 44100.0;
  1814. SettingsMailbox<SynthSettings> mailbox;
  1815. SynthSettings settings;
  1816. // automated knobs (issue #152): 0…1 or NaN (not automated); the Song values configure last saw (UI thread)
  1817. std::array<std::atomic<float>, synthparam::count> automatedKnobs; // (NaN from the constructor)
  1818. std::array<float, synthparam::count> configuredKnobs { [] {
  1819. std::array<float, synthparam::count> a {};
  1820. a.fill (std::numeric_limits<float>::quiet_NaN());
  1821. return a;
  1822. }() };
  1823. std::atomic<std::uint32_t> automatedGeneration { 0 };
  1824. std::uint32_t appliedGeneration = 0; // audio thread
  1825. float attackStep = 0.01f;
  1826. float decayCoeff = 0.999f;
  1827. float releaseCoeff = 0.999f;
  1828. SvfCoefficients sharedFilter; // without a cutoff envelope, all voices use this one
  1829. std::array<ModCoefficients, 2> modEnv {};
  1830. std::array<LfoCoefficients, lfoTargets> lfos {};
  1831. bool modulated = false, filterModulated = false;
  1832. std::array<double, 3> ratios { 1.0, 1.0, 1.0 };
  1833. std::atomic<double> bpm { 120.0 };
  1834. double lastPhaseDelta = 0.0; // pitch of the last note (where porta starts from)
  1835. double songTicks = 0.0; // song position in the block (global LFO)
  1836. std::array<float, 3> oscPanL { 1.0f, 1.0f, 1.0f }, oscPanR { 1.0f, 1.0f, 1.0f };
  1837. bool stereoOscillators = false;
  1838. bool osc3Modulates = false; // AM or FM: osc 3 is not summed
  1839. float fmDecayCoeff = 1.0f;
  1840. double sweepCoeff = 1.0;
  1841. bool useBands = false;
  1842. float toneCoeff[2] { 0.025f, 0.155f };
  1843. float nextPan = 0.0f, nextCents = 0.0f;
  1844. std::atomic<float> channelPitch { 0.0f }; // cents
  1845. double bendMul = 1.0; // the pitch wheel (round 162), audio thread
  1846. bool nextPorta = false;
  1847. Noise noise;
  1848. std::array<SynthVoice, 16> voices {};
  1849. };
  1850. // ---------------------------------------------------------------------------
  1851. // Sampler: plays the whole sample on each note (one-shot, like an FL step),
  1852. // transposed by the key (60 = original pitch), with FL's sampler interpolation (core/FlResampler.h: 24-point sinc while
  1853. // playing, 32-point when exporting, FL's defaults; REA_rodada69 §1).
  1854. // Issue #63: a note's Mod X / Y move LYNX's own sampler filter as FL's voice moves its channel filter (REA_rodada76
  1855. // §1 / §4): input X = the channel's X + (modX byte − 128) / 128, Y the same with Mod Y. LYNX's cutoff (Hz) and resonance
  1856. // go to FL's X / Y through the laws of FL's 12 dB filters (the X → frequency law FlpImport's channelFilterHz uses for
  1857. // types 1…5, the Y → Q law of FL's biquads, and the SVF's resonance = (2 − 1/Q) / 1.9 the import maps it with), get the
  1858. // note's offsets and come back. A channel at 19.5 kHz or above counts as fully open (FL's X = 1).
  1859. namespace notemod
  1860. {
  1861. constexpr double twoPi = 6.283185307179586;
  1862. inline double xOfHz (double hz) noexcept
  1863. {
  1864. if (hz >= 19500.0)
  1865. return 1.0;
  1866. return std::log (std::max (1.0e-6, (hz * twoPi / 44100.0 - 0.02) / 0.0596 + 1.0)) / std::log (51.0);
  1867. }
  1868. inline double hzOfX (double x) noexcept
  1869. {
  1870. if (x >= 1.0)
  1871. return 20000.0;
  1872. return std::clamp (((std::pow (51.0, x) - 1.0) * 0.0596 + 0.02) * 44100.0 / twoPi, 20.0, 20000.0);
  1873. }
  1874. inline double yOfResonance (double res) noexcept
  1875. {
  1876. const auto q = 1.0 / std::max (0.1, 2.0 - 1.9 * std::clamp (res, 0.0, 1.0));
  1877. return q <= 0.1 ? 0.0 : std::log ((q - 0.1) / 0.4 + 1.0) / (0.625 * std::log (51.0));
  1878. }
  1879. inline double resonanceOfY (double y) noexcept
  1880. {
  1881. const auto q = y <= 0.0 ? 0.1 : (std::pow (51.0, 0.625 * std::min (y, 1.0)) - 1.0) * 0.4 + 0.1;
  1882. return std::clamp ((2.0 - 1.0 / q) / 1.9, 0.0, 1.0);
  1883. }
  1884. inline float cutoff (float hz, float offset) noexcept { return offset == 0.0f ? hz : (float) hzOfX (xOfHz (hz) + offset); }
  1885. inline float resonance (float res, float offset) noexcept
  1886. {
  1887. return offset == 0.0f ? res : (float) resonanceOfY (yOfResonance (res) + offset);
  1888. }
  1889. } // namespace notemod
  1890. struct SamplerVoice
  1891. {
  1892. bool active = false;
  1893. double position = 0.0; // read position in region order (reversed voices read the region backwards)
  1894. double rate = 1.0; // frames per output sample (> 0)
  1895. double rateBpm = 0.0; // round 190hq: the tempo `rate` was set for (a tempo-synced Resample voice follows the tempo)
  1896. bool reversed = false;
  1897. int loops = 0; // times the zone loop has wrapped (FL lets taps before the loop start wrap only then)
  1898. flrs::Kernel kernel;
  1899. bool flEnvelope = false; // FL's volume articulator drives the level (the ADSR stays at 1)
  1900. flvp::Art volumeArt;
  1901. double tickLeft = 0.0; // samples until the next sequencer tick
  1902. float flLevel = 0.0f, flStep = 0.0f; // the level ramps linearly to each tick's value over the tick (FL)
  1903. float velocity = 0.0f;
  1904. float fade = 1.0f; // < 1 when the voice was stolen (declick)
  1905. bool stolen = false;
  1906. int cutFrames = 0, cutK = 0; // > 0: the stolen voice fades out with FL's declicker (a raised cosine over cutFrames)
  1907. int cutShape = 3; // FL's release shape: 3 raised cosine, 1 the follower declick (mode 1, "no bleeding")
  1908. float cutCurve = 0.0f; // the release curve (mode 5: 5)
  1909. float cutC = 0.0f, folL = 0.0f, folR = 0.0f; // shape 1: the follower's coefficient and state per side
  1910. // an audio clip's start declick (round 189i, FL's declicker attack, FUN_00978250): atkShape 2 removes the first frame's
  1911. // step (out = x - x0 * table), 3 a raised-cosine fade in; over atkFrames frames, atkCurve = FL's curve (mode 5)
  1912. int atkFrames = 0, atkK = 0, atkShape = 0;
  1913. float atkCurve = 0.0f, atkX0L = 0.0f, atkX0R = 0.0f;
  1914. bool clipEndHard = false; // the clip's end is a sharp cut (FL: Disabled, a manual side, a seamless join, a fade out)
  1915. int age = 0;
  1916. int key = 60;
  1917. double noteSemitones = 0.0; // its note's pitch at the start (semitones from the sample's own; round 190pi: a chord slide)
  1918. // the key a slide note's key counts from (issue #353): C5 for a note that transposes the sample (a slide to key K
  1919. // goes to K − 60), the note's own key for a slice (its key picks the slice, which plays at the sample's pitch: FL's
  1920. // Fruity Slicer bends it by the slide's interval, K − key, as Slicex does)
  1921. int slideFromKey = 60;
  1922. std::uint32_t noteId = 0; // the note that started it (round 190ej): only that note's end releases it
  1923. float env = 1.0f; // envelope
  1924. float envStep = 0.0f; // attack step (> 0) or release step (< 0)
  1925. // FL Studio Mobile's pad envelope (core/FlmPad.h, round 190bs): `env` moves towards padTarget by padRate each sample
  1926. bool padEnv = false;
  1927. float padTarget = 0.0f, padRate = 1.0f;
  1928. int padCount = 0, padLength = 0; // samples played, and the count at which the release starts (0 = never)
  1929. int padDelay = 0; // samples of silence before the sample starts (a negative Sample Start)
  1930. int stage = 1; // 0 attack, 1 decay, 2 sustain, 3 release
  1931. double first = 0.0, last = 0.0; // played region: first and last frame (inclusive)
  1932. double regionFirst = 0.0, regionLast = 0.0; // the whole region, before the start offset and slicing (round 190w: the locator)
  1933. float clipElapsed = 0.0f, clipRemaining = 0.0f, fadeIn = 0.0f, fadeOut = 0.0f; // clip fades
  1934. std::uint8_t fadeShape = 0; // bit 0 / 1: the fade-in / fade-out is on the S curve (else straight)
  1935. // the clip's envelope (round 190gi): its index in the block's table (−1 = none), the clip tick of the next sample,
  1936. // and the gain / pan gains ramping over 16-sample steps
  1937. std::int32_t envIndex = -1;
  1938. double envTick = 0.0;
  1939. float envGain = 1.0f, envGainStep = 0.0f, envL = 1.0f, envR = 1.0f, envLStep = 0.0f, envRStep = 0.0f;
  1940. int envLeft = 0;
  1941. bool envStarted = false;
  1942. float fadeInTension = 0.0f, fadeOutTension = 0.0f; // FL's raw fade tensions
  1943. float panL = 1.0f, panR = 1.0f;
  1944. double glideRatio = 1.0;
  1945. int glideLeft = 0;
  1946. // FL's stepped slide note (round 190jv, core/HostSlide.h Steps): the speed (or a shifted voice's transposition) times
  1947. // stepRatio at the start of the render call where stepDue reaches 0; the rack starts those calls on the ticks
  1948. double stepRatio = 1.0, stepDue = 0.0, stepEvery = 0.0;
  1949. int stepsLeft = 0;
  1950. float lowL = 0.0f, bandL = 0.0f, lowR = 0.0f, bandR = 0.0f; // channel filter
  1951. std::array<ModState, 2> mod {}; // cutoff and pitch envelopes
  1952. std::array<LfoState, lfoTargets> lfo {};
  1953. float lfoGain = 1.0f, lfoGainStep = 0.0f;
  1954. float basePan = 0.0f;
  1955. float cents = 0.0f; // the note's fine pitch (a VFX may move it while it sounds)
  1956. // the channel's pitch it started with (knob + fine tune + main pitch, cents; NaN = doesn't follow) and how far a
  1957. // live knob or main pitch move has taken it since (round 167a)
  1958. float liveRef = std::numeric_limits<float>::quiet_NaN(), liveApplied = 0.0f;
  1959. const SampleData* data = nullptr; // this voice's sample (the chosen zone, in multi-sample)
  1960. float zoneGain = 1.0f;
  1961. double loopStart = 0.0, loopEnd = 0.0; // loopEnd > loopStart: the voice jumps back to the loop start
  1962. bool loopWhileHeld = false;
  1963. SvfCoefficients filter; // this voice's (with a cutoff envelope, or the note's own Mod X / Y)
  1964. // issue #63: the note's Mod X / Y on LYNX's own sampler, as FL's voice takes them (REA_rodada76 §1): offsets of the
  1965. // channel filter's X / Y, (b − 128) / 128 = modX · 2 − 1 (0 = the note leaves the channel filter as it is)
  1966. float noteCut = 0.0f, noteRes = 0.0f;
  1967. float noteFc = -1.0f, noteQ = -1.0f; int noteType = -1; // the channel values `filter` was last set from
  1968. double pitchMul = 1.0;
  1969. int controlCountdown = 0;
  1970. // FL's native sampler voice (REA_rodada76): the channel's articulators and filter (flvp), the note's initial
  1971. // volume and pan, the stereo gains ramping between ticks, the fast LP's running coefficient, the song tick index
  1972. bool flVoice = false;
  1973. flvp::Proc flProc;
  1974. float initVol = 1.0f, notePan = 0.0f;
  1975. float gL = 0.0f, gR = 0.0f, sL = 0.0f, sR = 0.0f;
  1976. float fcRun = 0.0f, fcSlope = 0.0f;
  1977. std::int64_t tickIndex = 0;
  1978. double nextGap = 0.0; // samples from this tick to the next one on the song's grid
  1979. int endFade = -1; // ≥ 0: past the sample's end, the last frame fading out (FL's 10 ms end fade)
  1980. bool cutAtEnd = false; // Fruity Slicer: no end fade, the voice ends with its slice
  1981. bool endByDeclicker = false; // that fade is the declicking mode's release (modes 1–5, round 167k)
  1982. int offFade = -1; // ≥ 0: a looping voice fading out after its note-off (the same table)
  1983. float holdL = 0.0f, holdR = 0.0f; // the last frame read
  1984. };
  1985. // FL's note velocity → initial volume (FLEngine FUN_00d29aa0, REA_rodada76 §1): x = byte·0.01; 1 at x = 1, else
  1986. // (exp(x·ln 11) − 1)·0.1 — velocity 100 is unity, 128 ≈ 2.05
  1987. inline float flInitVolume (float velocity) noexcept
  1988. {
  1989. static const float ln11 = (float) std::log (11.0);
  1990. const auto x = (float) std::nearbyint (std::clamp (velocity, 0.0f, 1.0f) * 128.0f) * 0.01f;
  1991. if (x == 1.0f)
  1992. return 1.0f;
  1993. return (float) ((std::exp ((double) (x * ln11)) - 1.0) * (double) 0.1f);
  1994. }
  1995. class SamplerInstrument final : public Instrument
  1996. {
  1997. public:
  1998. // clipMode: Playlist audio clip (no transposition, stops on noteOff; it follows Reverse and the stretch)
  1999. SamplerInstrument (std::shared_ptr<const SampleData> s, bool clip) : sample (std::move (s)), clipMode (clip) {}
  2000. // FL's Sampler and audio clip channels are not plugins: "Reset plugins on transport" leaves their voices alone
  2001. void transportReset() noexcept override {}
  2002. // multi-sample: called before the instrument goes to the audio thread
  2003. void setZones (std::vector<LoadedZone> z)
  2004. {
  2005. zones = std::move (z);
  2006. zones.erase (std::remove_if (zones.begin(), zones.end(), [] (const LoadedZone& lz) { return lz.sample == nullptr || lz.sample->frames() < 2; }),
  2007. zones.end());
  2008. if (sample == nullptr && ! zones.empty())
  2009. sample = zones.front().sample;
  2010. }
  2011. // the zone for the key/velocity; several covering the same note take turns like FPC's "cycle" layers (REA_rodada69
  2012. // §4: among the zones covering the note, in order, the one after the last chosen, wrapping); if none covers it, the
  2013. // one with the nearest root key. The velocity index is FL's round(velocity · 128), at most 127.
  2014. const LoadedZone* zoneFor (int key, float velocity) noexcept
  2015. {
  2016. if (zones.empty())
  2017. return nullptr;
  2018. const auto vel = std::min (127, (int) std::nearbyint (std::clamp (velocity, 0.0f, 1.0f) * 128.0f));
  2019. const LoadedZone* nearest = nullptr;
  2020. int matches[16] {};
  2021. int matchCount = 0, lastAt = -1;
  2022. for (int i = 0; i < (int) zones.size(); ++i)
  2023. {
  2024. const auto& z = zones[(std::size_t) i];
  2025. if (key >= z.zone.lowKey && key <= z.zone.highKey && vel >= z.zone.lowVelocity && vel <= z.zone.highVelocity && matchCount < 16)
  2026. {
  2027. if (i == lastZone)
  2028. lastAt = matchCount;
  2029. matches[matchCount++] = i;
  2030. }
  2031. if (nearest == nullptr || std::abs (z.zone.rootKey - key) < std::abs (nearest->zone.rootKey - key))
  2032. nearest = &z;
  2033. }
  2034. if (matchCount == 0)
  2035. return nearest;
  2036. const auto pick = matchCount == 1 || lastAt + 1 >= matchCount ? 0 : lastAt + 1;
  2037. lastZone = matches[pick];
  2038. return &zones[(std::size_t) lastZone];
  2039. }
  2040. void prepare (double sr) noexcept override
  2041. {
  2042. sampleRate = sr;
  2043. preparedOffline = offlineRendering();
  2044. quality = preparedOffline ? flrs::renderQuality : flsettings::options().interpolation.load (std::memory_order_relaxed);
  2045. fadeStep = (float) (1.0 / (0.003 * sr)); // 3 ms
  2046. updateModulation();
  2047. allNotesOff();
  2048. }
  2049. // Fruity Slicer (round 180c): the sampler's voices on the slices of the sample the rack prepared
  2050. bool slicer = false;
  2051. void configure (const ChannelDef& channel, double songBpm) noexcept override
  2052. {
  2053. // a Slicer's slices, key table, PLAY TO END and voice block come from its state, not from the channel (issue
  2054. // #160): every configure takes them from it again. Before, the rack's next edit (a kept instrument is configured
  2055. // with the bare channel) emptied the slice table and every key played the sample from its start. A channel
  2056. // whose state isn't a Slicer's (tests hand a configured one) is taken as it is.
  2057. if (slicer && sample != nullptr)
  2058. if (const auto state = fslicer::parse (channel.pluginState))
  2059. {
  2060. auto def = channel;
  2061. fslicer::configureSampler (def, *state, (std::int64_t) sample->frames());
  2062. configureChannel (def, songBpm);
  2063. return;
  2064. }
  2065. configureChannel (channel, songBpm);
  2066. }
  2067. void configureChannel (const ChannelDef& channel, double songBpm) noexcept
  2068. {
  2069. const auto& s = channel.sampler;
  2070. pitch.store (std::clamp (s.pitch, -24.0f, 24.0f));
  2071. // the knobs an automation clip drives (issue #12, setParameter) keep the automated value until the song's own
  2072. // value changes (the knob turned by hand)
  2073. auto knob = [this] (int k, float natural) {
  2074. if (! (configuredKnobs[(std::size_t) k] == natural))
  2075. {
  2076. configuredKnobs[(std::size_t) k] = natural;
  2077. automatedKnob[(std::size_t) k].store (false, std::memory_order_relaxed);
  2078. }
  2079. if (! automatedKnob[(std::size_t) k].load (std::memory_order_relaxed))
  2080. storeKnob (k, natural);
  2081. };
  2082. knob (samplerparam::attack, s.attack);
  2083. knob (samplerparam::decay, s.decay);
  2084. knob (samplerparam::sustain, s.sustain);
  2085. knob (samplerparam::release, s.release);
  2086. {
  2087. const auto on = s.flmPad.size() == (std::size_t) flmpad::count;
  2088. const auto pad = [&s, on] (int k, float fallback) { return on ? std::clamp (s.flmPad[(std::size_t) k], 0.0f, 1.0f) : fallback; };
  2089. padAttack.store (pad (flmpad::attack, 0.0f));
  2090. padDecay.store (pad (flmpad::decay, 1.0f));
  2091. padSustain.store (pad (flmpad::sustain, 1.0f));
  2092. padRelease.store (pad (flmpad::release, 1.0f));
  2093. padLength.store (pad (flmpad::length, 0.0f));
  2094. padStart.store (pad (flmpad::start, 0.5f));
  2095. padHold.store (pad (flmpad::hold, 0.0f) >= 0.5f);
  2096. padOn.store (on);
  2097. }
  2098. reverse.store (s.reverse);
  2099. cutSelf.store (s.cut);
  2100. useLoops.store (s.useLoopPoints);
  2101. flVelocityLaw.store (s.flVelocityLaw);
  2102. clipNoteLegacy.store (s.clipNoteLegacy);
  2103. declickMode.store (std::clamp (s.declickMode, 0, 5));
  2104. // with "keep pitch" the sample arrives already stretched (RackState): play at normal speed; the keys then
  2105. // transpose it through each voice's pitch shifter (round 162), so its length stays
  2106. stretchBeats.store (s.keepPitch ? 0.0f : std::max (0.0f, s.stretchBeats));
  2107. warpedTempo.store (s.stretchBeats > 0.0f); // (issue #187: a warped sample follows the playing tempo)
  2108. // keep length (round 163): with "keep pitch" a transposition never changes the length — the keys of a sampler, the
  2109. // pitch knob and the fine tune of a sampler or an audio clip go through each voice's pitch shifter, stretched to
  2110. // the tempo or not
  2111. keyShift.store (s.keepPitch);
  2112. keyShiftMethod.store ((int) s.stretchMethod);
  2113. knob (samplerparam::start, s.regionStart);
  2114. knob (samplerparam::end, s.regionEnd);
  2115. startOffset.store (std::clamp (s.startOffset, 0.0f, 1.0f));
  2116. porta.store (s.porta);
  2117. portaBeats.store (std::max (0.0f, s.portaBeats));
  2118. // (with the Misc tab's Levels adjustment Mod X / Mod Y offsets, round 190dz)
  2119. knob (samplerparam::cutoff, adjustedCutoff (s.cutoff, channel.misc.levels.modX));
  2120. knob (samplerparam::resonance, adjustedResonance (s.resonance, channel.misc.levels.modY));
  2121. filterType.store (std::clamp (s.filterType, 0, 3));
  2122. outGain.store (samplerGain (s.gainDb));
  2123. bpm.store (std::max (1.0, songBpm)); // before the mailbox: the synced LFO reads it when updating
  2124. {
  2125. Modulation m { { s.filterEnv, s.pitchEnv }, s.lfo };
  2126. if (s.flChannel.size() == 89 || s.flChannel.size() == 90)
  2127. {
  2128. // FL's channel articulators and filter in the plugins' 364-byte snapshot layout (REA_rodada76 §4)
  2129. std::array<std::uint8_t, flvp::snapshotSize> snap {};
  2130. std::memcpy (snap.data(), s.flChannel.data(), 85 * 4);
  2131. std::memcpy (snap.data() + 0x15c, &s.flChannel[85], 4);
  2132. std::memcpy (snap.data() + 0x160, &s.flChannel[86], 4);
  2133. std::memcpy (snap.data() + 0x168, &s.flChannel[87], 4);
  2134. const auto ppq = std::clamp ((int) s.flChannel[88], 24, 3840);
  2135. m.flNative = true;
  2136. m.fl.build (snap.data(), ppq, std::max (1.0, songBpm));
  2137. m.ticksPerSecond = (double) ppq * std::max (1.0, songBpm) / 60.0;
  2138. }
  2139. else if (s.flVolumeEnvelope.size() == 18)
  2140. {
  2141. const auto ppq = std::clamp ((int) s.flVolumeEnvelope[17], 24, 3840);
  2142. m.flVolume = true;
  2143. m.volume.build (s.flVolumeEnvelope.data(), ppq, std::max (1.0, songBpm));
  2144. m.ticksPerSecond = (double) ppq * std::max (1.0, songBpm) / 60.0;
  2145. }
  2146. envelopeMailbox.write (m);
  2147. }
  2148. SliceTable table;
  2149. table.count = (int) std::min<std::size_t> (s.slices.size(), table.starts.size());
  2150. for (int i = 0; i < table.count; ++i)
  2151. table.starts[(std::size_t) i] = std::clamp (s.slices[(std::size_t) i], 0.0f, 1.0f);
  2152. table.firstKey = s.sliceFirstKey;
  2153. table.keyed = s.sliceKeys.size() == table.keys.size();
  2154. for (std::size_t k = 0; k < table.keys.size(); ++k)
  2155. table.keys[k] = (std::int16_t) (table.keyed ? std::clamp (s.sliceKeys[k], -1, 32767) : -1);
  2156. table.toEnd = s.slicesToEnd;
  2157. table.cutAtEnd = s.slicesCutAtEnd;
  2158. sliceMailbox.write (table);
  2159. bpm.store (std::max (1.0, songBpm));
  2160. }
  2161. // Sample frames read per output sample (before note tuning). With
  2162. // stretch, the whole sample lasts `stretchBeats` at the current tempo (resampling, like FL's
  2163. // "resample" mode: the pitch follows).
  2164. double baseRate (const SampleData& data) const noexcept
  2165. {
  2166. const auto beats = stretchBeats.load();
  2167. if (beats > 0.0f)
  2168. return (double) data.frames() / ((double) beats * 60.0 / bpm.load() * sampleRate);
  2169. return data.sampleRate * (1.0 / sampleRate);
  2170. }
  2171. void noteOn (int key, float velocity) noexcept override { noteOnAt (key, velocity, 0.0); }
  2172. void noteOnAt (int key, float velocity, double startSeconds) noexcept override
  2173. {
  2174. const auto noteGain = std::exchange (nextGain, 1.0f);
  2175. // this note's clip fades and flags, taken now so a note that does not sound leaves none to the next one
  2176. const auto clipFades = std::exchange (nextClip, {});
  2177. const auto clipShape = std::exchange (nextClipShape, (std::uint16_t) 0);
  2178. const auto clipEnvelope = std::exchange (nextClipEnvelope, -1);
  2179. const auto clipPitch = clipMode ? (double) std::clamp (std::exchange (nextClipPitch, 0.0f), -48.0f, 48.0f) : 0.0; // (round 190hr: Live's ±48 st Transpose; round gaps190kf: the shifter reaches it)
  2180. // FL 2026's clip stretch (round 167l, FL render of a 2 s 440 Hz ramp: ×2 lasts 4 s at 220 Hz in Resample, at
  2181. // 440 Hz in the stretch modes; ×0.5 lasts 1 s): the clip reads its file `stretch` times slower
  2182. const auto clipStretch = clipMode ? (double) std::clamp (std::exchange (nextClipStretch, 1.0f), 0.01f, 100.0f) : 1.0;
  2183. const auto* zone = clipMode && key >= audioClipKeyBase ? nullptr : zoneFor (key, velocity);
  2184. const auto* data = zone != nullptr ? zone->sample.get() : sample.get();
  2185. // Round 190lq (issue #204): a NOTE of an audio clip channel (a step, a Piano roll note, a key played on it; keys below
  2186. // audioClipKeyBase) plays as a Sampler note of the channel: FL 2026's /R renders of the same notes on an audio clip
  2187. // channel and on a Sampler of the same file are bit-identical (round 190lq: the whole sample whatever the note's
  2188. // length, overlapping notes layer, the key transposes it from the root note — A5 740 Hz for 0.6 s, C4 220 Hz for
  2189. // 2 s — and FL's velocity and channel laws: velocity 50 / 100 / 128 = 0.023 / 0.097 / 0.200 for a 0.25 sine).
  2190. // Playlist / session clips (their own keys) and the notes of older LYNX projects (SamplerSettings::
  2191. // clipNoteLegacy: the clip's own pitch, cut at the note's end) keep the clip voice.
  2192. const auto asClip = clipMode && (key >= audioClipKeyBase || clipNoteLegacy.load (std::memory_order_relaxed));
  2193. if (envelopeMailbox.read (modulation))
  2194. updateModulation();
  2195. if (data == nullptr || data->frames() < 2)
  2196. return;
  2197. sliceMailbox.read (slices);
  2198. // audio clips too (the clip menu's Reverse); a reversed clip (FL 2026's clip reverse, key 9) flips it again
  2199. const auto backwards = reverse.load() != (asClip && (clipShape & 4) != 0);
  2200. const auto total = (double) (data->frames() - 1);
  2201. // sample region (the start acts as "start offset"); audio clips use the whole file. `last` is the region's
  2202. // last frame: FL plays until the read position passes it, interpolating with that frame repeated.
  2203. auto knobStart = (double) std::min (regionStart.load(), regionEnd.load()), knobEnd = (double) regionEnd.load();
  2204. if (data->cropped) // FL's precomputed effects cut the region out (core/SamplePrecompute.h): the knobs map into it
  2205. {
  2206. const auto span = std::max (1.0e-9, data->cropTo - data->cropFrom);
  2207. knobStart = std::clamp ((knobStart - data->cropFrom) / span, 0.0, 1.0);
  2208. knobEnd = std::clamp ((knobEnd - data->cropFrom) / span, 0.0, 1.0);
  2209. if (knobEnd >= 1.0 - 1.0e-6)
  2210. knobEnd = 1.0;
  2211. }
  2212. auto first = asClip ? 0.0 : std::floor (total * knobStart);
  2213. auto last = asClip ? total : std::max (first + 1.0, std::floor (total * knobEnd));
  2214. // (the locator counts over the whole region, from before the start offset and across slices; round 190w)
  2215. const auto regionFirst = first, regionLast = last;
  2216. if (const auto offset = (double) startOffset.load (std::memory_order_relaxed); ! asClip && offset > 0.0)
  2217. first += offset * (last - first + 1.0); // FL: a fraction of the region's frames (not floored, FL render §4)
  2218. auto sliced = false;
  2219. // sliced sample: each key from C5 up plays one slice, at the original pitch; Fruity Slicer: the slice FL's key
  2220. // table gives the key (issue #160)
  2221. if (! asClip && slices.count > 0)
  2222. {
  2223. const auto index = ! slices.keyed ? key - slices.firstKey
  2224. : key >= 0 && key < (int) slices.keys.size() ? (int) slices.keys[(std::size_t) key]
  2225. : -1;
  2226. if (index < 0 || index >= slices.count)
  2227. return;
  2228. // the starts are fractions of the sample's frame count (p / frames, as every slicer stores them): the
  2229. // nearest frame, as a float a hair under p / frames made every Slicex slice start one frame early (round
  2230. // 170i2, REA_rodada170i §9). Scaling by the last frame's index (frames − 1) instead started every slice in
  2231. // the sample's second half one frame early: notes "1 frame late" against FL from the middle slice on
  2232. // (round 180c's note-timing, fixed in round 188g)
  2233. const auto frames = (double) data->frames();
  2234. first = std::min (total, std::round (frames * slices.starts[(std::size_t) index]));
  2235. last = index + 1 < slices.count && ! slices.toEnd ? std::max (first, std::round (frames * slices.starts[(std::size_t) index + 1]) - 1.0) : total;
  2236. sliced = true;
  2237. }
  2238. const auto base = baseRate (*data) / clipStretch;
  2239. auto startFrame = first + std::max (0.0, startSeconds * sampleRate * base);
  2240. // a resampled (pitched) clip reads its file faster or slower: a start inside it moves with that speed (the
  2241. // Playlist shows the file at that speed too, clipops::framesPerTick)
  2242. if (asClip && ! keyShift.load (std::memory_order_relaxed))
  2243. if (const auto cents = (double) pitch.load() * 100.0 + nextCents; cents != 0.0)
  2244. startFrame = first + std::max (0.0, startSeconds * sampleRate * flrs::speedFor ((float) cents, base));
  2245. if (asClip) // FL starts an audio clip on a whole source frame (round 110 §1: ceil or round fit, floor is 1 late)
  2246. startFrame = std::round (startFrame);
  2247. if (startFrame >= last + 1.0)
  2248. return;
  2249. if (! asClip && cutSelf.load())
  2250. for (auto& v : voices)
  2251. if (v.active)
  2252. startCut (v, true); // "cut itself": the previous note fades out quickly
  2253. SamplerVoice* target = nullptr;
  2254. for (auto& v : voices)
  2255. if (! v.active)
  2256. {
  2257. target = &v;
  2258. break;
  2259. }
  2260. if (target == nullptr)
  2261. {
  2262. // No free voice: steal the oldest.
  2263. target = &voices[0];
  2264. for (auto& v : voices)
  2265. if (v.age > target->age)
  2266. target = &v;
  2267. }
  2268. // with stretch in FL's Resample mode the note still transposes: pitch and length change together, like tape
  2269. // (FL's manual: "playing a chord plays each note at a different speed"; round 162, issue #9 — LYNX played every
  2270. // key at the sample's own pitch and ignored the pitch knob and the fine tune)
  2271. const auto root = zone != nullptr ? zone->zone.rootKey : 60;
  2272. const auto tune = zone != nullptr ? (double) zone->zone.tune : 0.0;
  2273. // an audio clip has no key: its channel's pitch and fine tune transpose it (round 163 — the Clip properties' and
  2274. // Channel settings' pitch did nothing to clips); Resample changes its speed, "keep pitch" its pitch only
  2275. const auto semitones = asClip ? (double) pitch.load() + nextCents / 100.0
  2276. : (sliced ? 0 : key - root) + tune + (double) pitch.load() + nextCents / 100.0;
  2277. const auto attackSeconds = asClip ? 0.0f : attack.load();
  2278. *target = {};
  2279. target->active = true;
  2280. target->key = key;
  2281. target->noteId = startingNoteId();
  2282. // FL plays a Playlist audio clip at unity gain at the channel's default volume (78%): the channel volume
  2283. // curve is relative to that point for clips (REA_rodada89 §4.2 [EXEC]: +5.2 dB at every volume and pan)
  2284. target->velocity = asClip ? velocity * audioClipUnity()
  2285. : flVelocityLaw.load (std::memory_order_relaxed) ? flInitVolume (velocity)
  2286. : velocity;
  2287. target->data = data;
  2288. target->zoneGain = (zone != nullptr ? zone->zone.gain : 1.0f) * noteGain;
  2289. // zone loop (DirectWave): only when playing forward and with the loop inside the region
  2290. if (zone != nullptr && zone->zone.loopMode != 0 && ! backwards && zone->zone.loopEnd > zone->zone.loopStart + 16
  2291. && (double) zone->zone.loopEnd <= last && (double) zone->zone.loopStart >= first)
  2292. {
  2293. target->loopStart = (double) zone->zone.loopStart;
  2294. target->loopEnd = (double) zone->zone.loopEnd;
  2295. target->loopWhileHeld = zone->zone.loopMode == 2;
  2296. }
  2297. target->position = startFrame;
  2298. newestVoice = (int) (target - voices.data()); // (the locator follows it, round 190w)
  2299. target->first = first;
  2300. target->regionFirst = regionFirst;
  2301. target->regionLast = regionLast;
  2302. target->last = last;
  2303. target->cutAtEnd = sliced && slices.cutAtEnd;
  2304. target->clipElapsed = clipFades[0];
  2305. target->clipRemaining = clipFades[1];
  2306. target->fadeIn = clipFades[2];
  2307. target->fadeOut = clipFades[3];
  2308. target->fadeShape = (std::uint8_t) (clipShape & (3 | 8 | 16)); // (bits 3 / 4: a comp crossfade, round 177c)
  2309. if (asClip) // (a note of the channel starts as a Sampler note: no clip edges, round 190lq)
  2310. startClipEdges (*target, clipShape, clipFades);
  2311. target->fadeInTension = std::exchange (nextClipTension[0], 0.0f);
  2312. target->fadeOutTension = std::exchange (nextClipTension[1], 0.0f);
  2313. target->envIndex = asClip ? clipEnvelope : -1;
  2314. target->envTick = nextClipEnvTick;
  2315. target->envLeft = 0;
  2316. target->envStarted = false;
  2317. target->envGain = target->envL = target->envR = 1.0f;
  2318. // FL's read speed: the rate ratio at the original pitch, else exp(cents·ln2/1200)·ratio
  2319. target->rate = flrs::speedFor ((float) (semitones * 100.0), base);
  2320. target->noteSemitones = semitones;
  2321. target->slideFromKey = sliced ? key : 60;
  2322. target->reversed = backwards;
  2323. if (asClip && data != nullptr && data->frames() > 0) // the DC a clip holds after its sample (a clip resumed past it)
  2324. {
  2325. const auto end = (std::int64_t) std::min ((double) (data->frames() - 1), last);
  2326. const auto q = (std::size_t) std::clamp<std::int64_t> (backwards ? (std::int64_t) first : end, 0, (std::int64_t) data->frames() - 1);
  2327. target->holdL = data->leftData()[q];
  2328. target->holdR = data->rightData()[q];
  2329. }
  2330. // the render quality is read at each note (round 160): the export engine prepares its instruments before it
  2331. // switches to offline rendering, so a value taken in prepare() kept the playback quality in most exports
  2332. // ...and the playback quality too (round 190bx): FL's Settings › Audio › Mixer › "Resampling quality" applies to the
  2333. // notes played from then on (core/FlSettings.h; 24-point sinc unless changed)
  2334. // (an instrument prepared for an export keeps the export's quality, as before)
  2335. if (! preparedOffline)
  2336. quality = flsettings::options().interpolation.load (std::memory_order_relaxed);
  2337. target->kernel.setQuality (offlineRendering() ? flrs::renderQuality : quality);
  2338. // portamento (channel porta, inverted by the note): starts from the previous note's pitch
  2339. // (FL's glide: porta ticks + 1 ticks at 96 PPQ, none under 1 tick; round 168l, core/ChannelPoly.h)
  2340. if (! asClip && (porta.load() != nextPorta) && lastRate != 0.0 && channelpoly::portaTicks (portaBeats.load()) >= 1)
  2341. {
  2342. const auto steps = (int) (channelpoly::glideBeats (portaBeats.load()) * 60.0 / bpm.load() * sampleRate);
  2343. const auto from = std::abs (lastRate);
  2344. if (steps >= 1 && from != 0.0)
  2345. {
  2346. target->glideRatio = std::pow (target->rate / from, 1.0 / steps);
  2347. target->glideLeft = steps;
  2348. target->rate = from;
  2349. }
  2350. }
  2351. if (! asClip)
  2352. lastRate = target->glideLeft > 0 ? target->rate * std::pow (target->glideRatio, target->glideLeft) : target->rate;
  2353. target->env = attackSeconds > 0.0f ? 0.0f : 1.0f;
  2354. target->envStep = attackSeconds > 0.0f ? (float) (1.0 / (attackSeconds * sampleRate)) : 0.0f;
  2355. target->stage = attackSeconds > 0.0f ? 0 : 1;
  2356. // FL Studio Mobile's pad (core/FlmPad.h): the level starts at 0 and takes its first step before the first
  2357. // sample, as FLM's voice does; Sample Start moves the read position (seconds of the file) or delays the voice.
  2358. // An imported FLM audio clip plays the same slot voice (round 190de): its clip channel may carry the envelope too
  2359. target->padEnv = padOn.load (std::memory_order_relaxed);
  2360. target->padDelay = 0;
  2361. if (target->padEnv)
  2362. {
  2363. target->env = 0.0f;
  2364. target->envStep = 0.0f;
  2365. target->stage = 1;
  2366. target->padTarget = 5.0f;
  2367. target->padRate = flmpad::rateAt (flmpad::attackRate (padAttack.load (std::memory_order_relaxed)), sampleRate);
  2368. target->padCount = 0;
  2369. const auto fileRate = base * sampleRate; // the file's frames per second
  2370. target->padLength = (int) ((double) data->frames() * (double) padLength.load (std::memory_order_relaxed) * sampleRate / std::max (1.0, fileRate));
  2371. if (const auto seconds = flmpad::startSeconds (padStart.load (std::memory_order_relaxed)); seconds > 0.0)
  2372. target->position = backwards ? std::max (target->first, target->position - seconds * fileRate)
  2373. : std::min (target->last, target->position + seconds * fileRate);
  2374. else if (seconds < 0.0)
  2375. target->padDelay = (int) (-seconds * fileRate / std::max (1.0e-6, target->rate));
  2376. padStep (*target);
  2377. }
  2378. // FL's volume articulator: starts at its initial level and is stepped on the voice's first block (FLEngine
  2379. // FUN_00d24ae0 steps a new voice at once, then once per sequencer tick)
  2380. target->flEnvelope = ! asClip && modulation.flVolume && modulation.ticksPerSecond > 0.0;
  2381. if (target->flEnvelope)
  2382. {
  2383. target->env = 1.0f;
  2384. target->envStep = 0.0f;
  2385. target->stage = 1;
  2386. target->volumeArt.init (modulation.volume);
  2387. target->flLevel = target->volumeArt.val;
  2388. target->flStep = 0.0f;
  2389. target->tickLeft = 0.0;
  2390. }
  2391. // FL's native sampler voice (REA_rodada76): the articulators start, the first render block steps them at once,
  2392. // the following steps fall on the song's tick grid (the tick this note starts on, then round(k · spt))
  2393. target->flVoice = ! asClip && modulation.flNative && modulation.ticksPerSecond > 0.0;
  2394. if (target->flVoice)
  2395. {
  2396. target->flEnvelope = false;
  2397. target->env = 1.0f;
  2398. target->envStep = 0.0f;
  2399. target->stage = 1;
  2400. target->flProc.init (modulation.fl);
  2401. target->initVol = flInitVolume (velocity);
  2402. target->notePan = nextPan;
  2403. // FL's note → voice levels (REA_rodada76 §1): Mod X / Y byte b (128 = centre) → (b − 128) / 128
  2404. target->flProc.noteCut = nextModX * 2.0f - 1.0f;
  2405. target->flProc.noteRes = nextModY * 2.0f - 1.0f;
  2406. const auto spt = sampleRate / modulation.ticksPerSecond;
  2407. target->tickIndex = (std::int64_t) std::nearbyint (songSample / spt);
  2408. target->tickLeft = 0.0;
  2409. target->nextGap = std::max (1.0, (double) flvp::roundEven ((double) (target->tickIndex + 1) * spt) - songSample);
  2410. // the file's own loop (WAV smpl): FL plays it while the note lasts (REA_rodada76 §8)
  2411. if (zone == nullptr && ! backwards && useLoops.load (std::memory_order_relaxed) && data->loopStart >= 0 && data->loopEnd > data->loopStart + 1
  2412. && (double) data->loopStart >= first && (double) data->loopEnd <= last + 1.0)
  2413. {
  2414. target->loopStart = (double) data->loopStart;
  2415. target->loopEnd = (double) data->loopEnd;
  2416. target->loopWhileHeld = false;
  2417. }
  2418. }
  2419. if (! asClip && ! target->flVoice) // issue #63 (FL's voice above takes them as its noteCut / noteRes)
  2420. {
  2421. target->noteCut = nextModX * 2.0f - 1.0f;
  2422. target->noteRes = nextModY * 2.0f - 1.0f;
  2423. }
  2424. voicePan (asClip ? 0.0f : nextPan, target->panL, target->panR);
  2425. target->basePan = asClip ? 0.0f : nextPan;
  2426. target->cents = asClip ? 0.0f : nextCents;
  2427. target->liveRef = asClip ? std::numeric_limits<float>::quiet_NaN() : pitch.load() * 100.0f + liveRest;
  2428. if (shaper != nullptr)
  2429. shaper->voiceStarted ((int) (target - voices.data()));
  2430. for (std::size_t i = 0; i < lfoTargets; ++i)
  2431. if (lfos[i].active && ! asClip)
  2432. lfos[i].start (target->lfo[i], songTicks);
  2433. // FL 2026's clip pitch (round 167k, FL render: +3 → 522.5 Hz from 440 Hz, the 2 s clip still 2 s on a channel
  2434. // that resamples): a shift on top of the channel's own pitch, whatever the channel's mode, the length stays
  2435. // (a stretched clip on a channel that keeps the pitch: read slower, shifted back up by the stretch)
  2436. // (round gaps190kf: only a clip whose own Transpose is beyond ±24 st — Live's range, never FL's ±12 — widens the
  2437. // shifter's range; a channel pitch plus a clip pitch that add up beyond ±24 keeps the old clamp)
  2438. wideClipShift = std::abs (clipPitch) > 24.0;
  2439. if (asClip && ! keyShift.load (std::memory_order_relaxed))
  2440. startKeyShift (*target, clipPitch, base, true);
  2441. else
  2442. startKeyShift (*target, semitones + clipPitch + (clipStretch != 1.0 ? 12.0 * std::log2 (clipStretch) : 0.0), base);
  2443. wideClipShift = false;
  2444. // issue #187: a warped voice that plays without a shifter reads at the playing tempo (its pitch follows, as a
  2445. // resampled stretch does); a shifted one keeps its rate and its shifter takes the tempo
  2446. if (tempoC != 1.0 && ! shifts[(std::size_t) (target - voices.data())].on)
  2447. target->rate *= tempoC;
  2448. nextPan = nextCents = 0.0f;
  2449. nextModX = nextModY = 0.5f;
  2450. nextPorta = false;
  2451. }
  2452. // stretch keeping pitch (round 162): each voice's pitch shifter and its source cursor
  2453. static constexpr int keyShiftBlock = 128;
  2454. static constexpr int keyShiftVoices = 8; // shifters per channel (more transposed voices at once play resampled)
  2455. struct KeyShift
  2456. {
  2457. VoicePitchShifter* shifter = nullptr; // from the pool (prepareKeyShift), while the voice is shifted
  2458. bool on = false;
  2459. bool primed = false; // primed in render (a few per block: it costs ~1 ms each)
  2460. SamplerVoice ahead; // reads the source primeLength() frames ahead of the voice
  2461. double factor = 1.0, glideRatio = 1.0; // the note's transposition and its portamento / slide
  2462. // the factor's range: ±2 octaves, or (round gaps190kf) ±4 for a clip transposed beyond ±24 st, Live's ±48 Transpose
  2463. double lowest = VoicePitchShifter::minFactor, highest = VoicePitchShifter::maxFactor;
  2464. float gain = 1.0f; // round gaps190kf: the level law of a clip transposed above +24 st (1 = none)
  2465. int glideLeft = 0;
  2466. std::array<float, keyShiftBlock * 4 + 2> inL {}, inR {}; // the source read `factor` times faster
  2467. std::array<float, keyShiftBlock> outL {}, outR {};
  2468. double owed = 0.0; // input frames owed to the shifter (n / factor per block, the fraction carried)
  2469. double tempoAt = 1.0; // issue #187: the tempo ratio the shifter's alignment is set for (its priming assumes 1)
  2470. int pos = 0, count = 0;
  2471. };
  2472. // Stretch keeping pitch (round 162, issue #9): a transposed note reads the stretched sample at its own speed, so it
  2473. // lasts as long as at the root key, and its pitch shifter transposes it (FL's Stretch modes: "pitch changes keep
  2474. // the original duration", the voices of a chord stay in sync). The root key plays the stretched sample untouched.
  2475. // keepRate: only the clip's own pitch is shifted (round 167k); the voice keeps its (resampled) speed
  2476. void startKeyShift (SamplerVoice& v, double semitones, double base, bool keepRate = false) noexcept
  2477. {
  2478. const auto index = (std::size_t) (&v - voices.data());
  2479. auto& ks = shifts[index];
  2480. ks.on = false;
  2481. ks.shifter = nullptr;
  2482. // (issue #187: while the tempo can move, a warped voice that keeps its pitch takes a shifter even untransposed, so a
  2483. // tempo change never changes its pitch)
  2484. const auto followsTempo = tempoMoves && keyShift.load (std::memory_order_relaxed) && warpedTempo.load (std::memory_order_relaxed);
  2485. if ((! keyShift.load (std::memory_order_relaxed) && ! (keepRate && clipShift)) || (std::abs (semitones) < 1.0e-6 && ! followsTempo))
  2486. {
  2487. if (keyShift.load (std::memory_order_relaxed))
  2488. lastFactor = 1.0;
  2489. return;
  2490. }
  2491. // a free shifter: none, or its voice ended or plays unshifted
  2492. for (std::size_t k = 0; k < shifterPool.size() && ks.shifter == nullptr; ++k)
  2493. {
  2494. // (round 190gn: a slot the build left empty takes a fresh shifter from the rack's stock the first time it is
  2495. // reached, and keeps it: the same shifter state as one made at build time, so the same sound)
  2496. if (shifterPool[k] == nullptr && shifterStock != nullptr)
  2497. if ((shifterPool[k] = shifterStock->take (shifterKind)) != nullptr)
  2498. heldShifters.fetch_add (1, std::memory_order_relaxed);
  2499. if (shifterPool[k] == nullptr || ! shifterPool[k]->ready() || primeL.size() < (std::size_t) shifterPool[k]->maxPrimeLength())
  2500. continue;
  2501. const auto user = shifterUser[k];
  2502. if (user < 0 || (std::size_t) user == index || ! voices[(std::size_t) user].active || shifts[(std::size_t) user].shifter != shifterPool[k].get())
  2503. {
  2504. shifterUser[k] = (int) index;
  2505. ks.shifter = shifterPool[k].get();
  2506. }
  2507. }
  2508. if (ks.shifter == nullptr)
  2509. return; // every shifter busy: this voice plays resampled
  2510. ks.on = true;
  2511. ks.factor = std::exp2 (semitones / 12.0);
  2512. // (round gaps190kf: an audio clip's own Transpose beyond ±24 st takes the shifter's ±48 range; its prime buffer is
  2513. // sized for it, prepareKeyShift)
  2514. const auto wide = clipMode && wideClipShift && primeL.size() >= (std::size_t) ks.shifter->maxClipPrimeLength();
  2515. ks.lowest = wide ? VoicePitchShifter::minClipFactor : VoicePitchShifter::minFactor;
  2516. ks.highest = wide ? VoicePitchShifter::maxClipFactor : VoicePitchShifter::maxFactor;
  2517. ks.glideLeft = 0;
  2518. // portamento: the transposition glides from the previous note's (its length stays)
  2519. if (v.glideLeft > 0 && lastFactor > 0.0)
  2520. {
  2521. ks.glideRatio = std::pow (ks.factor / lastFactor, 1.0 / v.glideLeft);
  2522. ks.glideLeft = v.glideLeft;
  2523. ks.factor = lastFactor;
  2524. }
  2525. lastFactor = std::exp2 (semitones / 12.0);
  2526. if (! keepRate)
  2527. {
  2528. v.rate = base;
  2529. v.glideLeft = 0;
  2530. lastRate = base;
  2531. }
  2532. ks.ahead = v;
  2533. // (round gaps190kf: above +24 st the source is read 8–16 times as fast; the voice's 24-point sinc then spans one
  2534. // or two lobes of its lowered cutoff and dulls the sound — W3 vs Live: −4 dB at +36, −9 dB at +48. Such a clip
  2535. // reads through FL's 512-point sinc instead: few input frames a block, so it costs little)
  2536. // The stretch back by 8–16 times still loses level against Live: W3 (tone, voice, chords; Complex and Tones) +36 st
  2537. // −2.4 dB, +48 st −4.1 dB beyond the ±24 path's own difference: 0.3 dB + 2.1 dB per octave above +24, made up here
  2538. // (fitted on those renders: mean |level| vs Live 0.75 dB as ±24 played them, 0.92 with 2.1 dB / octave alone).
  2539. ks.gain = 1.0f;
  2540. if (wide && std::exp2 (semitones / 12.0) > VoicePitchShifter::maxFactor)
  2541. {
  2542. ks.ahead.kernel.setQuality (9);
  2543. ks.gain = (float) std::pow (10.0, (0.3 + 2.1 * std::log2 (std::exp2 (semitones / 12.0) / VoicePitchShifter::maxFactor)) / 20.0);
  2544. }
  2545. ks.ahead.pitchMul = 1.0;
  2546. ks.primed = false;
  2547. ks.pos = ks.count = 0;
  2548. ks.owed = 0.0;
  2549. ks.tempoAt = 1.0;
  2550. }
  2551. // the transposition the shifter applies now: the note's (gliding), the pitch envelope / LFO and the pitch wheel
  2552. double shiftFactor (const SamplerVoice& v, const KeyShift& ks) const noexcept
  2553. {
  2554. return std::clamp (ks.factor * v.pitchMul * bendMul, ks.lowest, ks.highest);
  2555. }
  2556. // Primes a new shifted voice's shifter with the start of its source (so its output has no latency). A render
  2557. // primes at most two (about 1 ms each); a voice waiting for its turn starts one block later. Exports prime all.
  2558. bool primeKeyShift (const SamplerVoice& v, KeyShift& ks, int& budget) noexcept
  2559. {
  2560. if (ks.primed)
  2561. return true;
  2562. if (budget <= 0)
  2563. return false;
  2564. --budget;
  2565. const auto factor = shiftFactor (v, ks);
  2566. const auto prime = std::min (ks.shifter->primeLength (factor), (int) primeL.size());
  2567. for (int i = 0; i < prime; ++i)
  2568. readAhead (v, ks, factor, primeL[(std::size_t) i], primeR[(std::size_t) i]);
  2569. ks.shifter->start (primeL.data(), primeR.data(), prime);
  2570. ks.primed = true;
  2571. return true;
  2572. }
  2573. // the shifter's source: the stretched sample read at the voice's (untransposed) speed, ahead of the voice
  2574. void readAhead (const SamplerVoice& v, KeyShift& ks, double factor, float& outL, float& outR) noexcept
  2575. {
  2576. auto& a = ks.ahead;
  2577. const auto lastFrame = std::min ((double) (a.data->frames() - 1), a.last);
  2578. const auto looping = a.loopEnd > a.loopStart && (! a.loopWhileHeld || v.stage < 3);
  2579. if (looping && a.position >= a.loopEnd)
  2580. {
  2581. while (a.position >= a.loopEnd)
  2582. a.position = (a.position - a.loopEnd) + a.loopStart;
  2583. ++a.loops;
  2584. }
  2585. if ((double) flrs::wholeFrames (a.position) > lastFrame || a.position < a.first)
  2586. outL = outR = 0.0f;
  2587. else
  2588. readFrame (a, a.data->leftData(), a.data->rightData(), lastFrame, looping, outL, outR, a.rate * factor);
  2589. a.position += a.rate * factor;
  2590. }
  2591. // the next frame of a shifted voice (blocks of keyShiftBlock through its shifter): the transposition, its glide,
  2592. // the pitch envelope / LFO (pitchMul) and the pitch wheel change the shift, never the speed
  2593. void readShifted (const SamplerVoice& v, KeyShift& ks, float& outL, float& outR) noexcept
  2594. {
  2595. if (ks.pos >= ks.count)
  2596. {
  2597. if (ks.glideLeft > 0)
  2598. {
  2599. const auto k = std::min (keyShiftBlock, ks.glideLeft);
  2600. ks.factor *= std::pow (ks.glideRatio, (double) k);
  2601. ks.glideLeft -= k;
  2602. }
  2603. const auto factor = shiftFactor (v, ks);
  2604. ks.owed += keyShiftBlock * tempoC / factor; // (issue #187: the source read tempoC times faster, the pitch kept)
  2605. if (tempoC != ks.tempoAt)
  2606. {
  2607. // issue #187: the shifter's output lags its input by its output latency, in output frames; at another
  2608. // input rate that lag covers another stretch of the source, so the input moves by the difference and the
  2609. // content stays on the beat (measured: without it a 120 → 90 ramp drifted 12 ms early over 8 beats)
  2610. ks.owed += (double) ks.shifter->outputLatency() * (tempoC - ks.tempoAt) / factor;
  2611. ks.tempoAt = tempoC;
  2612. }
  2613. // round gaps190kf: a clip transposed below −24 st owes more input than one buffer holds (−48 st: 16 frames an
  2614. // output frame); the block then goes through the shifter in 2, 4, 8 or 16 equal parts, each with its share of
  2615. // the input (the same ratio). Within ±24 st it is one part, as before.
  2616. const auto owedNow = std::max (0, (int) ks.owed);
  2617. const auto room = (int) ks.inL.size();
  2618. int parts = 1;
  2619. while (parts < 16 && owedNow > parts * room)
  2620. parts *= 2;
  2621. const auto frames = std::clamp (owedNow, 0, parts * room);
  2622. ks.owed -= frames;
  2623. const auto outPart = keyShiftBlock / parts;
  2624. for (int part = 0, done = 0; part < parts; ++part)
  2625. {
  2626. const auto upTo = (int) ((std::int64_t) frames * (part + 1) / parts), n = upTo - done;
  2627. done = upTo;
  2628. for (int i = 0; i < n; ++i)
  2629. readAhead (v, ks, factor, ks.inL[(std::size_t) i], ks.inR[(std::size_t) i]);
  2630. ks.shifter->process (ks.inL.data(), ks.inR.data(), n, ks.outL.data() + part * outPart, ks.outR.data() + part * outPart, outPart);
  2631. }
  2632. ks.pos = 0;
  2633. ks.count = keyShiftBlock;
  2634. }
  2635. outL = ks.outL[(std::size_t) ks.pos];
  2636. outR = ks.outR[(std::size_t) ks.pos];
  2637. if (ks.gain != 1.0f) // (round gaps190kf: a clip transposed above +24 st, see startKeyShift)
  2638. {
  2639. outL *= ks.gain;
  2640. outR *= ks.gain;
  2641. }
  2642. ++ks.pos;
  2643. }
  2644. void setClipShift (bool on) override { clipShift = on; }
  2645. void setTempoRatio (double ratio, bool moves) noexcept override
  2646. {
  2647. tempoHooked = true; // (rollup 0.1.30: round 190hq's per-voice rate step below stands down, see render)
  2648. tempoMoves = moves;
  2649. const auto c = warpedTempo.load (std::memory_order_relaxed) && std::isfinite (ratio) && ratio > 0.0 ? std::clamp (ratio, 0.05, 20.0) : 1.0;
  2650. if (c == tempoC)
  2651. return;
  2652. // the voices already sounding: an unshifted one changes its speed by the step (its shifted ones take tempoC at
  2653. // their next shifter block); the step is a block's, never a jump in the read position
  2654. for (auto& v : voices)
  2655. if (v.active && ! shifts[(std::size_t) (&v - voices.data())].on)
  2656. v.rate *= c / tempoC;
  2657. tempoC = c;
  2658. }
  2659. void setNextClipPitch (float semitones) noexcept override { nextClipPitch = std::isfinite (semitones) ? semitones : 0.0f; }
  2660. void setNextClipStretch (float stretch) noexcept override { nextClipStretch = std::isfinite (stretch) && stretch > 0.0f ? stretch : 1.0f; }
  2661. void useShifterStock (std::shared_ptr<ShifterStock> stock, int makeNow) override
  2662. {
  2663. shifterStock = std::move (stock);
  2664. shiftersNow = std::clamp (makeNow, 0, keyShiftVoices);
  2665. }
  2666. void prepareKeyShift (double sr) override
  2667. {
  2668. if (! keyShift.load() && ! clipShift)
  2669. return;
  2670. const auto method = (StretchMethod) keyShiftMethod.load();
  2671. // round 190gn (A1): with the rack's stock (and its rate), only the shifters the song can use at once are made
  2672. // now; the other slots fill from the stock on the audio thread when a voice first reaches them
  2673. if (shifterStock != nullptr && shifterStock->sampleRate() != sr)
  2674. shifterStock = nullptr;
  2675. shifterKind = ShifterStock::kindOf (method);
  2676. const auto now = shifterStock != nullptr ? shiftersNow : keyShiftVoices;
  2677. for (int k = 0; k < keyShiftVoices; ++k)
  2678. {
  2679. auto& shifter = shifterPool[(std::size_t) k];
  2680. shifter = nullptr;
  2681. if (k < now)
  2682. {
  2683. shifter = std::make_unique<VoicePitchShifter>();
  2684. shifter->allocate (sr, method);
  2685. }
  2686. }
  2687. heldShifters.store (now, std::memory_order_relaxed);
  2688. shifterUser.fill (-1);
  2689. // (round gaps190kf: an audio clip's channel primes for its Transpose's −48 st as well)
  2690. const auto prime = (std::size_t) (clipMode ? (shifterPool[0] != nullptr ? shifterPool[0]->maxClipPrimeLength() : shifterStock->maxClipPrimeLength (shifterKind))
  2691. : (shifterPool[0] != nullptr ? shifterPool[0]->maxPrimeLength() : shifterStock->maxPrimeLength (shifterKind)));
  2692. primeL.assign (prime, 0.0f);
  2693. primeR.assign (prime, 0.0f);
  2694. }
  2695. int pitchShiftersHeld() const noexcept override { return heldShifters.load (std::memory_order_relaxed); }
  2696. double longestVoiceSeconds() const noexcept override
  2697. {
  2698. // a note plays its sample once to the end at most (a released note only ends sooner); a loop, zones or an FL
  2699. // Mobile pad (its own envelope and start delay) can hold a voice longer
  2700. const auto* data = sample.get();
  2701. if (data == nullptr || ! zones.empty() || padOn.load() || data->frames() < 2 || sampleRate <= 0.0)
  2702. return std::numeric_limits<double>::infinity();
  2703. if (useLoops.load() && data->loopStart >= 0 && data->loopEnd > data->loopStart)
  2704. return std::numeric_limits<double>::infinity();
  2705. const auto base = baseRate (*data);
  2706. if (! (base > 0.0))
  2707. return std::numeric_limits<double>::infinity();
  2708. // (+ the end fade or the slowest declicking release, 200 ms)
  2709. return (double) data->frames() / (base * sampleRate) + 0.25;
  2710. }
  2711. void pitchBend (float semitones) noexcept override
  2712. {
  2713. bendMul = clipMode || ! std::isfinite (semitones) ? 1.0 : std::exp2 ((double) std::clamp (semitones, -48.0f, 48.0f) / 12.0);
  2714. }
  2715. // FL's channel PITCH knob is its pitch bend (Misc › pitch bend range): a sounding note follows it, and the main
  2716. // pitch (round 167a, REA_rodada167a §1). A stretched voice that keeps its length moves its transposition instead.
  2717. void setChannelPitchNow (float knob, float rest) noexcept override
  2718. {
  2719. liveRest = rest;
  2720. const auto now = knob + rest;
  2721. if (clipMode || ! std::isfinite (now))
  2722. return;
  2723. for (auto& v : voices)
  2724. if (v.active && ! std::isnan (v.liveRef))
  2725. if (const auto want = now - v.liveRef; want != v.liveApplied)
  2726. {
  2727. const auto ratio = std::exp2 ((double) (want - v.liveApplied) / 1200.0);
  2728. v.liveApplied = want;
  2729. if (auto& ks = shifts[(std::size_t) (&v - voices.data())]; ks.on)
  2730. ks.factor *= ratio;
  2731. else
  2732. v.rate *= ratio;
  2733. }
  2734. }
  2735. // a VFX changes a sounding note (round 164b): its fine pitch, pan or volume
  2736. void voiceProperty (int key, int prop, float value) noexcept override
  2737. {
  2738. if (! std::isfinite (value))
  2739. return;
  2740. for (auto& v : voices)
  2741. if (v.active && v.stage != 3 && v.key == key)
  2742. {
  2743. if (prop == (int) vfx::Prop::pitch)
  2744. {
  2745. const auto ratio = std::exp2 ((double) (value - v.cents) / 1200.0);
  2746. v.rate *= ratio;
  2747. v.cents = value;
  2748. }
  2749. else if (prop == (int) vfx::Prop::pan)
  2750. {
  2751. v.basePan = v.notePan = std::clamp (value, -1.0f, 1.0f);
  2752. voicePan (v.basePan, v.panL, v.panR);
  2753. }
  2754. else if (prop == (int) vfx::Prop::velocity)
  2755. {
  2756. v.velocity = flVelocityLaw.load (std::memory_order_relaxed) ? flInitVolume (value) : std::clamp (value, 0.0f, 1.0f);
  2757. if (v.flVoice) // (issue #236: FL's native voice plays InitLevels.Vol · channel volume, the host's Final.Vol)
  2758. v.initVol = flInitVolume (std::clamp (value, 0.0f, 1.0f));
  2759. }
  2760. else if (prop == (int) vfx::Prop::modX || prop == (int) vfx::Prop::modY) // issue #63: the note's filter
  2761. {
  2762. const auto offset = std::clamp (value, 0.0f, 1.0f) * 2.0f - 1.0f;
  2763. auto& to = prop == (int) vfx::Prop::modX ? (v.flVoice ? v.flProc.noteCut : v.noteCut) : (v.flVoice ? v.flProc.noteRes : v.noteRes);
  2764. if (to != offset)
  2765. {
  2766. to = offset;
  2767. v.noteType = -1; // (its own filter is set again)
  2768. }
  2769. }
  2770. }
  2771. }
  2772. void setNextNoteExpression (float pan, float cents, bool porta) noexcept override
  2773. {
  2774. nextPan = pan;
  2775. nextCents = cents;
  2776. nextPorta = porta;
  2777. }
  2778. // issue #63: the note's Mod X / Y (0..1, 0.5 = centre) reach FL's voice filter as the note's Init.FCut / FRes
  2779. void setNextNoteModulation (float modX, float modY) noexcept override
  2780. {
  2781. nextModX = std::isfinite (modX) ? std::clamp (modX, 0.0f, 1.0f) : 0.5f;
  2782. nextModY = std::isfinite (modY) ? std::clamp (modY, 0.0f, 1.0f) : 0.5f;
  2783. }
  2784. void setNextClipFades (float elapsed, float remaining, float in, float out, std::uint16_t shape, float inTension, float outTension) noexcept override
  2785. {
  2786. nextClip = { elapsed, remaining, in, out };
  2787. nextClipShape = shape;
  2788. nextClipTension = { inTension, outTension };
  2789. }
  2790. void setNextClipEnvelope (int index, double tick) noexcept override
  2791. {
  2792. nextClipEnvelope = index;
  2793. nextClipEnvTick = tick;
  2794. }
  2795. void setClipEnvelopes (const std::vector<ClipEnvelope>* table, double ticksPerSample) noexcept override
  2796. {
  2797. clipEnvelopes = table;
  2798. clipEnvTps = std::isfinite (ticksPerSample) ? std::max (0.0, ticksPerSample) : 0.0;
  2799. }
  2800. // One sample of a voice's clip envelope: every 16 samples the gain and the pan gains are read at the step's end and
  2801. // ramp there (no steps in the sound, and a cost only on voices with an envelope)
  2802. void clipEnvelopeSample (SamplerVoice& v, float& sl, float& sr, float& gain) noexcept
  2803. {
  2804. constexpr int step = 16;
  2805. if (v.envLeft <= 0)
  2806. {
  2807. const ClipEnvelope* e = clipEnvelopes != nullptr && v.envIndex < (int) clipEnvelopes->size() ? &(*clipEnvelopes)[(std::size_t) v.envIndex] : nullptr;
  2808. const auto read = [e] (double tick, float& g, float& l, float& r) {
  2809. g = e != nullptr ? clipenv::gainAt (*e, tick) : 1.0f;
  2810. l = r = 1.0f;
  2811. if (e != nullptr && ! e->pan.empty())
  2812. voicePan (clipenv::panAt (*e, tick), l, r);
  2813. };
  2814. if (! v.envStarted)
  2815. {
  2816. read (v.envTick, v.envGain, v.envL, v.envR);
  2817. v.envStarted = true;
  2818. }
  2819. float g, l, r;
  2820. read (v.envTick + step * clipEnvTps, g, l, r);
  2821. v.envGainStep = (g - v.envGain) / (float) step;
  2822. v.envLStep = (l - v.envL) / (float) step;
  2823. v.envRStep = (r - v.envR) / (float) step;
  2824. v.envLeft = step;
  2825. }
  2826. gain *= std::max (0.0f, v.envGain);
  2827. sl *= v.envL;
  2828. sr *= v.envR;
  2829. v.envGain += v.envGainStep;
  2830. v.envL += v.envLStep;
  2831. v.envR += v.envRStep;
  2832. v.envTick += clipEnvTps;
  2833. --v.envLeft;
  2834. }
  2835. bool setNextNoteGain (float gain) noexcept override
  2836. {
  2837. nextGain = gain;
  2838. return true;
  2839. }
  2840. // FL's stepped slide (round 190jv): n + 1 equal steps of the whole move `ratio`, the first at once
  2841. void startSteps (SamplerVoice& v, double ratio, const HostSlide::Steps& stepped, float samples) noexcept
  2842. {
  2843. v.stepsLeft = stepped.ticks + 1;
  2844. v.stepRatio = std::pow (ratio, 1.0 / (double) v.stepsLeft);
  2845. v.stepEvery = (double) std::max (1.0f, samples) * (double) stepped.fraction;
  2846. v.stepDue = 0.0;
  2847. anyStepping = true;
  2848. }
  2849. // at the start of a render call: the steps that are due (a shifted voice steps its transposition)
  2850. void applySteps (int n) noexcept
  2851. {
  2852. for (auto& v : voices)
  2853. if (v.stepsLeft > 0)
  2854. {
  2855. if (! v.active || v.stolen)
  2856. {
  2857. v.stepsLeft = 0;
  2858. continue;
  2859. }
  2860. const auto tolerance = 1.0e-3 * v.stepEvery + 1.0e-6;
  2861. auto& ks = shifts[(std::size_t) (&v - voices.data())];
  2862. while (v.stepsLeft > 0 && v.stepDue <= tolerance)
  2863. {
  2864. if (ks.on)
  2865. ks.factor *= v.stepRatio;
  2866. else
  2867. v.rate *= v.stepRatio;
  2868. --v.stepsLeft;
  2869. v.stepDue += v.stepEvery;
  2870. }
  2871. v.stepDue -= (double) n;
  2872. }
  2873. }
  2874. bool anyStepping = false;
  2875. bool followsSlides() const noexcept override { return true; } // (round 168l: a Mono channel's notes)
  2876. void slideTo (int key, float cents, float samples) noexcept override
  2877. {
  2878. if (clipMode)
  2879. return;
  2880. const auto slideSemitones = (key - 60) + (double) pitch.load() + cents / 100.0;
  2881. const auto steps = std::max (1, (int) samples);
  2882. const auto stepped = HostSlide::pendingSteps(); // (round 190jv: FL's steps on its ticks)
  2883. const auto shift = HostSlide::pendingShift(); // (round 190pi: a chord moves by one interval)
  2884. for (auto& v : voices)
  2885. if (v.active && ! v.stolen && v.rate != 0.0 && v.data != nullptr)
  2886. {
  2887. if (shift.on && ! shift.moves (v.key))
  2888. continue; // (a note of another colour keeps its pitch, round 190pi)
  2889. // (a slice bends by the slide's interval from its own key, issue #353; FL 2026's renders of Fruity Slicer)
  2890. const auto semitones = shift.on ? v.noteSemitones + (double) shift.cents / 100.0
  2891. : v.slideFromKey == 60 ? slideSemitones
  2892. : (key - v.slideFromKey) + (double) pitch.load() + cents / 100.0;
  2893. // a shifted voice (stretch keeping pitch) glides its transposition, not its speed (round 162)
  2894. if (auto& ks = shifts[(std::size_t) (&v - voices.data())]; ks.on)
  2895. {
  2896. if (stepped.ticks > 0)
  2897. {
  2898. ks.glideLeft = 0;
  2899. startSteps (v, std::exp2 (semitones / 12.0) / ks.factor, stepped, samples);
  2900. continue;
  2901. }
  2902. v.stepsLeft = 0;
  2903. ks.glideRatio = std::pow (std::exp2 (semitones / 12.0) / ks.factor, 1.0 / steps);
  2904. ks.glideLeft = steps;
  2905. continue;
  2906. }
  2907. // (with stretch in Resample mode the speed is relative to the stretched one)
  2908. const auto target = flrs::speedFor ((float) (semitones * 100.0), baseRate (*v.data));
  2909. if (stepped.ticks > 0)
  2910. {
  2911. v.glideLeft = 0;
  2912. startSteps (v, target / v.rate, stepped, samples);
  2913. continue;
  2914. }
  2915. v.stepsLeft = 0;
  2916. v.glideRatio = std::pow (target / v.rate, 1.0 / steps);
  2917. v.glideLeft = steps;
  2918. }
  2919. }
  2920. void noteOff (int key) noexcept override
  2921. {
  2922. if (clipMode)
  2923. {
  2924. // the clip ended: its voice fades out quickly. A clip carries its own key (audioClipKey), so the next clip
  2925. // of the same channel that already started (a crossfade) keeps playing.
  2926. // FL's per-clip edge declicker (round 189i, FUN_00d253d0 / FUN_00d24400): the channel's declicking release,
  2927. // or a sharp cut where the clip's end has no declick (Disabled, manual, a seamless join, a fade out)
  2928. // Round 190jd (live check 190iw Q6): the end of a NOTE of the channel (a step, a Piano roll note, a key played
  2929. // on it; keys below audioClipKeyBase) leaves the clip playing to its end, as FL does — FL's renders of one
  2930. // step on a 1 / 2 / 5 s clip channel play 1.010 / 2.010 / 5.010 s, the same as a Sampler without its volume
  2931. // envelope; LYNX stopped every voice at the step's end (0.13 s). Stop, cut groups and choke still end it.
  2932. // Round 190lq (issue #204): a note's end goes to the Sampler's note-off below (FL plays the notes of an audio
  2933. // clip channel as a Sampler's: without a volume envelope the sample plays on). The legacy law of a project
  2934. // saved before 0.1.30 (SamplerSettings::clipNoteLegacy) ends the note's own voice at its end, as that project
  2935. // sounded; 0.1.29 stopped EVERY voice of the channel there (allNotesOff), so of two overlapping notes the
  2936. // second one ended where the first one did.
  2937. if (key < audioClipKeyBase)
  2938. {
  2939. if (! clipNoteLegacy.load (std::memory_order_relaxed))
  2940. return noteOffAsSampler (key);
  2941. for (auto& v : voices)
  2942. if (v.active && endsVoice (v.key, v.noteId, key))
  2943. v.stolen = true; // (the fade allNotesOff gave it)
  2944. return;
  2945. }
  2946. else
  2947. for (auto& v : voices)
  2948. if (v.active && v.key == key && ! v.stolen)
  2949. {
  2950. if (v.clipEndHard)
  2951. {
  2952. v.stolen = true;
  2953. v.fade = 0.0f;
  2954. }
  2955. else
  2956. startCut (v, false);
  2957. }
  2958. return;
  2959. }
  2960. noteOffAsSampler (key);
  2961. }
  2962. void noteOffAsSampler (int key) noexcept
  2963. {
  2964. // (round 190ej: of two overlapping notes of one key, FL's sampler ends only the note's own voice [EXEC: issue #158's
  2965. // 25 renders and round 190ej's]; endsVoice() takes every voice of the key for an off without a note id)
  2966. if (shaper != nullptr)
  2967. for (auto& v : voices)
  2968. if (v.active && endsVoice (v.key, v.noteId, key))
  2969. shaper->voiceReleased ((int) (&v - voices.data()));
  2970. // the cutoff/pitch envelopes always release
  2971. for (auto& v : voices)
  2972. if (v.active && endsVoice (v.key, v.noteId, key) && v.stage < 3)
  2973. for (std::size_t e = 0; e < 2; ++e)
  2974. modEnv[e].release (v.mod[e]);
  2975. // FL's voice: the volume, cutoff, resonance and pitch articulators release (FLEngine FUN_00d241e0); without a
  2976. // volume envelope the note-off changes nothing — the sample plays on and the other envelopes hold (EXEC: FL's
  2977. // renders, REA_rodada76 §6)
  2978. for (auto& v : voices)
  2979. if (v.active && endsVoice (v.key, v.noteId, key) && v.flVoice && v.stage < 3)
  2980. {
  2981. if (modulation.fl.recs[1].enabled != 0)
  2982. for (int k = 1; k < 5; ++k)
  2983. v.flProc.arts[(std::size_t) k].release (modulation.fl.recs[(std::size_t) k]);
  2984. else if ((v.loopEnd > v.loopStart || v.cutAtEnd) && v.offFade < 0)
  2985. // a looping sample without volume envelope fades out in 10 ms (EXEC, §8). So does a Fruity Slicer
  2986. // voice: the plugins' voice processor starts its end fade at a note-off when the volume envelope
  2987. // is off (Fruity Slicer FUN_007579d0 → FUN_00757a50, as 3x Osc's REA_rodada47 §3.1) — the channel
  2988. // sampler above plays on instead (issue #129, round 190f)
  2989. v.offFade = 0;
  2990. v.stage = 3;
  2991. }
  2992. // FL's volume articulator enters its release stage from the current level
  2993. for (auto& v : voices)
  2994. if (v.active && endsVoice (v.key, v.noteId, key) && v.flEnvelope && v.stage < 3)
  2995. {
  2996. v.volumeArt.release (modulation.volume);
  2997. v.stage = 3; // released (stops "while held" loops); the ADSR level stays at 1
  2998. }
  2999. // FL Studio Mobile's pad: the note's end starts the release only on a lane that holds its notes (core/FlmPad.h)
  3000. if (padHold.load (std::memory_order_relaxed))
  3001. for (auto& v : voices)
  3002. if (v.active && endsVoice (v.key, v.noteId, key) && v.padEnv && v.stage < 3)
  3003. {
  3004. v.stage = 3;
  3005. v.padTarget = 0.0f;
  3006. v.padRate = flmpad::rateAt (flmpad::decayRate (padRelease.load (std::memory_order_relaxed)), sampleRate);
  3007. }
  3008. // with release, the released note decays; without release the sample plays in full (one-shot)
  3009. const auto seconds = release.load();
  3010. if (seconds <= 0.0f)
  3011. return;
  3012. // linear release from the current level (like FL)
  3013. for (auto& v : voices)
  3014. if (v.active && endsVoice (v.key, v.noteId, key) && v.stage < 3 && ! v.flEnvelope && ! v.flVoice && ! v.padEnv)
  3015. {
  3016. v.stage = 3;
  3017. v.envStep = -(float) (std::max (v.env, 0.001f) / (seconds * sampleRate));
  3018. }
  3019. }
  3020. void allNotesOff() noexcept override
  3021. {
  3022. for (auto& v : voices)
  3023. if (v.active)
  3024. v.stolen = true; // fade out instead of a hard cut
  3025. }
  3026. // a cut group's cut: FL's voice takes its channel's declicker release, or the 2 ms one with "Fast declick for cut
  3027. // groups" (FLEngine FUN_00d24160, REA_rodada167h §3)
  3028. void cut() noexcept override
  3029. {
  3030. if (clipMode)
  3031. {
  3032. allNotesOff();
  3033. return;
  3034. }
  3035. for (auto& v : voices)
  3036. if (v.active)
  3037. startCut (v, true);
  3038. }
  3039. void setFastDeclick (bool fast) noexcept override { fastDeclick.store (fast, std::memory_order_relaxed); }
  3040. void setPanTriangular (bool on) noexcept override { panTriangular.store (on, std::memory_order_relaxed); }
  3041. void setVoiceShaper (VoiceShaper* s) noexcept override { shaper = s; }
  3042. // FL's declickers (FUN_012c6ae0: release ms of modes 0…5, and the fast one) as a raised cosine over
  3043. // max(1, round(ms·rate/1000)) frames: g = (1 + cos(k·π/(n+1))) / 2 (FUN_00977870, shape 3)
  3044. void startCut (SamplerVoice& v, bool byCut) const noexcept
  3045. {
  3046. if (v.stolen)
  3047. return;
  3048. static constexpr double releaseMs[] = { 10.0, 10.0, 20.0, 20.0, 100.0, 200.0 };
  3049. const auto ms = byCut && fastDeclick.load (std::memory_order_relaxed) ? 2.0 : releaseMs[std::clamp (declickMode.load (std::memory_order_relaxed), 0, 5)];
  3050. const auto mode = std::clamp (declickMode.load (std::memory_order_relaxed), 0, 5);
  3051. const auto fast = byCut && fastDeclick.load (std::memory_order_relaxed);
  3052. v.stolen = true;
  3053. v.cutFrames = std::max (1, (int) std::nearbyint (ms * 0.001 * sampleRate));
  3054. v.cutK = 0;
  3055. v.cutShape = mode == 1 && ! fast ? 1 : 3;
  3056. v.cutCurve = mode == 5 && ! fast ? 5.0f : 0.0f;
  3057. v.folL = v.folR = 0.0f;
  3058. v.cutC = (float) std::min (1.0, 2.0 / sampleRate * std::exp (std::log (22050.0) / (double) v.cutFrames));
  3059. }
  3060. // shape 1 (FL's mode 1 release, FUN_00977870): a one-pole follower whose coefficient climbs from 2/rate to 1
  3061. // (22050^(k/n)) is subtracted from the voice, so it sinks to silence without a step
  3062. static void cutFollow (SamplerVoice& v, float& l, float& r) noexcept
  3063. {
  3064. if (! v.stolen || v.cutShape != 1 || v.cutFrames <= 0)
  3065. return;
  3066. v.folL += v.cutC * (l - v.folL);
  3067. v.folR += v.cutC * (r - v.folR);
  3068. l -= v.folL;
  3069. r -= v.folR;
  3070. }
  3071. // FL's declickers' attacks (FUN_012c6ae0 / FUN_00977870): modes 1, 2 the transient one (4 ms, shape 2), 3 / 4 / 5 a
  3072. // raised cosine of 20 / 100 / 200 ms (5 with curve 5); mode 0 has none.
  3073. // An audio clip's edges (round 189i, FL's PLFadeHandleMenu Declicker, FUN_00d27cf0 / FUN_00d253d0): the start takes the
  3074. // attack unless its declicker choice is Disabled or a seamless join (shape bit 5), or a fade in / manual start
  3075. // (bits 7) covers it — then only a voice that starts more than 12 frames past that fade still takes it.
  3076. // The end (bits 6 / 8, a fade out) is a sharp cut instead of the channel's declicking release.
  3077. void startClipEdges (SamplerVoice& v, std::uint16_t shape, const std::array<float, 4>& fades) const noexcept
  3078. {
  3079. v.atkFrames = v.atkK = v.atkShape = 0;
  3080. v.clipEndHard = false;
  3081. if (! clipMode)
  3082. return;
  3083. const auto mode = std::clamp (declickMode.load (std::memory_order_relaxed), 0, 5);
  3084. // FL /R renders (round 189l, the same clip Automatic / Enabled / Disabled on channels in modes 0-4): modes 0 and 1
  3085. // end the clip with a sharp cut whatever the choice; modes 2, 3 and 4 take the channel's release (20 / 20 / 100 ms)
  3086. v.clipEndHard = (shape & (64 | 256)) != 0 || fades[3] > 0.0f || mode < 2;
  3087. if ((shape & 32) != 0)
  3088. return;
  3089. const auto covered = fades[2] > 0.0f || (shape & 128) != 0;
  3090. if (covered && fades[0] <= fades[2] + 12.0f)
  3091. return;
  3092. static constexpr double attackMs[] = { 0.0, 4.0, 4.0, 20.0, 100.0, 200.0 };
  3093. if (mode == 0)
  3094. return;
  3095. v.atkFrames = std::max (1, (int) std::nearbyint (attackMs[mode] * 0.001 * sampleRate));
  3096. v.atkShape = mode <= 2 ? 2 : 3;
  3097. v.atkCurve = mode == 5 ? 5.0f : 0.0f;
  3098. }
  3099. // shape 2: out = x - x0 * T[k], T[k] = (1 + cos((k + 1) pi / (n + 1))) / 2 (x0 = the first frame); shape 3: out = x * g[k],
  3100. // g[k] = (1 + cos((n - k) pi / (n + 1))) / 2, bent by the curve as the releases are
  3101. static void clipAttack (SamplerVoice& v, float& l, float& r) noexcept
  3102. {
  3103. if (v.atkK >= v.atkFrames)
  3104. return;
  3105. const auto n = v.atkFrames;
  3106. const auto k = v.atkK++;
  3107. if (v.atkShape == 2)
  3108. {
  3109. if (k == 0)
  3110. v.atkX0L = l, v.atkX0R = r;
  3111. const auto t = (float) (0.5 * (1.0 + std::cos ((double) (k + 1) * 3.141592653589793 / (double) (n + 1))));
  3112. l -= v.atkX0L * t;
  3113. r -= v.atkX0R * t;
  3114. return;
  3115. }
  3116. auto g = 0.5 * (1.0 + std::cos ((double) (n - k) * 3.141592653589793 / (double) (n + 1)));
  3117. if (v.atkCurve > 0.0f)
  3118. g = 1.0 - (std::exp ((1.0 - g) * std::log ((double) v.atkCurve + 1.0)) - 1.0) / (double) v.atkCurve;
  3119. l *= (float) g;
  3120. r *= (float) g;
  3121. }
  3122. void stepFade (SamplerVoice& v) const noexcept
  3123. {
  3124. if (v.cutFrames > 0)
  3125. {
  3126. ++v.cutK;
  3127. const auto n = v.cutFrames;
  3128. if (v.cutK > n)
  3129. v.fade = 0.0f;
  3130. else if (v.cutShape == 1)
  3131. {
  3132. // the next frame's coefficient and window: 1, then a raised cosine over the last round(rate·0.001)
  3133. const auto k = v.cutK + 1;
  3134. v.cutC = (float) std::min (1.0, 2.0 / sampleRate * std::exp ((double) k * std::log (22050.0) / (double) n));
  3135. const auto m = std::min (n, (int) std::nearbyint (sampleRate * 0.001));
  3136. const auto from = n - m;
  3137. v.fade = k > n ? 0.0f : k > from ? (float) (0.5 * (1.0 + std::cos ((double) (k - from) * 3.141592653589793 / (double) (m + 1)))) : 1.0f;
  3138. }
  3139. else
  3140. {
  3141. auto g = 0.5 * (1.0 + std::cos ((double) v.cutK * 3.141592653589793 / (double) (n + 1)));
  3142. if (v.cutCurve > 0.0f) // FL's curved release (FUN_006774b0 / FUN_00677540): 1 − ((c+1)^(1−g) − 1) / c
  3143. g = 1.0 - (std::exp ((1.0 - g) * std::log ((double) v.cutCurve + 1.0)) - 1.0) / (double) v.cutCurve;
  3144. v.fade = (float) std::max (0.0, g);
  3145. }
  3146. }
  3147. else
  3148. v.fade -= fadeStep;
  3149. }
  3150. void render (float* left, float* right, int n, float gl, float gr) noexcept override
  3151. {
  3152. const struct Advance
  3153. {
  3154. double& at;
  3155. int n;
  3156. ~Advance() { at += n; }
  3157. } advance { songSample, n };
  3158. if (anyStepping) // (round 190jv: FL's stepped slide note)
  3159. {
  3160. applySteps (n);
  3161. anyStepping = std::any_of (voices.begin(), voices.end(), [] (const SamplerVoice& v) { return v.stepsLeft > 0; });
  3162. }
  3163. // round 190w: the newest voice's place in its region, for the channel settings' locator, after every block
  3164. const struct Publish
  3165. {
  3166. SamplerInstrument& s;
  3167. ~Publish() { s.publishPosition(); }
  3168. } publish { *this };
  3169. // round 190hq (B11, complaint #22): a channel stretched to a number of beats in Resample mode lasts those beats at
  3170. // the tempo that plays now, as FL's does under its tempo automation: its sounding voices speed up or slow down with a
  3171. // moving tempo (tempo markers, a tempo clip) instead of keeping the project tempo they started with
  3172. // (rollup 0.1.30: issue #187's tempo hook (round 190ik, setTempoRatio) moves the same voices by the same ratio, for
  3173. // Resample and pitch-kept channels alike; with both, a stretched sample sped up twice under a moving tempo. This
  3174. // step stays only for a renderer that does not call the hook: tempofollow off, tests' A/B)
  3175. if (const auto now = liveBpm; now > 0.0 && ! tempoHooked && stretchBeats.load (std::memory_order_relaxed) > 0.0f)
  3176. for (auto& v : voices)
  3177. if (v.active)
  3178. {
  3179. if (! (v.rateBpm > 0.0))
  3180. v.rateBpm = bpm.load (std::memory_order_relaxed);
  3181. if (v.rateBpm > 0.0 && now != v.rateBpm)
  3182. {
  3183. v.rate *= now / v.rateBpm;
  3184. v.rateBpm = now;
  3185. }
  3186. }
  3187. if (sample == nullptr && zones.empty())
  3188. return;
  3189. if (envelopeMailbox.read (modulation))
  3190. updateModulation();
  3191. // FL's native sampler voices: the channel's volume and pan act inside each voice (REA_rodada76 §3), so they are
  3192. // recovered from the rack's gains (panGains: gain·√2·cos/sin of (1 + pan)·π/4)
  3193. if (modulation.flNative)
  3194. {
  3195. const auto chanVol = (float) std::sqrt (((double) gl * gl + (double) gr * gr) * 0.5);
  3196. auto chanPan = chanVol > 0.0f ? (float) (std::atan2 ((double) gr, (double) gl) * (4.0 / 3.141592653589793) - 1.0) : 0.0f;
  3197. if (std::fabs (chanPan) < 1.0e-6f)
  3198. chanPan = 0.0f;
  3199. const flvp::X87Extended precision;
  3200. auto primeBudget = offlineRendering() ? keyShiftVoices : 2;
  3201. for (auto& v : voices)
  3202. if (v.active && v.data != nullptr && v.flVoice)
  3203. if (auto& ks = shifts[(std::size_t) (&v - voices.data())]; ! ks.on || primeKeyShift (v, ks, primeBudget))
  3204. renderFl (v, left, right, n, chanVol, chanPan);
  3205. }
  3206. // the project's triangular panning law (round 167k: FL's render of FPC pads and the decompiled audio clip mixer
  3207. // FUN_00d0cc10 → FUN_006a3a00 follow it, 3x Osc keeps its own circular pan): the louder side keeps the centre
  3208. // level, the other falls linearly. The rack's gains are circular (gain·√2·cos/sin of (1 + pan)·π/4).
  3209. if (panTriangular.load (std::memory_order_relaxed) && (gl != gr))
  3210. {
  3211. const auto vol = (float) std::sqrt (((double) gl * gl + (double) gr * gr) * 0.5);
  3212. const auto pan = vol > 0.0f ? std::clamp ((float) (std::atan2 ((double) gr, (double) gl) * (4.0 / 3.141592653589793) - 1.0), -1.0f, 1.0f)
  3213. : 0.0f;
  3214. gl = pan > 0.0f ? (1.0f - pan) * vol : vol;
  3215. gr = pan < 0.0f ? (1.0f + pan) * vol : vol;
  3216. }
  3217. // the Gain knob scales the other voices with the channel's gains (FL voices apply it in renderFl)
  3218. {
  3219. const auto g = outGain.load (std::memory_order_relaxed);
  3220. gl *= g;
  3221. gr *= g;
  3222. }
  3223. // channel filter (TPT SVF, same as the synth); off when open, without resonance and without modulation
  3224. const auto fc = cutoff.load(), res = resonance.load();
  3225. const auto type = filterType.load();
  3226. const auto filterModulated = modEnv[0].active || lfos[lfoCutoff].active;
  3227. const auto filtered = fc < 19500.0f || res > 0.0f || type != 0 || filterModulated; // (the channel's own)
  3228. const auto modulated = modEnv[0].active || modEnv[1].active || anyLfo;
  3229. if (filtered && (fc != filterCutoff || res != filterResonance || type != sharedFilter.mode))
  3230. {
  3231. filterCutoff = fc;
  3232. filterResonance = res;
  3233. sharedFilter.set (fc, res, sampleRate, type);
  3234. }
  3235. const flvp::X87Extended precision; // FL's interpolators run the x87 unit at 64-bit precision
  3236. auto primeBudget = offlineRendering() ? keyShiftVoices : 2;
  3237. for (auto& v : voices)
  3238. {
  3239. if (! v.active || v.data == nullptr || v.flVoice)
  3240. continue;
  3241. if (auto& ks = shifts[(std::size_t) (&v - voices.data())]; ks.on && ! primeKeyShift (v, ks, primeBudget))
  3242. continue; // (its shifter primes in the next block)
  3243. const auto* l = v.data->leftData();
  3244. const auto* r = v.data->rightData();
  3245. const auto lastFrame = std::min ((double) (v.data->frames() - 1), v.last);
  3246. // the note's own Mod X / Y: its own filter, from the channel's moved by the note (issue #63)
  3247. const auto ownFilter = v.noteCut != 0.0f || v.noteRes != 0.0f;
  3248. const auto voiceFc = ownFilter ? notemod::cutoff (fc, v.noteCut) : fc;
  3249. const auto voiceRes = ownFilter ? notemod::resonance (res, v.noteRes) : res;
  3250. const auto voiceFiltered = filtered || ownFilter;
  3251. if (ownFilter && ! filterModulated && (v.noteFc != fc || v.noteQ != res || v.noteType != type))
  3252. {
  3253. v.noteFc = fc, v.noteQ = res, v.noteType = type;
  3254. v.filter.set (voiceFc, voiceRes, sampleRate, type);
  3255. }
  3256. for (int i = 0; i < n; ++i)
  3257. {
  3258. // loop: jump back to its start (the "while held" mode stops looping on release)
  3259. const auto looping = v.loopEnd > v.loopStart && (! v.loopWhileHeld || v.stage < 3);
  3260. if (looping && v.position >= v.loopEnd)
  3261. {
  3262. while (v.position >= v.loopEnd)
  3263. v.position = (v.position - v.loopEnd) + v.loopStart;
  3264. ++v.loops;
  3265. }
  3266. const auto pastEnd = (double) flrs::wholeFrames (v.position) > lastFrame || v.position < v.first;
  3267. // FL holds an audio clip's last value as DC to the clip's end (its note-off): the clip does not end with
  3268. // the sample (FL renders, REA_rodada167l §1 / round 168j); other voices end with their region.
  3269. // Round qafix190kq (QA-6 of 0.1.30): a NOTE of an audio clip channel (a step, a Piano roll note; keys below
  3270. // audioClipKeyBase) has no clip end since round 190jd lets it play the whole clip — it ends with the
  3271. // sample, as FL's 1 / 2 / 5 s renders do. It held the sample's last value for ever: every hi-hat step of
  3272. // "Never Out" left its DC voice, -73 dBFS summed, and the export's tail never fell silent.
  3273. if ((pastEnd && (! clipMode || v.key < audioClipKeyBase)) || (v.stolen && v.fade <= 0.0f) || (v.env <= 0.0f && v.stage >= 1))
  3274. {
  3275. v.active = false;
  3276. break;
  3277. }
  3278. if (v.padDelay > 0) // FLM's pad before its sample starts: silence, the envelope already running
  3279. {
  3280. --v.padDelay;
  3281. padAdvance (v);
  3282. continue;
  3283. }
  3284. float shapeL = 1.0f, shapeR = 1.0f;
  3285. if (shaper != nullptr && ! shaper->voiceGains ((int) (&v - voices.data()), shapeL, shapeR))
  3286. {
  3287. v.active = false;
  3288. break;
  3289. }
  3290. if (v.flEnvelope)
  3291. {
  3292. if (v.tickLeft <= 0.0)
  3293. {
  3294. // a sequencer tick: step the articulator; the level ramps to its value over round(tick) samples
  3295. v.volumeArt.step (modulation.volume);
  3296. const auto perTick = sampleRate / modulation.ticksPerSecond;
  3297. v.flStep = (v.volumeArt.val - v.flLevel) / (float) std::max (1.0, std::nearbyint (perTick));
  3298. v.tickLeft += perTick;
  3299. }
  3300. if (v.volumeArt.state == 9 && v.flLevel <= 0.0f && v.flStep <= 0.0f)
  3301. {
  3302. v.active = false;
  3303. break;
  3304. }
  3305. }
  3306. float sl, sr;
  3307. auto& ks = shifts[(std::size_t) (&v - voices.data())];
  3308. if (pastEnd) // (clips only, above)
  3309. sl = v.holdL, sr = v.holdR;
  3310. else
  3311. {
  3312. if (ks.on)
  3313. readShifted (v, ks, sl, sr);
  3314. else
  3315. readFrame (v, l, r, lastFrame, looping, sl, sr, v.rate * v.pitchMul * bendMul);
  3316. v.holdL = sl, v.holdR = sr;
  3317. }
  3318. if (modulated)
  3319. {
  3320. for (std::size_t e = 0; e < 2; ++e)
  3321. if (modEnv[e].active)
  3322. modEnv[e].advance (v.mod[e]);
  3323. if (--v.controlCountdown <= 0) // 16-sample control tick, as in the synth
  3324. {
  3325. v.controlCountdown = 16;
  3326. auto semitones = modEnv[1].active ? modEnv[1].amount * v.mod[1].level : 0.0f;
  3327. auto octaves = modEnv[0].active ? modEnv[0].amount * v.mod[0].level : 0.0f;
  3328. if (lfos[lfoPitch].active)
  3329. semitones += lfos[lfoPitch].amount * lfos[lfoPitch].tick (v.lfo[lfoPitch], 16);
  3330. if (lfos[lfoCutoff].active)
  3331. octaves += lfos[lfoCutoff].amount * lfos[lfoCutoff].tick (v.lfo[lfoCutoff], 16);
  3332. if (lfos[lfoVolume].active)
  3333. {
  3334. const auto target = std::max (0.0f, 1.0f + lfos[lfoVolume].amount * lfos[lfoVolume].tick (v.lfo[lfoVolume], 16));
  3335. v.lfoGainStep = (target - v.lfoGain) / 16.0f;
  3336. }
  3337. if (lfos[lfoPan].active)
  3338. voicePan (v.basePan + lfos[lfoPan].amount * lfos[lfoPan].tick (v.lfo[lfoPan], 16), v.panL, v.panR);
  3339. v.pitchMul = semitones != 0.0f ? std::exp2 (semitones / 12.0) : 1.0;
  3340. if (filterModulated)
  3341. v.filter.set (voiceFc * std::exp2 (octaves), voiceRes, sampleRate, type);
  3342. }
  3343. v.lfoGain += v.lfoGainStep;
  3344. }
  3345. if (voiceFiltered)
  3346. {
  3347. const auto& f = filterModulated || ownFilter ? v.filter : sharedFilter;
  3348. sl = f.process (sl, v.lowL, v.bandL);
  3349. sr = f.process (sr, v.lowR, v.bandR);
  3350. }
  3351. clipAttack (v, sl, sr);
  3352. cutFollow (v, sl, sr);
  3353. auto gain = v.velocity * v.fade * v.env * v.lfoGain * v.zoneGain;
  3354. if (v.flEnvelope)
  3355. {
  3356. gain *= std::max (0.0f, v.flLevel);
  3357. const auto next = v.flLevel + v.flStep;
  3358. // the ramp stops at the tick's value
  3359. v.flLevel = (v.flStep > 0.0f && next > v.volumeArt.val) || (v.flStep < 0.0f && next < v.volumeArt.val) ? v.volumeArt.val : next;
  3360. v.tickLeft -= 1.0;
  3361. }
  3362. if (v.fadeIn > 0.0f || v.fadeOut > 0.0f)
  3363. {
  3364. gain *= clipFadeGainOf (v.clipElapsed, v.clipRemaining, v.fadeIn, v.fadeOut, v.fadeShape, v.fadeInTension, v.fadeOutTension);
  3365. v.clipElapsed += 1.0f;
  3366. v.clipRemaining -= 1.0f;
  3367. }
  3368. if (v.envIndex >= 0)
  3369. clipEnvelopeSample (v, sl, sr, gain);
  3370. if (shaper != nullptr)
  3371. {
  3372. left[i] += sl * gain * gl * v.panL * shapeL;
  3373. right[i] += sr * gain * gr * v.panR * shapeR;
  3374. }
  3375. else
  3376. {
  3377. left[i] += sl * gain * gl * v.panL;
  3378. right[i] += sr * gain * gr * v.panR;
  3379. }
  3380. v.position += ks.on ? v.rate * tempoC : v.rate * v.pitchMul * bendMul;
  3381. ++v.age;
  3382. if (v.glideLeft > 0)
  3383. {
  3384. v.rate *= v.glideRatio;
  3385. --v.glideLeft;
  3386. }
  3387. // envelope: 0 attack, 1 decay, 2 sustain, 3 release
  3388. if (v.padEnv)
  3389. padAdvance (v);
  3390. else if (v.stage == 0)
  3391. {
  3392. v.env += v.envStep;
  3393. if (v.env >= 1.0f)
  3394. {
  3395. v.env = 1.0f;
  3396. v.stage = 1;
  3397. }
  3398. }
  3399. else if (v.stage == 1)
  3400. {
  3401. const auto s = sustain.load (std::memory_order_relaxed);
  3402. const auto d = decay.load (std::memory_order_relaxed);
  3403. if (s >= 1.0f)
  3404. v.stage = 2;
  3405. else if (d <= 0.0f)
  3406. {
  3407. v.env = s;
  3408. v.stage = 2;
  3409. }
  3410. else
  3411. {
  3412. // the ramp goes from 1 to 0 over `decay` and stops at sustain (like FL)
  3413. v.env -= (float) (1.0 / (d * sampleRate));
  3414. if (v.env <= s)
  3415. {
  3416. v.env = s;
  3417. v.stage = 2;
  3418. }
  3419. }
  3420. }
  3421. else if (v.stage == 3)
  3422. v.env += v.envStep;
  3423. if (v.stolen)
  3424. stepFade (v);
  3425. }
  3426. }
  3427. }
  3428. // FL Studio Mobile's pad envelope (core/FlmPad.h): one step of the level; reaching the top starts the decay
  3429. void padStep (SamplerVoice& v) const noexcept
  3430. {
  3431. v.env += (v.padTarget - v.env) * v.padRate;
  3432. if (v.env > 1.0f)
  3433. {
  3434. v.env = 1.0f;
  3435. v.padTarget = padSustain.load (std::memory_order_relaxed);
  3436. v.padRate = flmpad::rateAt (flmpad::decayRate (padDecay.load (std::memory_order_relaxed)), sampleRate);
  3437. }
  3438. }
  3439. // after a sample: Length's release point, the voice's end (below −80 dB on its way to 0), the next step
  3440. void padAdvance (SamplerVoice& v) const noexcept
  3441. {
  3442. if (++v.padCount == v.padLength)
  3443. {
  3444. v.padTarget = 0.0f;
  3445. v.padRate = flmpad::rateAt (flmpad::decayRate (padRelease.load (std::memory_order_relaxed)), sampleRate);
  3446. }
  3447. if (v.env < 0.0001f && v.padTarget == 0.0f)
  3448. {
  3449. v.env = 0.0f; // (ends the voice at the next sample)
  3450. return;
  3451. }
  3452. padStep (v);
  3453. }
  3454. // One sequencer tick of FL's sampler voice (FLEngine FUN_00d24ae0 / FUN_00d24500 / FUN_00d24650, REA_rodada76
  3455. // §3–§4): the articulators step; the target gains are the pan law of (note pan + channel pan + pan articulator,
  3456. // initial volume · channel volume · volume articulator); the filter coefficients follow Final.FCut/FRes plus the
  3457. // cutoff/resonance articulators; gains and the fast LP's coefficient ramp towards their targets over round(spt)
  3458. // samples, at most 0.001·44100/fs per sample.
  3459. void flTick (SamplerVoice& v, float chanVol, float chanPan, int perTick) noexcept
  3460. {
  3461. const auto& S = modulation.fl;
  3462. auto& pr = v.flProc;
  3463. // global LFOs (flag 0x20): one phase for the whole channel, advanced on every song tick — at tick k it is
  3464. // (k + 1)·increment (EXEC: FL's render of a global volume LFO, REA_rodada76 §10)
  3465. if (S.hasGlobal)
  3466. for (auto& r : modulation.fl.recs)
  3467. if ((r.flags & 0x20) != 0)
  3468. r.globalPhase = (std::uint32_t) ((std::uint64_t) (v.tickIndex + 1) * (std::uint64_t) r.lfoInc);
  3469. pr.control (S);
  3470. const auto finalVol = v.initVol * chanVol, finalPan = v.notePan + chanPan;
  3471. float tL, tR;
  3472. if (panTriangular.load (std::memory_order_relaxed))
  3473. {
  3474. // FL's pan-law mode 1 (FLEngine FUN_006a39c0, x87): vol·sin(π/4) on the louder side, (1 ∓ pan)·that on the
  3475. // other (EXEC: FL's render with the project's pan law 2, REA_rodada76 §9); the project's law (Song::panTriangular)
  3476. const auto pan = std::min (std::max (finalPan + pr.pan, -1.0f), 1.0f);
  3477. const auto vol = finalVol * pr.vol * 0.70710677f;
  3478. using ld = long double;
  3479. if (std::signbit (pan))
  3480. tL = vol, tR = (float) (((ld) 1 + (ld) pan) * (ld) vol);
  3481. else
  3482. tR = vol, tL = (float) (((ld) 1 - (ld) pan) * (ld) vol);
  3483. }
  3484. else
  3485. flvp::panLaw (finalPan + pr.pan, finalVol * pr.vol, tL, tR);
  3486. v.pitchMul = pr.pitch != 0.0f ? std::exp2 ((double) pr.pitch / 1200.0) : 1.0;
  3487. const auto first = pr.first;
  3488. const auto cx = ((float) S.modX * 0.00390625f + pr.noteCut) + pr.cut; // + the note's Init.FCut (issue #63)
  3489. const auto cy = ((float) S.modY * 0.00390625f + pr.noteRes) + pr.res;
  3490. if (pr.kind == 0)
  3491. {
  3492. flvp::coefFast (cx, cy, pr.fc, pr.fq, S.rateRatio);
  3493. if (flvp::bitsOf (pr.fc) != 0x3f800000 || flvp::bitsOf (pr.fq) != 0)
  3494. pr.active = true;
  3495. if (! pr.active || first > 0)
  3496. v.fcRun = pr.fc, v.fcSlope = 0.0f;
  3497. else
  3498. v.fcSlope = flvp::rampStep (pr.fc, v.fcRun, perTick, S.rampLimit);
  3499. }
  3500. else if (pr.kind >= 1 && pr.kind <= 4)
  3501. flvp::coefBiquad (pr.kind, cx, cy, pr.fc, pr.fq, pr.b, S.rateRatio);
  3502. else if (pr.kind == 6)
  3503. flvp::coefSvf (cx, cy, pr.fc, pr.fq, S.rateRatio);
  3504. // the first block: with the volume articulator past its attack the gains start at their (unscaled) target,
  3505. // else they ramp up from 0
  3506. auto prevL = v.gL, prevR = v.gR;
  3507. if (first > 1)
  3508. prevL = tL, prevR = tR;
  3509. pr.first = 0;
  3510. if (pr.active && pr.kind >= 1 && pr.kind <= 4 && pr.stage2 != 0)
  3511. {
  3512. const auto g = (float) (1.0 - (double) pr.fq * (3.2 - (double) pr.fc) * 0.046875);
  3513. tL = tL * g, tR = tR * g;
  3514. }
  3515. v.sL = flvp::rampStep (tL, prevL, perTick, S.rampLimit);
  3516. v.sR = flvp::rampStep (tR, prevR, perTick, S.rampLimit);
  3517. v.gL = prevL, v.gR = prevR;
  3518. // the volume envelope has ended and the level is down: the voice is done
  3519. if (pr.arts[1].state == 9 && tL == 0.0f && tR == 0.0f && std::fabs (prevL) < 1.0e-7f && std::fabs (prevR) < 1.0e-7f)
  3520. v.active = false;
  3521. }
  3522. // FL's sampler voice over n samples: split at the song's ticks, the sample read through FL's interpolators, the
  3523. // channel filter on the stereo block, the gains ramped per sample (the channel's volume and pan are inside)
  3524. void renderFl (SamplerVoice& v, float* left, float* right, int n, float chanVol, float chanPan) noexcept
  3525. {
  3526. const auto spt = sampleRate / modulation.ticksPerSecond;
  3527. const auto perTick = (int) std::max<std::int64_t> (1, flvp::roundEven (spt));
  3528. const auto* l = v.data->leftData();
  3529. const auto* r = v.data->rightData();
  3530. const auto lastFrame = std::min ((double) (v.data->frames() - 1), v.last);
  3531. auto& pr = v.flProc;
  3532. for (int pos = 0; pos < n && v.active;)
  3533. {
  3534. if (v.tickLeft <= 0.0)
  3535. {
  3536. flTick (v, chanVol, chanPan, perTick);
  3537. v.tickLeft += v.nextGap;
  3538. ++v.tickIndex;
  3539. v.nextGap = (double) (flvp::roundEven ((double) (v.tickIndex + 1) * spt) - flvp::roundEven ((double) v.tickIndex * spt));
  3540. if (! v.active)
  3541. break;
  3542. }
  3543. auto seg = std::min ({ n - pos, (int) std::ceil (v.tickLeft), flBlock });
  3544. // read the segment (loop wrap, region end, declick of stolen voices, clip fades)
  3545. auto ended = false;
  3546. int m = 0;
  3547. for (; m < seg; ++m)
  3548. {
  3549. const auto looping = v.loopEnd > v.loopStart && (! v.loopWhileHeld || v.stage < 3);
  3550. if (looping && v.position >= v.loopEnd)
  3551. {
  3552. while (v.position >= v.loopEnd)
  3553. v.position = (v.position - v.loopEnd) + v.loopStart;
  3554. ++v.loops;
  3555. }
  3556. if (v.stolen && v.fade <= 0.0f)
  3557. {
  3558. ended = true;
  3559. break;
  3560. }
  3561. // past the region's end FL holds the last frame and fades it out with the 441-entry end table (EXEC:
  3562. // FL's render, REA_rodada76 §6)
  3563. // With a declicking mode other than 0 that fade is the mode's release instead (FL render,
  3564. // REA_rodada167k §10: 20 / 20 / 100 / 200 ms, mode 1 the follower, mode 5 curved).
  3565. if (v.endFade < 0 && ((double) flrs::wholeFrames (v.position) > lastFrame || v.position < v.first))
  3566. {
  3567. if (v.cutAtEnd)
  3568. {
  3569. ended = true;
  3570. break;
  3571. }
  3572. v.endFade = 0;
  3573. if (! v.stolen && declickMode.load (std::memory_order_relaxed) != 0)
  3574. {
  3575. startCut (v, false);
  3576. v.endByDeclicker = true;
  3577. }
  3578. }
  3579. float sl, sr, endGain = 1.0f;
  3580. if (v.endFade >= 0)
  3581. {
  3582. const auto& table = flvp::endTable();
  3583. if (! v.endByDeclicker)
  3584. {
  3585. if (v.endFade >= (int) table.size())
  3586. {
  3587. ended = true;
  3588. break;
  3589. }
  3590. endGain = table[(std::size_t) v.endFade++];
  3591. }
  3592. sl = v.holdL, sr = v.holdR;
  3593. }
  3594. else
  3595. {
  3596. if (auto& ks = shifts[(std::size_t) (&v - voices.data())]; ks.on)
  3597. readShifted (v, ks, sl, sr);
  3598. else
  3599. readFrame (v, l, r, lastFrame, looping, sl, sr, v.rate * v.pitchMul * bendMul);
  3600. v.holdL = sl, v.holdR = sr;
  3601. }
  3602. clipAttack (v, sl, sr);
  3603. cutFollow (v, sl, sr);
  3604. auto gain = v.fade * v.zoneGain * outGain.load (std::memory_order_relaxed);
  3605. if (v.fadeIn > 0.0f || v.fadeOut > 0.0f)
  3606. {
  3607. gain *= clipFadeGainOf (v.clipElapsed, v.clipRemaining, v.fadeIn, v.fadeOut, v.fadeShape, v.fadeInTension, v.fadeOutTension);
  3608. v.clipElapsed += 1.0f;
  3609. v.clipRemaining -= 1.0f;
  3610. }
  3611. if (v.envIndex >= 0)
  3612. clipEnvelopeSample (v, sl, sr, gain);
  3613. flX[(std::size_t) (2 * m)] = sl;
  3614. flX[(std::size_t) (2 * m + 1)] = sr;
  3615. if (v.offFade >= 0)
  3616. {
  3617. const auto& table = flvp::endTable();
  3618. if (v.offFade >= (int) table.size())
  3619. {
  3620. ended = true;
  3621. break;
  3622. }
  3623. endGain *= table[(std::size_t) v.offFade++];
  3624. }
  3625. flG[(std::size_t) m] = gain * endGain;
  3626. v.position += shifts[(std::size_t) (&v - voices.data())].on ? v.rate * tempoC : v.rate * v.pitchMul * bendMul;
  3627. ++v.age;
  3628. if (v.glideLeft > 0)
  3629. {
  3630. v.rate *= v.glideRatio;
  3631. --v.glideLeft;
  3632. }
  3633. if (v.stolen)
  3634. stepFade (v);
  3635. }
  3636. seg = m;
  3637. // the channel filter (FLEngine FUN_00d247a0)
  3638. const float* y = flX.data();
  3639. if (pr.active && seg > 0)
  3640. {
  3641. if (pr.kind == 0)
  3642. {
  3643. flvp::renderFast (pr.fst, pr.fq, flX.data(), flY.data(), seg, v.fcRun, v.fcSlope);
  3644. v.fcRun = v.fcRun + (float) seg * v.fcSlope;
  3645. y = flY.data();
  3646. }
  3647. else if (pr.kind >= 1 && pr.kind <= 4)
  3648. {
  3649. flvp::renderBiquad (pr.st1, pr.b, flX.data(), flY.data(), seg);
  3650. if (pr.stage2 != 0)
  3651. flvp::renderBiquad (pr.st2, pr.b, flY.data(), flY.data(), seg);
  3652. y = flY.data();
  3653. }
  3654. else if (pr.kind == 6)
  3655. {
  3656. flvp::renderSvf (pr.st1, pr.fc, pr.fq, flX.data(), flY.data(), seg);
  3657. if (pr.stage2 != 0)
  3658. flvp::renderSvf (pr.st2, pr.fc, pr.fq + (1.0f - pr.fq) * 0.25f, flY.data(), flY.data(), seg);
  3659. y = flY.data();
  3660. }
  3661. }
  3662. for (int i = 0; i < seg; ++i)
  3663. {
  3664. const auto g = flG[(std::size_t) i];
  3665. left[pos + i] += y[2 * i] * ((v.gL + (float) i * v.sL) * g);
  3666. right[pos + i] += y[2 * i + 1] * ((v.gR + (float) i * v.sR) * g);
  3667. }
  3668. v.gL = v.gL + v.sL * (float) seg;
  3669. v.gR = v.gR + v.sR * (float) seg;
  3670. v.tickLeft -= seg;
  3671. pos += seg;
  3672. if (ended)
  3673. v.active = false;
  3674. }
  3675. }
  3676. // FL's sampler read (REA_rodada69 §1): the kernel's taps around the read position, frames outside the region
  3677. // repeating its first/last frame, taps past the loop end wrapping to the loop start (and, once the voice has
  3678. // looped, taps before the loop start wrapping to its end), a reversed voice reading the region backwards
  3679. void readFrame (SamplerVoice& v, const float* l, const float* r, double lastFrame, bool looping, float& outL, float& outR, double speed) noexcept
  3680. {
  3681. v.kernel.setSpeed (speed);
  3682. const auto half = v.kernel.halfWidth;
  3683. const auto whole = flrs::wholeFrames (v.position);
  3684. const auto frac = v.position - (double) whole;
  3685. const auto first = (std::int64_t) v.first, last = (std::int64_t) lastFrame;
  3686. const auto lo = whole - half + 1, hi = whole + half;
  3687. const auto loopStart = (std::int64_t) v.loopStart, loopEnd = (std::int64_t) v.loopEnd;
  3688. // at the original rate on a whole frame FL copies the sample instead of interpolating
  3689. if (speed == 1.0 && frac == 0.0)
  3690. {
  3691. const auto q = v.reversed ? first + last - whole : whole;
  3692. outL = l[q];
  3693. outR = r[q];
  3694. return;
  3695. }
  3696. if (! v.reversed && lo >= first && hi <= last && ! (looping && hi >= loopEnd))
  3697. {
  3698. flrs::interpolate (v.kernel, l + lo, r + lo, frac, outL, outR);
  3699. return;
  3700. }
  3701. for (std::int64_t t = 0; t < 2 * half; ++t)
  3702. {
  3703. auto q = lo + t;
  3704. if (looping && loopEnd > loopStart)
  3705. {
  3706. while (q >= loopEnd)
  3707. q -= loopEnd - loopStart;
  3708. if (v.loops > 0 && q < loopStart)
  3709. q += loopEnd - loopStart;
  3710. }
  3711. q = std::clamp (q, first, last);
  3712. if (v.reversed)
  3713. q = first + last - q;
  3714. tapL[(std::size_t) t] = l[q];
  3715. tapR[(std::size_t) t] = r[q];
  3716. }
  3717. flrs::interpolate (v.kernel, tapL.data(), tapR.data(), frac, outL, outR);
  3718. }
  3719. bool idle() const noexcept override
  3720. {
  3721. return std::none_of (voices.begin(), voices.end(), [] (const auto& v) { return v.active; });
  3722. }
  3723. public:
  3724. float playPosition() const noexcept override { return shownPosition.load (std::memory_order_relaxed); }
  3725. private:
  3726. void publishPosition() noexcept
  3727. {
  3728. auto at = -1.0f;
  3729. if (newestVoice >= 0 && newestVoice < (int) voices.size())
  3730. {
  3731. const auto& v = voices[(std::size_t) newestVoice];
  3732. if (v.active && ! v.stolen && v.regionLast > v.regionFirst)
  3733. at = (float) std::clamp ((v.position - v.regionFirst) / (v.regionLast - v.regionFirst), 0.0, 1.0);
  3734. }
  3735. shownPosition.store (at, std::memory_order_relaxed);
  3736. }
  3737. std::shared_ptr<const SampleData> sample;
  3738. VoiceShaper* shaper = nullptr; // (FPC's layers, round 190z)
  3739. bool clipMode = false;
  3740. double sampleRate = 44100.0;
  3741. float fadeStep = 0.01f;
  3742. std::array<SamplerVoice, 16> voices {};
  3743. int newestVoice = -1; // the voice the last note started (audio thread)
  3744. std::atomic<float> shownPosition { -1.0f }; // playPosition()
  3745. std::array<KeyShift, 16> shifts {};
  3746. std::array<std::unique_ptr<VoicePitchShifter>, keyShiftVoices> shifterPool;
  3747. std::array<int, keyShiftVoices> shifterUser {}; // the voice using each shifter (-1 = none)
  3748. std::shared_ptr<ShifterStock> shifterStock; // round 190gn: the rack's (null: all 8 made up front)
  3749. int shifterKind = 0; // ShifterStock::kindOf the method the shifters were made for
  3750. int shiftersNow = keyShiftVoices; // made by prepareKeyShift (useShifterStock)
  3751. std::atomic<int> heldShifters { 0 }; // shifterPool's filled slots (any thread may read it)
  3752. std::vector<float> primeL, primeR;
  3753. bool wideClipShift = false; // round gaps190kf: the note starting now is a clip transposed beyond ±24 st
  3754. std::atomic<bool> keyShift { false };
  3755. std::atomic<int> keyShiftMethod { 0 };
  3756. double lastFactor = 1.0; // the last shifted note's transposition (where its portamento starts)
  3757. // issue #187 (round 190ik): the playing tempo over the song's (1 unless the sample is warped), whether it can move
  3758. double tempoC = 1.0;
  3759. bool tempoHooked = false; // (rollup 0.1.30: the renderer calls setTempoRatio, issue #187's tempo following)
  3760. bool tempoMoves = false;
  3761. std::atomic<bool> warpedTempo { false };
  3762. double bendMul = 1.0; // the pitch wheel (pitchBend), audio thread
  3763. int quality = flrs::liveQuality; // FL's interpolation index (prepare)
  3764. bool preparedOffline = false; // prepare() ran for an export: `quality` stays the export's
  3765. std::array<float, 1024> tapL {}, tapR {}; // kernel taps gathered near the region edges and loops
  3766. static constexpr int flBlock = 512; // FL voices: longest segment rendered at once
  3767. std::array<float, 2 * flBlock> flX {}, flY {};
  3768. std::array<float, flBlock> flG {};
  3769. std::atomic<float> pitch { 0.0f }, attack { 0.0f }, decay { 0.0f }, sustain { 1.0f }, release { 0.0f }, stretchBeats { 0.0f };
  3770. float liveRest = std::numeric_limits<float>::quiet_NaN(); // fine tune + main pitch this block (round 167a), audio thread
  3771. std::atomic<double> bpm { 120.0 };
  3772. std::atomic<float> regionStart { 0.0f }, regionEnd { 1.0f }, startOffset { 0.0f };
  3773. std::atomic<float> cutoff { 20000.0f }, resonance { 0.0f };
  3774. // automated knobs (issue #12): which hold an automation's value, and the song values configure last saw (UI thread)
  3775. std::array<std::atomic<bool>, samplerparam::count> automatedKnob {};
  3776. std::array<float, samplerparam::count> configuredKnobs { [] {
  3777. std::array<float, samplerparam::count> a {};
  3778. a.fill (std::numeric_limits<float>::quiet_NaN());
  3779. return a;
  3780. }() };
  3781. void storeKnob (int k, float natural) noexcept
  3782. {
  3783. switch (k)
  3784. {
  3785. case samplerparam::attack: attack.store (std::clamp (natural, 0.0f, 2.0f)); break;
  3786. case samplerparam::decay: decay.store (std::clamp (natural, 0.0f, 10.0f)); break;
  3787. case samplerparam::sustain: sustain.store (std::clamp (natural, 0.0f, 1.0f)); break;
  3788. case samplerparam::release: release.store (std::clamp (natural, 0.0f, 4.0f)); break;
  3789. case samplerparam::cutoff: cutoff.store (std::clamp (natural, 20.0f, 20000.0f)); break;
  3790. case samplerparam::resonance: resonance.store (std::clamp (natural, 0.0f, 1.0f)); break;
  3791. case samplerparam::start: regionStart.store (std::clamp (natural, 0.0f, 1.0f)); break;
  3792. case samplerparam::end: regionEnd.store (std::clamp (natural, 0.0f, 1.0f)); break;
  3793. default: break;
  3794. }
  3795. }
  3796. public:
  3797. // an automation clip on one of the Sampler's knobs (samplerparam, issue #12). Audio thread.
  3798. void setParameter (int index, float value) noexcept override
  3799. {
  3800. if (index < 0 || index >= samplerparam::count)
  3801. return;
  3802. automatedKnob[(std::size_t) index].store (true, std::memory_order_relaxed);
  3803. storeKnob (index, samplerparam::toNatural (index, value));
  3804. }
  3805. private:
  3806. std::atomic<bool> porta { false };
  3807. std::atomic<float> outGain { 1.0f }; // SamplerSettings::gainDb as a factor
  3808. std::atomic<float> portaBeats { 0.125f };
  3809. std::vector<LoadedZone> zones; // multi-sample (fixed after creation)
  3810. double songTicks = 0.0; // song position in the block (global LFO)
  3811. double liveBpm = 0.0; // round 190hq: the tempo now (setSongTempo; audio thread)
  3812. public:
  3813. // round 190hq: the tempo of the block about to render (the renderer, while the tempo can move); 0 = the project's
  3814. void setSongTempo (double songBpm) noexcept override { liveBpm = songBpm; }
  3815. void setSongPosition (double ticks) noexcept override
  3816. {
  3817. songTicks = ticks;
  3818. // the song's sample position (FL's ticks fall at round(k · samples per tick) from the song start)
  3819. const auto tps = (double) ppq * bpm.load() / (60.0 * sampleRate);
  3820. songSample = tps > 0.0 ? std::nearbyint (ticks / tps) : 0.0;
  3821. }
  3822. private:
  3823. double songSample = 0.0; // sample position of the next render call in the song
  3824. int lastZone = -1; // the zone the last note chose (overlapping layers cycle from it)
  3825. double lastRate = 0.0; // read speed of the last note (where porta starts from)
  3826. std::atomic<int> filterType { 0 };
  3827. float filterCutoff = -1.0f, filterResonance = -1.0f; // values the coefficients were computed with
  3828. SvfCoefficients sharedFilter;
  3829. struct Modulation
  3830. {
  3831. std::array<ModEnvelope, 2> envelopes {};
  3832. std::array<ChannelLfo, lfoTargets> lfo {};
  3833. bool flVolume = false; // FL's volume articulator replaces the ADSR
  3834. flvp::Rec volume {}; // its settings (FLEngine FUN_009ce9e0 = the plugins' FUN_0071ff00, REA_rodada69 §3)
  3835. double ticksPerSecond = 0; // FL steps it once per sequencer tick
  3836. bool flNative = false; // FL's whole sampler voice (SamplerSettings::flChannel)
  3837. flvp::Settings fl {};
  3838. };
  3839. SettingsMailbox<Modulation> envelopeMailbox;
  3840. Modulation modulation;
  3841. std::array<LfoCoefficients, lfoTargets> lfos {};
  3842. bool anyLfo = false;
  3843. void updateModulation() noexcept
  3844. {
  3845. anyLfo = false;
  3846. if (modulation.flNative)
  3847. modulation.fl.setRate (sampleRate); // FLEngine FUN_006a0230: ratio 44100/fs, ramp limit ratio·0.001
  3848. for (std::size_t e = 0; e < 2; ++e)
  3849. modEnv[e] = ModCoefficients::make (modulation.envelopes[e], sampleRate);
  3850. for (std::size_t i = 0; i < lfoTargets; ++i)
  3851. {
  3852. lfos[i] = LfoCoefficients::make (modulation.lfo[i], sampleRate, bpm.load());
  3853. anyLfo = anyLfo || lfos[i].active;
  3854. }
  3855. }
  3856. std::array<ModCoefficients, 2> modEnv {};
  3857. std::array<float, 4> nextClip {}; // fades for the next noteOn (only the audio thread touches it)
  3858. float nextClipPitch = 0.0f; // the next clip's own pitch (semitones, audio thread)
  3859. float nextClipStretch = 1.0f; // the next clip's own stretch (round 167l, audio thread)
  3860. bool clipShift = false; // pitch shifters for the clips' own pitch (set before prepareKeyShift)
  3861. std::uint16_t nextClipShape = 0;
  3862. std::array<float, 2> nextClipTension {};
  3863. std::int32_t nextClipEnvelope = -1; // round 190gi: the next clip's envelope (audio thread)
  3864. double nextClipEnvTick = 0.0;
  3865. const std::vector<ClipEnvelope>* clipEnvelopes = nullptr; // the block's table (null: the song has none)
  3866. double clipEnvTps = 0.0;
  3867. struct SliceTable
  3868. {
  3869. std::array<float, 128> starts {};
  3870. int count = 0;
  3871. int firstKey = 60; // Fruity Slicer: the key of slice 1
  3872. std::array<std::int16_t, 125> keys {}; // Fruity Slicer: FL's key table, key → slice (−1 none), when `keyed`
  3873. bool keyed = false;
  3874. bool toEnd = false; // Fruity Slicer's "play to end"
  3875. bool cutAtEnd = false; // Fruity Slicer: the voice stops dead at the slice's end
  3876. };
  3877. SettingsMailbox<SliceTable> sliceMailbox;
  3878. SliceTable slices; // audio thread's copy
  3879. float nextPan = 0.0f, nextCents = 0.0f;
  3880. float nextModX = 0.5f, nextModY = 0.5f; // the next note's Mod X / Y (issue #63)
  3881. float nextGain = 1.0f; // the next note's volume factor (setNextNoteGain)
  3882. bool nextPorta = false;
  3883. std::atomic<bool> reverse { false }, cutSelf { false };
  3884. std::atomic<bool> useLoops { true }, fastDeclick { false }, panTriangular { false };
  3885. // FL Studio Mobile's pad (SamplerSettings::flmPad, core/FlmPad.h)
  3886. std::atomic<bool> padOn { false }, padHold { false };
  3887. std::atomic<float> padAttack { 0.0f }, padDecay { 1.0f }, padSustain { 1.0f }, padRelease { 1.0f }, padLength { 0.0f }, padStart { 0.5f };
  3888. std::atomic<bool> flVelocityLaw { false }; // SamplerSettings::flVelocityLaw
  3889. std::atomic<bool> clipNoteLegacy { false }; // SamplerSettings::clipNoteLegacy (round 190lq)
  3890. std::atomic<int> declickMode { 0 };
  3891. };
  3892. } // namespace
  3893. std::unique_ptr<Instrument> makeZonedSampler (std::vector<LoadedZone> zones)
  3894. {
  3895. auto sampler = std::make_unique<SamplerInstrument> (nullptr, false);
  3896. sampler->setZones (std::move (zones));
  3897. return sampler;
  3898. }
  3899. namespace
  3900. {
  3901. // FL's Envelope Controller (REA_rodada15 §10, REA_rodada162e-envelope.md): no audio; each articulator follows the last note in
  3902. // its key range (envelope, LFO and maps restart); with no note the output holds its last value, or with the
  3903. // controller's continuous flag follows base and the Mod X / Y maps.
  3904. class ControllerInstrument final : public Instrument
  3905. {
  3906. public:
  3907. void prepare (double sr) noexcept override { sampleRate = sr; }
  3908. void configure (const ChannelDef& channel, double bpm) noexcept override
  3909. {
  3910. Data data {};
  3911. if (auto keyboard = parseKeyboardController (channel.controllerState))
  3912. {
  3913. data.keyboard = true;
  3914. data.keys = *keyboard;
  3915. }
  3916. else if (auto parsed = parseEnvelopeController (channel.controllerState))
  3917. {
  3918. data.articulators = *parsed;
  3919. const auto beat = 60.0 / std::max (1.0, bpm);
  3920. data.beat = beat;
  3921. for (std::size_t k = 0; k < data.articulators.size(); ++k)
  3922. {
  3923. auto& a = data.articulators[k];
  3924. a = controllerWithKnobs (a);
  3925. if (a.tempo)
  3926. {
  3927. for (int i = 0; i < a.count; ++i)
  3928. a.time[(std::size_t) i] = (float) (a.time[(std::size_t) i] * beat);
  3929. a.tempo = false;
  3930. }
  3931. // LFO: cycles per second; its amplitude curve in seconds
  3932. data.lfoRate[k] = controllerLfoRate (a) / (a.lfoTempo ? beat : 1.0);
  3933. if (a.lfoTempo)
  3934. for (int i = 0; i < a.lfoAmp.count; ++i)
  3935. a.lfoAmp.time[(std::size_t) i] = (float) (a.lfoAmp.time[(std::size_t) i] * beat);
  3936. }
  3937. }
  3938. // (set here, not through the mailbox: the rack reads it before the first block renders)
  3939. sendsOnNotes.store (channel.engineRev >= 6 && ! data.keyboard && ! data.articulators.continuous, std::memory_order_relaxed);
  3940. mailbox.write (data);
  3941. }
  3942. void setNextNoteModulation (float modX, float modY) noexcept override
  3943. {
  3944. nextModX = modX;
  3945. nextModY = modY;
  3946. }
  3947. // automation / links of the global Mod X / Mod Y (FL's parameters 88 / 89, round 164f): they hold until the knob
  3948. // is moved in the editor
  3949. void setParameter (int index, float value) noexcept override
  3950. {
  3951. if (index == envelopeControllerModXParam)
  3952. autoModX = std::clamp (value, 0.0f, 1.0f);
  3953. else if (index == envelopeControllerModYParam)
  3954. autoModY = std::clamp (value, 0.0f, 1.0f);
  3955. }
  3956. void setSongPosition (double ticks) noexcept override { songTicks = ticks; }
  3957. void noteOn (int key, float velocity) noexcept override
  3958. {
  3959. mailbox.read (data);
  3960. lastKey.store ((float) key, std::memory_order_relaxed);
  3961. lastVelocity.store (velocity, std::memory_order_relaxed);
  3962. if (data.keyboard) // Keyboard Controller: output 0 is the key's value
  3963. {
  3964. heldKey = key;
  3965. if (key >= 0 && key < (int) data.keys.keys.size())
  3966. values[0] = data.keys.keys[(std::size_t) key];
  3967. return;
  3968. }
  3969. ControllerNote note;
  3970. note.key = (float) key;
  3971. note.velocity = velocity;
  3972. note.modX = nextModX;
  3973. note.modY = nextModY;
  3974. // one random value per note (FL draws it at the trigger)
  3975. randomState = randomState * 1664525u + 1013904223u;
  3976. note.random = (float) ((randomState >> 8) * (1.0 / 16777216.0));
  3977. nextModX = nextModY = 0.5f;
  3978. for (std::size_t k = 0; k < voices.size(); ++k)
  3979. {
  3980. const auto& a = data.articulators[k];
  3981. if (key >= a.lowKey && key <= a.highKey)
  3982. {
  3983. auto& v = voices[k];
  3984. v = { true, key, 0.0, -1.0, note, 0.0 };
  3985. v.lfoPhase = a.lfoGlobal ? globalPhase (k) : controllerLfoStartPhase (a);
  3986. v.used = true;
  3987. }
  3988. }
  3989. }
  3990. void noteOff (int key) noexcept override
  3991. {
  3992. if (data.keyboard)
  3993. {
  3994. if (key == heldKey && data.keys.autoRelease)
  3995. values[0] = data.keys.noteOffValue;
  3996. return;
  3997. }
  3998. for (auto& v : voices)
  3999. if (v.active && v.key == key && v.sinceRelease < 0.0)
  4000. v.sinceRelease = 0.0;
  4001. }
  4002. void allNotesOff() noexcept override
  4003. {
  4004. for (auto& v : voices)
  4005. if (v.active && v.sinceRelease < 0.0)
  4006. v.sinceRelease = 0.0;
  4007. }
  4008. void render (float*, float*, int n, float, float) noexcept override
  4009. {
  4010. const auto changed = mailbox.read (data);
  4011. if (data.keyboard)
  4012. return;
  4013. // the editor moved Mod X / Y: that value wins over the last automation value
  4014. if (data.articulators.modX != seenModX)
  4015. {
  4016. seenModX = data.articulators.modX;
  4017. autoModX = std::numeric_limits<float>::quiet_NaN();
  4018. }
  4019. if (data.articulators.modY != seenModY)
  4020. {
  4021. seenModY = data.articulators.modY;
  4022. autoModY = std::numeric_limits<float>::quiet_NaN();
  4023. }
  4024. const auto modX = std::isnan (autoModX) ? data.articulators.modX : autoModX;
  4025. const auto modY = std::isnan (autoModY) ? data.articulators.modY : autoModY;
  4026. if (changed)
  4027. for (std::size_t k = 0; k < values.size(); ++k)
  4028. if (! voices[k].active && (! voices[k].used || data.articulators.continuous))
  4029. values[k] = data.articulators.continuous ? controllerRestingValue (data.articulators[k], modX, modY) : data.articulators[k].base;
  4030. const auto seconds = n / sampleRate;
  4031. for (std::size_t k = 0; k < voices.size(); ++k)
  4032. {
  4033. auto& v = voices[k];
  4034. const auto& a = data.articulators[k];
  4035. if (! v.active)
  4036. {
  4037. if (data.articulators.continuous)
  4038. values[k] = controllerRestingValue (a, modX, modY);
  4039. continue;
  4040. }
  4041. v.sinceOn += seconds;
  4042. if (v.sinceRelease >= 0.0)
  4043. v.sinceRelease += seconds;
  4044. v.lfoPhase = a.lfoGlobal ? globalPhase (k) : v.lfoPhase + data.lfoRate[k] * seconds;
  4045. if (v.lfoPhase > 1.0e6)
  4046. v.lfoPhase -= std::floor (v.lfoPhase);
  4047. values[k] = controllerValue (a, v.sinceOn, v.sinceRelease, v.lfoPhase, v.note, modX, modY);
  4048. if (controllerVoiceFinished (a, v.sinceOn, v.sinceRelease))
  4049. v.active = false; // the output holds its last value
  4050. }
  4051. }
  4052. // outputs 0 … 7 drive the links; 8 and 9 are the last key (0 … 127) and velocity (0 … 1) received, -1 before the
  4053. // first note, for the editor's Keyboard / Velocity mapping line (round 190ih, FL's manual)
  4054. float controlOutput (int output) const noexcept override
  4055. {
  4056. if (output == lastKeyOutput)
  4057. return lastKey.load (std::memory_order_relaxed);
  4058. if (output == lastVelocityOutput)
  4059. return lastVelocity.load (std::memory_order_relaxed);
  4060. return output >= 0 && output < (int) values.size() ? values[(std::size_t) output] : 0.0f;
  4061. }
  4062. static constexpr int lastKeyOutput = 8, lastVelocityOutput = 9;
  4063. // round 190qz (ChannelDef::engineRev 6 on): an Envelope Controller's output sends nothing before a note has reached it
  4064. // (FL's tick sends a value only when it changes and keeps none without a voice: its links' targets keep their own
  4065. // values; FL renders of Asher Postman's "Basic Sidechain" → Love Philter, the intro and the solo with the controller
  4066. // off). Continuous output sends from the start. Below revision 6 the base was sent from the start, as before.
  4067. bool controlSent (int output) const noexcept override
  4068. {
  4069. return ! sendsOnNotes.load (std::memory_order_relaxed) || output < 0 || output >= (int) voices.size()
  4070. || voices[(std::size_t) output].used;
  4071. }
  4072. private:
  4073. std::atomic<float> lastKey { -1.0f }, lastVelocity { -1.0f };
  4074. std::atomic<bool> sendsOnNotes { false };
  4075. struct Data
  4076. {
  4077. EnvelopeControllerData articulators {};
  4078. std::array<double, 8> lfoRate {};
  4079. double beat = 0.5;
  4080. bool keyboard = false;
  4081. KeyboardControllerData keys {};
  4082. };
  4083. // a "global" LFO follows the song position instead of restarting on each note
  4084. double globalPhase (std::size_t k) const noexcept
  4085. {
  4086. const auto& a = data.articulators[k];
  4087. const auto seconds = songTicks / ppq * data.beat;
  4088. return controllerLfoStartPhase (a) + data.lfoRate[k] * seconds;
  4089. }
  4090. int heldKey = -1;
  4091. struct Voice
  4092. {
  4093. bool active = false;
  4094. int key = 0;
  4095. double sinceOn = 0.0, sinceRelease = -1.0;
  4096. ControllerNote note {};
  4097. double lfoPhase = 0.0;
  4098. bool used = false; // played once: a finished voice holds its last value
  4099. };
  4100. SettingsMailbox<Data> mailbox;
  4101. Data data {};
  4102. std::array<Voice, 8> voices {};
  4103. std::array<float, 8> values { 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f };
  4104. double sampleRate = 44100.0, songTicks = 0.0;
  4105. float nextModX = 0.5f, nextModY = 0.5f;
  4106. float autoModX = std::numeric_limits<float>::quiet_NaN(), autoModY = std::numeric_limits<float>::quiet_NaN();
  4107. float seenModX = -1.0f, seenModY = -1.0f;
  4108. std::uint32_t randomState = 0x2545F491u;
  4109. };
  4110. } // namespace
  4111. namespace
  4112. {
  4113. std::atomic<bool> offlineRenderingFlag { false };
  4114. }
  4115. void setSynthVoiceLanes (bool on) noexcept { synthLanesFlag.store (on, std::memory_order_relaxed); }
  4116. bool synthVoiceLanes() noexcept { return synthLanesFlag.load (std::memory_order_relaxed); }
  4117. void setOfflineRendering (bool on) noexcept { offlineRenderingFlag.store (on); }
  4118. bool offlineRendering() noexcept { return offlineRenderingFlag.load(); }
  4119. namespace
  4120. {
  4121. std::atomic<bool> renderInProgressFlag { false };
  4122. }
  4123. void setRenderInProgress (bool on) noexcept { renderInProgressFlag.store (on); }
  4124. bool renderInProgress() noexcept { return renderInProgressFlag.load(); }
  4125. namespace
  4126. {
  4127. std::atomic<bool> hqAllFlag { false };
  4128. }
  4129. void setHqForAllPlugins (bool on) noexcept { hqAllFlag.store (on); }
  4130. bool hqForAllPlugins() noexcept { return hqAllFlag.load (std::memory_order_relaxed); }
  4131. namespace
  4132. {
  4133. std::atomic<bool> sampleAccurateFlag { true };
  4134. }
  4135. void setSampleAccurateAutomation (bool on) noexcept { sampleAccurateFlag.store (on); }
  4136. bool sampleAccurateAutomation() noexcept { return sampleAccurateFlag.load (std::memory_order_relaxed); }
  4137. namespace
  4138. {
  4139. thread_local HostTimeline* threadTimeline = nullptr; // (round 190gq)
  4140. }
  4141. HostTimeline& hostTimeline() noexcept
  4142. {
  4143. static HostTimeline timeline;
  4144. return threadTimeline != nullptr ? *threadTimeline : timeline;
  4145. }
  4146. HostTimeline* swapThreadHostTimeline (HostTimeline* timeline) noexcept
  4147. {
  4148. return std::exchange (threadTimeline, timeline);
  4149. }
  4150. namespace
  4151. {
  4152. thread_local int hostBlockOffsetValue = 0;
  4153. }
  4154. void setHostBlockOffset (int samples) noexcept { hostBlockOffsetValue = samples; }
  4155. int hostBlockOffset() noexcept { return hostBlockOffsetValue; }
  4156. namespace
  4157. {
  4158. thread_local int hostLatencyShiftValue = 0; // (issue #356, round 190te)
  4159. }
  4160. void setHostLatencyShift (int samples) noexcept { hostLatencyShiftValue = samples; }
  4161. int hostLatencyShift() noexcept { return hostLatencyShiftValue; }
  4162. double hostPlayHeadTick() noexcept
  4163. {
  4164. const auto late = hostLatencyShiftValue;
  4165. return late > 0 ? hostTimeline().tickLate (hostBlockOffsetValue, late) : hostTimeline().tickAt (hostBlockOffsetValue);
  4166. }
  4167. namespace
  4168. {
  4169. // FL's MIDI Out: makes no sound itself (its notes are routed to the plugins on its port by the renderer)
  4170. class MidiOutInstrument final : public Instrument
  4171. {
  4172. public:
  4173. void prepare (double) noexcept override {}
  4174. void noteOn (int, float) noexcept override {}
  4175. void noteOff (int) noexcept override {}
  4176. void allNotesOff() noexcept override {}
  4177. void render (float*, float*, int, float, float) noexcept override {}
  4178. bool idle() const noexcept override { return true; }
  4179. };
  4180. // A VFX note processor in the Channel Rack or a Patcher (round 164b): no sound; the renderer / the graph run its
  4181. // processor on the notes and send what it plays to the instruments on its outputs.
  4182. class VfxInstrument final : public Instrument
  4183. {
  4184. public:
  4185. void prepare (double sampleRate) noexcept override
  4186. {
  4187. rate = sampleRate;
  4188. if (processor != nullptr)
  4189. processor->prepare (sampleRate);
  4190. }
  4191. void noteOn (int, float) noexcept override {}
  4192. void noteOff (int) noexcept override {}
  4193. void allNotesOff() noexcept override {}
  4194. void render (float*, float*, int, float, float) noexcept override {}
  4195. bool idle() const noexcept override { return true; }
  4196. vfx::Processor* noteProcessor() noexcept override { return processor.get(); }
  4197. // an automation / a Patcher control cable on one of its parameters, an incoming program change (round 165c)
  4198. void setParameter (int index, float value) noexcept override
  4199. {
  4200. if (processor != nullptr)
  4201. processor->setParameter (index, value);
  4202. }
  4203. void midiMessage (const std::uint8_t* bytes, int size) noexcept override
  4204. {
  4205. if (processor != nullptr && bytes != nullptr && size >= 2 && (bytes[0] & 0xF0) == 0xC0)
  4206. processor->programChange (bytes[1] & 127);
  4207. }
  4208. // (UI thread: the first call builds the processor before the instrument reaches the audio thread; later ones only
  4209. // hand the new settings over)
  4210. void configure (const ChannelDef& channel, double) noexcept override
  4211. {
  4212. const auto state = vfx::readState (channel.pluginState);
  4213. if (! state)
  4214. return;
  4215. if (processor == nullptr || processor->kind() != state->kind)
  4216. {
  4217. if (processor == nullptr)
  4218. {
  4219. processor = vfx::makeProcessor (state->kind, state->fl);
  4220. processor->prepare (rate);
  4221. processor->setTag (state->tag);
  4222. lastState = state->fl;
  4223. }
  4224. return;
  4225. }
  4226. processor->setTag (state->tag);
  4227. if (state->fl != lastState)
  4228. processor->configure (state->fl);
  4229. lastState = state->fl;
  4230. }
  4231. // a VFX Script's output controllers (round 165d; its controls come in through setParameter above)
  4232. float controlOutput (int output) const noexcept override { return processor != nullptr ? processor->controlOutput (output) : 0.0f; }
  4233. private:
  4234. std::unique_ptr<vfx::Processor> processor;
  4235. std::vector<std::uint8_t> lastState;
  4236. double rate = 44100.0;
  4237. };
  4238. } // namespace
  4239. float samplerGain (float db) noexcept
  4240. {
  4241. if (! std::isfinite (db) || db == 0.0f)
  4242. return 1.0f;
  4243. return (float) std::pow (10.0, (double) std::clamp (db, -24.0f, 24.0f) / 20.0);
  4244. }
  4245. std::unique_ptr<Instrument> makeInstrument (InstrumentKind kind, std::shared_ptr<const SampleData> sample)
  4246. {
  4247. if (kind == InstrumentKind::controller)
  4248. return std::make_unique<ControllerInstrument>();
  4249. if (kind == InstrumentKind::midiOut) // its knobs, patch and bank as MIDI messages (round 167i)
  4250. return midiout::makeInstrument();
  4251. if (kind == InstrumentKind::layer) // (a Layer's notes go to its children)
  4252. return std::make_unique<MidiOutInstrument>();
  4253. if (kind == InstrumentKind::dashboard) // its controls' values as control outputs (round 164)
  4254. return surface::makeDashboard();
  4255. if (kind == InstrumentKind::voltage) // its notes as control voltages (round 164)
  4256. return voltage::makeInstrument();
  4257. if (kind == InstrumentKind::vfx)
  4258. return std::make_unique<VfxInstrument>();
  4259. if (kind == InstrumentKind::videoplayer) // the video's sound, in sync with the song (round 165g)
  4260. return video::makeInstrument();
  4261. if (kind == InstrumentKind::sampler || kind == InstrumentKind::audioClip)
  4262. return std::make_unique<SamplerInstrument> (std::move (sample), kind == InstrumentKind::audioClip);
  4263. if (kind == InstrumentKind::synth)
  4264. return std::make_unique<SynthInstrument>();
  4265. if (kind == InstrumentKind::sakura)
  4266. return makeSakuraInstrument();
  4267. if (kind == InstrumentKind::drumpad)
  4268. return makeDrumpadInstrument();
  4269. if (kind == InstrumentKind::boobass)
  4270. return makeBooBassInstrument();
  4271. if (kind == InstrumentKind::drumsynth)
  4272. return makeDrumSynthInstrument();
  4273. if (kind == InstrumentKind::harmless)
  4274. return makeHarmlessInstrument();
  4275. if (kind == InstrumentKind::sytrus)
  4276. return makeSytrusInstrument();
  4277. if (kind == InstrumentKind::harmor)
  4278. return makeHarmorInstrument();
  4279. if (kind == InstrumentKind::gms)
  4280. return makeGmsInstrument();
  4281. if (kind == InstrumentKind::morphine)
  4282. return makeMorphineInstrument();
  4283. if (kind == InstrumentKind::ogun)
  4284. return makeOgunInstrument();
  4285. if (kind == InstrumentKind::minisynth)
  4286. return makeMiniSynthInstrument();
  4287. if (kind == InstrumentKind::dx10)
  4288. return makeDx10Instrument();
  4289. if (kind == InstrumentKind::kepler || kind == InstrumentKind::keplerExo)
  4290. return makeKeplerInstrument();
  4291. if (kind == InstrumentKind::poizone)
  4292. return makePoiZoneInstrument();
  4293. if (kind == InstrumentKind::fruitkick)
  4294. return makeFruitKickInstrument();
  4295. if (kind == InstrumentKind::bassdrum)
  4296. return makeBassDrumInstrument();
  4297. if (kind == InstrumentKind::toxic)
  4298. return makeToxicInstrument();
  4299. if (kind == InstrumentKind::threeosc)
  4300. return makeThreeOscInstrument (&offlineRendering);
  4301. if (kind == InstrumentKind::autogun)
  4302. return makeAutogunInstrument();
  4303. if (kind == InstrumentKind::transistorbass)
  4304. return makeTransistorBassInstrument();
  4305. if (kind == InstrumentKind::simsynth)
  4306. return makeSimSynthInstrument();
  4307. if (kind == InstrumentKind::wasp)
  4308. return makeWaspInstrument(); // makes no sound and keeps its state
  4309. if (kind == InstrumentKind::fruitydance)
  4310. return dance::makeInstrument(); // silent: its notes pick the dancer's moves (round 165e)
  4311. if (kind == InstrumentKind::plucked)
  4312. return makePluckedInstrument();
  4313. if (kind == InstrumentKind::beepmap)
  4314. return makeBeepMapInstrument();
  4315. if (kind == InstrumentKind::sawer)
  4316. return makeSawerInstrument();
  4317. if (kind == InstrumentKind::granulizer)
  4318. return makeGranulizerInstrument (std::move (sample));
  4319. if (kind == InstrumentKind::wavetraveller)
  4320. return makeWaveTravellerInstrument (std::move (sample));
  4321. if (kind == InstrumentKind::fruityslicer) // the sampler's voices on the slices (the rack prepares the sample)
  4322. {
  4323. auto slicer = std::make_unique<SamplerInstrument> (std::move (sample), false);
  4324. slicer->slicer = true;
  4325. return slicer;
  4326. }
  4327. if (kind == InstrumentKind::slicex)
  4328. return makeSlicexInstrument (std::move (sample), nullptr); // (deck B's sample comes from RackRenderer)
  4329. if (kind == InstrumentKind::fpc) // (without its channel: no pads; the rack builds it from the channel's kit)
  4330. return makeFpcInstrument ({}, {});
  4331. if (kind == InstrumentKind::pocketSuperSaw)
  4332. return makePocketSuperSawInstrument();
  4333. if (kind == InstrumentKind::tetra) // round 190hs
  4334. return makeTetraInstrument();
  4335. if (kind == InstrumentKind::helix) // round 190ja
  4336. return makeHelixInstrument();
  4337. if (kind == InstrumentKind::braid) // round 190ko
  4338. return makeBraidInstrument();
  4339. if (kind == InstrumentKind::lynxModel) // round 190ni
  4340. return makeLynxModelInstrument();
  4341. if (kind == InstrumentKind::drumaxx)
  4342. return makeDrumaxxInstrument();
  4343. if (kind == InstrumentKind::slayer)
  4344. return makeSlayerInstrument();
  4345. if (kind == InstrumentKind::directwave)
  4346. return dw::makeDirectWaveInstrument ({}); // samples come from RackRenderer
  4347. if (kind == InstrumentKind::soundfont)
  4348. return sf::makeInstrument (nullptr); // the font comes from RackRenderer
  4349. return std::make_unique<DrumInstrument> (kind);
  4350. }
  4351. } // namespace lynx