Instruments.cpp 198 KB

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