@audiofool/moondog 0.3.1 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/NOTICE +4 -0
- package/README.md +8 -4
- package/licenses/dawn-sdk-mit.md +27 -0
- package/package.json +2 -1
- package/src/core/capability-catalog.mjs +28 -5
- package/src/core/moondog-application.mjs +54 -3
- package/src/i18n/messages/de.mjs +3 -2
- package/src/i18n/messages/en.mjs +3 -2
- package/src/i18n/messages/es.mjs +3 -2
- package/src/i18n/messages/fr.mjs +3 -2
- package/src/i18n/messages/it.mjs +3 -2
- package/src/i18n/messages/ja.mjs +3 -2
- package/src/i18n/messages/ko.mjs +3 -2
- package/src/i18n/messages/pt.mjs +3 -2
- package/src/i18n/messages/zh-Hant.mjs +3 -2
- package/src/i18n/messages/zh.mjs +3 -2
- package/src/i18n/screen/es.mjs +36 -16
- package/src/i18n/screen/ja.mjs +36 -16
- package/src/i18n/screen/pt.mjs +36 -16
- package/src/i18n/screen/zh.mjs +36 -16
- package/src/integrations/score/render-score.mjs +105 -0
- package/src/integrations/score/sheet.mjs +31 -0
- package/src/integrations/score/track-score.mjs +325 -0
- package/src/integrations/score/vendor/dawn-sdk.mjs +561 -0
- package/src/integrations/stable-audio/local-generator.mjs +139 -42
- package/src/integrations/stable-audio/setup.mjs +95 -46
- package/src/integrations/stable-audio/sources.mjs +151 -2
- package/src/runtime/pi/agent-runtime.mjs +148 -16
- package/src/runtime/pi/model-settings.mjs +13 -7
- package/src/surfaces/cli/brand-components.mjs +1 -1
- package/src/surfaces/cli/command-completions.mjs +11 -3
- package/src/surfaces/cli/format-output.mjs +2 -2
- package/src/surfaces/cli/tui.mjs +54 -25
|
@@ -0,0 +1,561 @@
|
|
|
1
|
+
// Generated by scripts/vendor-dawn-sdk.mjs. Do not edit: change the script's pin and run it again.
|
|
2
|
+
// DAWN SDK 0.67.0 (github.com/hraness/dawn-sdk at 272ae807823c7dd8dd6fb750adb988616c8a6149), MIT License,
|
|
3
|
+
// Copyright (c) 2026 XTE Industries LLC. The license text is in licenses/dawn-sdk-mit.md.
|
|
4
|
+
// Bundled: the score SDK, the score model, the offline renderer, the loudness helper and the lint.
|
|
5
|
+
export const DAWN_SDK = Object.freeze({"version":"0.67.0","commit":"272ae807823c7dd8dd6fb750adb988616c8a6149"});
|
|
6
|
+
var DawnSdkError=class extends Error{constructor(message){super(message),this.name="DawnSdkError"}};var SEMITONES=Object.freeze({c:0,d:2,e:4,f:5,g:7,a:9,b:11});function midi(pitch2){if(typeof pitch2=="number"){if(Number.isInteger(pitch2)&&pitch2>=0&&pitch2<=127)return pitch2;throw new DawnSdkError(`pitch must be a MIDI integer 0..127: ${pitch2}`)}let match=typeof pitch2=="string"?pitch2.trim().match(/^([a-gA-G])([#b]?)(-?\d{1,2})$/):null;if(!match)throw new DawnSdkError(`pitch must be a name like "C4" or "F#2": ${JSON.stringify(pitch2)}`);let accidental=match[2]==="#"?1:match[2]==="b"?-1:0,value=(Number(match[3])+1)*12+SEMITONES[match[1].toLowerCase()]+accidental;if(value<0||value>127)throw new DawnSdkError(`pitch is outside MIDI 0..127: ${pitch2}`);return value}function pitchCents(pitch2){let match=typeof pitch2=="string"?pitch2.trim().match(/^(.+?)([+-]\d+(?:\.\d+)?)c$/):null;if(!match)return{pitch:midi(pitch2),cents:0};let cents=Number(match[2]);if(!(Math.abs(cents)<=1200))throw new DawnSdkError(`pitch cents must be within \xB11200: ${pitch2}`);return{pitch:midi(match[1]),cents}}var DRUM_PITCHES=Object.freeze({kick:36,rim:37,snare:38,clap:39,hat:42,tom:45,openhat:46}),DRUM_ALIASES=Object.freeze({kick:"kick",bd:"kick",snare:"snare",sd:"snare",clap:"clap",cp:"clap",rim:"rim",rimshot:"rim",perc:"rim",tom:"tom",lt:"tom",hat:"hat",hh:"hat",hihat:"hat","hi-hat":"hat",closedhat:"hat","closed-hat":"hat",chh:"hat",openhat:"openhat","open-hat":"openhat",ohh:"openhat",oh:"openhat",open:"openhat"}),KIT_INSTRUMENTS=Object.freeze(["kit","drums","drum","drumkit"]),SAMPLER_INSTRUMENT="sampler",SAMPLER_FIRST_SLOT=36,ARTICULATIONS=Object.freeze(["staccato","legato","accent","tenuto","marcato","ghost"]),DEFAULT_VIBRATO_RATE=5.5,NOTE_ID_LIMIT=64,DEFAULT_VIBRATO_DEPTH=20;function expression(input,label){if(input===void 0)return{};if(!isRecord(input))throw new DawnSdkError(`${label} expression must be an object`);for(let key of Object.keys(input))if(!["articulation","art","glide","bend","vibrato","humanize","vowel","lyric","drift","vox","id"].includes(key))throw new DawnSdkError(`${label} expression has an unknown field "${key.slice(0,32)}" (articulation glide bend vibrato humanize vowel lyric drift vox id)`);let out={};if(input.id!==void 0){if(typeof input.id!="string"||input.id.length===0||input.id.length>NOTE_ID_LIMIT)throw new DawnSdkError(`${label} id must be a string of 1..${NOTE_ID_LIMIT} characters`);out.id=input.id}let articulation=input.articulation??input.art;if(articulation!==void 0){if(!ARTICULATIONS.includes(articulation))throw new DawnSdkError(`${label} articulation must be one of ${ARTICULATIONS.join(" ")}`);out.articulation=articulation}if(input.glide!==void 0){let glide=finite(input.glide,`${label} glide`);if(glide<0)throw new DawnSdkError(`${label} glide must be \u2265 0`);out.glide=glide}if(input.bend!==void 0){if(!Array.isArray(input.bend)||input.bend.length>32)throw new DawnSdkError(`${label} bend must be at most 32 [at, cents] points`);input.bend.length>0&&(out.bend=Object.freeze(input.bend.map((point,index)=>{if(!Array.isArray(point)||point.length!==2)throw new DawnSdkError(`${label} bend[${index}] must be [at, cents]`);return Object.freeze([unit(point[0],`${label} bend[${index}] at`),finite(point[1],`${label} bend[${index}] cents`)])})))}if(input.vibrato!==void 0){if(!isRecord(input.vibrato))throw new DawnSdkError(`${label} vibrato must be { rate, depth, delay }`);let delay=input.vibrato.delay===void 0?0:finite(input.vibrato.delay,`${label} vibrato delay`);out.vibrato=Object.freeze({rate:finite(input.vibrato.rate??DEFAULT_VIBRATO_RATE,`${label} vibrato rate`),depth:finite(input.vibrato.depth??DEFAULT_VIBRATO_DEPTH,`${label} vibrato depth`),...delay!==0?{delay}:{}})}if(input.humanize!==void 0){if(!isRecord(input.humanize))throw new DawnSdkError(`${label} humanize must be { timing, velocity, length }`);let amounts={};for(let key of Object.keys(input.humanize)){if(key!=="timing"&&key!=="velocity"&&key!=="length")throw new DawnSdkError(`${label} humanize has an unknown field "${key.slice(0,32)}" (timing velocity length)`);let value=finite(input.humanize[key],`${label} humanize ${key}`);if(value<0)throw new DawnSdkError(`${label} humanize ${key} must be \u2265 0`);value>0&&(amounts[key]=value)}out.humanize=Object.freeze(amounts)}if(input.vowel!==void 0&&(out.vowel=singVowel(input.vowel,`${label} vowel`)),input.lyric!==void 0&&(out.lyric=lyricInput(input.lyric,label)),input.drift!==void 0){let drift=finite(input.drift,`${label} drift`);if(drift<0||drift>1)throw new DawnSdkError(`${label} drift must be 0..1`);out.drift=drift}if(input.vox!==void 0){let vox_=noteVoxInput(input.vox,`${label} vox`);vox_&&(out.vox=vox_)}return out}function lyricInput(value,label){if(typeof value!="string"||value.length===0||value.length>LYRIC_LIMIT||/\s/u.test(value))throw new DawnSdkError(`${label} lyric must be one syllable of 1..${LYRIC_LIMIT} characters without spaces`);return value}function note(pitch2,start,length=1,velocity=.8,how){let tuned=pitchCents(pitch2);return Object.freeze({kind:"note",pitch:tuned.pitch,start:beat(start,"note start"),length:positive(length,"note length"),velocity:unit(velocity,"note velocity"),...expression(how,"note"),...tuned.cents!==0?{cents:tuned.cents}:{}})}function hit(voice,start,velocity=.8,length=.25,how){if(typeof voice!="string"||voice.length===0||voice.length>32)throw new DawnSdkError("hit voice must be a short name");return Object.freeze({kind:"hit",voice,start:beat(start,"hit start"),length:positive(length,"hit length"),velocity:unit(velocity,"hit velocity"),...expression(how,"hit")})}function euclid(voice,pulses,steps2,rotate2,options={}){if(isRecord(voice)){let input=voice;return rhythmSpec(input.voice,input)}isRecord(rotate2)&&(options={...rotate2,...options},rotate2=void 0);let fields={...options};return pulses!==void 0&&(fields.pulses=pulses),steps2!==void 0&&(fields.steps=steps2),rotate2!==void 0&&(fields.rotate=rotate2),rhythmSpec(voice,fields)}function grid(voice,steps2,options={}){return rhythmSpec(voice,{...options,grid:steps2})}function rhythmSpec(voice,options){if(typeof voice!="string"||voice.trim().length===0||voice.length>32)throw new DawnSdkError("rhythm voice must be a short name");if(!isRecord(options))throw new DawnSdkError("rhythm options must be an object");let out={kind:"rhythm",voice:voice.trim()};for(let[key,value]of Object.entries(options))if(!(key==="voice"||key==="kind"||value===void 0)){if(!RHYTHM_KEYS.includes(key))throw new DawnSdkError(`rhythm ${voice}: unknown option "${key}" (${RHYTHM_KEYS.join(" ")})`);out[key]=key==="cycles"&&Array.isArray(value)?Object.freeze(value.map(cycle=>Object.freeze({...cycle}))):value}return Object.freeze(out)}var RHYTHM_KEYS=Object.freeze(["steps","pulses","rotate","division","grid","repeats","time","pace","ramp","velocity","accent","accents","gate","legato","probability","seed","swing","nudge","cycles"]);function drumPattern(name,label,tags,tempo,kit2,swing,rows,humanize){return Object.freeze({name,label,tags:Object.freeze([...tags]),tempo:Object.freeze({min:tempo[0],max:tempo[1],bpm:tempo[2]}),beatsPerBar:4,swing,kit:kit2,...humanize?{humanize:Object.freeze({...humanize})}:{},rows:Object.freeze(rows.map(row2=>swing!==0&&row2.swing===void 0&&row2.division===void 0?Object.freeze({...row2,swing}):row2))})}var DRUM_PATTERNS=Object.freeze([drumPattern("house","House four-on-the-floor",["house","dance","four-on-the-floor"],[118,128,124],"syn909",.16,[euclid("kick",4,16,0,{velocity:.71}),grid("clap","....X.......X.......X.......X.......X.......X.......X.......X..x",{velocity:.62,accent:.45}),grid("snare","...........x.......x......x....x",{velocity:.3}),grid("openhat","..x...x...x...x...x...x...x...X...x...x...x...x...X...X...X.....",{velocity:.55,accent:.15}),grid("hat","Xx.xXx.xXx.xXx.xXx.xXx.xXx.xXx.XXx.xXx.xXx.xXx.xXx.xXx.xXx.xXxxX",{velocity:.3,accent:.45})]),drumPattern("techno","Techno",["techno","dance","four-on-the-floor"],[125,140,132],"syn909",0,[grid("kick","x...x...x...x...x...x...x...x...x...x...x...x...x...x...x...x.x.",{velocity:.71}),grid("openhat",".......x.......x",{velocity:.45}),grid("hat","gxxXgxx.gxxXgxx.gxxXgxx.gxxXgxx...xX..x...xX..x.gxxXgxx.gxxXgxx.",{velocity:.42,accent:.4}),grid("snare","....x.......x.......x.......x..x....x.......x.......x.......x...",{velocity:.47}),grid("rim","...x..x...x..x.....x..x...x..x.x...x..x...x..x.....x..x...x.xxxX",{velocity:.5,accent:.3}),grid("clap","............x...............x...............x.................xx",{velocity:.47})]),drumPattern("amen-style","Amen-style break",["breaks","jungle","drum and bass"],[160,176,170],"acoustic",.04,[grid("kick","X.x.......xx....X.x.......xx....X.x.......x.....X.x...x...x..x..",{velocity:.85,accent:.25}),grid("snare","....X..x.x..X..g....X..x.x..X..g....X..x.x....X.....X..x.x.gX.xX",{velocity:.5,accent:.55}),grid("ride","X.x.X.x.X.x.X.x.X.x.X.x.X.x.X.x.X.x.X.x.X.x.X.x.X.x.X.x.X.......",{velocity:.42,accent:.3}),grid("crash","x.........................................................X.....",{velocity:.5,accent:.2})],{timing:5,velocity:10}),drumPattern("boom-bap","Boom bap",["hip hop","boom bap"],[84,96,90],"lofi",.14,[grid("kick","X......x..x.....X.x.......x...x.",{velocity:.82,accent:.5}),grid("snare","....X.......X..g....X..g....X.g.",{velocity:.8,accent:.5,nudge:.12,cycles:[{},{velocity:.84}]}),grid("hat","X.x.X.x.X.x.X.x.X.x.X.x.X.xxX.x.",{velocity:.48,accent:.4,seed:394,swing:.36,cycles:[{},{probability:.88}]})],{timing:4,velocity:8}),drumPattern("trap","Trap with hat rolls",["trap","hip hop"],[130,160,140],"trap",0,[grid("kick","X.........x.....x.....x...x.....X.........x.....x.....x...x..x..",{velocity:.58,accent:.25}),grid("snare","........X.......",{velocity:.62,accent:.2,time:"1/32",ramp:-.7,cycles:[{},{},{},{repeats:7}]}),grid("clap","........x...............x......x",{velocity:.39,nudge:.04}),grid("hat","X.x.X.x.X.x.XxxxX.x.X.x.X.x.X.x.X...X...X...X.x.X.x.....ggxxxxXX",{division:"1/32",velocity:.38,accent:.4}),grid("openhat","..........................x.....",{velocity:.31})]),drumPattern("reggaeton","Reggaeton / dembow",["reggaeton","dembow","latin"],[88,100,95],"synlinn",0,[grid("kick","X...X...X...X...X...X...X...X...X...X...X...X...X...X...X......x",{velocity:.7,accent:.6}),grid("snare","...x..x....x..x....x..x..g.x..x....x..x....x..x....x..x....x....",{velocity:.74}),grid("clap","......x.......x.",{velocity:.45}),grid("hat","x.X.x.X.x.X.x.X.x.X.x.X.x.X.xXxX",{velocity:.34,accent:.4}),grid("rim","..x.......x......x...x....x.....",{velocity:.38}),grid("openhat","..............................x.",{velocity:.4}),grid("hitom","................".repeat(3)+"............xx..",{velocity:.62}),grid("midtom","................".repeat(3)+"..............xX",{velocity:.62,accent:.4})]),drumPattern("one-drop","Reggae one drop",["reggae","dub"],[66,80,74],"acoustic",0,[grid("kick","......X...........X...........X...........X.....",{division:"1/8t",velocity:.9,accent:.3}),grid("rim","......x...........x....x......x...........x.....",{division:"1/8t",velocity:.9,nudge:.04}),grid("hat","X.xX.xX.xX.xX.xX.xX.xXxxX.xXxxX.xX.xX.xX.xX.x...",{division:"1/8t",velocity:.7,accent:.3}),grid("openhat","............".repeat(3)+"...........x",{division:"1/8t",velocity:.66}),grid("snare","............".repeat(3)+".........fgx",{division:"1/8t",velocity:.78})],{timing:8,velocity:8}),drumPattern("afrobeats","Afrobeats / afro-pop",["afrobeats","afro-pop","african"],[100,115,106],"syn707",.08,[grid("kick","x.....x.x.......x.....x.x..x....x.....x.x.......x.....x.x..x..x."),grid("rim","X..x..x.X..x..x.X..x..x.X..x.x..",{velocity:.5,accent:.3}),grid("cowbell","..........................x...x...........................x...xx",{velocity:.32}),grid("clap","............X...............X..x",{velocity:.5,accent:.3}),grid("snare",".......x...............x.....x.........x...............x.....xxX",{velocity:.3,accent:.4}),grid("hat","XxXxxxXxXxXxxxXxXxXxxxXxXxXxxx.X",{velocity:.46,accent:.4,seed:235,cycles:[{},{velocity:.54,probability:.95}]}),grid("openhat","..............................x.",{velocity:.4})],{timing:4,velocity:6}),drumPattern("bembe","Bemb\xE9 12/8 bell",["afro-cuban","african","euclidean"],[100,130,112],"acoustic",0,[grid("cowbell","X.x.xx.x.x.x",{division:"1/8t",velocity:.92,accent:.3}),grid("kick","X..x..X..x..",{division:"1/8t",velocity:.8,accent:.45}),grid("hat","...x.....x..",{division:"1/8t",velocity:.58}),grid("hitom",".x......x....x......x....x......x....x..........",{division:"1/8t",velocity:.55}),grid("snare","..........x....x......x...........x....x..X.....",{division:"1/8t",velocity:.45,accent:.5}),grid("midtom","............".repeat(3)+"........x.x.",{division:"1/8t",velocity:.72}),grid("floortom","............".repeat(3)+"...........x",{division:"1/8t",velocity:.76})],{timing:7,velocity:9}),drumPattern("garage","UK garage 2-step",["uk garage","2-step","dance"],[128,136,132],"syn909",.24,[grid("kick","X.........x..x....x.......X.....X.........x..x....x.......X..x.x",{velocity:.73,accent:.2}),grid("snare","....X.......X.......X.......X..g....X.......X.......X..g....X.g.",{velocity:.66,accent:.3}),grid("hat","Xx.XXx.XXx.XXx.XXx.XXx.XXx.XXX.X",{velocity:.18,accent:.25}),grid("openhat","..x...x...x...x.",{velocity:.36}),grid("rim","...........x.......x.......x....",{velocity:.3})],{timing:4,velocity:8}),drumPattern("jersey-club","Jersey club",["jersey club","club"],[135,145,140],"synlinn",.08,[grid("kick","X...X...X..x..x.X...X...X..x..xxX...X...X..x..x.X...X...X.x.x.xx",{velocity:.66,accent:.25}),grid("clap","....X.......X.......X..x....X.......X.......X.......X..x....X...",{velocity:.58,accent:.3}),grid("rim","..x...X...x..x....x...X...x.....",{velocity:.3,accent:.3}),grid("hat","..x...X...x...X...x...X...x...X.",{velocity:.38,accent:.4}),grid("openhat","..............................x.",{velocity:.4}),grid("snare","............................................................x...",{velocity:.36,repeats:7,time:"1/32",ramp:1})]),drumPattern("rock","Rock basic",["rock","pop"],[100,140,120],"acoustic",0,[grid("kick","x.......x.x.....x.......x.x...xxx.x.....x.x.....x.......x.......",{velocity:.85}),grid("snare","....X.......X.......X......gX.......X.......X.......X......gXx..",{velocity:.8,accent:.6}),grid("hat","..x.x.x.x.x.x.x.X.x.X.x.X.x.X...X.x.X.x.X.x.X.x.X.x.X.x.X.x.....",{velocity:.46,accent:.45}),grid("openhat","..............................x."+"-".repeat(32),{velocity:.6}),grid("crash","x"+"-".repeat(63),{velocity:.75}),grid("midtom","-".repeat(48)+"..............x.",{velocity:.8}),grid("floortom","-".repeat(48)+"...............x",{velocity:.88})],{timing:5,velocity:6}),drumPattern("funk","Funk with ghost notes",["funk","soul"],[95,110,102],"acoustic",.08,[grid("kick","x.x.......x..x..x..x......x.....x.x.......x..x..x..x...x..x....x",{velocity:.85}),grid("snare","....X..g.g..X..g.g..X..g.g..X.g.....X.g..g..X.g.....X..g.gX..gX.",{velocity:.75,accent:.85}),grid("hat","XxXxXxXxXxXxXx.xXxXxXxXxXxXxXxXxXxXxXx.xXxXxXxXxXxXxXxXxXxXxXx.x",{velocity:.42,accent:.5,nudge:-.04}),grid("openhat","..............x.......................x.......................x.",{velocity:.55,nudge:-.04})],{timing:6,velocity:8}),drumPattern("half-time-shuffle","Half-time shuffle (swung 16ths)",["shuffle","rock","funk"],[70,100,86],"acoustic",.33,[grid("kick","x.........x.....x.........x....xx......x..x.....x.........x...x.",{velocity:.95}),grid("snare",".g..g..g..g.X...g..g..g..g..g..g..g.X...g.g...g.",{division:"1/16t",velocity:.8,accent:.7}),grid("hat","XxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXXXxXxXxXxXxXxXxXxXxXxXx..",{velocity:.66,accent:.4}),grid("openhat","-".repeat(48)+"..............x.",{velocity:.7})],{timing:6,velocity:8}),drumPattern("jazz-swing","Jazz swing (ride spang-a-lang)",["jazz","swing","bebop"],[110,200,150],"acoustic",0,[grid("ride","x..X.xx..X.xx..X.xx..X.xx..X.xx.xX.xx..X.xx..X..",{division:"1/8t",velocity:.74,accent:.5}),grid("hat","...x.....x..".repeat(4),{division:"1/8t",velocity:.72}),grid("kick","x..x..x..x..x.Xx..x..x..x..x..x..x..x..x..x..x.X",{division:"1/8t",velocity:.4,accent:.75}),grid("snare","..x.................x........x..x.....X.........",{division:"1/8t",velocity:.6,accent:.5}),grid("crash","-".repeat(36)+"...........x",{division:"1/8t",velocity:.7})],{timing:8,velocity:10}),drumPattern("euclid-poly","Euclidean polymeter",["euclidean","experimental","polymeter"],[110,130,120],"electro",0,[euclid("kick",5,16,0,{velocity:.85,accent:.5,accents:2,cycles:[{},{},{},{pulses:6}]}),euclid("snare",2,16,4,{velocity:.85,cycles:[{},{},{},{pulses:3}]}),euclid("hat",7,12,0,{velocity:.62,accent:.5,accents:3}),euclid("rim",4,10,1,{velocity:.66,probability:.8,seed:21}),euclid("midtom",3,10,2,{velocity:.58,probability:.85,seed:5})])]);var WAVETABLE_INSTRUMENT="wavetable",WAVETABLE_KEYS=Object.freeze(["wt","wtenv","wtattack","wtdecay","wtsustain","wtrelease","wtrate","wtdepth","warp","wtphaserand"]);var STRING_INSTRUMENT="string";function stringed(preset5="nylon",params2={}){if(isRecord(preset5)){let{preset:name,...rest}=preset5;return stringed(name===void 0?"nylon":name,{...rest,...params2})}if(typeof preset5!="string"||preset5.length===0)throw new DawnSdkError("stringed needs a preset name");if(!isRecord(params2))throw new DawnSdkError("stringed params must be an object");let out={kind:"string",preset:preset5};for(let[key,value]of Object.entries(params2))value===void 0||key==="kind"||key==="preset"||(out[key]=typeof value=="string"?value:finite(value,`string ${key}`));return Object.freeze(out)}var GRANULAR_INSTRUMENT="granular";var MODAL_INSTRUMENT="modal",MODAL_KEYS=Object.freeze(["mallet","hardness","position","ring","tilt","damp","release","motor","motordepth","ombak","buzz","click","strikebend","strikedecay","gain","body"]),MODAL_MALLET_WORDS=Object.freeze(["yarn","cord","rubber","plastic","brass"]),MODAL_BODY_WORDS=Object.freeze(["marimba","vibraphone","xylophone","glockenspiel","celesta","chimes","crotale","mbira","kalimba","musicbox","toypiano","saron","bonang","gender","kempul","gong","bell","steelpan","bowl","timpani","tabla","frame"]),MODAL_RANGES=Object.freeze({hardness:[0,1],position:[0,1],ring:[.05,30],tilt:[0,2],damp:[0,1],release:[.005,2],motor:[0,12],motordepth:[0,1],ombak:[0,12],buzz:[0,1],click:[0,1],strikebend:[-24,24],strikedecay:[.001,2],gain:[0,2]}),MODAL_TWIN_PRESETS=Object.freeze(["gangsa"]),MODAL_PRESET_WORDS=Object.freeze(["marimba","vibes","xylophone","glock","celesta","chimes","kalimba","mbira","steelpan","bowl","gong","timpani","crotales","musicbox","toypiano","saron","demung","slenthem","gangsa","gender","bonang","kenong","kethuk","kempul","daf","bodhran","tabla"]);function modal(preset5,params2={}){let overrides=isRecord(preset5)?preset5:params2,name=isRecord(preset5)?void 0:preset5;if(!isRecord(overrides))throw new DawnSdkError("modal params must be an object");let out={kind:"modal"};if(name!==void 0){if(typeof name!="string"||!MODAL_PRESET_WORDS.includes(name))throw new DawnSdkError(`modal preset "${String(name).slice(0,32)}" is not one of ${MODAL_PRESET_WORDS.join(" ")}`);out.preset=name}for(let key of Object.keys(overrides)){let value=overrides[key];if(value!==void 0)if(key==="mallet"||key==="body"){let words=key==="mallet"?MODAL_MALLET_WORDS:MODAL_BODY_WORDS;if(typeof value!="string"||!words.includes(value))throw new DawnSdkError(`modal ${key} "${String(value).slice(0,32)}" is not one of ${words.join(" ")}`);out[key]=value}else if(key==="pair"){if(typeof value!="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(value))throw new DawnSdkError("modal pair must be a track id");out.pair=value}else if(MODAL_KEYS.includes(key)){let number=finite(value,`modal ${key}`),[min,max]=MODAL_RANGES[key];if(number<min||number>max)throw new DawnSdkError(`modal ${key} must be ${min}..${max}`);out[key]=number}else throw new DawnSdkError(`modal has no parameter "${key.slice(0,32)}" (${MODAL_KEYS.join(" ")} pair)`)}return Object.freeze(out)}var WIND_INSTRUMENT="wind",WIND_PRESET_WORDS=Object.freeze(["flute","recorder","whistle","ney","shakuhachi","panpipe","suling","bansuri","clarinet","bassclarinet","oboe","bassoon","sax","altosax","barisax","trumpet","harmon","plunger","trombone","tuba","horn"]),WIND_ENUMS=Object.freeze({model:Object.freeze(["jet","reed","sax","lips"]),mute:Object.freeze(["open","straight","cup","harmon","plunger"])}),WIND_RANGES=Object.freeze({breath:[0,1],noise:[0,1],attack:[.001,2],release:[.005,2],vib:[0,12],vibmod:[0,1],reed:[0,1],bright:[0,1],wah:[0,1],wahenv:[0,1],growl:[0,1],flutter:[0,1],players:[1,8],gain:[0,2]});function wind(preset5,params2={}){let overrides=isRecord(preset5)?preset5:params2,name=isRecord(preset5)?void 0:preset5;if(!isRecord(overrides))throw new DawnSdkError("wind params must be an object");let out={kind:"wind"};if(name!==void 0){if(typeof name!="string"||!WIND_PRESET_WORDS.includes(name))throw new DawnSdkError(`wind preset "${String(name).slice(0,32)}" is not one of ${WIND_PRESET_WORDS.join(" ")}`);out.preset=name}for(let key of Object.keys(overrides)){let value=overrides[key];if(value===void 0)continue;let words=WIND_ENUMS[key];if(words){if(typeof value!="string"||!words.includes(value))throw new DawnSdkError(`wind ${key} "${String(value).slice(0,32)}" is not one of ${words.join(" ")}`);out[key]=value}else if(key==="stopped"){if(typeof value!="boolean")throw new DawnSdkError("wind stopped must be true or false");out.stopped=value}else if(WIND_RANGES[key]){let number=finite(value,`wind ${key}`),[min,max]=WIND_RANGES[key];if(number<min||number>max)throw new DawnSdkError(`wind ${key} must be ${min}..${max}`);if(key==="players"&&!Number.isInteger(number))throw new DawnSdkError("wind players must be a whole number");out[key]=number}else throw new DawnSdkError(`wind has no parameter "${key.slice(0,32)}" (${[...Object.keys(WIND_ENUMS),"stopped",...Object.keys(WIND_RANGES)].join(" ")})`)}return Object.freeze(out)}var VOCODER_INSTRUMENT="vocoder",VOCODER_PRESET_WORDS=Object.freeze(["classic","robot","talkbox","choir","glass","whisper","smear","lofi"]),VOCODER_ENUMS=Object.freeze({tap:Object.freeze(["chain","dry"]),mode:Object.freeze(["channel","talkbox"]),carrier:Object.freeze(["saw","supersaw","pulse","noise"]),follow:Object.freeze(["notes","chords","drone"])}),VOCODER_RANGES=Object.freeze({root:[24,96],spread:[0,1],bands:[4,40],lo:[50,1e3],hi:[2e3,12e3],width:[.25,4],attack:[5e-4,.2],release:[.005,2],formant:[-24,24],unvoiced:[0,1],sens:[0,1],hiss:[0,1],gate:[-90,0],depth:[0,1],mix:[0,1],gain:[-24,24],seed:[0,2**31]}),VOCODER_INTEGERS=Object.freeze(["root","bands","seed"]);function trackVocoder(rawInstrument,field){let strip=spec=>{if(!isRecord(spec)||spec.kind!=="vocoder")throw new DawnSdkError("track vocoder must come from vocoder()");let{kind:_kind,...fields}=spec;return Object.freeze(fields)};if(field!=null)return strip(field);if(isRecord(rawInstrument)&&rawInstrument.kind==="vocoder")return strip(rawInstrument);if(rawInstrument===VOCODER_INSTRUMENT)return Object.freeze({})}var TEXTURE_INSTRUMENT="texture",TEXTURE_TYPE_WORDS=Object.freeze(["room","rain","wind","vinyl","tape","hum","city","crowd","data","air","ocean","stream","waterfall","crickets","birds","country-road","brush","paper","porcelain"]),TEXTURE_MOTION_WORDS=Object.freeze(["steady","rise","fall","swell"]),TEXTURE_RANGES=Object.freeze({density:[0,1],distance:[0,1],wear:[0,1],width:[0,1],mains:[40,70],attack:[.001,10],release:[.005,10],gain:[0,2],seed:[0,65535]});function trackTexture(raw){if(isRecord(raw)&&raw.kind==="texture"){let{kind:_kind,...fields}=raw;return Object.freeze(fields)}if(raw===TEXTURE_INSTRUMENT)return Object.freeze({})}function vocoderSlug(text2){let slug=text2.normalize("NFKD").replace(new RegExp("\\p{M}+","gu"),"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,64).replace(/-+$/g,"");return slug.length>0?slug:"track"}function resolveVocoderSrc(tracks,self,src){let byId=tracks.find(track2=>track2.id===src),matches=byId?[byId]:tracks.filter(track2=>vocoderSlug(track2.name)===vocoderSlug(src));if(matches.length===0)throw new DawnSdkError(`track ${self}: vocoder src "${src.slice(0,64)}" names no track; delete src (the carrier plays alone) or point it at a track in this song`);if(matches.length>1)throw new DawnSdkError(`track ${self}: vocoder src "${src.slice(0,64)}" matches ${matches.length} tracks; use an id`);if(matches[0].id===self)throw new DawnSdkError(`track ${self}: a track cannot vocode itself`);return matches[0].id}function trackWind(raw){if(isRecord(raw)&&raw.kind==="wind"){let{kind:_kind,...fields}=raw;return Object.freeze(fields)}if(typeof raw!="string"||raw===WIND_INSTRUMENT)return;let meaning=resolveInstrumentWord(raw);if(!(meaning?.instrument!==WIND_INSTRUMENT||!meaning.preset))return Object.freeze({preset:meaning.preset})}var SING_INSTRUMENT="sing",SING_PRESET_WORDS=Object.freeze(["aah","ooh","choir","oohchoir","chorale","airy","glass","lament","soprano","basso","drone","khoomei","sygyt","kargyraa","robot","speak"]),SING_VOWEL_LETTERS=Object.freeze(["a","e","i","o","u"]),SING_RANGES=Object.freeze({morph:[0,1],formant:[-12,12],bright:[0,1],breath:[0,1],jitter:[0,3],shimmer:[0,1],attack:[.005,2],release:[.01,4],vib:[0,9],vibmod:[0,1],vibdelay:[0,2],voices:[1,8],spread:[0,40],ring:[0,1],overtone:[0,1],sub:[0,1],articulate:[0,1],gain:[0,2]});function singVowel(value,label){let parts=typeof value=="string"?value.trim().toLowerCase().split(">"):[];if((parts.length===1||parts.length===2)&&parts.every(part=>SING_VOWEL_LETTERS.includes(part)))return parts.join(">");throw new DawnSdkError(`${label} must be one of ${SING_VOWEL_LETTERS.join(" ")} or a morph like a>o`)}function sing(preset5,params2={}){let overrides=isRecord(preset5)?preset5:params2,name=isRecord(preset5)?void 0:preset5;if(!isRecord(overrides))throw new DawnSdkError("sing params must be an object");let out={kind:"sing"};if(name!==void 0){if(typeof name!="string"||!SING_PRESET_WORDS.includes(name))throw new DawnSdkError(`sing preset "${String(name).slice(0,32)}" is not one of ${SING_PRESET_WORDS.join(" ")}`);out.preset=name}for(let key of Object.keys(overrides)){let value=overrides[key];if(value!==void 0)if(key==="voice"){let voices=["auto","soprano","alto","tenor","bass"];if(typeof value!="string"||!voices.includes(value))throw new DawnSdkError(`sing voice must be one of ${voices.join(" ")}`);out.voice=value}else if(key==="vowel")out.vowel=singVowel(value,"sing vowel");else if(key==="drone"){let midiValue=typeof value=="number"?value:midi(value);if(!Number.isInteger(midiValue)||midiValue<36||midiValue>67)throw new DawnSdkError('sing drone must be a note name C2..G4 (e.g. "D3") or MIDI 36..67');out.drone=midiValue}else if(key==="harmonics"){if(!Array.isArray(value)||value.length!==2||!value.every(h=>Number.isInteger(h)&&h>=2&&h<=24)||value[0]>=value[1])throw new DawnSdkError("sing harmonics must be [lo, hi], whole numbers 2..24 with lo < hi");out.harmonics=Object.freeze([value[0],value[1]])}else if(SING_RANGES[key]){let number=finite(value,`sing ${key}`),[min,max]=SING_RANGES[key];if(number<min||number>max)throw new DawnSdkError(`sing ${key} must be ${min}..${max}`);if(key==="voices"&&!Number.isInteger(number))throw new DawnSdkError("sing voices must be a whole number");out[key]=number}else throw new DawnSdkError(`sing has no parameter "${key.slice(0,32)}" (voice vowel drone harmonics ${Object.keys(SING_RANGES).join(" ")})`)}return Object.freeze(out)}function trackSing(raw){if(isRecord(raw)&&raw.kind==="sing"){let{kind:_kind,...fields}=raw;return Object.freeze(fields)}if(typeof raw!="string")return;let meaning=resolveInstrumentWord(raw);if(meaning?.instrument===SING_INSTRUMENT)return Object.freeze(meaning.preset?{preset:meaning.preset}:{})}var VOX_ENGINE_WORDS=Object.freeze(["formant","espeak-ng","kokoro","piper","openutau","say"]);var NOTE_VOX_FIELDS=Object.freeze(["ph","lang","cons","lead","shift","breath","dyn","p"]);function voxParams(value,label){if(!isRecord(value))throw new DawnSdkError(`${label} must be an object of numbers`);let out={};for(let key of Object.keys(value).sort())out[key]=finite(value[key],`${label}.${key}`);return Object.freeze(out)}function voxPhones(value,label){let list=typeof value=="string"?value.trim().split(/\s+/u).filter(Boolean):Array.isArray(value)?value:void 0;if(!list||list.length===0||list.length>12)throw new DawnSdkError(`${label} must be 1..12 phones like "hh eh l"`);return Object.freeze(list.map(phone=>{if(typeof phone!="string"||!/^[a-z]{1,3}[0-2]?$/iu.test(phone))throw new DawnSdkError(`${label} phones are words like hh eh l`);return phone.toLowerCase().replace(/[0-2]$/u,"")}))}function noteVoxInput(value,label){if(value===null)return;if(!isRecord(value))throw new DawnSdkError(`${label} must be an object`);for(let key of Object.keys(value))if(!NOTE_VOX_FIELDS.includes(key))throw new DawnSdkError(`${label} has no field "${key.slice(0,32)}" (${NOTE_VOX_FIELDS.join(" ")})`);let out={};for(let key of NOTE_VOX_FIELDS){let field=value[key];if(field!==void 0)if(key==="ph")out.ph=voxPhones(field,`${label} ph`);else if(key==="lang"){if(typeof field!="string")throw new DawnSdkError(`${label} lang must be a tag like en-us`);out.lang=field.toLowerCase()}else if(key==="cons")out.cons=isRecord(field)?Object.freeze({s:finite(field.s,`${label} cons.s`)}):finite(field,`${label} cons`);else if(key==="dyn"){if(!Array.isArray(field))throw new DawnSdkError(`${label} dyn must be { at, v } points`);out.dyn=Object.freeze(field.map((point,index)=>{if(!isRecord(point))throw new DawnSdkError(`${label} dyn[${index}] must be { at, v }`);return Object.freeze({at:finite(point.at,`${label} dyn[${index}].at`),v:finite(point.v,`${label} dyn[${index}].v`)})}))}else key==="p"?out.p=voxParams(field,`${label} p`):out[key]=finite(field,`${label} ${key}`)}return Object.keys(out).length>0?Object.freeze(out):void 0}function trackVoxInput(value,label){if(!isRecord(value))throw new DawnSdkError(`${label} must be vox(engine, voice) or an object`);for(let key of Object.keys(value))if(!["kind","engine","voice","lang","fit","p"].includes(key))throw new DawnSdkError(`${label} has no field "${key.slice(0,32)}" (engine voice lang fit p)`);let engine2=value.engine??"formant";if(typeof engine2!="string"||!VOX_ENGINE_WORDS.includes(engine2))throw new DawnSdkError(`${label} engine must be one of ${VOX_ENGINE_WORDS.join(" ")}`);let voice=value.voice??`${engine2}:default`;if(typeof voice!="string"||voice.length===0||voice.length>64||/\s/.test(voice))throw new DawnSdkError(`${label} voice must be 1..64 characters without spaces`);let out={engine:engine2,voice};if(value.lang!==void 0){if(typeof value.lang!="string")throw new DawnSdkError(`${label} lang must be a tag like en-us`);out.lang=value.lang.toLowerCase()}if(value.fit!==void 0){if(!["psola","world","none"].includes(value.fit))throw new DawnSdkError(`${label} fit must be psola, world or none`);out.fit=value.fit}return value.p!==void 0&&(out.p=voxParams(value.p,`${label} p`)),Object.freeze(out)}var AUTOTUNE_PRESET_WORDS=Object.freeze(["hard","robot","warble","trap","pop","natural","gentle","guided","locked"]),AUTOTUNE_PARAM_KEYS=Object.freeze(["to","from","key","speed","relax","hold","flex","glide","amount","vib","vibmod","center","drift","voice"]);function autotuneInput(raw,where2){if(typeof raw=="string"&&(raw={preset:raw}),!isRecord(raw))throw new DawnSdkError(`${where2} autotune must be a preset word or autotune()`);let out={};for(let[key,value]of Object.entries(raw))if(!(key==="kind"||value===void 0))if(key==="preset"){if(typeof value!="string"||!AUTOTUNE_PRESET_WORDS.includes(value))throw new DawnSdkError(`${where2} autotune preset "${String(value).slice(0,32)}" is not one of ${AUTOTUNE_PRESET_WORDS.join(" ")}`);out.preset=value}else if(AUTOTUNE_PARAM_KEYS.includes(key))if(["to","from","key","voice"].includes(key)){if(typeof value!="string")throw new DawnSdkError(`${where2} autotune ${key} must be a string`);out[key]=value}else out[key]=finite(value,`${where2} autotune ${key}`);else throw new DawnSdkError(`${where2} autotune has no field "${key.slice(0,32)}" (preset ${AUTOTUNE_PARAM_KEYS.join(" ")})`);if(Object.keys(out).length===0)throw new DawnSdkError(`${where2} autotune needs a preset or fields`);let ordered={};for(let key of["preset",...AUTOTUNE_PARAM_KEYS])out[key]!==void 0&&(ordered[key]=out[key]);return Object.freeze(ordered)}function sampleSpec(value,name){let spec=typeof value=="string"?{src:value}:value;if(!isRecord(spec)||typeof spec.src!="string"||spec.src.length===0)throw new DawnSdkError(`sampler voice ${name} needs a src path`);let out={src:spec.src};if(spec.src.startsWith("pack:")&&(spec.sha256!==void 0&&(out.sha256=text(spec.sha256,`${name} sha256`)),spec.url!==void 0&&(out.url=text(spec.url,`${name} url`)),spec.license!==void 0&&(out.license=text(spec.license,`${name} license`))),spec.root!==void 0&&(out.root=midi(spec.root)),spec.begin!==void 0&&(out.begin=unit(spec.begin,`${name} begin`)),spec.end!==void 0&&(out.end=unit(spec.end,`${name} end`)),spec.gain!==void 0&&(out.gain=finite(spec.gain,`${name} gain`)),spec.speed!==void 0&&(out.speed=finite(spec.speed,`${name} speed`)),spec.loop!==void 0){if(typeof spec.loop!="boolean")throw new DawnSdkError(`${name} loop must be boolean`);out.loop=spec.loop}if(spec.choke!==void 0){if(typeof spec.choke!="string")throw new DawnSdkError(`${name} choke must be a group name`);out.choke=spec.choke}let loopBegin=spec.loopBegin??spec.loopb;loopBegin!==void 0&&(out.loopBegin=unit(loopBegin,`${name} loopBegin`));let loopEnd=spec.loopEnd??spec.loope;loopEnd!==void 0&&(out.loopEnd=unit(loopEnd,`${name} loopEnd`));let clip=spec.clip??spec.legato;if(clip!==void 0&&(out.clip=finite(clip,`${name} clip`)),spec.unit!==void 0){if(spec.unit!=="r"&&spec.unit!=="c"&&spec.unit!=="s")throw new DawnSdkError(`${name} unit must be "r", "c" or "s"`);out.unit=spec.unit}if(spec.loopAt!==void 0){let bars=finite(spec.loopAt,`${name} loopAt`);if(bars<=0)throw new DawnSdkError(`${name} loopAt must be positive`);out.speed=(out.speed??1)/bars,out.unit="c"}if(spec.fit!==void 0){if(typeof spec.fit!="boolean")throw new DawnSdkError(`${name} fit must be boolean`);out.fit=spec.fit}if(spec.accelerate!==void 0&&(out.accelerate=finite(spec.accelerate,`${name} accelerate`)),spec.squiz!==void 0&&(out.squiz=finite(spec.squiz,`${name} squiz`)),spec.bpm!==void 0&&(out.bpm=finite(spec.bpm,`${name} bpm`)),spec.fitmode!==void 0){if(spec.fitmode!=="repitch"&&spec.fitmode!=="beats"&&spec.fitmode!=="tones")throw new DawnSdkError(`${name} fitmode must be "repitch", "beats" or "tones"`);out.fitmode=spec.fitmode}if(spec.len!==void 0&&(out.len=finite(spec.len,`${name} len`)),spec.shift!==void 0&&(out.shift=finite(spec.shift,`${name} shift`)),spec.formant!==void 0&&(out.formant=finite(spec.formant,`${name} formant`)),spec.fadeTime!==void 0&&(out.fadeTime=finite(spec.fadeTime,`${name} fadeTime`)),spec.fadeInTime!==void 0&&(out.fadeInTime=finite(spec.fadeInTime,`${name} fadeInTime`)),spec.from!==void 0){if(typeof spec.from!="object"||spec.from===null)throw new DawnSdkError(`${name} from must be an object`);out.from=spec.from}if(spec.vel!==void 0){if(!Array.isArray(spec.vel)||spec.vel.length!==2)throw new DawnSdkError(`${name} vel must be [lo, hi]`);out.vel=Object.freeze([finite(spec.vel[0],`${name} vel`),finite(spec.vel[1],`${name} vel`)])}return spec.rr!==void 0&&(out.rr=text(spec.rr,`${name} rr`)),Object.freeze(out)}var RIG_PRESETS=Object.freeze({clean:{stomp:void 0,head:{type:"clean",gain:3,treble:6},cab:{type:"1x12"}},crunch:{stomp:void 0,head:{type:"crunch",gain:5},cab:{type:"4x12"}},punk:{stomp:void 0,head:{type:"crunch",gain:7,mid:6,master:6},cab:{type:"4x12",mic:.2}},ragged:{stomp:{type:"face",gain:6,tone:.6},head:{type:"chime",gain:4},cab:{type:"2x12"}},lead:{stomp:{type:"od",gain:3,tone:.5,level:3},head:{type:"lead",gain:6,mid:6},cab:{type:"4x12"}},metal:{stomp:{type:"od",gain:0,tone:.6,level:6},head:{type:"high",gain:7,bass:6,mid:3,treble:7,gate:-55},cab:{type:"4x12",mic:.2}},fuzz:{stomp:{type:"fuzz",gain:7,tone:.5},head:{type:"clean",gain:4},cab:{type:"2x12"}},octave:{stomp:{type:"octave",gain:6,tone:.6,octave:.8},head:{type:"clean",gain:3},cab:{type:"1x12"}},funk:{stomp:void 0,head:{type:"clean",gain:2,treble:7,presence:6},cab:{type:"2x12"},autofilter:{type:"bpf",sync:0,rate:.01,depth:0,follow:3,cutoff:500,resonance:.6}},wah:{stomp:void 0,head:{type:"crunch",gain:4},cab:{type:"2x12"},autofilter:{type:"bpf",sync:.5,depth:2,shape:"sine",cutoff:700,resonance:.6}},bachata:{stomp:void 0,head:{type:"clean",gain:2,mid:6,treble:7},cab:{type:"1x12",mic:.2},chorus:{rate:.8,depth:.25,mix:.3}},spring:{stomp:void 0,head:{type:"clean",gain:3,treble:6},cab:{type:"open"}},bassdrive:{stomp:{type:"od",gain:4,tone:.5,mix:.6},head:{type:"bass",gain:4},cab:{type:"8x10"}},reese:{stomp:{type:"rat",gain:3,tone:.3,mix:.5},head:{type:"bass",gain:6,master:6},cab:{type:"1x15"}},jangle:{stomp:void 0,head:{type:"chime",gain:3,treble:7},cab:{type:"2x12",mic:.2},compressor:{threshold:-20,ratio:4,attack:.01,release:.15}},alt:{stomp:{type:"rat",gain:6,tone:.4},head:{type:"crunch",gain:4},cab:{type:"4x12"}},shoegaze:{stomp:{type:"fuzz",gain:7,tone:.45},head:{type:"chime",gain:4},cab:{type:"2x12"},wobble:{depth:25,rate:.4,drift:.4},bloom:{amount:.4,harm:2,delay:.6,time:1},double:{time:18,drift:2.5,width:.4},postgain:{gain:.86}},glide:{stomp:{type:"face",gain:5,tone:.5},head:{type:"clean",gain:4,treble:5},cab:{type:"2x12"},wobble:{depth:35,rate:.4,drift:.4},postgain:{gain:.8}},dreampop:{stomp:void 0,head:{type:"clean",gain:2,treble:6},cab:{type:"1x12"},chorus:{rate:.6,depth:.3,mix:.35},double:{time:14,drift:2,width:.4},postgain:{gain:1.45}},swell:{stomp:void 0,head:{type:"clean",gain:3,treble:5},cab:{type:"1x12"},swell:{time:.5},postgain:{gain:1.25}},ebow:{stomp:{type:"od",gain:3,tone:.5,level:3},head:{type:"lead",gain:5,mid:6},cab:{type:"4x12"},swell:{time:.25},bloom:{amount:.8,harm:1,delay:.1,time:.6}}}),RIG_REVERBS=Object.freeze({spring:{mix:.3,size:.35,fade:1.5,predelay:0,dim:3500},shoegaze:{mix:.35,size:.9,fade:4,predelay:.02,dim:6e3},glide:{mix:.35,size:.7,fade:2.5,predelay:.01,dim:6e3},dreampop:{mix:.4,size:.85,fade:5,predelay:.03,dim:7e3},swell:{mix:.45,size:.8,fade:4,predelay:.02,dim:6500}});function rig(name,overrides={}){if(typeof name!="string"||!Object.prototype.hasOwnProperty.call(RIG_PRESETS,name))throw new DawnSdkError(`unknown rig "${String(name)}" (rigs: ${Object.keys(RIG_PRESETS).join(", ")})`);if(!isRecord(overrides))throw new DawnSdkError("rig overrides must be an object");let out={};for(let[effect,values]of Object.entries(RIG_PRESETS[name]))values&&effect!=="stomp"&&effect!=="head"&&effect!=="cab"&&(out[effect]=Object.freeze({...values}));for(let stage of["stomp","head","cab"]){let base=RIG_PRESETS[name][stage],extra=overrides[stage];if(extra!==void 0&&!isRecord(extra))throw new DawnSdkError(`rig ${stage} overrides must be an object`);(base||extra)&&(out[stage]=Object.freeze({...base??{},...extra??{}}))}return Object.freeze(out)}var voicedKeys=(instrument,keys)=>Object.freeze({instrument,keys:Object.freeze(keys)}),voicedSynth=(instrument,synth)=>Object.freeze({instrument,synth:Object.freeze(synth)}),acousticVoice=instrument=>Object.freeze({instrument}),ambientVoicings={"felt-piano":w=>voicedKeys("felt",{hardness:.62-.34*w,touch:.88,felt:.48+.46*w,strike:.135,body:"grand",after:.52,decay:1.09,release:1.26,noise:.14,knock:.24,sym:.38,unison:1.28,width:.78}),"tine-piano":w=>voicedKeys("epiano",{hardness:.54-.24*w,bark:.31,bell:.46-.24*w,tone:3900-1500*w,vibe:.19,vibehz:2.1,release:1.28,width:.71}),"reed-piano":w=>voicedKeys("wurli",{hardness:.61-.27*w,bark:.48,bell:.18,tone:3400-1100*w,trem:.13,release:1.17,width:.62}),"prepared-piano":w=>voicedKeys("prepared",{hardness:.49-.21*w,prep:.82,felt:.16,strike:.19,after:.5,knock:.36,noise:.15,width:.67}),"drift-pad":w=>voicedSynth("supersaw",{partials:Object.freeze([1,.67,.83,.24,.52,.12,.23,.08]),attack:1.32,decay:1.1,sustain:.82,release:1.78,unison:3,detune:.115,spread:.76,lpf:1780-980*w,lpq:.66}),"sequence-haze":w=>voicedSynth("supersaw",{partials:Object.freeze([.9,.38,1,.27,.34,.12]),attack:1.48,decay:1.15,sustain:.71,release:1.35,unison:3,detune:.19,spread:.86,lpf:1260-480*w,lpq:.64}),"pulse-sequence":w=>voicedSynth("pulse",{attack:.009,decay:.19,sustain:.13,release:.13,pw:.3,pwrate:.19,pwsweep:.15,lpf:2200-1150*w,lpq:.72,lpenv:.58,lpattack:.008,lpdecay:.14,lpsustain:.09,unison:2,detune:.06,spread:.56}),"round-kick":w=>voicedSynth("sine",{attack:.004,decay:.15,sustain:.012,release:.06,fm:.62-.3*w,fmh:2,penv:12,pattack:0,pdecay:.049}),"offbeat-bass":w=>voicedSynth("triangle",{attack:.015,decay:.2,sustain:.33,release:.09,fm:.51-.22*w,fmh:1,lpf:1160-390*w}),"glass-bell":w=>acousticVoice(modal("crotales",{mallet:"rubber",hardness:.52-.27*w,position:.21,tilt:1.25,ring:3.1,damp:.19,release:.43,click:.055})),"soft-vibes":w=>acousticVoice(modal("vibes",{mallet:"yarn",hardness:.53-.29*w,position:.41,ring:2.75,tilt:1.15,damp:.43,release:.35,click:.035,motor:2.8,motordepth:.13})),marimba:w=>acousticVoice(modal("marimba",{mallet:"yarn",hardness:.6-.28*w,position:.4,ring:1.48,tilt:1.27,click:.06})),"thumb-piano":w=>acousticVoice(modal("kalimba",{hardness:.67-.21*w,position:.68,ring:1.42,tilt:1.12,buzz:.08,click:.12,gain:1.18})),"frame-drum":w=>acousticVoice(modal("bodhran",{mallet:"yarn",hardness:.36-.18*w,position:.31,ring:.61,damp:.59,strikebend:.62,strikedecay:.053,click:.04})),"singing-bowl":w=>acousticVoice(modal("bowl",{hardness:.37-.19*w,position:.2,ring:3.8,tilt:.9,damp:.12,click:.028})),cello:w=>acousticVoice(stringed("cello",{bright:.52-.25*w,pos:.23,pressure:.46,speed:.65,attack:.39,vib:4.65,vibmod:.14,vibdelay:.54,sord:.14+.24*w})),viola:w=>acousticVoice(stringed("viola",{bright:.61-.25*w,pos:.26,pressure:.42,speed:.62,attack:.29,vib:5.25,vibmod:.12,vibdelay:.39,sord:.16+.18*w})),harp:w=>acousticVoice(stringed("harp",{exciter:"finger",bright:.7-.37*w,pos:.24,damp:.39,noise:.025,ring:4.3,release:.64,sym:.24,symtune:"scale"})),dulcimer:w=>acousticVoice(stringed("dulcimer",{bright:.75-.28*w,pos:.19,damp:.44,ring:2.65,sym:.16,unison:2,detune:.045,spread:.46})),"upright-bass":w=>acousticVoice(stringed("upright",{exciter:"finger",bright:.54-.25*w,pos:.3,mute:.12,damp:.54,noise:.035,ring:2.8,release:.19,body:"bass"})),"bamboo-flute":w=>acousticVoice(wind("bansuri",{bright:.59-.28*w,breath:.56,noise:.105,reed:.47,attack:.11,release:.18,vib:4.7,vibmod:.075})),"alto-vowel":w=>acousticVoice(sing("ooh",{voice:"alto",vowel:"u>a",morph:.34,bright:.54-.25*w,breath:.16,jitter:.15,shimmer:.17,attack:.78,release:1.12,vib:4.85,vibmod:.085,vibdelay:.63})),"tenor-vowel":w=>acousticVoice(sing("airy",{voice:"tenor",vowel:"o",bright:.48-.24*w,breath:.19,jitter:.11,shimmer:.14,attack:.94,release:1.25,vib:4.45,vibmod:.095,vibdelay:.75}))},ambientVoicingNames=Object.freeze(Object.keys(ambientVoicings));function ambientVoicing(name,warmth=.5){if(!Object.hasOwn(ambientVoicings,name))throw new DawnSdkError("unknown ambient voicing: "+name);return ambientVoicings[name](unit(warmth,"ambient voicing warmth"))}var DEFAULT_GLIDE_SECONDS=.06,DEFAULT_FIXED_VELOCITY=.8;function trackPerformance(input,name){let out={};if(input.glide!==void 0){let raw=typeof input.glide=="number"?{time:input.glide}:input.glide;if(!isRecord(raw))throw new DawnSdkError(`track ${name}: glide must be seconds or { time, mode }`);let mode=raw.mode??"legato";if(!["legato","mono","poly"].includes(mode))throw new DawnSdkError(`track ${name}: glide mode must be legato, mono or poly`);out.glide=Object.freeze({time:finite(raw.time??DEFAULT_GLIDE_SECONDS,`${name} glide time`),mode})}let pedalLane=(key,states)=>{let value=input[key];if(value===void 0)return;let shape=`[beat, ${states.map(state=>`"${state}"`).join(" | ")}]`;if(!Array.isArray(value)||value.length>1024)throw new DawnSdkError(`track ${name}: ${key} must be at most 1024 ${shape} events`);value.length>0&&(out[key]=Object.freeze(value.map((event,index)=>{if(!Array.isArray(event)||event.length!==2||!states.includes(event[1]))throw new DawnSdkError(`track ${name}: ${key}[${index}] must be ${shape}`);return Object.freeze([beat(event[0],`${name} ${key}[${index}] beat`),event[1]])})))};if(pedalLane("pedal",["down","half","up"]),pedalLane("softPedal",["down","half","up"]),pedalLane("sostenuto",["down","up"]),input.velocityCurve!==void 0){let raw=typeof input.velocityCurve=="string"?{curve:input.velocityCurve}:input.velocityCurve;if(!isRecord(raw)||!["linear","soft","hard","fixed"].includes(raw.curve))throw new DawnSdkError(`track ${name}: velocityCurve must be linear, soft, hard or fixed`);raw.curve==="fixed"?out.velocityCurve=Object.freeze({curve:"fixed",fixed:unit(raw.fixed??DEFAULT_FIXED_VELOCITY,`${name} velocityCurve fixed`)}):raw.curve!=="linear"&&(out.velocityCurve=Object.freeze({curve:raw.curve}))}if(input.humanize!==void 0){if(!isRecord(input.humanize))throw new DawnSdkError(`track ${name}: humanize must be { timing, velocity, length, seed }`);let amount=key=>{let value=input.humanize[key];return value===void 0?0:finite(value,`${name} humanize ${key}`)},timing=amount("timing"),velocity=amount("velocity"),length=amount("length"),seed=input.humanize.seed??1;if(!Number.isInteger(seed)||seed<0)throw new DawnSdkError(`track ${name}: humanize seed must be an integer \u2265 0`);(timing!==0||velocity!==0||length!==0)&&(out.humanize=Object.freeze({...timing!==0?{timing}:{},...velocity!==0?{velocity}:{},...length!==0?{length}:{},seed}))}return out}var ZZFX_LAYOUT=Object.freeze(["gain","zrand",null,"attack",null,"release","shape","curve","slide","deltaSlide","pitchJump","pitchJumpTime","lfo","noise","zmod","zcrush","zdelay","sustain","decay","tremolo","filter"]),ZZFX_SHAPES=Object.freeze(["z_sine","z_triangle","z_sawtooth","z_tan","z_noise","z_square"]);function engineField(input,name){let fields=[["wind",WIND_INSTRUMENT,wind],["sing",SING_INSTRUMENT,sing]].filter(([key2])=>input[key2]!==void 0&&input[key2]!==null);if(fields.length===0)return;if(fields.length>1)throw new DawnSdkError(`track ${name}: use wind: or sing:, not both`);let[key,word2,make]=fields[0];if(input.instrument!==void 0&&input.instrument!==word2)throw new DawnSdkError(`track ${name}: ${key}: needs instrument "${word2}" or none (got ${typeof input.instrument=="string"?`"${input.instrument.slice(0,32)}"`:"an engine spec"})`);let value=input[key];if(typeof value=="string")return make(value);if(!isRecord(value))throw new DawnSdkError(`track ${name}: ${key}: must be a preset word or an object`);let{preset:preset5,...params2}=value;return make(preset5??params2,preset5===void 0?{}:params2)}function track(input){if(!isRecord(input))throw new DawnSdkError("track() needs an object");if(typeof input.name!="string"||input.name.trim().length===0)throw new DawnSdkError("track name must be a non-empty string");if(input.name.length>96)throw new DawnSdkError("track name must be at most 96 characters");let name=input.name,slug=slugify(name),id=input.id??slug;if(typeof id!="string"||id.length===0||id.length>64)throw new DawnSdkError(`track ${name}: id must be 1..64 characters`);let patchValue=trackPatchValue(input.instrument,name),fxPatches=trackFxPatches(input.fx,name);if(patchValue||fxPatches){let{patch:_patch,...effects}=isRecord(input.fx)?input.fx:{};input={...input,...patchValue?{instrument:PATCH_INSTRUMENT_WORD}:{},...fxPatches?{fx:effects}:{}}}let rawInstrument=engineField(input,name)??input.instrument??"sine",keptSampler=isRecord(input.sampler)&&input.sampler.kind==="sampler"&&isRecord(rawInstrument)&&rawInstrument.kind==="granular"?localizeSampler(input.sampler,slug):null;if(input.sampler!==void 0&&input.sampler!==null&&!keptSampler)throw new DawnSdkError(`track ${name}: sampler: is only for a granular(...) track; use instrument: sampler({...})`);let samplerSpec=isRecord(rawInstrument)&&rawInstrument.kind==="sampler"?localizeSampler(rawInstrument,slug):keptSampler,playedWavetable=isRecord(rawInstrument)&&rawInstrument.kind==="wavetable";if(input.wavetable!==void 0&&input.wavetable!==null){if(!isRecord(input.wavetable)||input.wavetable.kind!=="wavetable")throw new DawnSdkError(`track ${name}: wavetable: takes wavetable(...)`);if(playedWavetable||typeof rawInstrument=="string"&&rawInstrument.trim().toLowerCase()===WAVETABLE_INSTRUMENT)throw new DawnSdkError(`track ${name}: a wavetable track sets its table in instrument: wavetable(...)`)}let wavetableSpec=playedWavetable?localizeWavetable(rawInstrument,slug):isRecord(input.wavetable)?localizeWavetable(input.wavetable,slug):null,stringFromInstrument=isRecord(rawInstrument)&&rawInstrument.kind==="string"?stringInput(rawInstrument,name):null,granularFromInstrument=isRecord(rawInstrument)&&rawInstrument.kind==="granular"?granularInput(rawInstrument,name,slug):null,word2=typeof rawInstrument=="string"?resolveInstrumentWord(rawInstrument):void 0,modalSpec=trackModal(rawInstrument),guitarSpec=guitarInput(input.guitar,`track ${name}`),windSpec=trackWind(rawInstrument),singSpec=trackSing(rawInstrument),vocoderSpec=trackVocoder(rawInstrument,input.vocoder),textureSpec=trackTexture(rawInstrument),instrument=granularFromInstrument?GRANULAR_INSTRUMENT:samplerSpec?SAMPLER_INSTRUMENT:playedWavetable?WAVETABLE_INSTRUMENT:stringFromInstrument?STRING_INSTRUMENT:modalSpec?MODAL_INSTRUMENT:windSpec?WIND_INSTRUMENT:singSpec?SING_INSTRUMENT:isRecord(rawInstrument)&&rawInstrument.kind==="vocoder"?VOCODER_INSTRUMENT:textureSpec?TEXTURE_INSTRUMENT:typeof rawInstrument=="string"?word2?.instrument??rawInstrument:void 0,granularSpec=granularInput(input.granular,name,slug)??granularFromInstrument??(word2?.field==="granular"&&word2.preset?Object.freeze({preset:word2.preset}):instrument===GRANULAR_INSTRUMENT?Object.freeze({}):null);if(instrument===void 0||instrument.length===0||instrument.length>64)throw new DawnSdkError(`track ${name}: instrument must be a voice name, "kit", sampler(...), wavetable(...), stringed(...), granular(...) or modal(...)`);if(instrument===SAMPLER_INSTRUMENT&&!samplerSpec)throw new DawnSdkError(`track ${name}: use instrument: sampler({...}) for a sampler track`);let slots=samplerSpec&&instrument===SAMPLER_INSTRUMENT?voiceSlots(samplerSpec):void 0,kit2=KIT_INSTRUMENTS.includes(instrument.trim().toLowerCase()),notes=(input.notes??[]).map((item,index)=>{if(!isRecord(item)||item.kind!=="note"&&item.kind!=="hit")throw new DawnSdkError(`track ${name}: notes[${index}] must come from note(), seq(), hit() or hits()`);if(item.kind==="note")return item;let spec=item,pitch2=kit2?DRUM_PITCHES[DRUM_ALIASES[spec.voice.trim().toLowerCase()]??void 0]:slots?.get(spec.voice);if(pitch2===void 0)throw new DawnSdkError(kit2?`track ${name}: unknown drum "${spec.voice}" (kick snare clap rim tom hat openhat)`:slots?`track ${name}: unknown sampler voice "${spec.voice}" (${[...slots.keys()].join(" ")})`:`track ${name}: hit("${spec.voice}") needs instrument "kit" or sampler(...)`);let{kind:_kind,voice:_voice,...rest}=spec;return Object.freeze({...rest,kind:"note",pitch:pitch2})});if(notes.length>4096)throw new DawnSdkError(`track ${name}: at most 4096 notes`);let rhythm=input.rhythm??[];if(!Array.isArray(rhythm)||rhythm.length>16)throw new DawnSdkError(`track ${name}: rhythm must be at most 16 rows`);rhythm.forEach((row2,index)=>{if(!isRecord(row2)||row2.kind!=="rhythm")throw new DawnSdkError(`track ${name}: rhythm[${index}] must come from euclid() or grid()`)});let drumKit=input.kit??null;if(drumKit!==null&&(typeof drumKit!="string"||drumKit.trim().length===0||!kit2))throw new DawnSdkError(`track ${name}: kit needs instrument "kit" and a kit name`);let automation=input.automation??{};if(!isRecord(automation))throw new DawnSdkError(`track ${name}: automation must be an object`);let lane=key=>{let points=automation[key];if(points===void 0)return Object.freeze([]);if(!Array.isArray(points)||points.length>256)throw new DawnSdkError(`track ${name}: automation.${key} must be an array of at most 256 [beat, value] points`);return Object.freeze(points.map((point,index)=>{if(!Array.isArray(point)||point.length!==2)throw new DawnSdkError(`track ${name}: automation.${key}[${index}] must be [beat, value]`);return Object.freeze([beat(point[0],`automation.${key}[${index}] beat`),finite(point[1],`automation.${key}[${index}] value`)])}))};for(let key of Object.keys(automation))if(!AUTOMATION_KEYS.includes(key))throw new DawnSdkError(`track ${name}: unknown automation lane "${key}" (${AUTOMATION_KEYS.join(" ")})`);let presetFx=keysPresetFx(input.keys,rawInstrument);presetFx&&(input={...input,...input.filter===void 0&&presetFx.filter?{filter:presetFx.filter}:{},...input.reverb===void 0&&presetFx.reverb?{reverb:presetFx.reverb}:{},...presetFx.fx&&input.fx!==null?{fx:{...presetFx.fx,...isRecord(input.fx)?input.fx:{}}}:{}});let filter=input.filter===void 0||input.filter===null?null:Object.freeze({cutoff:finite(input.filter.cutoff,`${name} filter.cutoff`),resonance:finite(input.filter.resonance??0,`${name} filter.resonance`),...extras(input.filter,["type","ftype"],`${name} filter`)}),delay=input.delay===void 0||input.delay===null?null:Object.freeze({beats:finite(input.delay.beats,`${name} delay.beats`),feedback:finite(input.delay.feedback??.3,`${name} delay.feedback`),mix:finite(input.delay.mix??.35,`${name} delay.mix`),...extras(input.delay,["time","pingpong","highcut"],`${name} delay`)});if(input.reverb===void 0&&typeof rawInstrument=="string"){let rigName=resolveInstrumentWord(rawInstrument)?.fx,wash=rigName===void 0?void 0:RIG_REVERBS[rigName];wash&&(input={...input,reverb:wash})}let reverb=input.reverb===void 0||input.reverb===null?null:Object.freeze({mix:finite(input.reverb.mix,`${name} reverb.mix`),size:finite(input.reverb.size??.5,`${name} reverb.size`),...extras(input.reverb,["fade","lowpass","dim","predelay","center"],`${name} reverb`),...input.reverb.ir===void 0?{}:{ir:reverbIr(input.reverb.ir,name,slug)}}),aliasRig=typeof rawInstrument=="string"?resolveInstrumentWord(rawInstrument)?.fx:void 0,fx=fxInput(aliasRig===void 0?input.fx:{...rig(aliasRig),...isRecord(input.fx)?input.fx:{}},name),synth=synthInput(input.synth,name),string=stringInput(input.string,name)??stringFromInstrument??(word2?.field==="string"&&word2.preset?Object.freeze({preset:word2.preset}):null);return Object.freeze({kind:"track",id,name,slug,instrument,muted:bool(input.muted??!1,`${name} muted`),solo:bool(input.solo??!1,`${name} solo`),volume:finite(input.volume??1,`${name} volume`),pan:finite(input.pan??0,`${name} pan`),filter,delay,reverb,fx,synth,sampler:samplerSpec,wavetable:wavetableSpec,...string?{string}:{},...granularSpec?{granular:granularSpec}:{},automation:Object.freeze({volume:lane("volume"),pan:lane("pan"),filter:lane("filter"),resonance:lane("resonance"),delayFeedback:lane("delayFeedback"),delayMix:lane("delayMix"),fx:fxLanes(automation.fx,name),wt:lane("wt")}),notes:Object.freeze(notes),rhythm:Object.freeze([...rhythm]),kit:drumKit===null?null:drumKit.trim(),...trackTime(input.time,name),...trackPerformance(input,name),tuning:tuningSpec(input.tuning,`track ${name}`),...keysSpec(input.keys,rawInstrument,name),...modalSpec?{modal:modalSpec}:{},...textureSpec?{texture:textureSpec}:{},...guitarSpec?{guitar:guitarSpec}:{},...windSpec?{wind:windSpec}:{},...singSpec?{sing:singSpec}:{},...trackClips(input,name,slug),...vocoderSpec?{vocoder:vocoderSpec}:{},...input.autotune!==void 0?{autotune:autotuneInput(input.autotune,`track ${name}`)}:{},...input.vox!==void 0&&input.vox!==null?{vox:trackVoxInput(input.vox,`track ${name} vox`)}:{},...patchValue?{patch:patchValue}:{},...fxPatches?{fxPatch:fxPatches}:{},...trackSignals(input,name)})}var PATCH_INSTRUMENT_WORD="patch";function trackPatchValue(value,name){if(!isPatchValue(value))return null;if("ref"in value)return value;if(value.role!=="instrument")throw new DawnSdkError(`track ${name}: ${value.name} is an effect patch; place it with fx: { patch: [...] }`);return value}function trackFxPatches(fx,name){if(!isRecord(fx)||fx.patch===void 0)return null;if(!Array.isArray(fx.patch)||fx.patch.length>8)throw new DawnSdkError(`track ${name}: fx.patch must be a list of at most 8 effect patches`);for(let value of fx.patch)if(!isPatchValue(value)||"ref"in value||value.role!=="effect")throw new DawnSdkError(`track ${name}: fx.patch takes effect patches from fxPatch()`);return fx.patch.length>0?Object.freeze([...fx.patch]):null}function signalRecord(input,label){if(input==null)return null;if(!isRecord(input))throw new DawnSdkError(`${label} must be an object`);let out={};for(let[key,value]of Object.entries(input))if(value!==void 0){if(!isPatternSignal(value))throw new DawnSdkError(`${label}.${key} must be a signal (sine, saw, pat("\u2026"), \u2026)`);out[key]=value instanceof PatternSignal?value:signalFromData(value)}return Object.keys(out).length>0?Object.freeze(out):null}function trackSignals(input,name){let mods=signalRecord(input.mods,`track ${name}: mods`),lanes=signalRecord(input.lanes,`track ${name}: lanes`);return{...mods?{mods}:{},...lanes?{lanes}:{}}}var KEYS_PRESET_FX=Object.freeze({ballad:{reverb:{mix:.25,size:.7}},felt:{reverb:{mix:.2,size:.5}},lofi:{filter:{cutoff:3500,resonance:.1},fx:{crush:{bits:10}}},pipe:{reverb:{mix:.35,size:.9}},flutes:{reverb:{mix:.3,size:.8}},cornet:{reverb:{mix:.3,size:.8}},reeds:{reverb:{mix:.3,size:.85}},celeste:{reverb:{mix:.35,size:.9}}});function keysPresetFx(keys,word2){if(typeof word2!="string")return;let meaning=resolveInstrumentWord(word2);if(!(meaning?.field!=="keys"||!meaning.preset)&&!(keys!=null&&word2===meaning.instrument))return KEYS_PRESET_FX[meaning.preset]}function keysSpec(input,word2,name){let meaning=typeof word2=="string"?resolveInstrumentWord(word2):void 0,preset5=meaning?.field==="keys"?meaning.preset:void 0;if(input==null)return preset5?{keys:Object.freeze({preset:preset5})}:{};if(!isRecord(input))throw new DawnSdkError(`track ${name}: keys must be an object`);let out={};preset5&&input.preset===void 0&&word2!==meaning?.instrument&&(out.preset=preset5);for(let[key,value]of Object.entries(input))if(value!==void 0){if(key==="stops"&&Array.isArray(value)){if(!value.every(stop=>typeof stop=="string"))throw new DawnSdkError(`track ${name}: keys.stops must be stop names`);out[key]=value.join(" ");continue}out[key]=effectValue(value,`${name} keys.${key}`)}return{keys:Object.freeze(out)}}function trackModal(raw){if(isRecord(raw)&&raw.kind==="modal"){let{kind:_kind,...fields}=raw;return Object.freeze(fields)}if(typeof raw!="string"||raw===MODAL_INSTRUMENT)return;let meaning=resolveInstrumentWord(raw);if(!(meaning?.instrument!==MODAL_INSTRUMENT||!meaning.preset))return Object.freeze({preset:meaning.preset})}function trackTime(input,name){if(input==null)return{};if(!isRecord(input))throw new DawnSdkError(`track ${name}: time must be an object`);for(let key of Object.keys(input))if(key!=="rate"&&key!=="phase"&&key!=="cycle"&&key!=="steps")throw new DawnSdkError(`track ${name}: time takes rate, phase, cycle and steps, not ${key}`);let out={};if(input.rate!==void 0){let rate2=finite(input.rate,`track ${name} time.rate`);if(rate2<.125||rate2>8)throw new DawnSdkError(`track ${name}: time.rate must be 0.125..8`);rate2!==1&&(out.rate=rate2)}if(input.phase!==void 0){let phase=finite(input.phase,`track ${name} time.phase`);phase!==0&&(out.phase=phase)}if(input.cycle!==void 0){let cycle=finite(input.cycle,`track ${name} time.cycle`);if(cycle<=0)throw new DawnSdkError(`track ${name}: time.cycle must be > 0 beats`);out.cycle=cycle}if(input.steps!==void 0){if(!isRecord(input.steps))throw new DawnSdkError(`track ${name}: time.steps must be an object`);if(out.cycle===void 0)throw new DawnSdkError(`track ${name}: time.steps needs a cycle`);if(out.rate!==void 0)throw new DawnSdkError(`track ${name}: time takes rate or steps, not both`);out.steps=phaseSteps(input.steps,out.cycle,`track ${name} time.steps`)}return Object.keys(out).length>0?{time:Object.freeze(out)}:{}}function phaseSteps(input,cycle,label){let shift=positive(input.shift,`${label}.shift`);if(shift>cycle)throw new DawnSdkError(`${label}.shift must be at most the cycle`);let hold=finite(input.hold,`${label}.hold`);if(!Number.isInteger(hold)||hold<0||hold>64)throw new DawnSdkError(`${label}.hold must be a whole 0..64 cycles`);let drift=finite(input.drift,`${label}.drift`);if(!Number.isInteger(drift)||drift<1||drift>64)throw new DawnSdkError(`${label}.drift must be a whole 1..64 cycles`);return Object.freeze({shift,hold,drift})}var AUTOMATION_KEYS=Object.freeze(["volume","pan","filter","resonance","delayFeedback","delayMix","fx","wt"]);function effectValue(value,label){return typeof value=="string"||typeof value=="boolean"?value:finite(value,label)}function extras(input,keys,label){let out={};for(let key of keys){let value=input[key];value!==void 0&&(out[key]=effectValue(value,`${label}.${key}`))}return out}function fxInput(input,name){if(input==null)return null;if(!isRecord(input))throw new DawnSdkError(`track ${name}: fx must be an object of effects`);let out={};for(let[effect,params2]of Object.entries(input)){if(!isRecord(params2))throw new DawnSdkError(`track ${name}: fx.${effect} must be an object`);let values={};for(let[key,value]of Object.entries(params2))values[key]=effectValue(value,`${name} fx.${effect}.${key}`);out[effect]=Object.freeze(values)}return Object.keys(out).length>0?Object.freeze(out):null}function stringInput(input,name){if(input==null)return null;if(!isRecord(input))throw new DawnSdkError(`track ${name}: string must be an object`);let out={};for(let[key,value]of Object.entries(input))value===void 0||key==="kind"||(out[key]=typeof value=="string"?value:finite(value,`${name} string.${key}`));return Object.freeze(out)}function synthInput(input,name){if(input==null)return null;if(!isRecord(input))throw new DawnSdkError(`track ${name}: synth must be an object`);let out={};for(let[key,value]of Object.entries(input))value!==void 0&&(out[key]=Array.isArray(value)?Object.freeze(value.map((n2,index)=>finite(n2,`${name} synth.${key}[${index}]`))):effectValue(value,`${name} synth.${key}`));return Object.keys(out).length>0?Object.freeze(out):null}function fxLanes(input,name){if(input===void 0)return Object.freeze({});if(!isRecord(input))throw new DawnSdkError(`track ${name}: automation.fx must be an object`);let out={};for(let[key,points]of Object.entries(input)){if(!Array.isArray(points)||points.length>256)throw new DawnSdkError(`track ${name}: automation.fx["${key}"] must be an array of at most 256 [beat, value] points`);out[key]=Object.freeze(points.map((point,index)=>{if(!Array.isArray(point)||point.length!==2)throw new DawnSdkError(`track ${name}: automation.fx["${key}"][${index}] must be [beat, value]`);return Object.freeze([beat(point[0],`automation.fx["${key}"][${index}] beat`),finite(point[1],`automation.fx["${key}"][${index}] value`)])}))}return Object.freeze(out)}function slugify(name){let slug=name.normalize("NFKD").replace(new RegExp("\\p{M}+","gu"),"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,64).replace(/-+$/g,"");return slug.length>0?slug:"track"}function voiceSlots(spec){let slots=new Map;return spec.mode!=="oneshot"||Object.keys(spec.voices).sort().forEach((voice,index)=>slots.set(voice,SAMPLER_FIRST_SLOT+index)),slots}function reverbIr(value,name,slug){let spec=typeof value=="string"?{src:value}:value;if(!isRecord(spec)||typeof spec.src!="string"||spec.src.length===0)throw new DawnSdkError(`track ${name}: reverb.ir needs a src`);let src=spec.src.trim().replace(/^\.\//,"");if(src.startsWith("pack:")){let ref=sampleSpec(spec,`${name} reverb.ir`);return Object.freeze({src:ref.src,...ref.sha256?{sha256:ref.sha256}:{},...ref.url?{url:ref.url}:{},...ref.license?{license:ref.license}:{}})}return src.startsWith("builtin:")||!/[./]/.test(src)||src.startsWith("tracks/")?src:`tracks/${slug}/${src}`}function granularInput(input,name,slug){if(input==null)return null;if(!isRecord(input))throw new DawnSdkError(`track ${name}: granular must be an object`);let out={};for(let[key,value]of Object.entries(input))if(!(value===void 0||key==="kind"))if(key==="src"&&isRecord(value)){let ref=sampleSpec(value,`${name} granular src`),src=ref.src.replace(/^\.\//,"");out.src=Object.freeze({...ref,src:src.startsWith("tracks/")||src.startsWith("pack:")?src:`tracks/${slug}/${src}`})}else if(key==="src"&&typeof value=="string")out.src=value.startsWith("synth:")?value:granularInput({src:{src:value}},name,slug).src;else if(typeof value=="number")out[key]=finite(value,`${name} granular.${key}`);else if(typeof value=="string"||typeof value=="boolean")out[key]=value;else throw new DawnSdkError(`${name} granular.${key} must be a value`);return Object.freeze(out)}function localizeWavetable(spec,slug){let src=spec.table.src;if(!/\.wav$/i.test(src)||src.startsWith("pack:"))return spec;let bare=src.replace(/^\.\//,"");return Object.freeze({...spec,table:Object.freeze({...spec.table,src:bare.startsWith("tracks/")?bare:`tracks/${slug}/${bare}`})})}function localizeSampler(spec,slug){let voices={};for(let[name,voice]of Object.entries(spec.voices)){let src=voice.src.replace(/^\.\//,"");voices[name]=Object.freeze({...voice,src:src.startsWith("tracks/")||src.startsWith("pack:")?src:`tracks/${slug}/${src}`})}return Object.freeze({...spec,voices:Object.freeze(voices)})}var STYLE_ID_PATTERN=/^[a-z0-9][a-z0-9-]{0,63}$/;function style(id,options={}){if(typeof id!="string"||!STYLE_ID_PATTERN.test(id))throw new DawnSdkError(`style id must be lowercase words joined by hyphens, like "deep-house"; got ${JSON.stringify(id)}`);if(!isRecord(options))throw new DawnSdkError("style options must be an object");let seed=options.seed??1;if(!Number.isInteger(seed)||seed<0||seed>2147483647)throw new DawnSdkError("style seed must be an integer 0..2147483647");let bars=options.bars??8;if(!Number.isInteger(bars)||bars<1||bars>256)throw new DawnSdkError("style bars must be an integer 1..256");let blend2;if(options.blend!==void 0){let pair2=options.blend;if(!Array.isArray(pair2)||pair2.length!==2||typeof pair2[0]!="string"||!STYLE_ID_PATTERN.test(pair2[0])||typeof pair2[1]!="number"||!(pair2[1]>=0&&pair2[1]<=1))throw new DawnSdkError('style blend must be ["style-id", weight 0..1], like ["bebop", 0.3]');blend2=Object.freeze({id:pair2[0],weight:pair2[1]})}return Object.freeze({id,seed,bars,...blend2?{blend:blend2}:{}})}function songStyle(input){if(input==null)return{};if(!isRecord(input))throw new DawnSdkError('song style must come from style("id", { seed })');let blend2=input.blend;return{style:style(input.id,{seed:input.seed,bars:input.bars,...blend2!=null?isRecord(blend2)?{blend:[blend2.id,blend2.weight]}:{blend:blend2}:{}})}}var MASTER_KEYS=["trim","eq","tone","mseq","glue","multiband","tape","width","clip","limiter","target"];function masterData(input){if(input==null)return;if(!isRecord(input))throw new DawnSdkError("song master must be an object");let out={};for(let[key,value]of Object.entries(input))if(value!==void 0){if(!MASTER_KEYS.includes(key))throw new DawnSdkError(`song master has no "${key}"; use ${MASTER_KEYS.join(", ")}`);if(key==="target"){if(typeof value=="string")throw new DawnSdkError(`song master target takes LUFS, e.g. target: -14 (streaming), -8 (club, with limiter: { release: 60, lookahead: 2 }), -6 (loud, with limiter: { release: 20, lookahead: 1 }); got "${value}"`);out.target=finite(value,"song master target");continue}if(!isRecord(value))throw new DawnSdkError(`song master ${key} must be an object`);out[key]=Object.freeze({...value})}return Object.keys(out).length>0?Object.freeze(out):void 0}function parseSongForm(form){let items=typeof form=="string"?(form.includes(",")?form.split(","):form.trim().split(/\s+/u)).map(item=>item.trim()).filter(item=>item!==""):Array.isArray(form)?[...form]:(()=>{throw new DawnSdkError("song form must be a string or an array of section names")})();return Object.freeze(items.map((item,index)=>{let entry=item;if(typeof item=="string"){let match=/^(.*?)\s*(?:\*|\bx|×)\s*(\d+)$/iu.exec(item);entry=match&&match[1].length>0?{section:match[1],repeat:Number(match[2])}:{section:item}}if(!isRecord(entry)||typeof entry.section!="string")throw new DawnSdkError(`song form[${index}] must be a section name or { section, repeat }`);let repeat=entry.repeat??1;if(!Number.isInteger(repeat)||repeat<1||repeat>16)throw new DawnSdkError(`song form[${index}] repeat must be 1..16`);return Object.freeze(repeat===1?{section:entry.section}:{section:entry.section,repeat})}))}function songSections(sections){if(!Array.isArray(sections))throw new DawnSdkError("song sections must be an array");if(sections.length>64)throw new DawnSdkError("song has over 64 sections");return Object.freeze(sections.map((section,index)=>{let where2=`song sections[${index}]`;if(!isRecord(section)||typeof section.name!="string")throw new DawnSdkError(`${where2} needs a name`);let stored={name:section.name,startBar:finite(section.startBar,`${where2}.startBar`),bars:finite(section.bars,`${where2}.bars`)};if(section.mute!==void 0){if(!Array.isArray(section.mute)||section.mute.some(id=>typeof id!="string"))throw new DawnSdkError(`${where2}.mute must be track ids`);section.mute.length>0&&(stored.mute=Object.freeze([...section.mute]))}if(section.vary!==void 0){if(!isRecord(section.vary))throw new DawnSdkError(`${where2}.vary must be an object`);let vary=Object.entries(section.vary);vary.length>0&&(stored.vary=Object.freeze(Object.fromEntries(vary.map(([id,change])=>{if(!isRecord(change))throw new DawnSdkError(`${where2}.vary.${id} must be an object`);let out={};return change.transpose!==void 0&&(out.transpose=finite(change.transpose,`${where2}.vary.${id}.transpose`)),change.gain!==void 0&&(out.gain=finite(change.gain,`${where2}.vary.${id}.gain`)),[id,Object.freeze(out)]}))))}return Object.freeze(stored)}))}var SONG_CALIBRATION_LATEST=1;function songLoop(input,bars){if(typeof input!="string"||input.trim()==="")throw new DawnSdkError('song loop must be bars "5-6" or a section name');let match=/^\s*(\d{1,4})\s*(?:-|–|\.\.)?\s*(\d{1,4})?\s*$/u.exec(input);if(!match)return input.trim();let from=Number(match[1]),to=match[2]===void 0?from:Number(match[2]);if(from<1||to<from)throw new DawnSdkError(`song loop "${input}" runs low-high from bar 1`);if(to>bars)throw new DawnSdkError(`song loop "${input}" is past the song's ${bars} bars`);return Object.freeze({startBar:from-1,bars:to-from+1})}function song(input){if(!isRecord(input))throw new DawnSdkError("song() needs an object");let tempoBpm=finite(input.tempo??120,"song tempo"),meter=input.meter??4,beatsPerBar=Array.isArray(meter)?finite(meter[0],"song meter[0]"):finite(meter,"song meter"),beatUnit=Array.isArray(meter)?finite(meter[1],"song meter[1]"):4;if(![1,2,4,8,16,32].includes(beatUnit))throw new DawnSdkError("song meter note value must be 1, 2, 4, 8, 16 or 32");let bars=finite(input.bars??4,"song bars"),ticksPerBeat=input.ticksPerBeat??480;if(!Number.isInteger(ticksPerBeat)||ticksPerBeat<1||ticksPerBeat>4096)throw new DawnSdkError("song ticksPerBeat must be an integer 1..4096");let key=input.key??null;if(key!==null&&typeof key!="string")throw new DawnSdkError("song key must be a string or null");let songTuning=tuningSpec(input.tuning,"song"),master=masterData(input.master),calibration=input.calibration??0;if(typeof calibration!="number"||!Number.isInteger(calibration)||calibration<0||calibration>SONG_CALIBRATION_LATEST)throw new DawnSdkError(`song calibration must be an integer 0..${SONG_CALIBRATION_LATEST}`);if(!Array.isArray(input.tracks))throw new DawnSdkError("song tracks must be an array of track()");if(input.tracks.length>64)throw new DawnSdkError("song has over 64 tracks");let ticks=beats=>Math.round(beats*ticksPerBeat),points=lane=>Object.freeze(lane.map(([at3,value])=>Object.freeze({tick:ticks(at3),value}))),seen=new Set,tracks=[],notes=[],noteIds=new Set,library=songPatches(input.patches),ticksPerBar=Math.round(beatsPerBar*ticksPerBeat);input.tracks.forEach((spec,index)=>{if(!isRecord(spec)||spec.kind!=="track")throw new DawnSdkError(`song tracks[${index}] must come from track()`);let t=spec;if(seen.has(t.id))throw new DawnSdkError(`song has two tracks with id "${t.id}"`);seen.add(t.id);let filterAutomation=points(t.automation.filter),resonanceAutomation=points(t.automation.resonance),delayFeedbackAutomation=points(t.automation.delayFeedback),delayMixAutomation=points(t.automation.delayMix),wtAutomation=points(t.automation.wt??[]),stored={id:t.id,name:t.name,instrument:t.instrument,muted:t.muted,volume:t.volume,pan:t.pan,volumeAutomation:points(t.automation.volume),panAutomation:points(t.automation.pan)};t.solo&&(stored.solo=!0),t.filter&&(stored.filter=t.filter),t.delay&&(stored.delay=t.delay),filterAutomation.length>0&&(stored.filterAutomation=filterAutomation),resonanceAutomation.length>0&&(stored.resonanceAutomation=resonanceAutomation),delayFeedbackAutomation.length>0&&(stored.delayFeedbackAutomation=delayFeedbackAutomation),delayMixAutomation.length>0&&(stored.delayMixAutomation=delayMixAutomation),t.reverb&&(stored.reverb=t.reverb),t.fx&&(stored.fx=t.fx),t.synth&&(stored.synth=t.synth),t.patch&&(stored.patch=t.patch),t.fxPatch&&(stored.fxPatch=t.fxPatch);let written=Object.entries(t.automation.fx??{}).map(([key2,lane])=>[key2,points(lane)]).filter(([,lane])=>lane.length>0),baked=Object.entries(bakeTrackSignals(t,library,{bars,ticksPerBar})).filter(([key2])=>!written.some(([lane])=>lane===key2)),fxLaneEntries=[...written,...baked];if(fxLaneEntries.length>0&&(stored.fxAutomation=Object.freeze(Object.fromEntries(fxLaneEntries))),t.wavetable){let{kind:_kind,...fields}=t.wavetable;stored.wavetable=Object.freeze(fields)}if(wtAutomation.length>0&&(stored.wtAutomation=wtAutomation),t.granular&&(stored.granular=t.granular),t.sampler&&(stored.sampler=Object.freeze({voices:t.sampler.voices,mode:t.sampler.mode})),t.kit&&(stored.kit=t.kit),t.time){let time={};if(t.time.rate!==void 0&&(time.rate=t.time.rate),t.time.phase!==void 0){let phase=ticks(t.time.phase);phase!==0&&(time.phase=phase)}t.time.cycle!==void 0&&(time.cycle=Math.max(1,ticks(t.time.cycle))),t.time.steps&&(time.steps=Object.freeze({...t.time.steps,shift:Math.max(1,ticks(t.time.steps.shift))})),Object.keys(time).length>0&&(stored.time=Object.freeze(time))}t.glide&&(stored.glide=t.glide);for(let key2 of["pedal","softPedal","sostenuto"]){let lane=t[key2];if(!lane||lane.length===0)continue;let byTick=new Map;for(let[at3,state]of lane)byTick.set(ticks(at3),state);stored[key2]=Object.freeze([...byTick.entries()].sort((a,b)=>a[0]-b[0]).map(([tick,state])=>Object.freeze({tick,state})))}t.velocityCurve&&(stored.velocityCurve=t.velocityCurve),t.humanize&&(stored.humanize=t.humanize),t.tuning&&(stored.tuning=t.tuning),t.string&&(stored.string=t.string),t.keys&&(stored.keys=t.keys),t.modal&&(stored.modal=t.modal),t.texture&&(stored.texture=t.texture),t.guitar&&(stored.guitar=t.guitar),t.wind&&(stored.wind=t.wind),t.sing&&(stored.sing=t.sing),t.clips&&t.clips.length>0&&(stored.clips=Object.freeze(t.clips.map((clip,index2)=>storedClip(clip,index2,ticks)))),t.takes&&t.takes.length>0&&(stored.takes=Object.freeze(t.takes.map(spec2=>storedTake(spec2,ticks)))),t.vocoder&&(stored.vocoder=Object.freeze(t.vocoder.src===void 0?t.vocoder:{...t.vocoder,src:resolveVocoderSrc(input.tracks,t.id,t.vocoder.src)})),t.autotune&&(stored.autotune=t.autotune),t.vox&&(stored.vox=t.vox),t.rhythm&&t.rhythm.length>0&&(stored.rhythm=Object.freeze(t.rhythm.map(row2=>{let{kind:_kind,...fields}=row2;return Object.freeze(fields)}))),tracks.push(Object.freeze(stored));let ids=new Set;for(let n2 of t.notes){let startTick=ticks(n2.start),durationTicks=Math.max(1,ticks(n2.length)),id=n2.id??noteIdFor(t.id,n2.pitch,startTick,durationTicks,n2.velocity,ids);if(noteIds.has(id))throw new DawnSdkError(`track ${t.name}: note id "${id}" is used twice; remove one id and song() derives it`);noteIds.add(id),ids.add(id),notes.push(Object.freeze({id,trackId:t.id,startTick,durationTicks,pitch:n2.pitch,velocity:n2.velocity,...n2.articulation?{articulation:n2.articulation}:{},...n2.glide!==void 0?{glide:n2.glide}:{},...n2.bend?{bend:Object.freeze([...n2.bend].sort((a,b)=>a[0]-b[0]).map(([at3,cents])=>Object.freeze({at:at3,cents})))}:{},...n2.vibrato?{vibrato:n2.vibrato}:{},...n2.humanize?{humanize:n2.humanize}:{},...n2.drift!==void 0?{drift:n2.drift}:{},...n2.cents?{cents:n2.cents}:{},...n2.vowel?{vowel:n2.vowel}:{},...n2.lyric!==void 0?{lyric:n2.lyric}:{},...n2.vox?{vox:n2.vox}:{}}))}});for(let track2 of[...tracks]){let pair2=track2.modal?.pair;if(pair2===void 0)continue;let at3=tracks.findIndex(candidate=>candidate.id===pair2),partner=tracks[at3];partner?.modal&&partner.modal.ombak===void 0&&MODAL_TWIN_PRESETS.includes(String(partner.modal.preset))&&(tracks[at3]=Object.freeze({...partner,modal:Object.freeze({...partner.modal,ombak:0})}))}let arrangement={};if(input.sections!==void 0){let sections=songSections(input.sections);sections.length>0&&(arrangement.sections=sections)}if(input.form!==void 0){let form=parseSongForm(input.form);form.length>0&&(arrangement.form=form)}if(input.loopSection!==void 0){if(typeof input.loopSection!="string")throw new DawnSdkError("song loopSection must be a section name");arrangement.loopSection=input.loopSection}if(input.loop!==void 0){if(input.loopSection!==void 0)throw new DawnSdkError("song sets loop or loopSection, not both");let looped=songLoop(input.loop,bars);typeof looped=="string"?arrangement.loopSection=looped:arrangement.loop=looped}return Object.freeze({format:"track.loop/v1",version:1,tempoBpm,beatsPerBar,bars,ticksPerBeat,key,...songTime(input.time,tempoBpm,ticks,beatsPerBar,ticksPerBeat,beatUnit,bars),...songTuning?{tuning:songTuning}:{},tracks:Object.freeze(tracks),notes:Object.freeze(notes),...master?{master}:{},...songStyle(input.style),...arrangement,...calibration?{calibration}:{},...Object.keys(library).length>0?{patches:Object.freeze(library)}:{}})}function noteIdFor(trackId,pitch2,startTick,durationTicks,velocity,taken){for(let occurrence=0;;occurrence+=1){let id=`n-${hash64(`${trackId}|${pitch2}|${startTick}|${durationTicks}|${velocity}|${occurrence}`)}`;if(!taken.has(id))return id}}function songPatches(input){let out={};if(input===void 0)return out;if(!Array.isArray(input)||input.length>32)throw new DawnSdkError("song patches must be a list of at most 32 patch()");for(let value of input){if(!isPatchValue(value)||"ref"in value)throw new DawnSdkError("song patches must come from patch() or fxPatch()");if(out[value.name])throw new DawnSdkError(`song has two patches named ${value.name}`);out[value.name]=value}return out}function knobPosition(macro2,value){let v=Math.min(macro2.max,Math.max(macro2.min,value)),p=macro2.curve==="exp"?Math.log(v/macro2.min)/Math.log(macro2.max/macro2.min):(v-macro2.min)/(macro2.max-macro2.min);return Number.isFinite(p)?Math.min(1,Math.max(0,p)):0}function bakeTrackSignals(t,library,grid2){let out={};if(!t.patch&&!t.fxPatch&&!t.mods&&!t.lanes)return out;let seed=signalSeed(t.id),bake=(signal,map)=>bakeSignal(signal,{...grid2,seed,...map?{map}:{}}),played=[];if(t.patch)if("ref"in t.patch){let found=library[t.patch.ref];if(!found)throw new DawnSdkError(`track ${t.name}: no patch "${t.patch.ref}" in song({ patches })`);played.push(found)}else played.push(t.patch);played.push(...t.fxPatch??[]);let macros=new Map;for(let p of played)for(let macro2 of p.macros)macros.has(macro2.id)||macros.set(macro2.id,macro2);let signals=[];for(let p of played)signals.push(...patchSignals(p));for(let[id,signal]of Object.entries(t.mods??{})){if(!macros.has(id))throw new DawnSdkError(`track ${t.name}: mods.${id} names no macro of its patches (${[...macros.keys()].join(" ")||"none"})`);signals.push([id,signal])}for(let[id,signal]of signals){let macro2=macros.get(id);out[`patch-${id}`]=bake(signal,value=>knobPosition(macro2,value))}for(let[lane,signal]of Object.entries(t.lanes??{}))out[lane]=bake(signal);return out}var MAX_FERMATA_SECONDS=16.777;function bpmAtTick(tempo,start,tick){let from={tick:0,bpm:start};for(let event of tempo){if(event.tick<=tick){from=event;continue}if(!event.ramp)break;let t=(tick-from.tick)/(event.tick-from.tick);return event.ramp==="exp"?from.bpm*Math.pow(event.bpm/from.bpm,t):from.bpm+(event.bpm-from.bpm)*t}return from.bpm}function songTime(input,tempoBpm,ticks,beatsPerBar,ticksPerBeat,beatUnit=4,bars=1/0){if(input==null&&beatUnit===4)return{};if(input??=[],!Array.isArray(input))throw new DawnSdkError("song time must be an array of time marks");let marks=[];for(let[index,entry]of input.entries())for(let mark of Array.isArray(entry)?entry:[entry]){if(!isRecord(mark)||mark.kind!=="tempo"&&mark.kind!=="meter"&&mark.kind!=="fermata")throw new DawnSdkError(`song time[${index}] must come from tempo(), ramp(), rit(), accel(), fermata() or meter()`);marks.push(mark)}let byTick=new Map;for(let mark of marks){if(mark.kind!=="tempo")continue;let tick=ticks(mark.at),previous=byTick.get(tick),sets=e=>e.bpm!==void 0||e.back!==void 0;if(previous&&sets(previous)&&sets(mark)){let ramped=previous.ramp?previous:mark.ramp?mark:void 0,other=ramped===previous?mark:previous;if(ramped&&!other.ramp&&tick>1&&!byTick.has(tick-1)){byTick.set(tick-1,{tick:tick-1,...ramped.bpm!==void 0?{bpm:ramped.bpm}:{},ramp:ramped.ramp}),byTick.set(tick,{tick,...other.bpm!==void 0?{bpm:other.bpm}:{},...other.back?{back:other.back}:{}});continue}throw new DawnSdkError(`song time has two tempo changes at beat ${mark.at}; move one, or end a rit() where the next tempo starts`)}previous&&!sets(mark)||byTick.set(tick,{tick,...mark.bpm!==void 0?{bpm:mark.bpm}:{},...mark.ramp?{ramp:mark.ramp}:{},...mark.back?{back:mark.back}:{}})}let events=[...byTick.values()].sort((a,b)=>a.tick-b.tick),tempo=[];events.forEach((event,index)=>{if(event.back){let bpm=tempoBpm;if(event.back==="a-tempo"){let last=-1;if(tempo.forEach((e,i)=>{e.ramp!==void 0&&(last=i)}),last<0)throw new DawnSdkError(`aTempo() at beat ${event.tick/ticksPerBeat} has no rit() or accel() before it`);bpm=last>0?tempo[last-1].bpm:tempoBpm}tempo.push(Object.freeze({tick:event.tick,bpm}));return}if(event.bpm!==void 0){let mark=marks.find(m=>m.kind==="tempo"&&ticks(m.at)===event.tick&&m.gradual);if(mark?.gradual){let from=tempo[tempo.length-1]?.bpm??tempoBpm;if(mark.gradual==="rit"&&event.bpm>from)throw new DawnSdkError(`rit() target ${event.bpm} BPM is faster than ${from}; use accel()`);if(mark.gradual==="accel"&&event.bpm<from)throw new DawnSdkError(`accel() target ${event.bpm} BPM is slower than ${from}; use rit()`)}tempo.push(Object.freeze({tick:event.tick,bpm:event.bpm,...event.ramp?{ramp:event.ramp}:{}}));return}if(!events.slice(index+1).find(e=>e.bpm!==void 0||e.back!==void 0)?.ramp)return;let before=tempo[tempo.length-1]?.bpm??tempoBpm;tempo.push(Object.freeze({tick:event.tick,bpm:before}))});let meters=marks.filter(mark=>mark.kind==="meter").sort((a,b)=>a.at-b.at);beatUnit!==4&&!meters.some(mark=>ticks(mark.at)===0)&&meters.unshift({kind:"meter",at:0,beatsPerBar,beatUnit});let meterOut=[],barTick=0,barIndex=0,barLength=beatsPerBar*ticksPerBeat;for(let mark of meters){let tick=ticks(mark.at),bars2=(tick-barTick)/barLength;if(!Number.isInteger(bars2)||bars2<0)throw new DawnSdkError(`meter() at beat ${mark.at} is not on a bar line`);if(meterOut.length>0&&bars2===0)throw new DawnSdkError(`song time has two meters at beat ${mark.at}`);barIndex+=bars2,barTick=tick,barLength=mark.beatsPerBar*ticksPerBeat*4/mark.beatUnit,meterOut.push(Object.freeze({bar:barIndex,beatsPerBar:mark.beatsPerBar,...mark.beatUnit!==4?{beatUnit:mark.beatUnit}:{}}))}let fermatas=marks.filter(mark=>mark.kind==="fermata").map(mark=>Object.freeze({tick:ticks(mark.at),beats:mark.beats})).sort((a,b)=>a.tick-b.tick);for(let i=1;i<fermatas.length;i+=1)if(fermatas[i].tick===fermatas[i-1].tick)throw new DawnSdkError("song time has two fermatas on one beat");if(Number.isFinite(bars)){let end=0,fromBar=0,length=beatsPerBar*ticksPerBeat;for(let change of meterOut){if(change.bar>=bars)break;end+=(change.bar-fromBar)*length,fromBar=change.bar,length=change.beatsPerBar*ticksPerBeat*4/(change.beatUnit??4)}end+=(bars-fromBar)*length;let beatOf=tick=>tick/ticksPerBeat;tempo.forEach((event,index)=>{event.tick===end&&event.ramp&&end-1>(tempo[index-1]?.tick??0)&&(tempo[index]=Object.freeze({...event,tick:end-1}))});for(let event of tempo)if(event.tick>=end)throw new DawnSdkError(`tempo at beat ${beatOf(event.tick)} is past the song end (${beatOf(end)} beats); add bars`);for(let change of meterOut)if(change.bar>=bars)throw new DawnSdkError(`meter() at bar ${change.bar+1} is past the song end (${bars} bars); add bars`);for(let hold of fermatas)if(hold.tick>=end)throw new DawnSdkError(`fermata() at beat ${beatOf(hold.tick)} is past the song end (${beatOf(end)} beats); add bars`)}let feltBeats=tick=>{let at3=0,fromBar=0,meter={beatsPerBar,beatUnit:4},length=beatsPerBar*ticksPerBeat;for(let change of meterOut){let start=at3+(change.bar-fromBar)*length;if(start>tick)break;at3=start,fromBar=change.bar,meter={beatsPerBar:change.beatsPerBar,beatUnit:change.beatUnit??4},length=meter.beatsPerBar*ticksPerBeat*4/meter.beatUnit}if(meterOut.length===0)return 1;let unit4=4/meter.beatUnit,compound=meter.beatUnit>=8&&meter.beatsPerBar>3&&meter.beatsPerBar%3===0;return Math.max(1,compound?unit4*3:unit4)};for(let hold of fermatas){let bpm=bpmAtTick(tempo,tempoBpm,hold.tick),held=(1+hold.beats)*feltBeats(hold.tick)*60/bpm;if(held>MAX_FERMATA_SECONDS+1e-9)throw new DawnSdkError(`fermata() at beat ${hold.tick/ticksPerBeat} holds ${held.toFixed(1)} s; at most ${MAX_FERMATA_SECONDS} s (MIDI tempo limit), so use fewer beats or a faster tempo`)}let time={};return tempo.length>0&&(time.tempo=Object.freeze(tempo)),meterOut.length>0&&(time.meter=Object.freeze(meterOut)),fermatas.length>0&&(time.fermatas=Object.freeze(fermatas)),Object.keys(time).length>0?{time:Object.freeze(time)}:{}}var TUNING_FIELDS=Object.freeze(["name","edo","ratios","cents","scl","kbm","ref","root","map"]);function tuningSpec(input,where2){if(input==null)return null;if(typeof input=="string"){if(input.trim()==="")throw new DawnSdkError(`${where2} tuning must be a name or an object`);return Object.freeze({name:input.trim()})}if(!isRecord(input))throw new DawnSdkError(`${where2} tuning must be a name or an object`);let out={};for(let[field,value]of Object.entries(input)){if(!TUNING_FIELDS.includes(field))throw new DawnSdkError(`${where2} tuning has an unknown field "${field}" (use ${TUNING_FIELDS.join(", ")})`);if(value!=null)if(field==="root")out.root=midi(value);else if(field==="ratios"||field==="cents"){if(!Array.isArray(value))throw new DawnSdkError(`${where2} tuning ${field} must be a list`);out[field]=Object.freeze(field==="ratios"?value.map(ratio2=>String(ratio2)):[...value])}else out[field]=value}let sources=["edo","ratios","cents","scl"].filter(field=>out[field]!==void 0);if(sources.length>1)throw new DawnSdkError(`${where2} tuning has ${sources.join(" and ")}; give one table`);return Object.freeze(out)}function chord(symbol,start=0,length=4,options={}){if(typeof symbol!="string"||parseChord(symbol)===void 0)throw new DawnSdkError(`unknown chord symbol ${JSON.stringify(symbol)}`);return progression([symbol],{...options,from:start,each:length,lead:!1})}function progression(chords,options={}){let symbols=typeof chords=="string"?chords.trim().split(/\s+/):[...chords];if(symbols.length===0||symbols.length>256||symbols[0]==="")throw new DawnSdkError("progression needs 1..256 chords");let key=parseKey(options.key??"C major");if(!key)throw new DawnSdkError(`unknown key ${JSON.stringify(options.key)}`);let parsed=symbols.map(symbol=>{let value=typeof symbol=="string"?resolveChord(key,symbol):void 0;if(!value)throw new DawnSdkError(`unknown chord ${JSON.stringify(symbol)} (roman numeral or symbol)`);return value}),from=beat(options.from??0,"progression from"),each=positive(options.each??4,"progression each"),vel=unit(options.vel??.8,"chord vel"),voicing=finite(options.voicing??0,"chord voicing"),spread=options.spread??"close";if(!SPREADS.includes(spread))throw new DawnSdkError('chord spread must be "close", "open" or "wide"');let mode=options.perform??"block";if(!PERFORM_MODES.includes(mode))throw new DawnSdkError(`unknown chord perform ${JSON.stringify(mode)}`);if(options.bass!==void 0&&!BASS_MODES.includes(options.bass))throw new DawnSdkError(`chord bass must be one of ${BASS_MODES.map(m=>JSON.stringify(m)).join(", ")}`);if(options.pattern!==void 0&&!findChordPattern(options.pattern))throw new DawnSdkError(`unknown chord pattern ${JSON.stringify(options.pattern)} (1..${CHORD_PATTERNS.length} or ${CHORD_PATTERNS.map(p=>p.name).join(", ")})`);let part=options.bass===void 0?options.part??"chords":options.bass==="off"?"chords":options.bass==="solo"?"bass":"both";if(part!=="chords"&&part!=="bass"&&part!=="both")throw new DawnSdkError('chord part must be "chords", "bass" or "both"');let rendered=renderProgression({key,chords:parsed,beatsPerChord:each,start:from,inversion:voicing,spread,bass:part!=="chords",...options.bass==="unison"?{bassMode:"unison"}:{},lead:options.lead??!0,anchor:midi(options.anchor??60),perform:{mode,rate:positive(options.rate??DEFAULT_ARP_RATE,"chord rate"),octaves:finite(options.octaves??1,"chord octaves"),...options.strum!==void 0?{strum:beat(options.strum,"chord strum")}:{},seed:finite(options.seed??0,"chord seed"),...options.pattern!==void 0?{pattern:options.pattern}:{},velocity:vel,...mode==="guitar"?guitarPerform(options):{}}}),out=[...part==="bass"?[]:rendered.notes,...part==="chords"?[]:rendered.bass];if(out.length>4096)throw new DawnSdkError("progression would produce over 4096 notes");return Object.freeze(out.map(n2=>note(n2.pitch,round(n2.start),n2.length,n2.velocity)))}function guitarInput(input,where2){if(input===void 0)return;if(!isRecord(input))throw new DawnSdkError(`${where2} guitar must be an object`);let out={};for(let key of Object.keys(input))if(!["tune","capo","hand","ring","position"].includes(key))throw new DawnSdkError(`${where2} guitar has no field "${key.slice(0,32)}" (tune capo hand ring position)`);if(input.tune!==void 0)if(typeof input.tune=="string"){let name=input.tune.toLowerCase().replace(/[\s_-]/g,"");if(!GUITAR_TUNING_NAMES.includes(name))throw new DawnSdkError(`${where2} guitar tune must be one of ${GUITAR_TUNING_NAMES.join(" ")} or a list of pitches`);out.tune=name}else if(Array.isArray(input.tune)&&input.tune.length>=3&&input.tune.length<=12)out.tune=Object.freeze(input.tune.map(p=>midi(p)));else throw new DawnSdkError(`${where2} guitar tune must be a name or 3..12 pitches`);let int=(key,min,max)=>{let value=input[key];if(value!==void 0){if(!Number.isInteger(value)||value<min||value>max)throw new DawnSdkError(`${where2} guitar ${key} must be an integer ${min}..${max}`);out[key]=value}};return int("capo",0,12),int("hand",3,6),input.ring!==void 0&&(out.ring=Math.round(unit(input.ring,`${where2} guitar ring`)*1e3)/1e3),int("position",0,12),Object.keys(out).length>0?Object.freeze(out):void 0}function guitarPerform(options){if(options.strokes!==void 0&&!strokeGrid(options.strokes))throw new DawnSdkError(`chord strokes must be one of ${STROKE_PATTERN_NAMES.join(" ")} or a grid of D U d u x - .`);let setup=guitarInput(options.guitar,"chord");return{...options.strokes!==void 0?{strokes:options.strokes}:{},...options.step!==void 0?{step:positive(options.step,"chord step")}:{},...options.speed!==void 0?{speed:Math.min(200,Math.max(0,finite(options.speed,"chord speed")))/1e3}:{},...options.tempo!==void 0?{tempo:positive(options.tempo,"chord tempo")}:{},...setup?{guitar:setup}:{}}}var LYRIC_LIMIT=32;var SYL_ONSETS=new Set("bl br cl cr dr fl fr gl gr pl pr sc sk sl sm sn sp st sw tr tw dw thr shr chr phr phl spl spr str scr squ skr".split(" ")),SYL_SILENT_E_HEADS="some home life time love fire side care where there here more one make lone like name game base wide grace face place space stone bone".split(" ");var LEGACY_WORDS=Object.freeze(["piano","pluck","bass","saw","square","triangle","marimba","wind","cello","contrabass","ebass","sitar","organ","strings","bell","keys","lead"]),INSTRUMENT_WORDS=Object.freeze([{word:"nylon",instrument:"string",field:"string",preset:"nylon"},{word:"steel",instrument:"string",field:"string",preset:"steel"},{word:"electric",instrument:"string",field:"string",preset:"electric"},{word:"slap",instrument:"string",field:"string",preset:"slap"},{word:"motown",instrument:"string",field:"string",preset:"motown"},{word:"tanpura",instrument:"string",field:"string",preset:"tanpura"},{word:"harpsichord",instrument:"string",field:"string",preset:"harpsichord"},{word:"lute",instrument:"string",field:"string",preset:"lute"},{word:"oud",instrument:"string",field:"string",preset:"oud"},{word:"setar",instrument:"string",field:"string",preset:"setar"},{word:"tar",instrument:"string",field:"string",preset:"tar"},{word:"santur",instrument:"string",field:"string",preset:"santur"},{word:"dulcimer",instrument:"string",field:"string",preset:"dulcimer"},{word:"koto",instrument:"string",field:"string",preset:"koto"},{word:"harp",instrument:"string",field:"string",preset:"harp"},{word:"banjo",instrument:"string",field:"string",preset:"banjo"},{word:"tres",instrument:"string",field:"string",preset:"tres"},{word:"requinto",instrument:"string",field:"string",preset:"requinto"},{word:"acoustic",instrument:"string",field:"string",preset:"steel"},{word:"classical",instrument:"string",field:"string",preset:"nylon"},{word:"bassguitar",instrument:"string",field:"string",preset:"ebass"},{word:"fender",instrument:"string",field:"string",preset:"ebass"},{word:"doublebass",instrument:"string",field:"string",preset:"upright"},{word:"cembalo",instrument:"string",field:"string",preset:"harpsichord"},{word:"hammered",instrument:"string",field:"string",preset:"dulcimer"},{word:"sehtar",instrument:"string",field:"string",preset:"setar"},{word:"violin",instrument:"string",field:"string",preset:"violin"},{word:"viola",instrument:"string",field:"string",preset:"viola"},{word:"fiddle",instrument:"string",field:"string",preset:"fiddle"},{word:"erhu",instrument:"string",field:"string",preset:"erhu"},{word:"kamancheh",instrument:"string",field:"string",preset:"kamancheh"},{word:"kemence",instrument:"string",field:"string",preset:"kamancheh"},{word:"violins",instrument:"string",field:"string",preset:"violins"},{word:"violas",instrument:"string",field:"string",preset:"violas"},{word:"cellos",instrument:"string",field:"string",preset:"cellos"},{word:"contrabasses",instrument:"string",field:"string",preset:"contrabasses"},{word:"pizzicato",instrument:"string",field:"string",preset:"pizz"},{word:"tremolo",instrument:"string",field:"string",preset:"trem"},{word:"bowed-cello",instrument:"string",field:"string",preset:"cello"},{word:"jangle",instrument:"string",field:"string",preset:"jangle",fx:"jangle"},{word:"punk",instrument:"pluck",voice:"electric",fx:"punk"},{word:"funk",instrument:"pluck",voice:"electric",fx:"funk"},{word:"ragged",instrument:"pluck",voice:"electric",fx:"ragged"},{word:"gtr-lead",instrument:"pluck",voice:"electric",fx:"lead"},{word:"gtr-metal",instrument:"pluck",voice:"electric",fx:"metal"},{word:"bachata",instrument:"pluck",voice:"electric",fx:"bachata"},{word:"granular",instrument:"granular",field:"granular",preset:"cloud"},{word:"grains",instrument:"granular",field:"granular",preset:"cloud"},{word:"cloud",instrument:"granular",field:"granular",preset:"cloud"},{word:"sparkle",instrument:"granular",field:"granular",preset:"sparkle"},{word:"swarm",instrument:"granular",field:"granular",preset:"swarm"},{word:"microloop",instrument:"granular",field:"granular",preset:"microloop"},{word:"grand",instrument:"grand",field:"keys",preset:"grand"},{word:"ballad",instrument:"grand",field:"keys",preset:"ballad"},{word:"upright",instrument:"upright",field:"keys",preset:"upright"},{word:"felt",instrument:"felt",field:"keys",preset:"felt"},{word:"lofi",instrument:"felt",field:"keys",preset:"lofi"},{word:"honkytonk",instrument:"honkytonk",field:"keys",preset:"honkytonk"},{word:"prepared",instrument:"prepared",field:"keys",preset:"prepared"},{word:"tonewheel",instrument:"tonewheel",field:"keys",preset:"tonewheel"},{word:"hammond",instrument:"tonewheel",field:"keys",preset:"tonewheel"},{word:"b3",instrument:"tonewheel",field:"keys",preset:"tonewheel"},{word:"gospel",instrument:"tonewheel",field:"keys",preset:"gospel"},{word:"jazzorgan",instrument:"tonewheel",field:"keys",preset:"jazzorgan"},{word:"combo",instrument:"combo",field:"keys",preset:"combo"},{word:"farfisa",instrument:"combo",field:"keys",preset:"combo"},{word:"vox",instrument:"combo",field:"keys",preset:"vox"},{word:"pipe",instrument:"pipe",field:"keys",preset:"pipe"},{word:"church",instrument:"pipe",field:"keys",preset:"pipe"},{word:"pipeorgan",instrument:"pipe",field:"keys",preset:"pipe"},{word:"churchorgan",instrument:"pipe",field:"keys",preset:"pipe"},{word:"flutes",instrument:"pipe",field:"keys",preset:"flutes"},{word:"cornet",instrument:"pipe",field:"keys",preset:"cornet"},{word:"reeds",instrument:"pipe",field:"keys",preset:"reeds"},{word:"celeste",instrument:"pipe",field:"keys",preset:"celeste"},{word:"modal",instrument:"modal",field:"modal",preset:"marimba"},{word:"vibes",instrument:"modal",field:"modal",preset:"vibes"},{word:"vibraphone",instrument:"modal",field:"modal",preset:"vibes"},{word:"xylophone",instrument:"modal",field:"modal",preset:"xylophone"},{word:"glock",instrument:"modal",field:"modal",preset:"glock"},{word:"glockenspiel",instrument:"modal",field:"modal",preset:"glock"},{word:"celesta",instrument:"modal",field:"modal",preset:"celesta"},{word:"chimes",instrument:"modal",field:"modal",preset:"chimes"},{word:"tubular",instrument:"modal",field:"modal",preset:"chimes"},{word:"kalimba",instrument:"modal",field:"modal",preset:"kalimba"},{word:"thumbpiano",instrument:"modal",field:"modal",preset:"kalimba"},{word:"mbira",instrument:"modal",field:"modal",preset:"mbira"},{word:"steelpan",instrument:"modal",field:"modal",preset:"steelpan"},{word:"bowl",instrument:"modal",field:"modal",preset:"bowl"},{word:"gong",instrument:"modal",field:"modal",preset:"gong"},{word:"gongageng",instrument:"modal",field:"modal",preset:"gong"},{word:"timpani",instrument:"modal",field:"modal",preset:"timpani"},{word:"steeldrum",instrument:"modal",field:"modal",preset:"steelpan"},{word:"singingbowl",instrument:"modal",field:"modal",preset:"bowl"},{word:"kettledrum",instrument:"modal",field:"modal",preset:"timpani"},{word:"tubularbells",instrument:"modal",field:"modal",preset:"chimes"},{word:"epiano",instrument:"epiano",field:"keys",preset:"epiano"},{word:"rhodes",instrument:"epiano",field:"keys",preset:"epiano"},{word:"suitcase",instrument:"epiano",field:"keys",preset:"suitcase"},{word:"dyno",instrument:"epiano",field:"keys",preset:"dyno"},{word:"wurli",instrument:"wurli",field:"keys",preset:"wurli"},{word:"wurlitzer",instrument:"wurli",field:"keys",preset:"wurli"},{word:"clav",instrument:"clav",field:"keys",preset:"clav"},{word:"clavinet",instrument:"clav",field:"keys",preset:"clav"},{word:"funkclav",instrument:"clav",field:"keys",preset:"funkclav"},{word:"shoegaze",instrument:"pluck",voice:"electric",fx:"shoegaze"},{word:"dreampop",instrument:"pluck",voice:"electric",fx:"dreampop"},{word:"ebow",instrument:"pluck",voice:"electric",fx:"ebow"},{word:"crotales",instrument:"modal",field:"modal",preset:"crotales"},{word:"crotale",instrument:"modal",field:"modal",preset:"crotales"},{word:"musicbox",instrument:"modal",field:"modal",preset:"musicbox"},{word:"toypiano",instrument:"modal",field:"modal",preset:"toypiano"},{word:"saron",instrument:"modal",field:"modal",preset:"saron"},{word:"demung",instrument:"modal",field:"modal",preset:"demung"},{word:"slenthem",instrument:"modal",field:"modal",preset:"slenthem"},{word:"gangsa",instrument:"modal",field:"modal",preset:"gangsa"},{word:"gender",instrument:"modal",field:"modal",preset:"gender"},{word:"bonang",instrument:"modal",field:"modal",preset:"bonang"},{word:"kenong",instrument:"modal",field:"modal",preset:"kenong"},{word:"kethuk",instrument:"modal",field:"modal",preset:"kethuk"},{word:"kempul",instrument:"modal",field:"modal",preset:"kempul"},{word:"daf",instrument:"modal",field:"modal",preset:"daf"},{word:"bodhran",instrument:"modal",field:"modal",preset:"bodhran"},{word:"framedrum",instrument:"modal",field:"modal",preset:"bodhran"},{word:"tabla",instrument:"modal",field:"modal",preset:"tabla"},{word:"flute",instrument:"wind",field:"wind",preset:"flute"},{word:"recorder",instrument:"wind",field:"wind",preset:"recorder"},{word:"whistle",instrument:"wind",field:"wind",preset:"whistle"},{word:"ney",instrument:"wind",field:"wind",preset:"ney"},{word:"shakuhachi",instrument:"wind",field:"wind",preset:"shakuhachi"},{word:"panpipe",instrument:"wind",field:"wind",preset:"panpipe"},{word:"suling",instrument:"wind",field:"wind",preset:"suling"},{word:"bansuri",instrument:"wind",field:"wind",preset:"bansuri"},{word:"clarinet",instrument:"wind",field:"wind",preset:"clarinet"},{word:"bassclarinet",instrument:"wind",field:"wind",preset:"bassclarinet"},{word:"oboe",instrument:"wind",field:"wind",preset:"oboe"},{word:"bassoon",instrument:"wind",field:"wind",preset:"bassoon"},{word:"sax",instrument:"wind",field:"wind",preset:"sax"},{word:"altosax",instrument:"wind",field:"wind",preset:"altosax"},{word:"barisax",instrument:"wind",field:"wind",preset:"barisax"},{word:"trumpet",instrument:"wind",field:"wind",preset:"trumpet"},{word:"harmon",instrument:"wind",field:"wind",preset:"harmon"},{word:"plunger",instrument:"wind",field:"wind",preset:"plunger"},{word:"trombone",instrument:"wind",field:"wind",preset:"trombone"},{word:"tuba",instrument:"wind",field:"wind",preset:"tuba"},{word:"horn",instrument:"wind",field:"wind",preset:"horn"},{word:"tinwhistle",instrument:"wind",field:"wind",preset:"whistle"},{word:"pennywhistle",instrument:"wind",field:"wind",preset:"whistle"},{word:"nay",instrument:"wind",field:"wind",preset:"ney"},{word:"panflute",instrument:"wind",field:"wind",preset:"panpipe"},{word:"panpipes",instrument:"wind",field:"wind",preset:"panpipe"},{word:"saxophone",instrument:"wind",field:"wind",preset:"sax"},{word:"tenorsax",instrument:"wind",field:"wind",preset:"sax"},{word:"tenor",instrument:"wind",field:"wind",preset:"sax"},{word:"alto",instrument:"wind",field:"wind",preset:"altosax"},{word:"bari",instrument:"wind",field:"wind",preset:"barisax"},{word:"baritonesax",instrument:"wind",field:"wind",preset:"barisax"},{word:"frenchhorn",instrument:"wind",field:"wind",preset:"horn"},{word:"mutedtrumpet",instrument:"wind",field:"wind",preset:"harmon"},{word:"wahtrumpet",instrument:"wind",field:"wind",preset:"plunger"},{word:"sing",instrument:"sing",field:"sing"},{word:"aah",instrument:"sing",field:"sing",preset:"aah"},{word:"ooh",instrument:"sing",field:"sing",preset:"ooh"},{word:"choir",instrument:"sing",field:"sing",preset:"choir"},{word:"chorale",instrument:"sing",field:"sing",preset:"chorale"},{word:"khoomei",instrument:"sing",field:"sing",preset:"khoomei"},{word:"sygyt",instrument:"sing",field:"sing",preset:"sygyt"},{word:"kargyraa",instrument:"sing",field:"sing",preset:"kargyraa"},{word:"vocal",instrument:"vocal"},{word:"vocoder",instrument:"vocoder",field:"vocoder",preset:"classic"},{word:"texture",instrument:"texture",field:"texture"}]);function resolveInstrumentWord(word2){if(LEGACY_WORDS.includes(word2))return Object.freeze({instrument:word2});let row2=INSTRUMENT_WORDS.find(entry=>entry.word===word2);if(!row2)return;let{word:_word,voice,...meaning}=row2,borrowed=voice===void 0?void 0:INSTRUMENT_WORDS.find(entry=>entry.word===voice&&!entry.voice);return Object.freeze(borrowed?{instrument:borrowed.instrument,...borrowed.field===void 0?{}:{field:borrowed.field},...borrowed.preset===void 0?{}:{preset:borrowed.preset},...meaning.fx===void 0?{}:{fx:meaning.fx}}:meaning)}var EXTENSIONS=["6","m7","M7","9"];var QUALITY_INTERVALS=Object.freeze({maj:[0,4,7],min:[0,3,7],dim:[0,3,6],sus4:[0,5,7],aug:[0,4,8],sus2:[0,2,7],5:[0,7],madd4:[0,3,5,7],mb6:[0,3,7,8],b6:[0,4,7,8],"7#9":[0,4,7,10,15],b5:[0,4,6]}),SECRET_EXTENSION=Object.freeze({mb6:"6",b6:"6","7#9":"m7"}),EXTENSION_INTERVAL=Object.freeze({6:9,m7:10,M7:11,9:14}),COMBINED_TYPES=Object.freeze({"dim+sus":"5","maj+sus":"aug","min+sus":"madd4","dim+min":"mb6","dim+maj":"b6","maj+min":"7#9"});function makeChord(root,quality,extensions=[],bass,tensions=[]){let held=new Set(extensions),own=SECRET_EXTENSION[quality],ext=EXTENSIONS.filter(value=>held.has(value)&&value!==own),pc=mod12(root),slash=bass===void 0?void 0:mod12(bass);return Object.freeze({root:pc,quality,extensions:Object.freeze(ext),...slash!==void 0&&slash!==pc?{bass:slash}:{},...tensions.length>0?{tensions:Object.freeze([...new Set(tensions)].sort((a,b)=>a-b))}:{}})}function chordIntervals(chord2){let set=new Set(QUALITY_INTERVALS[chord2.quality]);for(let ext of chord2.extensions)set.add(EXTENSION_INTERVAL[ext]);for(let step2 of chord2.tensions??[])set.add(step2);return[...set].sort((a,b)=>a-b)}var SHARP_NAMES=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],FLAT_NAMES=["C","Db","D","Eb","E","F","Gb","G","Ab","A","Bb","B"];function noteName(pc,flats=!1){return(flats?FLAT_NAMES:SHARP_NAMES)[mod12(pc)]}var LETTERS="CDEFGAB",LETTER_PCS=[0,2,4,5,7,9,11];function spellOnLetter(pc,letter){let l=(Math.trunc(letter)%7+7)%7,diff=(mod12(pc)-LETTER_PCS[l]+18)%12-6;if(!(Math.abs(diff)>1))return`${LETTERS[l]}${diff===1?"#":diff===-1?"b":""}`}function tonicLetter(key){return LETTERS.indexOf(noteName(key.tonic,keyUsesFlats(key))[0])}var SECRET_SUFFIX=Object.freeze({madd4:"m(add4)",mb6:"m(b6)",b6:"(b6)","7#9":"7#9"});function chordSuffix(chord2){if(chord2.tensions?.length){let typed=TENSION_SUFFIXES.find(([,quality,ext2,tensions])=>quality===chord2.quality&&ext2.join()===chord2.extensions.join()&&tensions.join()===chord2.tensions.join());if(typed)return typed[0];let names=chord2.tensions.map(step2=>TENSION_NAMES[step2]??step2);return`${chordSuffix({...chord2,tensions:void 0})}(${names.join(",")})`}let ext=new Set(chord2.extensions),b7=ext.has("m7"),M7=ext.has("M7"),six=ext.has("6"),nine=ext.has("9"),q3=chord2.quality,add=(base2,parts)=>parts.length===0?base2:`${base2}(${parts.join(",")})`,extras2=[],base,secret=SECRET_SUFFIX[q3];if(secret!==void 0){let names={6:"6",m7:"7",M7:"maj7",9:"9"},parts=chord2.extensions.map(e=>names[e]);return parts.length===0||!secret.endsWith(")")?add(secret,parts):`${secret.slice(0,-1)},${parts.join(",")})`}if(q3==="dim"&&six&&!b7&&!M7)return base="dim7",nine&&extras2.push("add9"),add(base,extras2);b7&&M7&&extras2.push("maj7");let seventh=b7?"7":M7?"maj7":"";if(seventh){let ninth=nine?seventh==="7"?"9":"maj9":seventh;switch(q3){case"maj":base=ninth;break;case"min":base=b7?nine?"m9":"m7":nine?"m(maj9)":"m(maj7)";break;case"dim":base=b7?nine?"m9b5":"m7b5":"dim(maj7)",!b7&&nine&&extras2.push("9");break;case"aug":base=b7?nine?"aug9":"aug7":"aug(maj7)",!b7&&nine&&extras2.push("9");break;case"sus4":base=`${ninth}sus4`;break;case"sus2":base=`${seventh}sus2`,nine&&extras2.push("9");break;case"5":base=`${seventh}(no3)`,nine&&extras2.push("9");break;case"b5":base=`${ninth}b5`;break;default:base=seventh}return six&&extras2.push("13"),add(base,b7&&M7?extras2:extras2.filter(e=>e!=="maj7"))}if(base={maj:"",min:"m",dim:"dim",sus4:"sus4",aug:"aug",sus2:"sus2",5:"5",madd4:"m(add4)",mb6:"m(b6)",b6:"(b6)","7#9":"7#9",b5:"(b5)"}[q3],six&&nine&&(q3==="maj"||q3==="min"))return`${base}6/9`;if(six&&(q3==="maj"||q3==="min"?base=`${base}6`:extras2.push("6")),nine){if(extras2.length===0&&(q3==="maj"||q3==="min"))return`${base}${q3==="min"&&!six?"(add9)":"add9"}`;extras2.push("9")}return add(base,extras2)}function chordName(chord2,flats=!1){let slash=chord2.bass===void 0?"":`/${noteName(chord2.bass,flats)}`;return`${(chord2.letter===void 0?void 0:spellOnLetter(chord2.root,chord2.letter))??noteName(chord2.root,flats)}${chordSuffix(chord2)}${slash}`}var SUFFIXES=[["","maj",[]],["maj","maj",[]],["M","maj",[]],["m","min",[]],["min","min",[]],["-","min",[]],["dim","dim",[]],["\xB0","dim",[]],["o","dim",[]],["aug","aug",[]],["+","aug",[]],["sus","sus4",[]],["sus4","sus4",[]],["sus2","sus2",[]],["5","5",[]],["6","maj",["6"]],["m6","min",["6"]],["6/9","maj",["6","9"]],["69","maj",["6","9"]],["m6/9","min",["6","9"]],["m69","min",["6","9"]],["7","maj",["m7"]],["dom7","maj",["m7"]],["maj7","maj",["M7"]],["M7","maj",["M7"]],["\u0394","maj",["M7"]],["\u03947","maj",["M7"]],["m7","min",["m7"]],["min7","min",["m7"]],["-7","min",["m7"]],["m(maj7)","min",["M7"]],["mM7","min",["M7"]],["m7b5","dim",["m7"]],["\xF8","dim",["m7"]],["\xF87","dim",["m7"]],["dim7","dim",["6"]],["\xB07","dim",["6"]],["o7","dim",["6"]],["aug7","aug",["m7"]],["+7","aug",["m7"]],["9","maj",["m7","9"]],["maj9","maj",["M7","9"]],["M9","maj",["M7","9"]],["m9","min",["m7","9"]],["add9","maj",["9"]],["madd9","min",["9"]],["m(add9)","min",["9"]],["7sus4","sus4",["m7"]],["7sus","sus4",["m7"]],["9sus4","sus4",["m7","9"]],["7sus2","sus2",["m7"]],["maj7sus4","sus4",["M7"]],["m(add4)","madd4",[]],["madd4","madd4",[]],["m(b6)","mb6",[]],["mb6","mb6",[]],["(b6)","b6",[]],["addb6","b6",[]],["7#9","7#9",[]],["-maj7","min",["M7"]],["mmaj7","min",["M7"]],["mMaj7","min",["M7"]],["m(maj7)","min",["M7"]],["-\u03947","min",["M7"]],["m\u03947","min",["M7"]],["add2","maj",["9"]],["2","maj",["9"]],["madd2","min",["9"]],["6add9","maj",["6","9"]],["m6add9","min",["6","9"]],["-6","min",["6"]],["-9","min",["m7","9"]],["dom9","maj",["m7","9"]],["aug(maj7)","aug",["M7"]],["augmaj7","aug",["M7"]],["+maj7","aug",["M7"]],["aug9","aug",["m7","9"]],["+9","aug",["m7","9"]],["m(maj9)","min",["M7","9"]],["mmaj9","min",["M7","9"]],["dim(maj7)","dim",["M7"]],["7(no3)","5",["m7"]],["maj7(no3)","5",["M7"]]],TENSION_SUFFIXES=[["11","maj",["m7","9"],[17]],["m11","min",["m7","9"],[17]],["maj11","maj",["M7","9"],[17]],["add11","maj",[],[17]],["madd11","min",[],[17]],["13","maj",["m7","9"],[21]],["m13","min",["m7","9"],[21]],["maj13","maj",["M7","9"],[21]],["7b9","maj",["m7"],[13]],["7#11","maj",["m7"],[18]],["maj7#11","maj",["M7"],[18]],["M7#11","maj",["M7"],[18]],["7b13","maj",["m7"],[20]],["13b9","maj",["m7"],[13,21]]],TENSION_NAMES=Object.freeze({13:"b9",15:"#9",17:"11",18:"#11",20:"b13",21:"13"}),SUFFIX_TABLE=new Map([...SUFFIXES.map(([suffix,quality,ext])=>[suffix,{quality,ext}]),...TENSION_SUFFIXES.map(([suffix,quality,ext,tensions])=>[suffix,{quality,ext,tensions}])]),LETTER=Object.freeze({c:0,d:2,e:4,f:5,g:7,a:9,b:11});function parsePitchClass(text2){let match=text2.trim().match(/^([a-gA-G])(#|b|♯|♭)?$/);if(!match)return;let accidental=match[2]==="#"||match[2]==="\u266F"?1:match[2]==="b"||match[2]==="\u266D"?-1:0;return mod12(LETTER[match[1].toLowerCase()]+accidental)}var ALTERATION_TENSION=Object.freeze({b9:13,"#9":15,11:17,"#11":18,"+11":18,b13:20,13:21}),TOKEN="b5|#5|\\+5|b9|#9|#11|\\+11|b13|alt|add9|add11|add13|11|13|9|6",ALTERATIONS=new RegExp(`^(?:(?:${TOKEN})|\\((?:${TOKEN})(?:,(?:${TOKEN}))*\\))+$`);function parseAlteredSuffix(suffix){for(let cut=suffix.length-1;cut>=0;cut-=1){let base=SUFFIX_TABLE.get(suffix.slice(0,cut));if(!base)continue;let raw=suffix.slice(cut);if(!ALTERATIONS.test(raw))continue;let rest=raw.replace(/[(),]/g,""),tokens=rest.match(/b5|#5|\+5|b9|#9|#11|\+11|b13|alt|add9|add11|add13|11|13|9|6/g);if(!tokens||tokens.join("")!==rest)continue;let quality=base.quality,ext=new Set(base.ext),tensions=new Set(base.tensions??[]),ok=!0;for(let token of tokens)if(token==="#5"||token==="+5")quality==="maj"||quality==="aug"?quality="aug":ok=!1;else if(token==="b5")quality==="maj"||quality==="b5"?quality="b5":quality==="min"||quality==="dim"?quality="dim":ok=!1;else if(token==="alt"){quality!=="maj"&&(ok=!1),ext.add("m7");for(let step2 of[13,15,18,20])tensions.add(step2)}else if(token==="9"||token==="add9")ext.add("9");else if(token==="6")ext.add("6");else{let step2=ALTERATION_TENSION[token.replace(/^add/,"")];step2===void 0?ok=!1:tensions.add(step2)}if(ok)return{quality,ext:[...ext],tensions:[...tensions].sort((a,b)=>a-b)}}}function parseChord(symbol){if(typeof symbol!="string"||symbol.length>24)return;let match=symbol.trim().replace(/6\/9$/,"69").replace(/6\/9\//,"69/").match(/^([A-Ga-g])(#|b|♯|♭)?([^/]*)(?:\/(.+))?$/);if(!match)return;let root=parsePitchClass(`${match[1]}${match[2]??""}`),entry=SUFFIX_TABLE.get(match[3]??"")??parseAlteredSuffix(match[3]??"");if(root===void 0||!entry)return;let bass;if(!(match[4]!==void 0&&(bass=parsePitchClass(match[4]),bass===void 0)))return makeChord(root,entry.quality,entry.ext,bass,entry.tensions)}var MODES=Object.freeze({major:[0,2,4,5,7,9,11],minor:[0,2,3,5,7,8,10],dorian:[0,2,3,5,7,9,10],phrygian:[0,1,3,5,7,8,10],lydian:[0,2,4,6,7,9,11],mixolydian:[0,2,4,5,7,9,10],locrian:[0,1,3,5,6,8,10],"harmonic-minor":[0,2,3,5,7,8,11],"melodic-minor":[0,2,3,5,7,9,11],"phrygian-dominant":[0,1,4,5,7,8,10]}),MODE_NAMES=Object.keys(MODES),MODE_ALIASES=Object.freeze({"":"major",maj:"major",major:"major",ionian:"major",m:"minor",min:"minor",minor:"minor",aeolian:"minor",dorian:"dorian",phrygian:"phrygian",lydian:"lydian",mixolydian:"mixolydian",mixo:"mixolydian",locrian:"locrian","harmonic-minor":"harmonic-minor","harmonic minor":"harmonic-minor",harmonic:"harmonic-minor","melodic-minor":"melodic-minor","melodic minor":"melodic-minor",melodic:"melodic-minor","jazz minor":"melodic-minor","phrygian-dominant":"phrygian-dominant","phrygian dominant":"phrygian-dominant",freygish:"phrygian-dominant",spanish:"phrygian-dominant",ajam:"major",mahur:"major",bilawal:"major"}),SCALES=Object.freeze({"major-pentatonic":{steps:[0,2,4,7,9],mode:"major",family:"pentatonic",aliases:["pentatonic","major pentatonic","pent"]},"minor-pentatonic":{steps:[0,3,5,7,10],mode:"minor",family:"pentatonic",aliases:["minor pentatonic","m pentatonic","min pentatonic"]},blues:{steps:[0,3,5,6,7,10],mode:"minor",family:"blues",aliases:["minor blues"]},"major-blues":{steps:[0,2,3,4,7,9],mode:"major",family:"blues",aliases:["major blues"]},"yonanuki-minor":{steps:[0,2,3,7,8],mode:"minor",family:"pentatonic",aliases:["yonanuki","yonanuki minor","enka minor"]},hijaz:{steps:[0,1,4,5,7,8,10],mode:"phrygian-dominant",family:"maqam"},bayati:{steps:[0,1.5,3,5,7,8,10],mode:"phrygian",family:"maqam"},rast:{steps:[0,2,3.5,5,7,9,10.5],mode:"major",family:"maqam"},saba:{steps:[0,1.5,3,4,7,8,10],mode:"phrygian",family:"maqam"},kurd:{steps:[0,1,3,5,7,8,10],mode:"phrygian",family:"maqam"},nahawand:{steps:[0,2,3,5,7,8,11],mode:"harmonic-minor",family:"maqam"},sikah:{steps:[0,1.5,3.5,5.5,7,8.5,10.5],mode:"phrygian",family:"maqam",aliases:["sika"]},huzam:{steps:[0,1.5,3.5,4.5,7.5,8.5,10.5],mode:"phrygian",family:"maqam",aliases:["houzam"]},nikriz:{steps:[0,2,3,6,7,9,10],mode:"dorian",family:"maqam"},shur:{steps:[0,1.5,3,5,7,8,10],mode:"phrygian",family:"dastgah"},homayoun:{steps:[0,1.5,4,5,7,8,10],mode:"phrygian-dominant",family:"dastgah",aliases:["homayun"]},chahargah:{steps:[0,1.5,4,5,7,8.5,11],mode:"phrygian-dominant",family:"dastgah",aliases:["chahar-gah"]},segah:{steps:[0,1.5,3.5,5,6.5,8.5,10.5],mode:"phrygian",family:"dastgah",aliases:["sehgah","se-gah"]},nava:{steps:[0,2,3.5,5,7,8,10],mode:"minor",family:"dastgah"},yaman:{steps:[0,2,4,6,7,9,11],mode:"lydian",family:"raga",intonation:[0,203.91,386.31,611.73,701.96,884.36,1088.27],aliases:["kalyan","yaman kalyan"]},bhairav:{steps:[0,1,4,5,7,8,11],mode:"phrygian-dominant",family:"raga",intonation:[0,90.22,386.31,498.04,701.96,792.18,1088.27]},kafi:{steps:[0,2,3,5,7,9,10],mode:"dorian",family:"raga",intonation:[0,203.91,315.64,498.04,701.96,884.36,1017.6]},bhairavi:{steps:[0,1,3,5,7,8,10],mode:"phrygian",family:"raga",intonation:[0,90.22,294.13,498.04,701.96,792.18,996.09]},asavari:{steps:[0,2,3,5,7,8,10],mode:"minor",family:"raga",intonation:[0,203.91,315.64,498.04,701.96,813.69,996.09]},khamaj:{steps:[0,2,4,5,7,9,10],mode:"mixolydian",family:"raga",intonation:[0,203.91,386.31,498.04,701.96,884.36,996.09]},todi:{steps:[0,1,3,6,7,8,11],mode:"phrygian",family:"raga",intonation:[0,95,294,606,702,792,1107]},purvi:{steps:[0,1,4,6,7,8,11],mode:"phrygian-dominant",family:"raga",intonation:[0,90.22,386.31,590.22,701.96,792.18,1088.27]},marwa:{steps:[0,1,4,6,9,11],mode:"lydian",family:"raga",intonation:[0,111.73,386.31,590.22,884.36,1088.27]},darbari:{steps:[0,2,3,5,7,8,10],mode:"minor",family:"raga",intonation:[0,203.91,294.13,498.04,701.96,792.18,996.09],aliases:["darbari kanada"]},malkauns:{steps:[0,3,5,8,10],mode:"minor",family:"raga",intonation:[0,315.64,498.04,813.69,996.09]},bhupali:{steps:[0,2,4,7,9],mode:"major",family:"raga",intonation:[0,203.91,386.31,701.96,884.36]},durga:{steps:[0,2,5,7,9],mode:"major",family:"raga",intonation:[0,203.91,498.04,701.96,884.36]},"messiaen-1":{steps:[0,2,4,6,8,10],mode:"lydian",family:"messiaen",aliases:["whole-tone","whole tone","wholetone"]},"messiaen-2":{steps:[0,1,3,4,6,7,9,10],mode:"mixolydian",family:"messiaen",aliases:["octatonic","diminished","half-whole"]},"messiaen-3":{steps:[0,2,3,4,6,7,8,10,11],mode:"minor",family:"messiaen"},"messiaen-4":{steps:[0,1,2,5,6,7,8,11],mode:"harmonic-minor",family:"messiaen"},"messiaen-5":{steps:[0,1,5,6,7,11],mode:"lydian",family:"messiaen"},"messiaen-6":{steps:[0,2,4,5,6,8,10,11],mode:"major",family:"messiaen"},"messiaen-7":{steps:[0,1,2,3,5,6,7,8,9,11],mode:"harmonic-minor",family:"messiaen"},chromatic:{steps:[0,1,2,3,4,5,6,7,8,9,10,11],mode:"minor",family:"chromatic",aliases:["twelve-tone","aggregate"]},"harmonic-series":{steps:[0,2,4,6,7,9,10,11],mode:"mixolydian",family:"overtone",intonation:[0,204,386,551,702,841,969,1088],aliases:["overtone","overtone-scale","partials"]},"quarter-tone":{steps:[0,1.5,2,3.5,4,5,5.5,7,8.5,9,10.5],mode:"major",family:"quarter-tone",aliases:["quartertone","24-tone"]}}),SCALE_NAMES=Object.keys(SCALES),SCALE_ALIASES=(()=>{let aliases={};for(let name of SCALE_NAMES){let info=SCALES[name];aliases[name]=name,aliases[name.replace(/-/g," ")]=name;for(let alias of info.aliases??[])aliases[alias]=name}return Object.freeze(aliases)})();function scaleNamed(text2){let word2=text2.trim().toLowerCase().replace(/\s+/g," ");return SCALE_ALIASES[word2]??SCALE_ALIASES[word2.replace(/ /g,"-")]}function parseKey(text2){if(typeof text2!="string"||text2.length>40)return;let match=text2.trim().match(/^([a-gA-G])(#|b|♯|♭)?\s*(m(?![a-z])|[a-zA-Z][a-zA-Z0-9 -]*)?$/);if(!match)return;let tonic=parsePitchClass(`${match[1]}${match[2]??""}`);if(tonic===void 0)return;let word2=(match[3]??"").trim(),mode=MODE_ALIASES[word2==="m"?"m":word2.toLowerCase()];if(mode!==void 0)return Object.freeze({tonic,mode});let scale3=scaleNamed(word2);if(scale3!==void 0)return Object.freeze({tonic,mode:SCALES[scale3].mode,scale:scale3})}function keyUsesFlats(key){let parentOffset={major:0,dorian:2,phrygian:4,lydian:5,mixolydian:7,minor:9,locrian:11,"harmonic-minor":9,"melodic-minor":9,"phrygian-dominant":4},parent=mod12(key.tonic-parentOffset[key.mode]);return[5,10,3,8,1].includes(parent)}function scaleOf(key){return MODES[key.mode].map(step2=>mod12(key.tonic+step2))}function qualityFromThirds(third,fifth){return third===4&&fifth===7?"maj":third===3&&fifth===7?"min":third===3&&fifth===6?"dim":third===4&&fifth===8?"aug":"maj"}function diatonicChord(key,degree,sevenths=!1){let scale3=MODES[key.mode],at3=index=>{let octave2=Math.floor(index/7);return scale3[(index%7+7)%7]+12*octave2},d=(degree%7+7)%7,root=at3(d),third=at3(d+2)-root,fifth=at3(d+4)-root,quality=qualityFromThirds(third,fifth),ext=[];if(sevenths){let seventh=at3(d+6)-root;quality==="dim"&&seventh===9?ext.push("6"):ext.push(seventh===11?"M7":"m7")}return makeChord(key.tonic+root,quality,ext)}function degreeOf(key,pc){let index=scaleOf(key).indexOf(mod12(pc));return index<0?void 0:index}var NUMERALS=["i","ii","iii","iv","v","vi","vii"];function romanOf(key,chord2){let degree=scaleOf(key).indexOf(chord2.root),accidental="";if(degree<0){let major=MODES.major.map(step2=>mod12(key.tonic+step2)),natural=major.indexOf(chord2.root),flat=major.indexOf(mod12(chord2.root+1)),sharp=major.indexOf(mod12(chord2.root-1));natural>=0?(degree=natural,accidental="\u266E"):flat>=0?(degree=flat,accidental="b"):(degree=Math.max(0,sharp),accidental="#")}let lower=chord2.quality==="min"||chord2.quality==="dim"||chord2.quality==="madd4"||chord2.quality==="mb6",numeral=NUMERALS[degree],body2=lower?numeral:numeral.toUpperCase(),ext=new Set(chord2.extensions),mark="";chord2.quality==="dim"?mark=ext.has("m7")?"\xF8":"\xB0":chord2.quality==="aug"&&(mark="+");let seventh=ext.has("6")&&chord2.quality==="dim"||ext.has("m7")?"7":ext.has("M7")?"maj7":"",plain=`${accidental}${body2}${mark}${seventh}`,bare=makeChord(chord2.root,chord2.quality,chord2.extensions,void 0,chord2.tensions);for(let candidate of[plain,`${accidental}${body2}${mark}${seventh==="7"?"dom7":seventh}`])if(sameChord(parseRoman(key,candidate),bare))return candidate;return`${accidental}${body2}[${chordSuffix(bare)}]`}function sameChord(a,b){return a!==void 0&&a.root===b.root&&a.quality===b.quality&&a.bass===b.bass&&a.extensions.join()===b.extensions.join()&&(a.tensions??[]).join()===(b.tensions??[]).join()}function parseRoman(key,text2){return romanIn(key,text2,tonicLetter(key))}function romanIn(key,text2,tonic){if(typeof text2!="string"||text2.length>32)return;let trimmed=text2.trim(),exact=trimmed.match(/^(b|#|♭|♯|♮)?(vii|vi|v|iv|iii|ii|i|VII|VI|V|IV|III|II|I)\[([^\]]*)\]$/);if(exact){let degree2=NUMERALS.indexOf(exact[2].toLowerCase()),shift=exact[1]==="b"||exact[1]==="\u266D"?-1:exact[1]==="\u266E"||!exact[1]?0:1,root2=exact[1]?mod12(key.tonic+MODES.major[degree2]+shift):scaleOf(key)[degree2];if(root2===void 0)return;let letter=(tonic+degree2)%7,chord2=parseChord(`${spellOnLetter(root2,letter)??noteName(root2)}${exact[3]}`);return chord2&&Object.freeze({...chord2,letter})}let slash=trimmed.match(/^(.+)\/(.+)$/);if(slash){let target=romanIn(key,slash[2],tonic);return target?romanIn({tonic:target.root,mode:"major"},slash[1],target.letter??tonic):void 0}let match=trimmed.match(/^(b|#|♭|♯|♮)?(vii|vi|v|iv|iii|ii|i|VII|VI|V|IV|III|II|I)(°|o|ø|\+)?(maj7|M7|dom7|7|9|maj9|6|sus4|sus2|sus|add9)?$/);if(!match)return;let accidental=match[1]==="b"||match[1]==="\u266D"?-1:match[1]==="#"||match[1]==="\u266F"?1:0,numeral=match[2],lower=numeral===numeral.toLowerCase(),degree=NUMERALS.indexOf(numeral.toLowerCase()),mark=match[3],suffix=match[4]??"",root=match[1]?mod12(key.tonic+MODES.major[degree]+accidental):scaleOf(key)[degree],inKey=degreeOf(key,root),triad=inKey===void 0?void 0:diatonicChord(key,inKey),seventh=inKey===void 0?void 0:diatonicChord(key,inKey,!0),diatonicLower=triad!==void 0&&(triad.quality==="min"||triad.quality==="dim"),matches=triad!==void 0&&diatonicLower===lower,quality;mark==="\xB0"||mark==="o"||mark==="\xF8"?quality="dim":mark==="+"?quality="aug":matches?quality=triad.quality:quality=lower?"min":"maj";let diatonicSeventh=()=>mark==="\xF8"?["m7"]:seventh&&seventh.quality===quality?[...seventh.extensions]:quality==="dim"&&mark!==void 0?["6"]:["m7"],ext=mark==="\xF8"?["m7"]:[];switch(suffix){case"7":ext=diatonicSeventh();break;case"dom7":ext=["m7"];break;case"maj7":case"M7":ext=["M7"];break;case"9":ext=[...diatonicSeventh(),"9"];break;case"maj9":ext=["M7","9"];break;case"6":ext=["6"];break;case"add9":ext=["9"];break;case"sus4":case"sus":quality="sus4";break;case"sus2":quality="sus2";break}return Object.freeze({...makeChord(root,quality,ext),letter:(tonic+degree)%7})}var VOICING_RANGE=Object.freeze({low:48,high:79}),MAX_VOICING_STEP=12,SPREADS=["close","open","wide"];function rotate(pitches,steps2){let notes=[...pitches].sort((a,b)=>a-b);if(notes.length===0)return notes;for(let i=0;i<Math.abs(Math.trunc(steps2));i+=1)steps2>0?notes.push(notes.shift()+12):notes.unshift(notes.pop()-12);return notes}function rootPosition(chord2,anchor=60){let rootPitch=anchor+mod12(chord2.root-anchor),steps2=chordIntervals(chord2),clash=steps2.includes(4)&&steps2.includes(17)&&(steps2.includes(10)||steps2.includes(11));return steps2.filter(step2=>!(clash&&step2===4)).map(step2=>rootPitch+step2)}function applySpread(pitches,spread){let notes=[...pitches].sort((a,b)=>a-b);if(spread==="close"||notes.length<3)return notes;let n2=notes.length;return notes[n2-2]=notes[n2-2]-12,spread==="wide"&&n2>=4&&(notes[n2-4]=notes[n2-4]-12),notes.sort((a,b)=>a-b)}function movement(a,b){if(a.length===0||b.length===0)return 0;let nearest2=(pitch2,set)=>Math.min(...set.map(other=>Math.abs(other-pitch2))),total=0;for(let pitch2 of b)total+=nearest2(pitch2,a);for(let pitch2 of a)total+=nearest2(pitch2,b);return total}function voiceChord(chord2,options={}){let anchor=options.anchor??60,spread=options.spread??"close",low=options.low??VOICING_RANGE.low,high=options.high??VOICING_RANGE.high,dial=clampInt(options.inversion??0,-MAX_VOICING_STEP,MAX_VOICING_STEP),base=rootPosition(chord2,anchor),size=base.length,fit=notes=>notes.every(pitch2=>pitch2>=low&&pitch2<=high),clampMidi=notes=>notes.map(pitch2=>Math.max(0,Math.min(127,pitch2))),at3=steps2=>applySpread(rotate(base,steps2),spread);if(!options.previous||options.previous.length===0)return clampMidi(at3(dial));let best;for(let offset=-size;offset<=size;offset+=1){let notes=at3(dial+offset);if(!fit(notes)&&offset!==0)continue;let cost=movement(options.previous,notes),distance=Math.abs(offset);(!best||cost<best.cost||cost===best.cost&&distance<best.distance)&&(best={notes,cost,distance})}return clampMidi(best.notes)}function bassNote(chord2,low=36){return low+mod12((chord2.bass??chord2.root)-low)}var BASS_MODES=["off","chords","unison","single","solo"];var PERFORM_MODES=["block","strum-up","strum-down","arp-up","arp-down","arp-updown","arp-random","harp","slop","pattern","guitar"],DEFAULT_ARP_RATE=.25,DEFAULT_STRUM=1/32,DEFAULT_SLOP=.5,MAX_SLOP=1/8,everyStep=(step2,beats,hit2)=>Array.from({length:Math.round(beats/step2)},(_,index)=>({at:index*step2,...hit2(index)})),BAR_ACCENT=[1,.84,.93,.86],CHORD_PATTERNS=Object.freeze([{name:"eighths",description:"straight 8ths: the full chord on the beat, upper voices between",beats:4,hits:everyStep(.5,4,i=>i%2===0?{length:.42,voices:"all",velocity:BAR_ACCENT[i/2]}:{length:.3,voices:"upper",velocity:i===7?.76:.66}),feel:{roll:6}},{name:"sixteenths",description:"straight 16ths: full on the beat, the & lighter, e and a thin",beats:4,hits:everyStep(.25,4,i=>{let beat2=Math.floor(i/4),place=i%4;return place===0?{length:.2,voices:"all",velocity:BAR_ACCENT[beat2]}:place===2?{length:.16,voices:"all",velocity:.76}:{length:.13,voices:"upper",velocity:place===1?.54:.62}}),feel:{roll:4,timing:7}},{name:"offbeat",description:"short stabs on every &, programmed tight",beats:4,hits:everyStep(1,4,()=>({length:.25,voices:"all",velocity:.9})).map(hit2=>({...hit2,at:hit2.at+.5})),feel:{tight:!0}},{name:"pop",description:"syncopated pop comp: 16th pushes, the & of 2 held over 3",beats:4,hits:[{at:0,length:.55,voices:"all",velocity:1},{at:.75,length:.2,voices:"upper",velocity:.6},{at:1.5,length:.9,voices:"all",velocity:.9},{at:2.5,length:.3,voices:"upper",velocity:.64},{at:3,length:.2,voices:"upper",velocity:.52},{at:3.5,length:.45,voices:"all",velocity:.86}],feel:{roll:6,lay:-3}},{name:"charleston",description:"jazz Charleston: a short 1, then the accented & of 2",beats:4,hits:[{at:0,length:.5,voices:"all",velocity:.86},{at:1.5,length:.42,voices:"all",velocity:.95}],feel:{roll:9,swing:.08}},{name:"bossa",description:"two-bar bossa: thumb on 1 and 3 (the 3 heavier), fingers on the clave",beats:8,hits:[...everyStep(2,8,i=>({length:1.7,voices:[0],velocity:i%2===0?.78:.86,octave:-1,bass:i%2===0?"root":"fifth"})),...[0,1.5,3,5,6.5].map(at3=>({at:at3,length:at3===3||at3===6.5?.7:.5,voices:"upper",velocity:at3%1===0?.68:.74}))],feel:{roll:10,timing:8}},{name:"skank",description:"reggae skank: choked upper chops on 2 and 4, laid back",beats:4,hits:[1,3].map(at3=>({at:at3,length:.18,voices:"upper",velocity:at3===1?.92:.97})),feel:{roll:3,lay:8,timing:6}},{name:"gallop",description:"gallop: an 8th and two 16ths per beat",beats:4,hits:everyStep(1,4,i=>({length:.38,voices:"all",velocity:BAR_ACCENT[i]})).flatMap(hit2=>[hit2,{...hit2,at:hit2.at+.5,length:.18,velocity:.62},{...hit2,at:hit2.at+.75,length:.18,velocity:.7}]),feel:{roll:3,timing:6}},{name:"half-time",description:"half-time: a long rolled hit and a pickup per two bars",beats:8,hits:[{at:0,length:3.6,voices:"all",velocity:.96},{at:4,length:2.2,voices:"all",velocity:.8},{at:6.5,length:.8,voices:"upper",velocity:.56},{at:7.5,length:.45,voices:"upper",velocity:.68}],feel:{roll:11}},{name:"tresillo",description:"tresillo 3+3+2",beats:4,hits:[{at:0,length:1,voices:"all",velocity:1},{at:1.5,length:1,voices:"all",velocity:.84},{at:3,length:.6,voices:"all",velocity:.92}],feel:{roll:5}},{name:"oom-pah",description:"alternating bass and chord: low root, detached upper chord",beats:4,hits:everyStep(1,4,i=>i%2===0?{length:.85,voices:[0],velocity:i===0?1:.9,octave:-1,bass:i===0?"root":"fifth"}:{length:.5,voices:"upper",velocity:i===1?.72:.76}),feel:{roll:4}},{name:"roll",description:"broken-chord roll up in 16ths, ringing to the half bar",beats:4,hits:[0,2].flatMap(half=>[0,1,2,3].map(step2=>({at:half+step2*.25,length:2-step2*.25,voices:[step2],velocity:(half===0?1:.92)*[.84,.64,.7,.78][step2]})))},{name:"pick",description:"broken-chord picking: low, high, middle, high in 8ths",beats:4,hits:everyStep(.5,4,i=>({length:i%4===0?1.9:.9,voices:[[0,-1,1,-1][i%4]],velocity:[i<4?.92:.84,.7,.6,.66][i%4]})),feel:{timing:8}}]);function findChordPattern(value){if(value===void 0)return;let text2=String(value).trim().toLowerCase(),number=Number(text2);return/^\d+$/.test(text2)?CHORD_PATTERNS[number-1]:CHORD_PATTERNS.find(pattern=>pattern.name===text2)}var BASS_FLOOR=36;function patternVoices(notes,hit2,root,slash){let n2=notes.length;if(hit2.bass&&root!==void 0){let fifth=[7,6,8].find(step2=>notes.some(pitch3=>mod12(pitch3-root)===step2)),pc=mod12(slash!==void 0?slash:hit2.bass==="fifth"?root+(fifth??0):root),target=notes[0]+12*(hit2.octave??-1),pitch2=target-mod12(target-pc);for(;pitch2<BASS_FLOOR;)pitch2+=12;return pitch2>=0&&pitch2<=127?[pitch2]:[]}let indices=hit2.voices==="all"?notes.map((_,i)=>i):hit2.voices==="upper"?n2>1?notes.slice(1).map((_,i)=>i+1):[0]:hit2.voices,shift=12*(hit2.octave??0),out=new Set;for(let index of indices){let i=index<0?(index%n2+n2)%n2:index,wrapped=(i%n2+n2)%n2,pitch2=notes[wrapped]+12*Math.floor(i/n2)+shift;pitch2>=0&&pitch2<=127&&out.add(pitch2)}return[...out].sort((a,b)=>a-b)}var msToBeats=(ms2,tempo)=>ms2/1e3*(tempo/60);function voiceWeight(index,count2,tight){return tight||count2<2?1:index===count2-1?1.07:index===0?1:.95}function releaseRestrikes(notes){let last=new Map,sorted=notes.sort((a,b)=>a.start-b.start||a.pitch-b.pitch);return sorted.forEach((note2,index)=>{let before=last.get(note2.pitch);if(before!==void 0){let held=sorted[before];held.start+held.length>note2.start+1e-6&&(sorted[before]={...held,length:round6(Math.max(.001,note2.start-held.start-.001))})}last.set(note2.pitch,index)}),sorted}function performPattern(pattern,notes,start,end,velocity,options){let feel=pattern.feel??{},tight=feel.tight===!0,human=options.seed!==void 0&&!tight,random2=mulberry32((options.seed??0)*7919+101>>>0),wobble=()=>random2()+random2()-1,tempo=options.tempo&&options.tempo>0?options.tempo:120,bar=4,into=(start%pattern.beats+pattern.beats)%pattern.beats,phase=pattern.beats>bar?Math.floor((into+1e-9)/bar)*bar:0,out=[];for(let cycle=start-phase;cycle<end-1e-9;cycle+=pattern.beats)for(let hit2 of pattern.hits){let from=cycle+hit2.at;if(from<start-1e-9||from>=end-1e-9)continue;let voices=patternVoices(notes,hit2,options.root,options.slash),onset=from,length=hit2.length,level2=velocity*hit2.velocity;if(human){let offbeat=Math.abs(hit2.at%1-.5)<1e-9;onset+=(offbeat?feel.swing??0:0)+msToBeats((feel.lay??0)+wobble()*(feel.timing??10),tempo),length*=1+wobble()*.1,level2*=1+wobble()*.07}if(onset=Math.max(start,onset),onset>=end-1e-9)continue;let to=Math.min(end,onset+length);voices.forEach((pitch2,index)=>{let roll=human&&voices.length>1?msToBeats((feel.roll??7)*(index===voices.length-1?.15:.35+.65*random2()),tempo):0,from2=Math.min(onset+roll,to-.001),weight=voiceWeight(index,voices.length,tight),scatter=human?1+wobble()*.04:1;out.push({pitch:pitch2,start:round6(from2),length:round6(Math.max(.001,to-from2)),velocity:round6(Math.max(.02,Math.min(1,level2*weight*scatter)))})})}return releaseRestrikes(out)}function perform(pitches,start,length,options={}){let mode=options.mode??"block",velocity=options.velocity??.8,notes=[...pitches].sort((a,b)=>a-b);if(notes.length===0||!(length>0))return[];let end=start+length,octaves=clampInt(options.octaves??1,1,4),spanned=[];for(let o=0;o<octaves;o+=1)for(let pitch2 of notes)pitch2+12*o<=127&&spanned.push(pitch2+12*o);let at3=(pitch2,from,to)=>({pitch:pitch2,start:round6(from),length:round6(Math.max(1e-6,to-from)),velocity});switch(mode){case"block":return notes.map(pitch2=>at3(pitch2,start,end));case"strum-up":case"strum-down":{let gap=Math.max(0,options.strum??DEFAULT_STRUM);return(mode==="strum-up"?notes:[...notes].reverse()).map((pitch2,index)=>at3(pitch2,Math.min(end-gap,start+index*gap),end)).filter(note2=>note2.length>0)}case"slop":{let amount=Math.min(1,Math.max(0,options.slop??DEFAULT_SLOP)),random2=mulberry32(options.seed??0),late=Math.min(amount*MAX_SLOP,length/2);return notes.map(pitch2=>at3(pitch2,start+random2()*late,end))}case"pattern":return performPattern(findChordPattern(options.pattern??1)??CHORD_PATTERNS[0],notes,start,end,velocity,options);case"guitar":{let bass=options.slash??notes[0],voicing=voiceGuitar(notes.map(mod12),mod12(bass),options.root??mod12(bass),options.guitar);return voicing?strokeVoicing(voicing,start,length,{...options.strokes!==void 0?{strokes:options.strokes}:{},...options.step!==void 0?{step:options.step}:{},...options.speed!==void 0?{speed:options.speed}:{},...options.tempo!==void 0?{tempo:options.tempo}:{},...options.seed!==void 0?{seed:options.seed}:{},velocity,strings:guitarStrings(options.guitar?.tune).length}):notes.map(pitch2=>at3(pitch2,start,end))}case"harp":{let gap=Math.max(0,options.strum??DEFAULT_STRUM*2);return spanned.map((pitch2,index)=>at3(pitch2,Math.min(end-.001,start+index*gap),end))}default:{let rate2=options.rate&&options.rate>0?options.rate:DEFAULT_ARP_RATE,steps2=Math.max(1,Math.floor(length/rate2+1e-9)),order;mode==="arp-down"?order=[...spanned].reverse():mode==="arp-updown"?order=spanned.length>2?[...spanned,...spanned.slice(1,-1).reverse()]:spanned:order=spanned;let random2=mulberry32(options.seed??0),out=[];for(let step2=0;step2<steps2;step2+=1){let from=start+step2*rate2,to=Math.min(end,from+rate2),pitch2=mode==="arp-random"?spanned[Math.floor(random2()*spanned.length)]:order[step2%order.length];out.push(at3(pitch2,from,to))}return out}}}var GUITAR_TUNINGS=Object.freeze({standard:[40,45,50,55,59,64],dropd:[38,45,50,55,59,64],doubledropd:[38,45,50,55,59,62],dadgad:[38,45,50,55,57,62],openg:[38,43,50,55,59,62],opend:[38,45,50,54,57,62],opene:[40,47,52,56,59,64],halfdown:[39,44,49,54,58,63],nashville:[52,57,62,67,59,64],bass:[28,33,38,43],ukulele:[67,60,64,69],requinto:[45,50,55,60,64,69]}),GUITAR_TUNING_NAMES=Object.keys(GUITAR_TUNINGS);function guitarStrings(tune){if(Array.isArray(tune))return tune;let name=String(tune??"standard").toLowerCase().replace(/[\s_-]/g,"");return GUITAR_TUNINGS[name]??GUITAR_TUNINGS.standard}function guitarFingers(frets){let fretted=frets.filter(f=>f>0);if(fretted.length===0)return 0;let min=Math.min(...fretted),at3=frets.flatMap((f,i)=>f===min?[i]:[]),between=frets.slice(at3[0],at3[at3.length-1]+1);return(at3.length>1&&!between.includes(0)?1:at3.length)+fretted.filter(f=>f>min).length}function requiredTones(tones,root,drops){let dropped=(tones.some(pc=>[3,4].includes(mod12(pc-root)))?[7,5,2]:[7,2]).map(step2=>mod12(root+step2)).filter(pc=>tones.includes(pc)).slice(0,drops);return tones.filter(pc=>!dropped.includes(pc))}function voiceGuitar(tones,bass,root,setup={},previous){let key=JSON.stringify([[...new Set([...tones,bass].map(mod12))],mod12(bass),mod12(root),setup.tune??null,setup.capo??null,setup.hand??null,setup.ring??null,setup.position??null,previous??null]);if(voicingCache.has(key)){let hit2=voicingCache.get(key);return voicingCache.delete(key),voicingCache.set(key,hit2),hit2}let voiced=searchGuitar(tones,bass,root,setup,previous);return voicingCache.set(key,voiced),voicingCache.size>VOICING_CACHE_SIZE&&voicingCache.delete(voicingCache.keys().next().value),voiced}var VOICING_CACHE_SIZE=256,voicingCache=new Map;function searchGuitar(tones,bass,root,setup,previous){let pcs=[...new Set([...tones,bass].map(mod12))],capo=clampInt(setup.capo??0,0,12),open=guitarStrings(setup.tune).map(pitch2=>pitch2+capo),n2=open.length,ring=Math.min(1,Math.max(0,setup.ring??.5)),stretch=clampInt(setup.hand??4,3,6),fifth=mod12(root+7),third=pcs.find(pc=>[3,4].includes(mod12(pc-root))),prev=previous?[...previous].sort((a,b)=>a-b):void 0;for(let drops=0;drops<=3;drops+=1){let required=requiredTones(pcs,root,drops),best,choose=frets=>{let idx=frets.flatMap((f,i)=>f<0?[]:[i]);if(idx.length<Math.min(n2,n2>=6?4:3))return;let interior=frets.slice(idx[0]).filter(f=>f<0).length;if(interior>(n2>=6?1:0))return;let pitches=idx.map(i=>open[i]+frets[i]);if(mod12(Math.min(...pitches))!==mod12(bass))return;let sounding=new Set(pitches.map(mod12));if(required.some(pc=>!sounding.has(pc)))return;let fingers=guitarFingers(frets);if(fingers>4)return;let fretted=frets.filter(f=>f>0),span4=fretted.length?Math.max(...fretted)-Math.min(...fretted):0;if(span4>stretch-1)return;let opens=frets.filter(f=>f===0).length;if(ring===0&&opens>0)return;let pos=fretted.length?Math.min(...fretted):0,cost=span4*.6+pos*.25+fingers*.4-idx.length-opens*.7*ring;if(cost+=interior*1.5,!sounding.has(fifth)&&pcs.includes(fifth)&&(cost+=.6),third!==void 0&&pitches.filter(p=>mod12(p)===third).length>1&&(cost+=.5),setup.position!==void 0&&(cost+=Math.abs(pos-setup.position)*.5),prev&&prev.length){let cur=[...pitches].sort((a,b)=>a-b),move=0;for(let i=0;i<cur.length;i+=1)move+=Math.abs(cur[i]-prev[Math.min(i,prev.length-1)]);cost+=move*.05}(!best||cost<best.cost-1e-9||Math.abs(cost-best.cost)<=1e-9&&frets.join()<best.frets.join())&&(best={frets:[...frets],cost})};for(let p=1;p<=12;p+=1){let options=open.map(o=>{let list=[-1];pcs.includes(mod12(o))&&list.push(0);for(let f=p;f<p+stretch;f+=1)pcs.includes(mod12(o+f))&&list.push(f);return list}),frets=new Array(n2).fill(-1),walk=s=>{if(s===n2)return choose(frets);for(let f of options[s])frets[s]=f,walk(s+1)};walk(0)}if(best){let{frets}=best,strings=frets.flatMap((f,i)=>f<0?[]:[i]);return Object.freeze({frets:Object.freeze(frets),pitches:Object.freeze(strings.map(i=>open[i]+frets[i])),strings:Object.freeze(strings)})}}}var STROKE_PATTERNS=Object.freeze({down:"D",folk:"D-DU-UDU",pop:"D-DU-UD-",punk:"DDDDDDDD",funk:"xuxuDuxuxuDuxuxu",reggae:".U.U",waltz:"Ddd",jangle:"D-DUDUDU",island:"D-DU-UDU",chuck:"D-xU-UxU",soul:"..D...D."}),STROKE_PATTERN_NAMES=Object.keys(STROKE_PATTERNS),STROKE_CHARS=/^[DUdux.\-]+$/,DEFAULT_STROKE_SPEED=.022,DEFAULT_STROKE_STEP=.5;function strokeGrid(text2){let raw=(text2??"down").trim(),named=STROKE_PATTERNS[raw.toLowerCase()];if(named)return named;let grid2=raw.replace(/[|\s]/g,"");return grid2.length>0&&grid2.length<=64&&STROKE_CHARS.test(grid2)?grid2:void 0}var STROKE_TIMING=8,UPSTROKE_LAG=3,CHOP_MS=120;function strokeAccent(beat2){let near=value=>Math.abs(value-Math.round(value))<1e-9;return near(beat2)?Math.round(beat2)%2===0?1:.92:near(beat2*2)?.82:.74}function strokeVoicing(voicing,start,length,options={}){let grid2=strokeGrid(options.strokes)??"D",step2=options.step&&options.step>0?options.step:DEFAULT_STROKE_STEP,tempo=options.tempo&&options.tempo>0?options.tempo:120,pace=Math.min(1.4,Math.max(.7,Math.sqrt(120/tempo))),sweep=Math.max(0,options.speed??DEFAULT_STROKE_SPEED)*pace*tempo/60,base=options.velocity??.8,total=Math.max(2,options.strings??6),human=options.seed!==void 0,random2=mulberry32((options.seed??0)*7919+211>>>0),wobble=()=>random2()+random2()-1,ms2=value=>value/1e3*(tempo/60),sounding=voicing.strings,end=start+length,ringing=new Map,out=[],stop=(string,at3)=>{let held=ringing.get(string);if(!held)return;let cut=round6(Math.max(.001,Math.min(held.note.length,at3-held.note.start)));out[held.index]={...held.note,length:cut},ringing.delete(string)},steps2=Math.max(1,Math.round(length/step2)),struck=Array.from({length:steps2},(_,s)=>s).filter(s=>!"-.".includes(grid2[s%grid2.length])),top=Math.max(.5,...struck.map(s=>strokeAccent(s*step2)));for(let s=0;s<steps2;s+=1){let ch=grid2[s%grid2.length],t0=start+s*step2;if(t0>=end-1e-9)break;if(ch==="-")continue;if(ch==="."){for(let string of[...ringing.keys()])stop(string,t0);continue}let accent=strokeAccent(s*step2),order,velocity=base*accent/top,ring=end-t0,all=sounding.map((_,k)=>k);switch(ch){case"D":order=all;break;case"U":order=all.slice(-4).reverse(),velocity*=.85;break;case"d":order=all.slice(-4),velocity*=.62;break;case"u":order=all.slice(-3).reverse(),velocity*=.55;break;default:order=all,velocity*=accent===.92?.8:.5,ring=Math.min(ring,.03*(tempo/60))}let up=ch==="U"||ch==="u",onset=human?Math.max(start,t0+ms2(wobble()*STROKE_TIMING+(up?UPSTROKE_LAG:0))):t0;human&&(velocity*=1+wobble()*.06);let choke=grid2[(s+1)%grid2.length]==="."?onset+Math.min(step2,ms2(CHOP_MS*(human?1+wobble()*.1:1))):end,gaps=order.map((k,position)=>position===0?0:Math.abs(sounding[k]-sounding[order[position-1]])/(total-1)*sweep),even=gaps.reduce((sum,gap)=>sum+gap,0),uneven=human?gaps.map(gap=>gap*(1+wobble()*.3)):gaps,scale3=human&&even>0?even/uneven.reduce((a,b)=>a+b,0):1,offset=0;order.forEach((k,position)=>{offset+=uneven[position]*scale3;let string=sounding[k],at3=onset+offset;if(at3>=end-1e-9)return;stop(string,at3);let scatter=human?1+wobble()*.04:1,note2={pitch:voicing.pitches[k],start:round6(at3),length:round6(Math.max(.001,Math.min(ring,end-at3,choke-at3))),velocity:round6(Math.max(.05,Math.min(1,velocity*(1-.04*position)*scatter)))};out.push(note2),ch!=="x"&&ringing.set(string,{note:note2,index:out.length-1})})}return out.sort((a,b)=>a.start-b.start||a.pitch-b.pitch)}var PROGRESSION_PRESETS=Object.freeze([{name:"axis",mode:"major",numerals:["I","V","vi","IV"],description:"I\u2013V\u2013vi\u2013IV, the four-chord pop loop"},{name:"sad-pop",mode:"major",numerals:["vi","IV","I","V"],description:"vi\u2013IV\u2013I\u2013V, the same loop from the relative minor"},{name:"fifties",mode:"major",numerals:["I","vi","IV","V"],description:"I\u2013vi\u2013IV\u2013V doo-wop"},{name:"ii-v-i",mode:"major",numerals:["ii","V","I","I"],sevenths:!0,description:"ii7\u2013V7\u2013Imaj7, the jazz cadence"},{name:"turnaround",mode:"major",numerals:["I","vi","ii","V"],sevenths:!0,description:"Imaj7\u2013vi7\u2013ii7\u2013V7 turnaround"},{name:"canon",mode:"major",numerals:["I","V","vi","iii","IV","I","IV","V"],description:"Pachelbel's canon"},{name:"aeolian",mode:"minor",numerals:["i","VI","III","VII"],description:"i\u2013VI\u2013III\u2013VII minor anthem"},{name:"andalusian",mode:"minor",numerals:["i","VII","VI","V"],description:"i\u2013VII\u2013VI\u2013V descending (major V)"},{name:"minor-ii-v",mode:"minor",numerals:["ii\xF8","V7","i","i"],sevenths:!0,description:"ii\xF87\u2013V7\u2013i minor cadence"},{name:"dorian-vamp",mode:"dorian",numerals:["i","IV"],sevenths:!0,description:"i7\u2013IV7 dorian vamp"},{name:"mixolydian-rock",mode:"mixolydian",numerals:["I","bVII","IV","I"],description:"I\u2013bVII\u2013IV\u2013I mixolydian rock"}]);function mulberry32(seed){let state=Math.trunc(seed)>>>0;return()=>{state=state+1831565813>>>0;let t=state;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}}function voiceProgression(key,chords,options={}){let flats=keyUsesFlats(key),previous;return chords.map(chord2=>{let pitches=voiceChord(chord2,{...options.inversion!==void 0?{inversion:options.inversion}:{},...options.spread?{spread:options.spread}:{},...options.anchor!==void 0?{anchor:options.anchor}:{},previous:options.lead===!1?void 0:previous});return previous=pitches,Object.freeze({name:chordName(chord2,flats),roman:romanOf(key,chord2),pitches:Object.freeze(pitches),...options.bass?{bass:bassNote(chord2)}:{}})})}function mod12(value){return(Math.trunc(value)%12+12)%12}function clampInt(value,min,max){return Number.isFinite(value)?Math.max(min,Math.min(max,Math.round(value))):min}function round6(value){return Math.round(value*1e6)/1e6}function resolveChord(key,text2){return parseRoman(key,text2)??parseChord(text2)}function renderProgression(options){let span4=options.beatsPerChord&&options.beatsPerChord>0?options.beatsPerChord:4,start=options.start??0,voiced=voiceProgression(options.key,options.chords,{...options.inversion!==void 0?{inversion:options.inversion}:{},...options.spread?{spread:options.spread}:{},...options.anchor!==void 0?{anchor:options.anchor}:{},...options.lead!==void 0?{lead:options.lead}:{},bass:!0}),notes=[],bass=[],velocity=options.perform?.velocity??.8,mode=options.bassMode??(options.bass?"chords":"off");return voiced.forEach((chord2,index)=>{let at3=start+index*span4;mode!=="solo"&¬es.push(...perform(chord2.pitches,at3,span4,{...options.perform,seed:(options.perform?.seed??0)+index,...options.perform?.mode==="guitar"||options.perform?.mode==="pattern"?{root:options.chords[index].root,...options.chords[index].bass!==void 0?{slash:options.chords[index].bass}:{}}:{}}));let source=options.chords[index],under=mode==="off"?void 0:mode==="unison"?bassNote({...source,bass:void 0}):chord2.bass;under!==void 0&&bass.push({pitch:under,start:round6(at3),length:round6(span4),velocity})}),{voiced:mode!=="off"?voiced:voiced.map(({bass:_bass,...rest})=>Object.freeze(rest)),notes,bass}}function storedClip(clip,index,ticks){let{kind:_kind,at:at3,id,...rest}=clip;return Object.freeze({id:id??defaultClipId(index),...rest,startTick:ticks(at3)})}function defaultClipId(index){return index===0?"clip":`clip${index+1}`}function storedTake(spec,ticks){let{kind:_kind,at:at3,in:from,out:to,...rest}=spec;return Object.freeze({offset:0,latency:0,...rest,startTick:ticks(at3),inTick:ticks(from),outTick:ticks(to)})}function trackClips(input,name,slug){let local=src=>{let path=src.replace(/^\.\//,"");return path.startsWith("tracks/")||path.startsWith("pack:")?path:`tracks/${slug}/${path}`},out={};if(input.clips!==void 0){if(!Array.isArray(input.clips))throw new DawnSdkError(`track ${name}: clips must be an array of audio()`);let clips=input.clips.flat().map((item,index)=>{if(!isRecord(item)||item.kind!=="audio")throw new DawnSdkError(`track ${name}: clips[${index}] must come from audio() or repeatAudio()`);let clip=item;return Object.freeze({...clip,src:local(clip.src)})});if(clips.length>256)throw new DawnSdkError(`track ${name}: at most 256 clips`);clips.length>0&&(out.clips=Object.freeze(clips))}if(input.takes!==void 0){if(!Array.isArray(input.takes))throw new DawnSdkError(`track ${name}: takes must be an array of take()`);let takes=input.takes.map((item,index)=>{if(!isRecord(item)||item.kind!=="take")throw new DawnSdkError(`track ${name}: takes[${index}] must come from take()`);let spec=item;return Object.freeze({...spec,src:local(spec.src)})});takes.length>0&&(out.takes=Object.freeze(takes))}return out}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function finite(value,label){if(typeof value!="number"||!Number.isFinite(value))throw new DawnSdkError(`${label} must be a finite number`);return value}function text(value,label){if(typeof value!="string"||value.length===0||value.length>1024)throw new DawnSdkError(`${label} must be a short string`);return value}function beat(value,label){let number=finite(value,label);if(number<0)throw new DawnSdkError(`${label} must be \u2265 0 beats`);return number}function positive(value,label){let number=finite(value,label);if(number<=0)throw new DawnSdkError(`${label} must be > 0`);return number}function unit(value,label){let number=finite(value,label);if(number<0||number>1)throw new DawnSdkError(`${label} must be between 0 and 1`);return number}function bool(value,label){if(typeof value!="boolean")throw new DawnSdkError(`${label} must be true or false`);return value}function round(value){return Math.round(value*1e9)/1e9}function hash64(text2){let a=2166136261,b=3421674724;for(let index=0;index<text2.length;index+=1){let code=text2.charCodeAt(index);a=Math.imul(a^code,16777619)>>>0,b=Math.imul(b^code*31+index&65535,16777619)>>>0}return a.toString(16).padStart(8,"0")+b.toString(16).padStart(8,"0")}var PatternSignal=class _PatternSignal{constructor(op,args=[],xf=[]){this.op=op;this.args=args;this.xf=xf;Object.freeze(this.args),Object.freeze(this.xf),Object.freeze(this)}op;args;xf;kind="signal";with(transform){return new _PatternSignal(this.op,this.args,[...this.xf,transform])}range(lo,hi){return this.with(["range",finite(lo,"range lo"),finite(hi,"range hi")])}rangex(lo,hi){return this.with(["rangex",positive(lo,"rangex lo"),positive(hi,"rangex hi")])}slow(n2){return this.with(["slow",positive(n2,"slow")])}fast(n2){return this.with(["fast",positive(n2,"fast")])}segment(n2){return this.with(["segment",positive(n2,"segment")])}add(value){return this.with(["add",signalOperand(value,"add")])}mul(value){return this.with(["mul",signalOperand(value,"mul")])}early(bars){return this.with(["early",finite(bars,"early")])}late(bars){return this.with(["late",finite(bars,"late")])}every(n2,transform){let count2=finite(n2,"every");if(!Number.isInteger(count2)||count2<1)throw new DawnSdkError("every needs a whole number of bars \u2265 1");let applied=transform(new _PatternSignal("self"));if(!(applied instanceof _PatternSignal)||applied.op!=="self")throw new DawnSdkError("every(n, f): f must return its argument with transforms, like (s) => s.fast(2)");return this.with(["every",count2,applied.xf])}};function signalOperand(value,label){return value instanceof PatternSignal?value:finite(value,label)}function isPatternSignal(value){return value instanceof PatternSignal||isRecord(value)&&value.kind==="signal"&&typeof value.op=="string"}var sine=new PatternSignal("sine"),cosine=new PatternSignal("cosine"),saw=new PatternSignal("saw"),isaw=new PatternSignal("isaw"),tri=new PatternSignal("tri"),square=new PatternSignal("square"),rand=new PatternSignal("rand"),perlin=new PatternSignal("perlin");function irand(n2){let count2=finite(n2,"irand");if(!Number.isInteger(count2)||count2<1)throw new DawnSdkError("irand needs a whole number \u2265 1");return new PatternSignal("irand",[count2])}function pat(text2){if(typeof text2!="string"||text2.length>512)throw new DawnSdkError("pat needs a mini-notation string (\u2264 512 characters)");return parseMini(text2),new PatternSignal("seq",[text2])}function steady(value){return new PatternSignal("const",[finite(value,"steady")])}var miniCache=new Map;function parseMini(text2){let cached=miniCache.get(text2);if(cached)return cached;let tokens=text2.match(/\[|\]|<|>|\*|!|[^\s[\]<>*!]+/g)??[],at3=0,fail6=why=>{throw new DawnSdkError(`pat("${text2.slice(0,40)}"): ${why}`)},steps2=close=>{let out=[];for(;at3<tokens.length&&tokens[at3]!==close;){let token=tokens[at3];at3+=1;let node2;if(token==="["||token==="<"){let inner=steps2(token==="["?"]":">");tokens[at3]!==(token==="["?"]":">")&&fail6(`unclosed ${token}`),at3+=1,inner.length===0&&fail6(`empty ${token}`),node2=token==="["?{t:"seq",c:inner}:{t:"alt",c:inner}}else/^-?(\d+\.?\d*|\.\d+)(e-?\d+)?$/.test(token)?node2={t:"num",v:Number(token)}:fail6(`"${token}" is not a number`);for(;tokens[at3]==="*"||tokens[at3]==="!";){let op=tokens[at3],count2=Number(tokens[at3+1]);if((!Number.isFinite(count2)||count2<=0||op==="!"&&!Number.isInteger(count2))&&fail6(`${op} needs a positive number`),at3+=2,op==="*")node2={t:"fast",n:count2,c:node2};else for(let i=1;i<count2;i+=1)out.push(node2)}out.push(node2)}return out},top=steps2(void 0);at3<tokens.length&&fail6(`unexpected ${tokens[at3]}`),top.length===0&&fail6("no values");let root={t:"seq",c:top};return miniCache.size>256&&miniCache.clear(),miniCache.set(text2,root),root}function catTime(t,n2){let m=Math.floor(t);return[(m%n2+n2)%n2,t-(m-Math.floor(m/n2))]}function miniAt(node2,t){switch(node2.t){case"num":return node2.v;case"fast":return miniAt(node2.c,t*node2.n);case"alt":{let[index,local]=catTime(t,node2.c.length);return miniAt(node2.c[index],local)}case"seq":{let[index,local]=catTime(t*node2.c.length,node2.c.length);return miniAt(node2.c[index],local)}}}function signalHash(text2){let hash=Number.parseInt(hash64(text2).slice(0,8),16);return hash^=hash>>>16,hash=Math.imul(hash,2246822507),hash^=hash>>>13,hash=Math.imul(hash,3266489909),hash^=hash>>>16,hash>>>0}function randAt(t,seed){return finite(t,"random signal cycle"),finite(seed,"random signal seed"),signalHash(`dawn.signal.random/v2|${seed}|${t}`)/4294967296}function perlinAt(t,seed){finite(t,"perlin cycle");let ta=Math.floor(t);if(!Number.isSafeInteger(ta)||!Number.isSafeInteger(ta+1))throw new DawnSdkError("perlin cycle needs safe adjacent integer coordinates");let x=t-ta,smoother=Math.max(0,Math.min(1,6*x**5-15*x**4+10*x**3)),a=randAt(ta,seed),b=randAt(ta+1,seed);return a+smoother*(b-a)}function sourceAt(signal,t,seed){let frac2=t-Math.floor(t);switch(signal.op){case"sine":return(Math.sin(Math.PI*2*t)+1)/2;case"cosine":return(Math.sin(Math.PI*2*(t+.25))+1)/2;case"saw":return frac2;case"isaw":return 1-frac2;case"tri":return frac2<.5?frac2*2:2-frac2*2;case"square":return Math.floor((t*2%2+2)%2);case"rand":return randAt(t,seed);case"perlin":return perlinAt(t,seed);case"irand":return Math.trunc(randAt(t,seed)*Number(signal.args[0]));case"seq":return miniAt(parseMini(String(signal.args[0])),t);case"const":return Number(signal.args[0]);case"self":throw new DawnSdkError("a signal from every(n, f) cannot stand alone")}}function chainAt(signal,xf,count2,t,seed){if(count2===0)return sourceAt(signal,t,seed);let step2=xf[count2-1],inner=time=>chainAt(signal,xf,count2-1,time,seed),operand=value=>typeof value=="number"?value:signalAt(value,t,seed);switch(step2[0]){case"range":return inner(t)*(step2[2]-step2[1])+step2[1];case"rangex":{let lo=Math.log(step2[1]);return Math.exp(inner(t)*(Math.log(step2[2])-lo)+lo)}case"slow":return inner(t/step2[1]);case"fast":return inner(t*step2[1]);case"segment":return inner(Math.floor(t*step2[1])/step2[1]);case"early":return inner(t+step2[1]);case"late":return inner(t-step2[1]);case"add":return inner(t)+operand(step2[1]);case"mul":return inner(t)*operand(step2[1]);case"every":{if((Math.floor(t)%step2[1]+step2[1])%step2[1]!==0)return inner(t);let nested=[...xf.slice(0,count2-1),...step2[2]];return chainAt(signal,nested,nested.length,t,seed)}}}function signalAt(signal,cycle,seed=0){return chainAt(signal,signal.xf,signal.xf.length,cycle,seed)}function signalSeed(trackId){return signalHash(`dawn.signal.track/v2|${trackId}`)}function signalSteps(signal){let stepped=xf=>xf.some(step2=>step2[0]==="segment"||step2[0]==="every"&&stepped(step2[2])||(step2[0]==="add"||step2[0]==="mul")&&step2[1]instanceof PatternSignal&&signalSteps(step2[1]));return["square","rand","irand","seq","const"].includes(signal.op)||stepped(signal.xf)}function bakeSignal(signal,options){let steps2=signalSteps(signal),budget=steps2?128:256,perBar=Math.max(1,Math.min(16,Math.floor(budget/Math.max(1,options.bars)))),count2=Math.max(1,Math.min(budget,Math.ceil(options.bars*perBar))),map=options.map??(value=>value),out=[],push=(tick,value)=>{let last=out[out.length-1];last&&last.tick>=tick||out.push({tick,value})},ticksAt=k=>Math.round(k*options.ticksPerBar/perBar);for(let k=0;k<count2;k+=1){let value=Math.round(map(signalAt(signal,k/perBar,options.seed))*1e6)/1e6||0;if(!Number.isFinite(value))throw new DawnSdkError("a signal produced a value that is not finite");let tick=ticksAt(k);if(steps2){let previous=out[out.length-1];if(previous&&previous.value===value)continue;previous&&ticksAt(k)-1>previous.tick&&push(tick-1,previous.value),push(tick,value)}else push(tick,value)}let lean=out.filter((point,index)=>index===0||index===out.length-1||!(out[index-1].value===point.value&&out[index+1].value===point.value));return Object.freeze(lean.map(point=>Object.freeze(point)))}var SIGNAL_OPS=["sine","cosine","saw","isaw","tri","square","rand","perlin","irand","seq","const"];function signalFromData(input,depth=0){if(input instanceof PatternSignal)return input;if(!isRecord(input)||input.kind!=="signal")throw new DawnSdkError("a signal must come from sine, saw, pat(), \u2026");if(depth>8)throw new DawnSdkError("signals nest at most 8 deep");let op=input.op;if(!SIGNAL_OPS.includes(op))throw new DawnSdkError(`unknown signal "${String(input.op).slice(0,32)}"`);let args=Array.isArray(input.args)?input.args:[],base;op==="irand"?base=irand(args[0]):op==="seq"?base=pat(args[0]):op==="const"?base=steady(args[0]):base=new PatternSignal(op);let xf=Array.isArray(input.xf)?input.xf:[];if(xf.length>32)throw new DawnSdkError("a signal holds at most 32 transforms");let apply=(signal,steps2)=>steps2.reduce((acc,raw)=>{if(!Array.isArray(raw))throw new DawnSdkError("a signal transform must be a list");let[name,a,b]=raw;switch(name){case"range":case"rangex":return acc[name](a,b);case"slow":case"fast":case"segment":case"early":case"late":return acc[name](a);case"add":case"mul":return acc[name](typeof a=="number"?a:signalFromData(a,depth+1));case"every":{if(!Array.isArray(b)||b.length>32)throw new DawnSdkError("every holds at most 32 transforms");return acc.every(a,self=>apply(self,b))}default:throw new DawnSdkError(`unknown signal transform "${String(name).slice(0,32)}"`)}},signal);return apply(base,xf)}var PATCH_SIGNALS=new WeakMap;function isPatchValue(value){return isRecord(value)&&value.kind==="patch"}function patchSignals(value){return PATCH_SIGNALS.get(value)??[]}var SONG_ARCHETYPES=Object.freeze(["banger","ballad","anthem","lullaby","interlude"]),GROOVE_FAMILIES=Object.freeze(["four-floor-pop","trance-4x4","uk-2step","dnb","gallop","jersey","trap-halftime","brushed-halftime","breakbeat","drumless"]),VOCAL_SPACES=Object.freeze(["slapback","pingpong-8th","bone-dry","room-double","dotted-multitap","bright-plate","reverse-swell","quarter-trail","gap-bloom"]),SONG_FORMS=Object.freeze(["verse-chorus","verse-chorus-bridge","build-drop","through-composed","lullaby-arc"]),ENERGY_SHAPES=Object.freeze(["rise","build-drop-build","arc","flat-filter-arc"]);var SONG_STYLE_GROUPS=Object.freeze({extends:null,archetype:null,tempo:null,swing:null,key:null,mode:null,modulation:null,groove:null,drums:["kit","pump"],palette:null,harmony:["extensions","changesPerBar"],register:["verseMidi","chorusMedianMidi","p90Max"],vocal:["space","themes"],form:null,seconds:null,energy:null,density:["chorus","maxBarsWithoutNew"],instrumentalPeak:null,tricks:["require","prefer","forbid","featured"],mix:["leadBand","sectionSpread"],master:["lufs","tpMax"],lint:null,schema:null});var RHYTHM_LIMITS=Object.freeze({maxRows:16,maxSteps:64,maxRepeats:16,maxCycles:16,maxRotate:64,maxSeed:1e6,minGate:.05,maxGate:4,maxSwing:.5,maxNudge:.5,minDivisionBeats:1/24,maxDivisionBeats:16}),RHYTHM_DEFAULTS=Object.freeze({steps:16,pulses:4,rotate:0,division:"1/16",repeats:0,pace:0,ramp:0,velocity:.8,accent:0,accents:1,gate:1,probability:1,seed:0,swing:0,nudge:0}),DIVISIONS=Object.freeze(["1/32","1/16t","1/16","1/8t","1/8","1/4t","1/4","1/2","1/1"]);function divisionBeats(value){let match=/^(\d{1,2})\/(\d{1,3})(t?)$/i.exec(value.trim());if(!match)return;let numerator=Number(match[1]),denominator=Number(match[2]);if(numerator<1||denominator<1)return;let beats=4*numerator/denominator*(match[3]?2/3:1);if(!(beats<RHYTHM_LIMITS.minDivisionBeats-1e-12||beats>RHYTHM_LIMITS.maxDivisionBeats+1e-12))return beats}function canonicalDivision(value){return divisionBeats(value)===void 0?void 0:value.trim().toLowerCase()}var GRID=/^[xXgf.\-]{1,64}$/;function normalizeRhythmRow(input,label="rhythm"){if(typeof input!="object"||input===null||Array.isArray(input))throw new Error(`${label} must be an object`);let value=input;for(let key of Object.keys(value))if(!ROW_KEYS.has(key))throw new Error(`${label} has unknown field ${key}`);if(typeof value.voice!="string"||value.voice.trim().length===0||value.voice.length>32)throw new Error(`${label} voice must be a short non-empty string`);let out={voice:value.voice.trim()},steps2=RHYTHM_DEFAULTS.steps;if(value.grid!==void 0){if(typeof value.grid!="string"||!GRID.test(value.grid))throw new Error(`${label} grid must be 1..64 of x X g f . -`);if(out.grid=value.grid.replace(/-/g,"."),steps2=value.grid.length,value.steps!==void 0&&value.steps!==steps2)throw new Error(`${label} steps must match the grid length`)}else steps2=integer(value.steps,RHYTHM_DEFAULTS.steps,1,RHYTHM_LIMITS.maxSteps,`${label} steps`),steps2!==RHYTHM_DEFAULTS.steps&&(out.steps=steps2);let pulses=integer(value.pulses,RHYTHM_DEFAULTS.pulses,0,RHYTHM_LIMITS.maxSteps,`${label} pulses`);if(value.grid===void 0&&pulses>steps2)throw new Error(`${label} pulses must be at most steps (${steps2})`);value.grid===void 0&&pulses!==RHYTHM_DEFAULTS.pulses&&(out.pulses=pulses);let rotate2=integer(value.rotate,0,-RHYTHM_LIMITS.maxRotate,RHYTHM_LIMITS.maxRotate,`${label} rotate`);value.grid===void 0&&rotate2!==0&&(out.rotate=rotate2);for(let key of["division","time"]){if(value[key]===void 0)continue;let text2=typeof value[key]=="string"?canonicalDivision(value[key]):void 0;if(text2===void 0)throw new Error(`${label} ${key} must be a note value like "1/16" or "1/8t"`);key==="division"&&text2===RHYTHM_DEFAULTS.division||(out[key]=text2)}let repeats=integer(value.repeats,0,0,RHYTHM_LIMITS.maxRepeats,`${label} repeats`);repeats!==0&&(out.repeats=repeats);let ranged=[["pace",-1,1],["ramp",-1,1],["velocity",0,1],["accent",0,1],["gate",RHYTHM_LIMITS.minGate,RHYTHM_LIMITS.maxGate],["probability",0,1],["swing",-RHYTHM_LIMITS.maxSwing,RHYTHM_LIMITS.maxSwing],["nudge",-RHYTHM_LIMITS.maxNudge,RHYTHM_LIMITS.maxNudge]];for(let[key,min,max]of ranged){let number=finite2(value[key],RHYTHM_DEFAULTS[key],min,max,`${label} ${key}`);number!==RHYTHM_DEFAULTS[key]&&(out[key]=number)}if(value.legato!==void 0&&typeof value.legato!="boolean")throw new Error(`${label} legato must be true or false`);value.legato===!0&&(out.legato=!0);let accents=integer(value.accents,1,0,RHYTHM_LIMITS.maxSteps,`${label} accents`);accents!==1&&(out.accents=accents);let seed=integer(value.seed,0,0,RHYTHM_LIMITS.maxSeed,`${label} seed`);if(seed!==0&&(out.seed=seed),value.cycles!==void 0){if(!Array.isArray(value.cycles)||value.cycles.length<1||value.cycles.length>RHYTHM_LIMITS.maxCycles)throw new Error(`${label} cycles must be 1..${RHYTHM_LIMITS.maxCycles} entries`);out.cycles=Object.freeze(value.cycles.map((cycle,index)=>normalizeCycle(cycle,steps2,`${label} cycles[${index}]`)))}return Object.freeze(ORDER.filter(key=>key in out).reduce((row2,key)=>(row2[key]=out[key],row2),{}))}var ORDER=["voice","steps","pulses","rotate","division","grid","repeats","time","pace","ramp","velocity","accent","accents","gate","legato","probability","seed","swing","nudge","cycles"],ROW_KEYS=new Set(ORDER),CYCLE_KEYS=new Set(["pulses","rotate","repeats","probability","velocity"]);function normalizeCycle(input,steps2,label){if(typeof input!="object"||input===null||Array.isArray(input))throw new Error(`${label} must be an object`);let value=input,out={};for(let key of Object.keys(value))if(!CYCLE_KEYS.has(key))throw new Error(`${label} has unknown field ${key}`);return value.pulses!==void 0&&(out.pulses=integer(value.pulses,0,0,steps2,`${label} pulses`)),value.rotate!==void 0&&(out.rotate=integer(value.rotate,0,-RHYTHM_LIMITS.maxRotate,RHYTHM_LIMITS.maxRotate,`${label} rotate`)),value.repeats!==void 0&&(out.repeats=integer(value.repeats,0,0,RHYTHM_LIMITS.maxRepeats,`${label} repeats`)),value.probability!==void 0&&(out.probability=finite2(value.probability,1,0,1,`${label} probability`)),value.velocity!==void 0&&(out.velocity=finite2(value.velocity,.8,0,1,`${label} velocity`)),Object.freeze(out)}function integer(value,fallback,min,max,label){if(value===void 0)return fallback;if(typeof value!="number"||!Number.isInteger(value)||value<min||value>max)throw new Error(`${label} must be an integer ${min}..${max}`);return value}function finite2(value,fallback,min,max,label){if(value===void 0)return fallback;if(typeof value!="number"||!Number.isFinite(value)||value<min||value>max)throw new Error(`${label} must be a number ${min}..${max}`);return value}var DRUM_VOICES=Object.freeze([Object.freeze({voice:"kick",pitch:36,label:"kick",short:"kick"}),Object.freeze({voice:"snare",pitch:38,label:"snare",short:"snr"}),Object.freeze({voice:"clap",pitch:39,label:"clap",short:"clap"}),Object.freeze({voice:"rim",pitch:37,label:"rim",short:"rim"}),Object.freeze({voice:"tom",pitch:45,label:"tom",short:"tom"}),Object.freeze({voice:"hat",pitch:42,label:"hat",short:"chh"}),Object.freeze({voice:"openhat",pitch:46,label:"open",short:"ohh"})]),DRUM_INSTRUMENTS=Object.freeze(["kit","drums","drum","drumkit"]),VOICE_ALIASES=Object.freeze({kick:"kick",bd:"kick",snare:"snare",sd:"snare",clap:"clap",cp:"clap",rim:"rim",rimshot:"rim",perc:"rim",tom:"tom",lt:"tom",hat:"hat",hh:"hat",hihat:"hat","hi-hat":"hat",closedhat:"hat","closed-hat":"hat",chh:"hat",openhat:"openhat","open-hat":"openhat",ohh:"openhat",oh:"openhat",open:"openhat"}),PITCH_ALIASES=Object.freeze({35:"kick",40:"snare",41:"tom",43:"tom",44:"hat",47:"tom",48:"tom",50:"tom"});function isDrumInstrument(instrument){return typeof instrument!="string"?!1:DRUM_INSTRUMENTS.includes(instrument.trim().toLowerCase())}function drumVoiceForPitch(pitch2){return DRUM_VOICES.find(info=>info.pitch===pitch2)?.voice??PITCH_ALIASES[pitch2]??"rim"}var BASE=Object.freeze({kick:{base:45,sweep:105,sweepRate:28,decay:7.5,click:.12,clickDecay:300,level:1},tom:{base:105,sweep:95,sweepRate:18,decay:9,click:0,clickDecay:300,level:1},snare:{tone:185,toneLevel:.45,toneDecay:22,noise:.7,noiseDecay:16,snap:0},clap:{gap:.01,tail:18,band:.35,level:1},hat:{level:.42,decay:60,tone:1,metal:0},openhat:{level:.36,decay:9,tone:1,metal:0},rim:{high:1700,low:820,decay:90,level:1},seconds:.6,drive:0,bits:0,hold:1,gain:1});function kit(name,label,description,overrides){let out={name,label,description};for(let[key,value]of Object.entries(BASE)){let override=overrides[key];out[key]=typeof value=="object"?Object.freeze({...value,...override}):override??value}return Object.freeze(out)}var SYNTH_KITS=Object.freeze([kit("syn808","808 (synth)","long sub boom, snappy snare, metallic hats",{kick:{base:49,sweep:70,sweepRate:20,decay:2.6,click:.03,clickDecay:400},tom:{base:95,sweep:40,sweepRate:14,decay:5},snare:{tone:238,toneLevel:.5,toneDecay:18,noise:.55,noiseDecay:20,snap:.8},clap:{gap:.011,tail:14},hat:{level:.36,decay:70,metal:1},openhat:{level:.3,decay:7,metal:1},rim:{high:1870,low:470,decay:110},seconds:1.4}),kit("syn909","909 (synth)","punchy clicky kick, bright noisy snare",{kick:{base:52,sweep:190,sweepRate:38,decay:6,click:.35,clickDecay:500},snare:{tone:205,toneLevel:.4,toneDecay:26,noise:.9,noiseDecay:12,snap:1},clap:{gap:.009,tail:12,band:.5},hat:{level:.4,decay:55,tone:1,metal:.3},openhat:{level:.34,decay:6,metal:.3},drive:.35}),kit("acoustic","Acoustic-ish","beater kick, wire snare, darker cymbals",{kick:{base:62,sweep:45,sweepRate:30,decay:11,click:.3,clickDecay:180},tom:{base:120,sweep:50,sweepRate:10,decay:7,click:.1},snare:{tone:175,toneLevel:.35,toneDecay:18,noise:.85,noiseDecay:9,snap:.3},clap:{tail:22,band:.25},hat:{level:.4,decay:45,tone:.55,metal:.5},openhat:{level:.34,decay:4.5,tone:.55,metal:.5},rim:{high:1300,low:640,decay:70},seconds:.9}),kit("lofi","Lo-fi dusty","soft round kick, crushed and dark",{kick:{base:50,sweep:70,sweepRate:22,decay:8,click:.05},snare:{toneLevel:.5,noise:.6,noiseDecay:14,snap:0},hat:{level:.38,decay:50,tone:.3},openhat:{level:.3,decay:8,tone:.3},drive:.25,bits:8,hold:3,gain:.95}),kit("electro","Electro minimal","tight short kick, clicky rim, ticking hats",{kick:{base:56,sweep:240,sweepRate:60,decay:13,click:.2,clickDecay:700},tom:{base:140,sweep:160,sweepRate:40,decay:14},snare:{tone:310,toneLevel:.55,toneDecay:35,noise:.5,noiseDecay:28,snap:1},clap:{gap:.008,tail:26,band:.6},hat:{level:.38,decay:120,metal:.6},openhat:{level:.32,decay:14,metal:.6},rim:{high:2400,low:1100,decay:140},seconds:.5}),kit("trap","Trap","distorted long 808, crisp hats, high snare",{kick:{base:43,sweep:90,sweepRate:16,decay:1.6,click:.08,clickDecay:400,level:.9},snare:{tone:265,toneLevel:.45,toneDecay:20,noise:.8,noiseDecay:15,snap:1},clap:{gap:.012,tail:16,band:.55},hat:{level:.4,decay:95,tone:1,metal:.4},openhat:{level:.32,decay:8,metal:.4},seconds:1.6,drive:.55}),kit("syn606","606 (synth)","thin tight kick, snappy snare, ticking metal hats",{kick:{base:58,sweep:120,sweepRate:45,decay:11,click:.1,clickDecay:600,level:.95},tom:{base:120,sweep:60,sweepRate:22,decay:11},snare:{tone:250,toneLevel:.35,toneDecay:30,noise:.85,noiseDecay:22,snap:1},clap:{gap:.009,tail:22,band:.55},hat:{level:.34,decay:90,metal:1},openhat:{level:.3,decay:11,metal:1},rim:{high:2100,low:640,decay:160},seconds:.6}),kit("syn707","707 (synth)","punchy short kick, crisp snare, bright noisy hats",{kick:{base:55,sweep:140,sweepRate:34,decay:8,click:.22,clickDecay:420},tom:{base:110,sweep:70,sweepRate:20,decay:8},snare:{tone:215,toneLevel:.45,toneDecay:24,noise:.8,noiseDecay:15,snap:.9},clap:{gap:.012,tail:15,band:.5},hat:{level:.36,decay:65,tone:1,metal:.15},openhat:{level:.3,decay:7,tone:1,metal:.15},rim:{high:2e3,low:900,decay:150},seconds:.7,drive:.15}),kit("synlinn","Linn (synth)","fat 80s kick, big tonal snare, bright clap",{kick:{base:50,sweep:110,sweepRate:30,decay:7,click:.25,clickDecay:350},tom:{base:100,sweep:80,sweepRate:16,decay:6},snare:{tone:190,toneLevel:.6,toneDecay:16,noise:.75,noiseDecay:10,snap:.6},clap:{gap:.013,tail:10,band:.45},hat:{level:.32,decay:50,tone:.85,metal:.1},openhat:{level:.28,decay:5,tone:.85,metal:.1},rim:{high:1600,low:760,decay:120},seconds:.9,drive:.2}),kit("breaks","Breaks (synth)","dusty live break: thuddy kick, cracking snare",{kick:{base:60,sweep:60,sweepRate:32,decay:10,click:.35,clickDecay:200},tom:{base:95,sweep:50,sweepRate:20,decay:7},snare:{tone:200,toneLevel:.55,toneDecay:20,noise:.85,noiseDecay:13,snap:.5},clap:{gap:.011,tail:14,band:.4},hat:{level:.34,decay:45,tone:.55,metal:.25},openhat:{level:.28,decay:6,tone:.55,metal:.25},rim:{high:1500,low:700,decay:110},seconds:.8,drive:.35,bits:12,hold:2}),kit("dnb","Drum and bass (synth)","tight punchy kick, body-heavy snare, bright hats",{kick:{base:58,sweep:130,sweepRate:40,decay:9,click:.1,clickDecay:350},tom:{base:100,sweep:60,sweepRate:20,decay:8},snare:{tone:168,toneLevel:.75,toneDecay:14,noise:.4,noiseDecay:22,snap:0},clap:{gap:.011,tail:16,band:.4},hat:{level:.4,decay:70,tone:1,metal:.3},openhat:{level:.32,decay:8,tone:1,metal:.3},seconds:.7,drive:.1})]),BY_NAME=new Map(SYNTH_KITS.map(entry=>[entry.name,entry])),KIT_ALIASES=Object.freeze({synth808:"syn808","synth-808":"syn808","syn-808":"syn808",synth909:"syn909","synth-909":"syn909","syn-909":"syn909","lo-fi":"lofi",dusty:"lofi",minimal:"electro",synth606:"syn606",synth707:"syn707",synthlinn:"synlinn",break:"breaks"});function synthKit(name){if(typeof name!="string")return;let key=name.trim().toLowerCase();return BY_NAME.get(KIT_ALIASES[key]??key)}var SYNTH_KIT_NAMES=Object.freeze(SYNTH_KITS.map(entry=>entry.name));var spaceEffectParameters=Object.freeze({delay:{beats:{kind:"number",min:.0625,max:4,default:.75,step:.0625,unit:"beats",doc:"delay time in beats (0.75 = dotted eighth)",strudel:["delaytime (seconds = beats\xB760/bpm)"]},feedback:{kind:"number",min:0,max:.9,default:.35,step:.05,automate:!0,doc:"fraction of each echo fed back",strudel:["delayfeedback","delayfb","dfb"]},mix:{kind:"number",min:0,max:1,default:.25,step:.05,automate:!0,doc:"wet level",strudel:["delay"]},time:{kind:"number",min:0,max:4,default:0,step:.01,unit:"s",optional:!0,doc:"delay time in seconds; 0 or absent uses beats",strudel:["delaytime","delayt","dt"]},pingpong:{kind:"boolean",default:!0,optional:!0,doc:"repeats alternate left/right (absent: the original cross-fed stereo)"},highcut:{kind:"number",min:500,max:2e4,default:5e3,step:"log",unit:"Hz",optional:!0,doc:"low-pass inside the feedback loop so repeats darken"}},reverb:{mix:{kind:"number",min:0,max:1,default:.3,step:.05,automate:!0,doc:"wet level",strudel:["room"]},size:{kind:"number",min:0,max:1,default:.5,step:.05,doc:"room size (Strudel roomsize 0..10 = size\xB710)",strudel:["roomsize","rsize","sz","size"]},fade:{kind:"number",min:.1,max:20,default:2,step:.1,unit:"s",optional:!0,doc:"decay time to -60 dB; overrides the size-derived decay",strudel:["roomfade","rfade"]},lowpass:{kind:"number",min:200,max:2e4,default:8e3,step:"log",unit:"Hz",optional:!0,doc:"low-pass on the reverb input",strudel:["roomlp","rlp"]},dim:{kind:"number",min:200,max:2e4,default:3e3,step:"log",unit:"Hz",optional:!0,doc:"damping: the tail darkens toward this frequency as it decays",strudel:["roomdim","rdim"]},predelay:{kind:"number",min:0,max:.5,default:.02,step:.005,unit:"s",optional:!0,doc:"gap before the tail starts"},center:{kind:"number",min:0,max:1,default:1,step:.05,optional:!0,doc:"matches the tail's left and right energy over the render (1 equal, 0 as the room gives); the algorithmic tail only"}}});var LEGACY_WORDS2=Object.freeze(["piano","pluck","bass","saw","square","triangle","marimba","wind","cello","contrabass","ebass","sitar","organ","strings","bell","keys","lead"]),INSTRUMENT_WORDS2=Object.freeze([{word:"nylon",instrument:"string",field:"string",preset:"nylon"},{word:"steel",instrument:"string",field:"string",preset:"steel"},{word:"electric",instrument:"string",field:"string",preset:"electric"},{word:"slap",instrument:"string",field:"string",preset:"slap"},{word:"motown",instrument:"string",field:"string",preset:"motown"},{word:"tanpura",instrument:"string",field:"string",preset:"tanpura"},{word:"harpsichord",instrument:"string",field:"string",preset:"harpsichord"},{word:"lute",instrument:"string",field:"string",preset:"lute"},{word:"oud",instrument:"string",field:"string",preset:"oud"},{word:"setar",instrument:"string",field:"string",preset:"setar"},{word:"tar",instrument:"string",field:"string",preset:"tar"},{word:"santur",instrument:"string",field:"string",preset:"santur"},{word:"dulcimer",instrument:"string",field:"string",preset:"dulcimer"},{word:"koto",instrument:"string",field:"string",preset:"koto"},{word:"harp",instrument:"string",field:"string",preset:"harp"},{word:"banjo",instrument:"string",field:"string",preset:"banjo"},{word:"tres",instrument:"string",field:"string",preset:"tres"},{word:"requinto",instrument:"string",field:"string",preset:"requinto"},{word:"acoustic",instrument:"string",field:"string",preset:"steel"},{word:"classical",instrument:"string",field:"string",preset:"nylon"},{word:"bassguitar",instrument:"string",field:"string",preset:"ebass"},{word:"fender",instrument:"string",field:"string",preset:"ebass"},{word:"doublebass",instrument:"string",field:"string",preset:"upright"},{word:"cembalo",instrument:"string",field:"string",preset:"harpsichord"},{word:"hammered",instrument:"string",field:"string",preset:"dulcimer"},{word:"sehtar",instrument:"string",field:"string",preset:"setar"},{word:"violin",instrument:"string",field:"string",preset:"violin"},{word:"viola",instrument:"string",field:"string",preset:"viola"},{word:"fiddle",instrument:"string",field:"string",preset:"fiddle"},{word:"erhu",instrument:"string",field:"string",preset:"erhu"},{word:"kamancheh",instrument:"string",field:"string",preset:"kamancheh"},{word:"kemence",instrument:"string",field:"string",preset:"kamancheh"},{word:"violins",instrument:"string",field:"string",preset:"violins"},{word:"violas",instrument:"string",field:"string",preset:"violas"},{word:"cellos",instrument:"string",field:"string",preset:"cellos"},{word:"contrabasses",instrument:"string",field:"string",preset:"contrabasses"},{word:"pizzicato",instrument:"string",field:"string",preset:"pizz"},{word:"tremolo",instrument:"string",field:"string",preset:"trem"},{word:"bowed-cello",instrument:"string",field:"string",preset:"cello"},{word:"jangle",instrument:"string",field:"string",preset:"jangle",fx:"jangle"},{word:"punk",instrument:"pluck",voice:"electric",fx:"punk"},{word:"funk",instrument:"pluck",voice:"electric",fx:"funk"},{word:"ragged",instrument:"pluck",voice:"electric",fx:"ragged"},{word:"gtr-lead",instrument:"pluck",voice:"electric",fx:"lead"},{word:"gtr-metal",instrument:"pluck",voice:"electric",fx:"metal"},{word:"bachata",instrument:"pluck",voice:"electric",fx:"bachata"},{word:"granular",instrument:"granular",field:"granular",preset:"cloud"},{word:"grains",instrument:"granular",field:"granular",preset:"cloud"},{word:"cloud",instrument:"granular",field:"granular",preset:"cloud"},{word:"sparkle",instrument:"granular",field:"granular",preset:"sparkle"},{word:"swarm",instrument:"granular",field:"granular",preset:"swarm"},{word:"microloop",instrument:"granular",field:"granular",preset:"microloop"},{word:"grand",instrument:"grand",field:"keys",preset:"grand"},{word:"ballad",instrument:"grand",field:"keys",preset:"ballad"},{word:"upright",instrument:"upright",field:"keys",preset:"upright"},{word:"felt",instrument:"felt",field:"keys",preset:"felt"},{word:"lofi",instrument:"felt",field:"keys",preset:"lofi"},{word:"honkytonk",instrument:"honkytonk",field:"keys",preset:"honkytonk"},{word:"prepared",instrument:"prepared",field:"keys",preset:"prepared"},{word:"tonewheel",instrument:"tonewheel",field:"keys",preset:"tonewheel"},{word:"hammond",instrument:"tonewheel",field:"keys",preset:"tonewheel"},{word:"b3",instrument:"tonewheel",field:"keys",preset:"tonewheel"},{word:"gospel",instrument:"tonewheel",field:"keys",preset:"gospel"},{word:"jazzorgan",instrument:"tonewheel",field:"keys",preset:"jazzorgan"},{word:"combo",instrument:"combo",field:"keys",preset:"combo"},{word:"farfisa",instrument:"combo",field:"keys",preset:"combo"},{word:"vox",instrument:"combo",field:"keys",preset:"vox"},{word:"pipe",instrument:"pipe",field:"keys",preset:"pipe"},{word:"church",instrument:"pipe",field:"keys",preset:"pipe"},{word:"pipeorgan",instrument:"pipe",field:"keys",preset:"pipe"},{word:"churchorgan",instrument:"pipe",field:"keys",preset:"pipe"},{word:"flutes",instrument:"pipe",field:"keys",preset:"flutes"},{word:"cornet",instrument:"pipe",field:"keys",preset:"cornet"},{word:"reeds",instrument:"pipe",field:"keys",preset:"reeds"},{word:"celeste",instrument:"pipe",field:"keys",preset:"celeste"},{word:"modal",instrument:"modal",field:"modal",preset:"marimba"},{word:"vibes",instrument:"modal",field:"modal",preset:"vibes"},{word:"vibraphone",instrument:"modal",field:"modal",preset:"vibes"},{word:"xylophone",instrument:"modal",field:"modal",preset:"xylophone"},{word:"glock",instrument:"modal",field:"modal",preset:"glock"},{word:"glockenspiel",instrument:"modal",field:"modal",preset:"glock"},{word:"celesta",instrument:"modal",field:"modal",preset:"celesta"},{word:"chimes",instrument:"modal",field:"modal",preset:"chimes"},{word:"tubular",instrument:"modal",field:"modal",preset:"chimes"},{word:"kalimba",instrument:"modal",field:"modal",preset:"kalimba"},{word:"thumbpiano",instrument:"modal",field:"modal",preset:"kalimba"},{word:"mbira",instrument:"modal",field:"modal",preset:"mbira"},{word:"steelpan",instrument:"modal",field:"modal",preset:"steelpan"},{word:"bowl",instrument:"modal",field:"modal",preset:"bowl"},{word:"gong",instrument:"modal",field:"modal",preset:"gong"},{word:"gongageng",instrument:"modal",field:"modal",preset:"gong"},{word:"timpani",instrument:"modal",field:"modal",preset:"timpani"},{word:"steeldrum",instrument:"modal",field:"modal",preset:"steelpan"},{word:"singingbowl",instrument:"modal",field:"modal",preset:"bowl"},{word:"kettledrum",instrument:"modal",field:"modal",preset:"timpani"},{word:"tubularbells",instrument:"modal",field:"modal",preset:"chimes"},{word:"epiano",instrument:"epiano",field:"keys",preset:"epiano"},{word:"rhodes",instrument:"epiano",field:"keys",preset:"epiano"},{word:"suitcase",instrument:"epiano",field:"keys",preset:"suitcase"},{word:"dyno",instrument:"epiano",field:"keys",preset:"dyno"},{word:"wurli",instrument:"wurli",field:"keys",preset:"wurli"},{word:"wurlitzer",instrument:"wurli",field:"keys",preset:"wurli"},{word:"clav",instrument:"clav",field:"keys",preset:"clav"},{word:"clavinet",instrument:"clav",field:"keys",preset:"clav"},{word:"funkclav",instrument:"clav",field:"keys",preset:"funkclav"},{word:"shoegaze",instrument:"pluck",voice:"electric",fx:"shoegaze"},{word:"dreampop",instrument:"pluck",voice:"electric",fx:"dreampop"},{word:"ebow",instrument:"pluck",voice:"electric",fx:"ebow"},{word:"crotales",instrument:"modal",field:"modal",preset:"crotales"},{word:"crotale",instrument:"modal",field:"modal",preset:"crotales"},{word:"musicbox",instrument:"modal",field:"modal",preset:"musicbox"},{word:"toypiano",instrument:"modal",field:"modal",preset:"toypiano"},{word:"saron",instrument:"modal",field:"modal",preset:"saron"},{word:"demung",instrument:"modal",field:"modal",preset:"demung"},{word:"slenthem",instrument:"modal",field:"modal",preset:"slenthem"},{word:"gangsa",instrument:"modal",field:"modal",preset:"gangsa"},{word:"gender",instrument:"modal",field:"modal",preset:"gender"},{word:"bonang",instrument:"modal",field:"modal",preset:"bonang"},{word:"kenong",instrument:"modal",field:"modal",preset:"kenong"},{word:"kethuk",instrument:"modal",field:"modal",preset:"kethuk"},{word:"kempul",instrument:"modal",field:"modal",preset:"kempul"},{word:"daf",instrument:"modal",field:"modal",preset:"daf"},{word:"bodhran",instrument:"modal",field:"modal",preset:"bodhran"},{word:"framedrum",instrument:"modal",field:"modal",preset:"bodhran"},{word:"tabla",instrument:"modal",field:"modal",preset:"tabla"},{word:"flute",instrument:"wind",field:"wind",preset:"flute"},{word:"recorder",instrument:"wind",field:"wind",preset:"recorder"},{word:"whistle",instrument:"wind",field:"wind",preset:"whistle"},{word:"ney",instrument:"wind",field:"wind",preset:"ney"},{word:"shakuhachi",instrument:"wind",field:"wind",preset:"shakuhachi"},{word:"panpipe",instrument:"wind",field:"wind",preset:"panpipe"},{word:"suling",instrument:"wind",field:"wind",preset:"suling"},{word:"bansuri",instrument:"wind",field:"wind",preset:"bansuri"},{word:"clarinet",instrument:"wind",field:"wind",preset:"clarinet"},{word:"bassclarinet",instrument:"wind",field:"wind",preset:"bassclarinet"},{word:"oboe",instrument:"wind",field:"wind",preset:"oboe"},{word:"bassoon",instrument:"wind",field:"wind",preset:"bassoon"},{word:"sax",instrument:"wind",field:"wind",preset:"sax"},{word:"altosax",instrument:"wind",field:"wind",preset:"altosax"},{word:"barisax",instrument:"wind",field:"wind",preset:"barisax"},{word:"trumpet",instrument:"wind",field:"wind",preset:"trumpet"},{word:"harmon",instrument:"wind",field:"wind",preset:"harmon"},{word:"plunger",instrument:"wind",field:"wind",preset:"plunger"},{word:"trombone",instrument:"wind",field:"wind",preset:"trombone"},{word:"tuba",instrument:"wind",field:"wind",preset:"tuba"},{word:"horn",instrument:"wind",field:"wind",preset:"horn"},{word:"tinwhistle",instrument:"wind",field:"wind",preset:"whistle"},{word:"pennywhistle",instrument:"wind",field:"wind",preset:"whistle"},{word:"nay",instrument:"wind",field:"wind",preset:"ney"},{word:"panflute",instrument:"wind",field:"wind",preset:"panpipe"},{word:"panpipes",instrument:"wind",field:"wind",preset:"panpipe"},{word:"saxophone",instrument:"wind",field:"wind",preset:"sax"},{word:"tenorsax",instrument:"wind",field:"wind",preset:"sax"},{word:"tenor",instrument:"wind",field:"wind",preset:"sax"},{word:"alto",instrument:"wind",field:"wind",preset:"altosax"},{word:"bari",instrument:"wind",field:"wind",preset:"barisax"},{word:"baritonesax",instrument:"wind",field:"wind",preset:"barisax"},{word:"frenchhorn",instrument:"wind",field:"wind",preset:"horn"},{word:"mutedtrumpet",instrument:"wind",field:"wind",preset:"harmon"},{word:"wahtrumpet",instrument:"wind",field:"wind",preset:"plunger"},{word:"sing",instrument:"sing",field:"sing"},{word:"aah",instrument:"sing",field:"sing",preset:"aah"},{word:"ooh",instrument:"sing",field:"sing",preset:"ooh"},{word:"choir",instrument:"sing",field:"sing",preset:"choir"},{word:"chorale",instrument:"sing",field:"sing",preset:"chorale"},{word:"khoomei",instrument:"sing",field:"sing",preset:"khoomei"},{word:"sygyt",instrument:"sing",field:"sing",preset:"sygyt"},{word:"kargyraa",instrument:"sing",field:"sing",preset:"kargyraa"},{word:"vocal",instrument:"vocal"},{word:"vocoder",instrument:"vocoder",field:"vocoder",preset:"classic"},{word:"texture",instrument:"texture",field:"texture"}]);function resolveInstrumentWord2(word2){if(LEGACY_WORDS2.includes(word2))return Object.freeze({instrument:word2});let row2=INSTRUMENT_WORDS2.find(entry=>entry.word===word2);if(!row2)return;let{word:_word,voice,...meaning}=row2,borrowed=voice===void 0?void 0:INSTRUMENT_WORDS2.find(entry=>entry.word===voice&&!entry.voice);return Object.freeze(borrowed?{instrument:borrowed.instrument,...borrowed.field===void 0?{}:{field:borrowed.field},...borrowed.preset===void 0?{}:{preset:borrowed.preset},...meaning.fx===void 0?{}:{fx:meaning.fx}}:meaning)}var FxValidationError=class extends Error{constructor(message){super(message),this.name="FxValidationError"}};function normalizeParam(spec,value,label){if(spec.kind==="enum"){if(typeof value!="string"||!spec.values.includes(value))throw new FxValidationError(`${label} must be one of ${spec.values.join(", ")}`);return value}if(spec.kind==="boolean"){if(typeof value!="boolean")throw new FxValidationError(`${label} must be true or false`);return value}if(typeof value!="number"||!Number.isFinite(value))throw new FxValidationError(`${label} must be a finite number`);if(value<spec.min||value>spec.max)throw new FxValidationError(`${label} must be between ${spec.min} and ${spec.max}`);return spec.integer?Math.round(value):value}function normalizeParams(params2,input,label,fill2=!0){if(!isRecord2(input))throw new FxValidationError(`${label} must be an object`);for(let key of Object.keys(input))if(!Object.prototype.hasOwnProperty.call(params2,key))throw new FxValidationError(`${label} has no parameter "${key}"`);let out={};for(let[key,spec]of Object.entries(params2)){let value=input[key];if(value===void 0){fill2&&!spec.optional&&(out[key]=spec.default);continue}out[key]=normalizeParam(spec,value,`${label} ${key}`)}return Object.freeze(out)}function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var WIND_INSTRUMENT2="wind",WIND_MODELS=Object.freeze(["jet","reed","sax","lips"]),WIND_MUTES=Object.freeze(["open","straight","cup","harmon","plunger"]),WIND_PRESET_NAMES=Object.freeze(["flute","recorder","whistle","ney","shakuhachi","panpipe","suling","bansuri","clarinet","bassclarinet","oboe","bassoon","sax","altosax","barisax","trumpet","harmon","plunger","trombone","tuba","horn"]),WIND_ALIASES=Object.freeze({tinwhistle:"whistle",pennywhistle:"whistle",nay:"ney",panflute:"panpipe",panpipes:"panpipe",saxophone:"sax",tenorsax:"sax",tenor:"sax",alto:"altosax",bari:"barisax",baritonesax:"barisax",frenchhorn:"horn",mutedtrumpet:"harmon",wahtrumpet:"plunger"}),WIND_GROUPS=Object.freeze([{label:"Flutes",presets:["flute","recorder","whistle","ney","shakuhachi","panpipe","suling","bansuri"]},{label:"Saxophones",presets:["sax","altosax","barisax"]},{label:"Reeds",presets:["clarinet","bassclarinet","oboe","bassoon"]},{label:"Brass",presets:["trumpet","harmon","plunger","trombone","tuba","horn"]}]),num=(min,max,fallback,step2,doc,extra={})=>Object.freeze({kind:"number",min,max,default:fallback,step:step2,optional:!0,doc,...extra}),WIND_PARAMS=Object.freeze({model:Object.freeze({kind:"enum",values:WIND_MODELS,default:"jet",optional:!0,doc:"exciter and bore: jet (flute), reed (clarinet), sax (conical reed), lips (brass)"}),breath:num(0,1,.6,.05,"blowing pressure: swells, louder and fuller",{automate:!0}),noise:num(0,1,.08,.05,"breath noise",{automate:!0}),attack:num(.001,2,.04,"log","breath rise",{unit:"s",strudel:["att"]}),release:num(.005,2,.08,"log","breath fall",{unit:"s",strudel:["rel"]}),vib:num(0,12,5,.25,"vibrato rate",{unit:"Hz",strudel:["vibrato"]}),vibmod:num(0,1,0,.02,"vibrato depth",{unit:"st",strudel:["vmod","vibdepth","depth"]}),reed:num(0,1,.5,.05,"reed stiffness, jet offset or lip tension"),bright:num(0,1,.5,.05,"bore loss: dark to bright"),stopped:Object.freeze({kind:"boolean",default:!1,optional:!0,doc:"stopped pipe, odd harmonics (jet only)"}),mute:Object.freeze({kind:"enum",values:WIND_MUTES,default:"open",optional:!0,doc:"brass mute: open, straight, cup, harmon or plunger"}),wah:num(0,1,1,.05,"plunger opening: 0 closed, 1 open",{automate:!0}),wahenv:num(0,1,0,.05,"plunger opens with each note (doo-wah)"),growl:num(0,1,0,.05,"hum into the horn: rough, raspy",{automate:!0}),flutter:num(0,1,0,.05,"flutter tongue (rolled r)",{automate:!0}),players:num(1,8,1,1,"section size, spread over chord tones",{integer:!0}),gain:num(0,2,.8,.05,"level")}),WIND_SIMPLE=Object.freeze(["breath","bright","mute","players","growl"]),WIND_DEFAULTS=Object.freeze({model:"jet",breath:.6,noise:.08,attack:.04,release:.08,vib:5,vibmod:0,reed:.5,bright:.5,stopped:!1,mute:"open",wah:1,wahenv:0,growl:0,flutter:0,players:1,gain:.8}),preset=(settings,range,doc,styles)=>Object.freeze({settings:Object.freeze({...WIND_DEFAULTS,...settings}),range:Object.freeze(range),doc,styles}),WIND_PRESETS=Object.freeze({flute:preset({model:"jet",breath:.6,noise:.12,attack:.06,vib:5,vibmod:.12,bright:.5},[60,96],"concert flute, airy with gentle vibrato","Debussy, Bach cantata, jazz flute"),recorder:preset({model:"jet",breath:.5,noise:.06,attack:.02,bright:.6},[65,93],"alto recorder, pure and straight","Bach cantata, early music"),whistle:preset({model:"jet",breath:.6,noise:.08,attack:.015,bright:.7},[74,98],"tin whistle, bright and reedy","celtic"),ney:preset({model:"jet",breath:.45,noise:.35,attack:.12,vib:5.5,vibmod:.08,bright:.3},[55,86],"Persian reed flute, very breathy","Persian, Sufi, ambient"),shakuhachi:preset({model:"jet",breath:.55,noise:.3,attack:.08,vib:4,vibmod:.2,bright:.35},[62,86],"bamboo end-blown flute, breath accents","Sakamoto, OPN, ambient"),panpipe:preset({model:"jet",stopped:!0,breath:.6,noise:.2,attack:.03,bright:.5},[60,96],"stopped cane pipes, hollow odd harmonics","ambient, Andean, Eno"),suling:preset({model:"jet",breath:.5,noise:.25,attack:.05,vib:5.5,vibmod:.1,bright:.45},[67,93],"Sundanese and Balinese ring flute, soft and breathy","gamelan, degung, ambient"),bansuri:preset({model:"jet",breath:.55,noise:.22,attack:.07,vib:5,vibmod:.15,bright:.4},[55,84],"Indian bamboo flute, warm with deep vibrato","Hindustani, Bollywood, ambient"),clarinet:preset({model:"reed",breath:.6,noise:.05,attack:.04,reed:.5},[50,91],"cylindrical bore, woody odd harmonics","Brahms, jazz, klezmer, Motown"),bassclarinet:preset({model:"reed",breath:.6,noise:.06,attack:.05,reed:.4,bright:.4},[37,72],"bass clarinet, dark and hollow","Bitches Brew, Messiaen, film"),oboe:preset({model:"sax",breath:.6,noise:.04,attack:.03,vib:5.5,vibmod:.08,reed:.8,bright:.75},[58,91],"double reed, nasal and singing","Bach, Ravel, Morricone"),bassoon:preset({model:"sax",breath:.6,noise:.04,attack:.04,vib:5,vibmod:.06,reed:.7,bright:.35},[34,72],"bassoon, reedy and woody low voice","Stravinsky, Prokofiev, orchestral"),sax:preset({model:"sax",breath:.65,noise:.1,attack:.03,vib:5.2,vibmod:.15},[44,79],"tenor sax, warm to raspy with breath","jazz, Motown, soul, funk"),altosax:preset({model:"sax",breath:.65,noise:.09,attack:.03,vib:5.4,vibmod:.12,bright:.55},[49,81],"alto sax, bright and vocal","bebop, Motown, soul"),barisax:preset({model:"sax",breath:.68,noise:.1,attack:.04,vib:5,vibmod:.08,bright:.45},[36,69],"baritone sax, honking low end","Motown, funk, ska"),trumpet:preset({model:"lips",breath:.7,noise:.03,attack:.03,bright:.6,vib:5.5},[52,82],"open trumpet, brightens as it gets louder","Louis Armstrong, Motown, salsa, jazz"),harmon:preset({model:"lips",breath:.7,noise:.03,attack:.03,bright:.6,mute:"harmon"},[52,82],"trumpet with a harmon mute, buzzy and close","jazz, Radiohead, Sakamoto"),plunger:preset({model:"lips",breath:.75,noise:.04,attack:.03,bright:.6,mute:"plunger",wah:.3},[52,82],"trumpet with a plunger: automate wah for ya-ya","Louis Armstrong, Duke Ellington, funk"),trombone:preset({model:"lips",breath:.7,noise:.03,attack:.04,bright:.45},[40,72],"slide trombone, broad","salsa, Motown, jazz"),tuba:preset({model:"lips",breath:.7,noise:.02,attack:.06,bright:.3},[28,58],"tuba, round and deep","New Orleans brass band, oompah, orchestral"),horn:preset({model:"lips",breath:.6,noise:.02,attack:.06,bright:.25},[41,77],"French horn, dark and round","Brahms, Beethoven, orchestral")}),DEFAULT_WIND_PRESET="flute";function isWindPreset(name){return WIND_PRESET_NAMES.includes(name)}function windPresetFor(word2){let lower=word2.trim().toLowerCase();return isWindPreset(lower)?lower:WIND_ALIASES[lower]}function isWindParam(name){return Object.prototype.hasOwnProperty.call(WIND_PARAMS,name)}function windParamName(name){if(isWindParam(name))return name;for(let[key,spec]of Object.entries(WIND_PARAMS))if(spec.strudel?.includes(name))return key}function normalizeWind(input){if(input==null)return;if(!isRecord2(input))throw new FxValidationError("track wind must be an object or null");let params2={},presetName;for(let[key,value]of Object.entries(input)){if(value==null)continue;if(key==="preset"){let resolved=typeof value=="string"?windPresetFor(value):void 0;if(!resolved)throw new FxValidationError(`wind preset must be one of ${WIND_PRESET_NAMES.join(", ")}`);presetName=resolved;continue}let name=windParamName(key);if(!name)throw new FxValidationError(`wind has no parameter "${key.slice(0,32)}"`);params2[name]=value}let values=normalizeParams(WIND_PARAMS,params2,"wind",!1);return Object.freeze({...presetName?{preset:presetName}:{},...values})}function windPresetOf(wind2){return wind2?.preset??DEFAULT_WIND_PRESET}function windSettings(wind2,lane){let out={...WIND_PRESETS[windPresetOf(wind2)].settings};if(wind2)for(let[key,value]of Object.entries(wind2))key!=="preset"&&value!==void 0&&(out[key]=value);if(lane)for(let{param:param2}of WIND_LANE_PARAMS){let value=lane(param2);value!==void 0&&(out[param2]=value)}return Object.freeze(out)}var WIND_LANE_PARAMS=Object.freeze(Object.entries(WIND_PARAMS).filter(entry=>entry[1].kind==="number"&&entry[1].automate===!0).map(([param2,spec])=>Object.freeze({param:param2,spec}))),MAX_WIND_VOICES=24;function windTailSeconds(wind2){return windSettings(wind2).release+.15}var SING_INSTRUMENT2="sing",SING_VERSION=1,SING_VOICES=Object.freeze(["auto","soprano","alto","tenor","bass"]),SING_VOWELS=Object.freeze(["a","e","i","o","u"]),SING_PRESET_NAMES=Object.freeze(["aah","ooh","choir","oohchoir","chorale","airy","glass","lament","soprano","basso","drone","khoomei","sygyt","kargyraa","robot","speak"]),SING_WORDS=Object.freeze(["aah","ooh","choir","chorale","khoomei","sygyt","kargyraa"]),SING_GROUPS=Object.freeze([{label:"Choir",presets:["aah","ooh","choir","oohchoir","chorale","airy","glass"]},{label:"Solo",presets:["lament","soprano","basso"]},{label:"Throat",presets:["drone","khoomei","sygyt","kargyraa"]},{label:"Machine vox",presets:["robot","speak"]}]),num2=(min,max,fallback,step2,doc,extra={})=>Object.freeze({kind:"number",min,max,default:fallback,step:step2,optional:!0,doc,...extra}),SING_DRONE_RANGE=Object.freeze([36,67]),SING_HARMONIC_RANGE=Object.freeze([2,24]),SING_PARAMS=Object.freeze({voice:Object.freeze({kind:"enum",values:SING_VOICES,default:"auto",optional:!0,doc:"formant table: auto picks one per part from its median pitch (bass < F3, tenor < C#4, alto < G4, soprano)"}),vowel:Object.freeze({kind:"enum",values:SING_VOWELS,default:"a",optional:!0,doc:"sung vowel; a>o morphs across each note; a note's vowel wins",strudel:["vowel"]}),morph:num2(0,1,1,.05,"how far an a>o vowel travels by the note's end",{automate:!0}),formant:num2(-12,12,0,.5,"throat size: formant shift, keeps pitch",{unit:"st",automate:!0}),bright:num2(0,1,.5,.05,"voice quality: breathy and dark .. pressed",{automate:!0}),breath:num2(0,1,.12,.02,"aspiration noise",{automate:!0}),jitter:num2(0,3,.3,.1,"period jitter",{unit:"%"}),shimmer:num2(0,1,.3,.05,"amplitude jitter"),attack:num2(.005,2,.08,"log","onset",{unit:"s",strudel:["att"]}),release:num2(.01,4,.18,"log","fade after the note",{unit:"s",strudel:["rel"]}),vib:num2(0,9,5.5,.25,"vibrato rate",{unit:"Hz",strudel:["vibrato"]}),vibmod:num2(0,1,.3,.05,"vibrato depth",{unit:"st",automate:!0,strudel:["vmod"]}),vibdelay:num2(0,2,.25,.05,"vibrato fades in after this",{unit:"s"}),voices:num2(1,8,1,1,"singers per note (choir)",{integer:!0}),spread:num2(0,40,10,1,"ensemble detune scatter",{unit:"cents"}),ring:num2(0,1,0,.05,"singer's formant (bright 3 kHz ring)",{automate:!0}),drone:num2(SING_DRONE_RANGE[0],SING_DRONE_RANGE[1],50,1,"throat singing: a held drone at this pitch; notes steer the overtone",{integer:!0}),overtone:num2(0,1,0,.05,"overtone filter sharpness and level",{automate:!0}),sub:num2(0,1,0,.05,"kargyraa subharmonic (an octave below)",{automate:!0}),articulate:num2(0,1,0,.05,"machine vox: sing the lyric's consonants (0 sings vowels only, as before)"),gain:num2(0,2,.8,.05,"engine output")}),SING_KEY_ORDER=Object.freeze(Object.keys(SING_PARAMS).flatMap(key=>key==="sub"?["harmonics","sub"]:[key])),SING_THROAT_PARAMS=Object.freeze(["drone","overtone","harmonics","sub"]),SING_DEFAULTS=Object.freeze({voice:"auto",vowel:"a",morph:1,formant:0,bright:.5,breath:.12,jitter:.3,shimmer:.3,attack:.08,release:.18,vib:5.5,vibmod:.3,vibdelay:.25,voices:1,spread:10,ring:0,overtone:0,harmonics:Object.freeze([6,12]),sub:0,articulate:0,gain:.8}),preset2=(settings,doc,styles)=>Object.freeze({settings:Object.freeze({...SING_DEFAULTS,...settings}),doc,styles}),pair=(lo,hi)=>Object.freeze([lo,hi]),SING_PRESETS=Object.freeze({aah:preset2({vowel:"a"},'warm "aah", one voice, gentle vibrato',"wordless leads, Sakamoto, ballads"),ooh:preset2({vowel:"u",bright:.3},'soft rounded "ooh", darker',"dark ballad, Beach House, Mitski backing"),choir:preset2({voices:6,ring:.2},'six-voice "aah" ensemble',"Eno, Bach cantata color, pads"),oohchoir:preset2({voices:6,vowel:"u",breath:.3,bright:.35},'six-voice breathy "ooh"',"Beach House, shoegaze, ambient"),chorale:preset2({voices:4,vibmod:.15,ring:.35,bright:.6},"four voices, little vibrato, clear ring","Bach and Brahms chorales"),airy:preset2({voices:8,breath:.35,spread:18,attack:.6,release:1.2,bright:.35},"eight breathy voices, slow swell","Eno, OPN, Four Tet pads"),glass:preset2({voices:4,vowel:"i",formant:5,bright:.8,vibmod:0},'four bright "ee" voices, no vibrato',"OPN, A. G. Cook, hyperpop pads"),lament:preset2({vowel:"o",formant:-2,vib:4.5,vibmod:.5,vibdelay:.4},'solo low "oh", slow wide vibrato',"dark ballad, Gesaffelstein intros"),soprano:preset2({voice:"soprano",ring:.5,vib:6,vibmod:.5,bright:.65},"solo soprano with an operatic ring","Messiaen, Debussy, wordless arias"),basso:preset2({voice:"bass",vowel:"o",ring:.4},'solo bass "oh"',"cantata recitative color, drones"),drone:preset2({voice:"tenor",drone:48,overtone:.3,harmonics:pair(2,16),vibmod:0,release:1.5},"held drone, the melody colors its overtones","La Monte Young, Barbieri, Eno"),khoomei:preset2({voice:"tenor",vowel:"o",drone:50,overtone:.85,harmonics:pair(6,10),vibmod:0},"Tuvan khoomei: a D3 drone with a whistled melody","Tuvan khoomei"),sygyt:preset2({voice:"tenor",vowel:"u>i",drone:55,bright:.85,overtone:1,harmonics:pair(9,12),vibmod:0},"Tuvan sygyt: a G3 drone with a high flute-like whistle","Tuvan sygyt"),kargyraa:preset2({voice:"bass",vowel:"a",drone:45,sub:.8,overtone:.25,harmonics:pair(5,9),vibmod:0,bright:.6},"Tuvan kargyraa: an A2 growl with a sub an octave below","Tuvan kargyraa"),robot:preset2({articulate:1,bright:.75,breath:.04,jitter:0,shimmer:0,vibmod:0,attack:.01,release:.06},"machine vox: every consonant of the lyric, steady pitch, no vibrato","Kraftwerk, Daft Punk, Speak & Spell"),speak:preset2({articulate:.8,bright:.55,breath:.1,vibmod:.12,vibdelay:.4,attack:.02,release:.1},"machine vox: sung words, softer consonants, a little vibrato","Laurie Anderson, Imogen Heap, vocoder leads")}),DEFAULT_SING_PRESET="aah";function isSingPreset(name){return SING_PRESET_NAMES.includes(name)}function isSingParam(name){return name==="harmonics"||Object.prototype.hasOwnProperty.call(SING_PARAMS,name)}function singParamName(name){if(isSingParam(name))return name;for(let[key,spec]of Object.entries(SING_PARAMS))if(spec.strudel?.includes(name))return key}var NOTE_LETTERS=Object.freeze({c:0,d:2,e:4,f:5,g:7,a:9,b:11});function singNoteNumber(text2){let match=/^([a-gA-G])(#|b|s)?(-?\d)$/.exec(text2.trim());if(!match)return;let base=NOTE_LETTERS[match[1].toLowerCase()],accidental=match[2]==="#"||match[2]==="s"?1:match[2]?-1:0;return(Number(match[3])+1)*12+base+accidental}function parseDrone(value){let n2=typeof value=="string"?singNoteNumber(value)??(/^\d+$/.test(value.trim())?Number(value):void 0):typeof value=="number"?value:void 0,[lo,hi]=SING_DRONE_RANGE;if(n2===void 0||!Number.isInteger(n2)||n2<lo||n2>hi)throw new FxValidationError(`sing drone must be a note name C2..G4 (e.g. "D3") or a MIDI number ${lo}..${hi}`);return n2}var VOWEL_SPELLINGS=Object.freeze({ah:"a",eh:"e",ee:"i",oh:"o",oo:"u"});function parseVowel(text2){let parts=typeof text2=="string"?text2.trim().toLowerCase().split(">").map(part=>VOWEL_SPELLINGS[part.trim()]??part.trim()):[],ok=v=>v!==void 0&&SING_VOWELS.includes(v);if(parts.length===1&&ok(parts[0]))return Object.freeze([parts[0]]);if(parts.length===2&&ok(parts[0])&&ok(parts[1]))return Object.freeze([parts[0],parts[1]]);throw new FxValidationError(`vowel must be one of ${SING_VOWELS.join(" ")} or a morph like a>o`)}function normalizeVowel(text2){if(typeof text2!="string")throw new FxValidationError(`vowel must be one of ${SING_VOWELS.join(" ")} or a morph like a>o`);return parseVowel(text2).join(">")}var SPELLINGS=Object.freeze([[/igh|ie$|i[^aeiou]e$/,"a>i"],[/[^aeiou]y$/,"i"],[/ou|ow/,"a>u"],[/oi|oy/,"o>i"],[/ai|ay|ey|eigh|a[^aeiou]e$/,"e>i"],[/oo|ew|ue|u[^aeiou]e$/,"u"],[/ee|ea|ie|ei/,"i"],[/oa|o[^aeiou]e$|o$/,"o"],[/[^aeiou]u$/,"u"],[/au|aw|ah|ar/,"a"],[/a/,"a"],[/e/,"e"],[/i/,"i"],[/o/,"o"],[/u/,"a"]]),VOWEL_WORDS=Object.freeze({you:"u",to:"u",do:"u",who:"u",heart:"a",are:"a",yeah:"e",eye:"a>i",eyes:"a>i",i:"a>i",...Object.fromEntries(["my","by","why","fly","cry","sky","try","dry","shy","spy","fry"].map(word2=>[word2,"a>i"])),love:"a",come:"a",some:"a",one:"a",done:"a",none:"a",above:"a",was:"a",of:"a",the:"a"});function vowelOf(syllable){if(!syllable)return;let lower=syllable.toLowerCase();try{return normalizeVowel(lower)}catch{}let word2=lower.replace(/[^a-z]/g,""),exception=VOWEL_WORDS[word2];if(exception)return exception;for(let[pattern,vowel]of SPELLINGS)if(pattern.test(word2))return vowel}function normalizeSing(input){if(input==null)return;if(!isRecord2(input))throw new FxValidationError("track sing must be an object or null");let params2={},presetName,vowel,drone,harmonics;for(let[key,value]of Object.entries(input)){if(value==null)continue;if(key==="preset"){let name2=typeof value=="string"?value.trim().toLowerCase():"";if(!isSingPreset(name2))throw new FxValidationError(`sing preset must be one of ${SING_PRESET_NAMES.join(", ")}`);presetName=name2;continue}let name=singParamName(key);if(!name)throw new FxValidationError(`sing has no parameter "${key.slice(0,32)}" (try ${[...Object.keys(SING_PARAMS),"harmonics"].join(", ")})`);if(name==="vowel")vowel=normalizeVowel(value);else if(name==="drone")drone=parseDrone(value);else if(name==="harmonics")harmonics=parseHarmonics(value);else{let spec=SING_PARAMS[name];if(spec?.kind==="number"&&spec.integer===!0&&typeof value=="number"&&!Number.isInteger(value))throw new FxValidationError(`sing ${name} must be a whole number`);params2[name]=value}}let values=normalizeParams(SING_PARAMS,params2,"sing",!1),out={};presetName&&(out.preset=presetName);let special={vowel,drone,harmonics};for(let key of SING_KEY_ORDER){let value=key in special?special[key]:values[key];value!==void 0&&(out[key]=value)}return Object.freeze(out)}function parseHarmonics(value){let[lo,hi]=SING_HARMONIC_RANGE;if(!Array.isArray(value)||value.length!==2||!value.every(h=>Number.isInteger(h)&&h>=lo&&h<=hi)||value[0]>=value[1])throw new FxValidationError(`sing harmonics must be [lo, hi], whole numbers ${lo}..${hi} with lo < hi`);return pair(value[0],value[1])}function singPresetOf(sing2){return sing2?.preset??DEFAULT_SING_PRESET}function resolveSing(sing2,keyRoot){let base=SING_PRESETS[singPresetOf(sing2)].settings,out={...base};if(sing2)for(let[key,value]of Object.entries(sing2))key!=="preset"&&value!==void 0&&(out[key]=value);if(keyRoot!==void 0&&sing2?.drone===void 0&&base.drone!==void 0){let offset=((Math.round(keyRoot)-base.drone)%12+18)%12,drone=base.drone+offset-6;drone>SING_DRONE_RANGE[1]&&(drone-=12),drone<SING_DRONE_RANGE[0]&&(drone+=12),out.drone=drone}return Object.freeze(out)}var SING_LANE_PARAMS=Object.freeze(Object.entries(SING_PARAMS).filter(entry=>entry[1].kind==="number"&&entry[1].automate===!0).map(([param2,spec])=>Object.freeze({param:param2,spec})));function autoVoice(pitch2){return pitch2<48?"bass":pitch2<55?"tenor":pitch2<72?"alto":"soprano"}function autoPartVoice(pitches){if(pitches.length===0)return;let sorted=[...pitches].sort((a,b)=>a-b),median=sorted[Math.floor((sorted.length-1)/2)];return median<53?"bass":median<61?"tenor":median<67?"alto":"soprano"}function singTailSeconds(sing2){return resolveSing(sing2).release+.05}var MODAL_INSTRUMENT2="modal",MODAL_BODIES=Object.freeze(["marimba","vibraphone","xylophone","glockenspiel","celesta","chimes","crotale","mbira","kalimba","musicbox","toypiano","saron","bonang","gender","kempul","gong","bell","steelpan","bowl","timpani","tabla","frame"]),MODAL_MALLETS=Object.freeze({yarn:.15,cord:.35,rubber:.55,plastic:.75,brass:.95}),MODAL_MALLET_NAMES=Object.freeze(Object.keys(MODAL_MALLETS)),MODAL_PRESET_NAMES=Object.freeze(["marimba","vibes","xylophone","glock","celesta","chimes","kalimba","mbira","steelpan","bowl","gong","timpani","crotales","musicbox","toypiano","saron","demung","slenthem","gangsa","gender","bonang","kenong","kethuk","kempul","daf","bodhran","tabla"]),MODAL_ALIASES=Object.freeze({vibraphone:"vibes",glockenspiel:"glock",tubular:"chimes",thumbpiano:"kalimba",gongageng:"gong",steeldrum:"steelpan",singingbowl:"bowl",kettledrum:"timpani",tubularbells:"chimes",crotale:"crotales",musicalbox:"musicbox",framedrum:"bodhran"}),GAMELAN_PRESETS=Object.freeze(["saron","demung","slenthem","gangsa","gender","bonang","kenong","kethuk","kempul","gong"]),num3=(min,max,fallback,step2,doc,extra={})=>Object.freeze({kind:"number",min,max,default:fallback,step:step2,optional:!0,doc,...extra}),MODAL_PARAMS=Object.freeze({mallet:Object.freeze({kind:"enum",values:MODAL_MALLET_NAMES,default:"cord",optional:!0,doc:"mallet: yarn, cord, rubber, plastic or brass (sets hardness)"}),hardness:num3(0,1,.4,.05,"mallet hardness: 0 yarn/felt, 1 brass",{automate:!0}),position:num3(0,1,.42,.05,"strike point: 0 end or edge, 0.5 center",{automate:!0}),ring:num3(.05,30,1.6,"log","ring time (T60) at middle C",{unit:"s",automate:!0}),tilt:num3(0,2,.9,.05,"how much faster high modes and notes decay",{automate:!0}),damp:num3(0,1,0,.05,"damping at note-off: 0 rings on, 1 chokes",{automate:!0}),release:num3(.005,2,.12,"log","choke time when damp is 1",{unit:"s",strudel:["release","rel"]}),motor:num3(0,12,0,.25,"vibraphone motor tremolo rate",{unit:"Hz"}),motordepth:num3(0,1,0,.05,"motor tremolo depth",{automate:!0}),ombak:num3(0,12,0,.25,"paired-instrument beat rate (gamelan ombak)",{unit:"Hz"}),buzz:num3(0,1,0,.05,"buzzer or jingle amount",{automate:!0}),click:num3(0,1,0,.05,"mallet contact click",{automate:!0}),strikebend:num3(-24,24,0,.5,"strike pitch glide start",{unit:"st",strudel:["penv"]}),strikedecay:num3(.001,2,.1,"log","strike pitch glide time",{unit:"s",strudel:["pdecay"]}),gain:num3(0,2,.8,.05,"level",{automate:!0}),body:Object.freeze({kind:"enum",values:MODAL_BODIES,default:"marimba",optional:!0,doc:"mode table (from the preset)"})}),MODAL_SIMPLE=Object.freeze(["mallet","hardness","position","ring","damp"]),MODAL_DEFAULTS=Object.freeze({body:"marimba",hardness:.4,position:.42,ring:1.6,tilt:.9,damp:0,release:.12,motor:0,motordepth:0,ombak:0,buzz:0,click:0,strikebend:0,strikedecay:.1,gain:.8}),preset3=(settings,range,doc,styles)=>Object.freeze({settings:Object.freeze({...MODAL_DEFAULTS,...settings}),range:Object.freeze(range),doc,styles}),MODAL_PRESETS=Object.freeze({marimba:preset3({body:"marimba",ring:1.6,tilt:.9,hardness:.35,position:.42},[45,96],"rosewood bars, yarn mallets, warm and round","Reich, Glass, Four Tet, Caribou, jazz"),vibes:preset3({body:"vibraphone",ring:6,tilt:.6,hardness:.5,position:.42,damp:.3,release:.15,motor:5.5,motordepth:.45},[53,89],"aluminium bars with motor tremolo, damped unless the pedal is down","jazz, Motown, soul, Four Tet"),xylophone:preset3({body:"xylophone",ring:.6,tilt:1.2,hardness:.85,position:.45},[65,108],"hard, dry and bright","orchestral, Messiaen, Shostakovich"),glock:preset3({body:"glockenspiel",ring:3.5,tilt:.5,hardness:.9,position:.45},[79,108],"steel bars, brass mallets, sparkling","orchestral, Motown, The Field, Beach House"),celesta:preset3({body:"celesta",ring:1.2,tilt:.7,hardness:.5,position:.45},[60,108],"felt-hammered steel plates, soft and glassy","Debussy, OPN, Radiohead, ambient"),chimes:preset3({body:"chimes",ring:7,tilt:.35,hardness:.8,position:.05},[60,77],"tubular bells struck at the cap","orchestral, Messiaen, ambient"),kalimba:preset3({body:"kalimba",ring:1.4,tilt:.8,hardness:.6,position:.7},[60,88],"clean thumb piano","Four Tet, Caribou, ambient, hyperpop"),mbira:preset3({body:"mbira",ring:1.4,tilt:.8,hardness:.7,position:.7,buzz:.35},[48,84],"thumb-plucked tines with a bottle-cap buzz","mbira, Four Tet, Caribou"),steelpan:preset3({body:"steelpan",ring:1.6,tilt:.6,hardness:.6,position:.5},[60,88],"tuned steel drum with near-harmonic partials","Caribou, ambient, calypso"),bowl:preset3({body:"bowl",ring:18,tilt:.25,hardness:.2,position:.5},[48,79],"singing bowl, beating split modes","ambient, Eno, La Monte Young"),gong:preset3({body:"gong",ring:12,tilt:.3,hardness:.15,position:.5},[31,55],"gong ageng: deep, beating, very long","gamelan, ambient, La Monte Young"),timpani:preset3({body:"timpani",ring:2.2,tilt:.6,hardness:.4,position:.75,strikebend:.3,strikedecay:.15},[40,60],"pedal timpani, felt sticks, a small strike glide","Beethoven, Brahms, Shostakovich, orchestral"),crotales:preset3({body:"crotale",ring:6,tilt:.4,hardness:.85,position:.5,gain:1.6},[84,108],"antique cymbals, long shimmering ring","Messiaen, ambient"),musicbox:preset3({body:"musicbox",ring:1.8,tilt:.7,hardness:1,position:.8,gain:1.7},[60,100],"plucked steel comb","ambient, OPN, A. G. Cook"),toypiano:preset3({body:"toypiano",ring:1,tilt:.6,hardness:.9,position:.6,click:.3,gain:2},[60,96],"hammered toy-piano rods, clanky","hyperpop, A. G. Cook, Four Tet"),saron:preset3({body:"saron",ring:2.5,tilt:.6,hardness:.85,position:.5,damp:.85,release:.1},[60,84],"saron barung: bronze keys, horn mallet, the balungan melody; damped at the next note (tutupan)","Javanese gamelan, Reich"),demung:preset3({body:"saron",ring:3.2,tilt:.6,hardness:.75,position:.5,damp:.8,release:.12},[48,72],"demung: the saron an octave lower, fuller","Javanese gamelan"),slenthem:preset3({body:"gender",ring:4.5,tilt:.5,hardness:.25,position:.5},[43,60],"slenthem: low bronze keys over tubes, padded mallet","Javanese gamelan, ambient"),gangsa:preset3({body:"saron",ring:2.2,tilt:.6,hardness:.9,position:.5,ombak:7,damp:.85,release:.1},[60,89],"Balinese metallophone: pengumbang and pengisep beating at 7 Hz (ombak)","Balinese gamelan, Lopatin, Four Tet"),gender:preset3({body:"gender",ring:5,tilt:.5,hardness:.3,position:.5},[48,84],"gender: thin bronze keys over tubes, padded mallets, long ring","Javanese gamelan, ambient"),bonang:preset3({body:"bonang",ring:1.8,tilt:.7,hardness:.6,position:.5,damp:.7,release:.12},[55,84],"bonang: small kettle gongs in a row, padded sticks","Javanese gamelan, Reich"),kenong:preset3({body:"bonang",ring:4,tilt:.5,hardness:.45,position:.5},[55,72],"kenong: large kettle gong that marks the phrase","Javanese gamelan"),kethuk:preset3({body:"bonang",ring:.5,tilt:.7,hardness:.5,position:.5,damp:1,release:.08},[55,67],"kethuk: small kettle gong, struck and damped (tutupan)","Javanese gamelan"),kempul:preset3({body:"kempul",ring:6,tilt:.4,hardness:.25,position:.5},[43,67],"kempul: hanging gong, slow beating","Javanese gamelan"),daf:preset3({body:"frame",ring:.5,tilt:.8,hardness:.6,position:.85,buzz:.6},[43,55],"Persian frame drum with ring jingles","Persian, Sufi"),bodhran:preset3({body:"frame",ring:.35,tilt:.9,hardness:.5,position:.8,damp:.4,gain:2},[40,52],"Irish frame drum, tipper","celtic"),tabla:preset3({body:"tabla",ring:1.2,tilt:.5,hardness:.7,position:.75,strikebend:.4,strikedecay:.12,gain:2},[57,69],"dayan: tuned treble drum with near-harmonic syahi modes","Hindustani, Talvin Singh, Four Tet")}),DEFAULT_MODAL_PRESET="marimba";function isModalPreset(name){return MODAL_PRESET_NAMES.includes(name)}function modalPresetFor(word2){let lower=word2.trim().toLowerCase();return isModalPreset(lower)?lower:MODAL_ALIASES[lower]}function isModalParam(name){return Object.prototype.hasOwnProperty.call(MODAL_PARAMS,name)}function modalParamName(name){if(isModalParam(name))return name;for(let[key,spec]of Object.entries(MODAL_PARAMS))if(spec.strudel?.includes(name))return key}function normalizeModal(input){if(input==null)return;if(!isRecord2(input))throw new FxValidationError("track modal must be an object or null");let params2={},presetName,pair2;for(let[key,value]of Object.entries(input)){if(value==null)continue;if(key==="pair"){if(typeof value!="string"||!PAIR_ID.test(value))throw new FxValidationError("modal pair must be a track id (letters, digits, - or _)");pair2=value;continue}if(key==="preset"){if(typeof value!="string")throw new FxValidationError(`modal preset must be one of ${MODAL_PRESET_NAMES.join(", ")}`);let resolved=modalPresetFor(value);if(!resolved)throw new FxValidationError(`modal preset must be one of ${MODAL_PRESET_NAMES.join(", ")}`);presetName=resolved;continue}let name=modalParamName(key);if(!name)throw new FxValidationError(`modal has no parameter "${key.slice(0,32)}"`);params2[name]=value}let values=normalizeParams(MODAL_PARAMS,params2,"modal",!1);return Object.freeze({...presetName?{preset:presetName}:{},...values,...pair2===void 0?{}:{pair:pair2}})}function modalSettings(modal2,lane){let out={...MODAL_PRESETS[modal2?.preset??DEFAULT_MODAL_PRESET].settings};if(modal2?.mallet&&(out.hardness=MODAL_MALLETS[modal2.mallet]),modal2)for(let[key,value]of Object.entries(modal2))key!=="preset"&&key!=="mallet"&&key!=="pair"&&value!==void 0&&(out[key]=value);if(lane)for(let key of MODAL_LANE_PARAMS){let value=lane(key.param);value!==void 0&&(out[key.param]=value)}return Object.freeze(out)}var MODAL_LANE_PARAMS=Object.freeze(Object.entries(MODAL_PARAMS).filter(entry=>entry[1].kind==="number"&&entry[1].automate===!0).map(([param2,spec])=>Object.freeze({param:param2,spec}))),MAX_RESONATOR_TAIL=30,MAX_RESONATOR_VOICES=32,RESONATOR_TABLE_VERSION=2,PAIR_ID=/^[A-Za-z0-9_-]{1,64}$/;function modalTailSeconds(modal2,lowestPitch){let s=modalSettings(modal2);if(s.damp>=.999)return Math.min(MAX_RESONATOR_TAIL,s.release+.05);let octavesBelowC4=lowestPitch===void 0?1:Math.max(1,(60-lowestPitch)/12);return Math.min(MAX_RESONATOR_TAIL,s.ring*2**(s.tilt*octavesBelowC4))}var TEXTURE_INSTRUMENT2="texture",TEXTURE_TYPES=Object.freeze(["room","rain","wind","vinyl","tape","hum","city","crowd","data","air","ocean","stream","waterfall","crickets","birds","country-road","brush","paper","porcelain"]),TEXTURE_MOTIONS=Object.freeze(["steady","rise","fall","swell"]),TEXTURE_DOCS=Object.freeze({room:"room tone: shaped noise through an 8x8 Hadamard FDN with moving delays",rain:"Poisson raindrops as rising bubble chirps over a filtered-noise bed",wind:"band-passed noise whose center and Q follow gusts, plus whistles",vinyl:"record surface: crackle, pops and rumble",tape:"tape hiss with wow, flutter, modulation noise and a head bump",hum:"50 or 60 Hz mains hum: a harmonic series plus noise",city:"traffic swells, distant rumble and clatter through a street FDN",crowd:"murmur: seeded formant bursts (syllables) from many talkers",data:"glitches: bit-flips, buffer stutters, sample-rate sweeps, clicks, modem bursts",air:"high shimmering band noise",ocean:"grouped ocean swell, asymmetric breaks and foamy wash",stream:"running water with bright gurgling bubbles",waterfall:"a broad sheet of falling water with deep turbulence",crickets:"stereo night insects in pulsed chirp trains",birds:"scattered birdsong with bent whistle calls","country-road":"distant tires and a low engine drifting across a quiet road",brush:"bristles brushing a drum skin in soft, uneven strokes",paper:"flexing paper, with clusters of creases and a dry rustle",porcelain:"tapped ceramic with a hollow body and beating partials"}),num4=(min,max,fallback,step2,doc,extra={})=>Object.freeze({kind:"number",min,max,default:fallback,step:step2,optional:!0,doc,...extra}),TEXTURE_PARAMS=Object.freeze({type:Object.freeze({kind:"enum",values:TEXTURE_TYPES,default:"room",optional:!0,doc:`texture: ${TEXTURE_TYPES.join(", ")}`}),density:num4(0,1,.5,.05,"how much happens: drops, gusts, crackle, talkers, glitches",{automate:!0}),distance:num4(0,1,.3,.05,"near and bright to far, dark and roomy",{automate:!0}),wear:num4(0,1,.3,.05,"clean to worn: grit, whistles, pops, flutter, buzz",{automate:!0}),width:num4(0,1,.7,.05,"mono to wide (left and right stay correlated)",{automate:!0}),motion:Object.freeze({kind:"enum",values:TEXTURE_MOTIONS,default:"steady",optional:!0,doc:"over each note: steady, rise (riser), fall (downlifter) or swell (whoosh)"}),mains:num4(40,70,60,10,"hum fundamental (50 or 60 Hz mains)",{unit:"Hz"}),attack:num4(.001,10,.4,"log","fade in at each note",{unit:"s",strudel:["att"]}),release:num4(.005,10,1,"log","fade out after each note",{unit:"s",strudel:["rel"]}),gain:num4(0,2,1,.05,"level",{automate:!0}),seed:num4(0,65535,0,1,"variation: another seed, another bed",{integer:!0})}),TEXTURE_TYPE_DEFAULTS=Object.freeze({room:{density:.4,distance:.5,wear:.2,width:.7},rain:{density:.5,distance:.3,wear:.3,width:.8},wind:{density:.5,distance:.3,wear:.3,width:.7},vinyl:{density:.4,distance:.1,wear:.3,width:.5},tape:{density:.5,distance:.1,wear:.3,width:.5},hum:{density:.4,distance:.2,wear:.3,width:.2},city:{density:.5,distance:.5,wear:.3,width:.8},crowd:{density:.5,distance:.5,wear:.2,width:.8},data:{density:.5,distance:.1,wear:.4,width:.6},air:{density:.5,distance:.2,wear:.2,width:.8},ocean:{density:.5,distance:.25,wear:.32,width:.78},stream:{density:.5,distance:.25,wear:.32,width:.78},waterfall:{density:.5,distance:.25,wear:.32,width:.78},crickets:{density:.5,distance:.25,wear:.32,width:.78},birds:{density:.5,distance:.25,wear:.32,width:.78},"country-road":{density:.5,distance:.25,wear:.32,width:.78},brush:{density:.46,distance:.22,wear:.23,width:.58,attack:.005,release:.07},paper:{density:.43,distance:.16,wear:.51,width:.78,attack:.004,release:.12},porcelain:{density:.35,distance:.22,wear:.26,width:.72,attack:.001,release:.65}}),TEXTURE_DEFAULTS=Object.freeze({type:"room",density:.5,distance:.3,wear:.3,width:.7,motion:"steady",mains:60,attack:.4,release:1,gain:1,seed:0});function isTextureParam(name){return Object.prototype.hasOwnProperty.call(TEXTURE_PARAMS,name)}function textureParamName(name){if(isTextureParam(name))return name;for(let[key,spec]of Object.entries(TEXTURE_PARAMS))if(spec.strudel?.includes(name))return key}function normalizeTexture(input){if(input==null)return;if(!isRecord2(input))throw new FxValidationError("track texture must be an object or null");let params2={};for(let[key,value]of Object.entries(input)){if(value==null)continue;let name=textureParamName(key);if(!name)throw new FxValidationError(`texture has no parameter "${key.slice(0,32)}"`);params2[name]=name==="type"&&typeof value=="string"?value.trim().toLowerCase():value}return normalizeParams(TEXTURE_PARAMS,params2,"texture",!1)}function textureSettings(texture){let type=texture?.type??TEXTURE_DEFAULTS.type,out={...TEXTURE_DEFAULTS,...TEXTURE_TYPE_DEFAULTS[type]};if(texture)for(let[key,value]of Object.entries(texture))value!==void 0&&(out[key]=value);return out.type=type,Object.freeze(out)}var TEXTURE_LANE_PARAMS=Object.freeze(Object.entries(TEXTURE_PARAMS).filter(entry=>entry[1].kind==="number"&&entry[1].automate===!0).map(([param2,spec])=>Object.freeze({param:param2,spec}))),MAX_TEXTURE_VOICES=8,TEXTURE_ENGINE_VERSION=3;function textureTailSeconds(texture,distanceLane=!1){let settings=textureSettings(texture),distance=distanceLane?1:settings.distance;return Math.min(12,settings.release+.5+2.5*distance)}var VOCODER_INSTRUMENT2="vocoder",VOCODER_PRESET_NAMES=Object.freeze(["classic","robot","talkbox","choir","glass","whisper","smear","lofi"]),DEFAULT_VOCODER_PRESET="classic",VOCODER_TAPS=Object.freeze(["chain","dry"]),VOCODER_MODES=Object.freeze(["channel","talkbox"]),VOCODER_CARRIERS=Object.freeze(["saw","supersaw","pulse","noise"]),VOCODER_FOLLOWS=Object.freeze(["notes","chords","drone"]),VOCODER_GATE_AUTO="auto",TALKBOX_FORMANT_MAX=12,num5=(min,max,fallback,step2,doc,extra={})=>Object.freeze({kind:"number",min,max,default:fallback,step:step2,optional:!0,doc,...extra}),choice=(values,fallback,doc)=>Object.freeze({kind:"enum",values,default:fallback,optional:!0,doc}),VOCODER_PARAMS=Object.freeze({tap:choice(VOCODER_TAPS,"chain","modulator after its mono chain (pre-pan) or dry before it"),mode:choice(VOCODER_MODES,"channel","band bank or LPC talkbox"),carrier:choice(VOCODER_CARRIERS,"supersaw","built-in carrier (instrument vocoder only)"),follow:choice(VOCODER_FOLLOWS,"notes","built-in carrier pitch: notes, song chords or a drone"),root:num5(24,96,45,1,"drone pitch (MIDI)",{integer:!0}),spread:num5(0,1,.15,.05,"supersaw detune spread (semitones)",{unit:"st",automate:!0}),bands:num5(4,40,16,1,"channel bands (heavy above 24)",{integer:!0}),lo:num5(50,1e3,100,"log","lowest band center",{unit:"Hz"}),hi:num5(2e3,12e3,8e3,"log","highest band center",{unit:"Hz"}),width:num5(.25,4,1,.05,"band width (x spacing)",{automate:!0}),attack:num5(5e-4,.2,.005,"log","follower attack",{unit:"s",strudel:["att"]}),release:num5(.005,2,.04,"log","follower release (long = smear)",{unit:"s",automate:!0,strudel:["rel"]}),formant:num5(-24,24,0,.5,"formant shift (+ is smaller and brighter; talkbox \xB112)",{unit:"st",automate:!0}),unvoiced:num5(0,1,.5,.05,"noise carrier on fricatives",{automate:!0}),sens:num5(0,1,.5,.05,"unvoiced detection sensitivity"),hiss:num5(0,1,0,.05,"high-passed modulator added through",{automate:!0}),gate:num5(-90,0,-60,1,'modulator gate in dBFS, or "auto"',{unit:"dB"}),enhance:Object.freeze({kind:"boolean",default:!0,optional:!0,doc:"whiten the carrier so every band speaks"}),depth:num5(0,1,1,.05,"how much the voice shapes the carrier",{automate:!0}),freeze:Object.freeze({kind:"boolean",default:!1,optional:!0,doc:"hold the last sung vowel through rests"}),mix:num5(0,1,1,.05,"wet against the carrier",{automate:!0}),gain:num5(-24,24,0,.5,"output trim",{unit:"dB",automate:!0}),seed:num5(0,2**31,1,1,"noise seed (absent: from the track id)",{integer:!0})}),VOCODER_DEFAULTS=Object.freeze({tap:"chain",mode:"channel",carrier:"supersaw",follow:"notes",root:45,spread:.15,bands:16,lo:100,hi:8e3,width:1,attack:.005,release:.04,formant:0,unvoiced:.5,sens:.5,hiss:0,gate:"auto",enhance:!0,depth:1,freeze:!1,mix:1,gain:0}),VOCODER_PRESETS=Object.freeze({classic:{doc:"70s/80s band vocoder lead",values:{}},robot:{doc:"monotone machine voice on a drone",values:{bands:12,carrier:"pulse",follow:"drone",root:45,release:.03,unvoiced:.3}},talkbox:{doc:"wet mouth-shaped lead, sharp vowels",values:{mode:"talkbox",carrier:"saw",unvoiced:.3,hiss:.1}},choir:{doc:"stereo vocal-stack chord pad",values:{bands:24,spread:.25,follow:"chords",release:.08,width:1.3}},glass:{doc:"bright crystalline lead",values:{bands:24,carrier:"saw",formant:3,hiss:.3,attack:.001}},whisper:{doc:"breathy unpitched ghost voice",values:{bands:24,carrier:"noise",unvoiced:0,hiss:.2}},smear:{doc:"blurred vowel wash (try freeze)",values:{bands:24,follow:"chords",release:.6,attack:.02,width:1.5}},lofi:{doc:"narrow murky 8-band",values:{bands:8,carrier:"pulse",formant:-3,width:.7,hi:4e3,gain:5}}}),VOCODER_LANE_PARAMS=Object.freeze([...Object.entries(VOCODER_PARAMS).filter(entry=>entry[1].kind==="number"&&entry[1].automate===!0).map(([param2,spec])=>Object.freeze({param:param2,spec})),Object.freeze({param:"freeze",spec:num5(0,1,0,1,"hold the vowel while 1",{automate:!0})})]);function isVocoderPreset(name){return VOCODER_PRESET_NAMES.includes(name)}function isVocoderParam(name){return Object.prototype.hasOwnProperty.call(VOCODER_PARAMS,name)}function vocoderParamName(name){if(isVocoderParam(name))return name;for(let[key,spec]of Object.entries(VOCODER_PARAMS))if(spec.strudel?.includes(name))return key}function normalizeVocoder(input){if(input==null)return;if(!isRecord2(input))throw new FxValidationError("track vocoder must be an object or null");let params2={},presetName,src,gate;for(let[key,value]of Object.entries(input)){if(value==null)continue;if(key==="src"){if(typeof value!="string"||value.length===0||value.length>64)throw new FxValidationError("vocoder src must be a track id (1 to 64 characters)");src=value;continue}if(key==="preset"){let lower=typeof value=="string"?value.toLowerCase():"";if(!isVocoderPreset(lower))throw new FxValidationError(`vocoder preset must be one of ${VOCODER_PRESET_NAMES.join(", ")}`);presetName=lower;continue}let name=vocoderParamName(key);if(!name)throw new FxValidationError(`vocoder has no parameter "${key.slice(0,32)}"`);if(name==="gate"&&value===VOCODER_GATE_AUTO){gate=VOCODER_GATE_AUTO;continue}params2[name]=value}let values=normalizeParams(VOCODER_PARAMS,params2,"vocoder",!1),out={};src!==void 0&&(out.src=src),presetName&&(out.preset=presetName);for(let key of Object.keys(VOCODER_PARAMS))key==="gate"&&gate!==void 0?out.gate=gate:values[key]!==void 0&&(out[key]=values[key]);return Object.freeze(out)}function vocoderPresetOf(vocoder){return vocoder?.preset??DEFAULT_VOCODER_PRESET}function resolveVocoder(vocoder,lane){let out={...VOCODER_DEFAULTS,...VOCODER_PRESETS[vocoderPresetOf(vocoder)].values};if(vocoder)for(let[key,value]of Object.entries(vocoder))key!=="preset"&&key!=="src"&&value!==void 0&&(out[key]=value);if(lane)for(let{param:param2}of VOCODER_LANE_PARAMS){let value=lane(param2);value!==void 0&&(out[param2]=param2==="freeze"?value>=.5:value)}return out.mode==="talkbox"&&(out.formant=Math.max(-TALKBOX_FORMANT_MAX,Math.min(TALKBOX_FORMANT_MAX,out.formant))),Object.freeze(out)}function vocoderTailSeconds(vocoder){return vocoder?Math.min(2.05,resolveVocoder(vocoder).release+.05):0}function vocoderPrerollSeconds(vocoder){return vocoder?Math.max(.5,5*resolveVocoder(vocoder).release+.1):0}function vocoderScoreError(tracks,maxTracks){let vocoded=tracks.filter(track2=>track2.vocoder);if(vocoded.length>maxTracks)return`a song holds at most ${maxTracks} vocoder tracks`;let src=new Map;for(let track2 of vocoded){let from=track2.vocoder.src;if(from!==void 0){if(from===track2.id)return`track ${track2.id} cannot vocode itself (vocoder src)`;src.set(track2.id,from)}}for(let start of src.keys()){let path=[start],at3=src.get(start);for(;at3!==void 0;){if(at3===start)return`vocoder cycle: ${[...path,at3].join(" -> ")}`;if(path.includes(at3))break;path.push(at3),at3=src.get(at3)}}}var SYNTH_SOUNDS=Object.freeze(["sine","sawtooth","square","triangle","supersaw","pulse","user","white","pink","brown","crackle","z_sine","z_triangle","z_sawtooth","z_square","z_tan","z_noise"]),LEGACY_SOUNDS=Object.freeze(["sine","piano","pluck","bass","saw","square","triangle"]),SOUND_ALIASES=Object.freeze({sin:"sine",tri:"triangle",sqr:"square",supersaw:"supersaw",pulse:"pulse",noise:"white",whitenoise:"white",pinknoise:"pink",brownnoise:"brown"}),FM_OPERATORS=8,FM_WAVES=["sine","sawtooth","square","triangle"],FILTER_SLOPES=["12db","24db","ladder"],seconds=(fallback,doc,strudel,max=10)=>({kind:"number",min:0,max,default:fallback,step:.01,unit:"s",automate:!0,doc,strudel}),level=(fallback,doc,strudel)=>({kind:"number",min:0,max:1,default:fallback,step:.05,automate:!0,doc,strudel}),hz=(fallback,doc,strudel)=>({kind:"number",min:20,max:2e4,default:fallback,step:"log",unit:"Hz",automate:!0,doc,strudel}),q=strudel=>({kind:"number",min:0,max:50,default:1,step:.5,automate:!0,doc:"resonance as filter Q (0..50; 0.7 is flat, higher rings)",strudel});function filterParams(prefix,name,aliases,qAliases){let f=prefix==="lp"?"lpf":prefix==="hp"?"hpf":"bpf",qName=`${prefix}q`;return{[f]:hz(prefix==="lp"?2e3:prefix==="hp"?200:1e3,`per-note ${name} cutoff; unset is no ${name}`,[f,...aliases]),[qName]:q([qName,...qAliases]),[`${prefix}env`]:{kind:"number",min:-10,max:10,default:0,step:.25,unit:"oct",automate:!0,doc:`${name} envelope depth in octaves above (below, negative) the cutoff`,strudel:[`${prefix}env`,`${prefix}e`]},[`${prefix}attack`]:seconds(.005,`${name} envelope attack`,[`${prefix}attack`,`${prefix}a`]),[`${prefix}decay`]:seconds(.15,`${name} envelope decay`,[`${prefix}decay`,`${prefix}d`]),[`${prefix}sustain`]:level(0,`${name} envelope sustain level`,[`${prefix}sustain`,`${prefix}s`]),[`${prefix}release`]:seconds(.1,`${name} envelope release`,[`${prefix}release`,`${prefix}r`])}}function fmParams(){let out={};for(let op=1;op<=FM_OPERATORS;op+=1){let n2=op===1?"":String(op),who=op===1?"FM":`FM ${op}`;out[`fm${n2}`]={kind:"number",min:0,max:64,default:0,step:.25,automate:!0,doc:`${who} modulation index (peak deviation \xF7 modulator frequency); 0 is off`,strudel:op===1?["fm","fmi"]:[`fm${n2}`,`fmi${n2}`]},out[`fmh${n2}`]={kind:"number",min:0,max:32,default:1,step:.01,automate:!0,doc:`${who} harmonicity: modulator \xF7 carrier frequency (integers sound harmonic)`,strudel:[`fmh${n2}`]},out[`fmattack${n2}`]=seconds(0,`${who} envelope attack`,[`fmattack${n2}`,`fmatt${n2}`]),out[`fmdecay${n2}`]=seconds(0,`${who} envelope decay`,[`fmdecay${n2}`,`fmdec${n2}`]),out[`fmsustain${n2}`]=level(1,`${who} envelope sustain level`,[`fmsustain${n2}`,`fmsus${n2}`]),out[`fmrelease${n2}`]=seconds(0,`${who} envelope release`,[`fmrelease${n2}`,`fmrel${n2}`]),out[`fmenv${n2}`]={kind:"enum",values:["lin","exp"],default:"lin",doc:`${who} envelope curve`,strudel:[`fmenv${n2}`,`fme${n2}`]},out[`fmwave${n2}`]={kind:"enum",values:FM_WAVES,default:"sine",doc:`${who} modulator waveform`,strudel:[`fmwave${n2}`]}}return out}var SYNTH_PARAMS=Object.freeze({attack:seconds(.003,"amplitude attack: onset to peak",["attack","att"]),decay:seconds(.05,"amplitude decay: peak to sustain level",["decay","dec"]),sustain:level(1,"amplitude sustain level held until note-off",["sustain","sus"]),release:seconds(.05,"amplitude release after note-off",["release","rel"]),gain:{kind:"number",min:0,max:4,default:1,step:.05,automate:!0,doc:"voice gain before the effects chain (track volume follows the chain)",strudel:["gain"]},noise:level(0,"pink noise mixed into the oscillator (z_* sounds: phase jitter)",["noise"]),density:level(.03,"crackle density (impulses \u2248 density\xB71000/s)",["density"]),unison:{kind:"number",min:1,max:16,default:1,step:1,integer:!0,doc:"stacked oscillator voices (supersaw defaults to 5)",strudel:["unison"]},detune:{kind:"number",min:0,max:12,default:.2,step:.05,unit:"st",automate:!0,doc:"total pitch spread of the unison voices in semitones",strudel:["detune"]},spread:level(.6,"stereo spread of the unison voices",["spread"]),pw:level(.5,"pulse width (pulse sound)",["pw"]),pwrate:{kind:"number",min:0,max:40,default:1,step:.1,unit:"Hz",automate:!0,doc:"pulse-width LFO rate (triangle)",strudel:["pwrate"]},pwsweep:level(0,"pulse-width LFO depth",["pwsweep"]),vib:{kind:"number",min:0,max:64,default:0,step:.25,unit:"Hz",automate:!0,doc:"vibrato rate; 0 is off",strudel:["vib","vibrato","v"]},vibmod:{kind:"number",min:0,max:24,default:.5,step:.05,unit:"st",automate:!0,doc:"vibrato depth in semitones",strudel:["vibmod","vmod"]},penv:{kind:"number",min:-48,max:48,default:0,step:1,unit:"st",automate:!0,doc:"pitch envelope depth in semitones (negative inverts); 0 is off",strudel:["penv"]},pattack:seconds(.2,"pitch envelope attack",["pattack","patt"]),pdecay:seconds(0,"pitch envelope decay",["pdecay","pdec"]),psustain:level(1,"pitch envelope sustain level",["psustain","psus"]),prelease:seconds(0,"pitch envelope release",["prelease","prel"]),pcurve:{kind:"number",min:0,max:1,default:0,step:1,integer:!0,doc:"pitch envelope curve: 0 linear, 1 exponential (kicks)",strudel:["pcurve"]},panchor:{kind:"number",min:0,max:1,default:0,step:.05,doc:"pitch envelope anchor: 0 sweeps note\u2192note+penv, 1 note\u2212penv\u2192note (defaults to psustain when unset)",strudel:["panchor"]},...filterParams("lp","low-pass",["cutoff","ctf","lp"],["resonance"]),...filterParams("hp","high-pass",["hcutoff","hp"],["hresonance"]),...filterParams("bp","band-pass",["bandf","bp"],["bandq"]),ftype:{kind:"enum",values:FILTER_SLOPES,default:"12db",doc:"per-note filter slope: 12db, 24db, ladder (low-pass only)",strudel:["ftype"]},fanchor:level(0,"filter envelope anchor: 0 sweeps up from the cutoff, 1 down to it",["fanchor"]),faccent:{kind:"number",min:0,max:4,default:0,step:.25,doc:"accent/marcato notes add this many octaves to the low-pass envelope depth and halve its decay (TB-303 accent)",strudel:["faccent"]},...fmParams(),zrand:level(0,"z_*: random pitch offset per note, \xB1 fraction",["zrand"]),curve:{kind:"number",min:0,max:3,default:1,step:.1,automate:!0,doc:"z_*: wave shape exponent (0 squares the wave off, >1 thins it)",strudel:["curve"]},slide:{kind:"number",min:-20,max:20,default:0,step:.1,automate:!0,doc:"z_*: pitch slide, 500\xB7slide Hz per second",strudel:["slide"]},deltaSlide:{kind:"number",min:-20,max:20,default:0,step:.1,automate:!0,doc:"z_*: slide acceleration, 500\xB7deltaSlide Hz per second\xB2",strudel:["deltaSlide","deltaslide"]},pitchJump:{kind:"number",min:-2e3,max:2e3,default:0,step:10,unit:"Hz",automate:!0,doc:"z_*: pitch change applied after pitchJumpTime",strudel:["pitchJump","pitchjump"]},pitchJumpTime:seconds(0,"z_*: time before pitchJump applies (0: never)",["pitchJumpTime","pitchjumptime"]),lfo:seconds(0,"z_*: repeat period: restarts slide and pitchJump, sets the tremolo period",["lfo"]),zmod:{kind:"number",min:0,max:1e3,default:0,step:1,unit:"Hz",automate:!0,doc:"z_*: frequency-modulation speed (\xB150 % depth)",strudel:["zmod"]},zcrush:level(0,"z_*: sample-hold bit crush, 0..1",["zcrush"]),zdelay:seconds(0,"z_*: one echo this many seconds later, half level",["zdelay"],1),tremolo:level(0,"z_*: volume modulation amount at the lfo period",["tremolo"])}),SYNTH_LISTS=Object.freeze({partials:{doc:"amplitude of each harmonic, fundamental first (sound `user`, or any oscillator)",min:-1,max:1},phases:{doc:"start phase of each harmonic in cycles 0..1",min:0,max:1}}),MAX_PARTIALS=64,SYNTH_SIMPLE=Object.freeze(["attack","decay","sustain","release","lpf","lpq","lpenv","detune","vib","fm"]),SYNTH_GROUPS=Object.freeze([{id:"amp",label:"amplitude",params:["attack","decay","sustain","release","gain"]},{id:"osc",label:"oscillator",params:["noise","density","unison","detune","spread","pw","pwrate","pwsweep"]},{id:"vib",label:"vibrato",params:["vib","vibmod"]},{id:"pitch",label:"pitch envelope",params:["penv","pattack","pdecay","psustain","prelease","pcurve","panchor"]},...["lp","hp","bp"].map(prefix=>({id:prefix,label:prefix==="lp"?"low-pass filter":prefix==="hp"?"high-pass filter":"band-pass filter",params:[prefix==="lp"?"lpf":prefix==="hp"?"hpf":"bpf",`${prefix}q`,`${prefix}env`,`${prefix}attack`,`${prefix}decay`,`${prefix}sustain`,`${prefix}release`,...prefix==="lp"?["ftype","fanchor","faccent"]:[]]})),...Array.from({length:FM_OPERATORS},(_,index)=>{let n2=index===0?"":String(index+1);return{id:`fm${n2||1}`,label:index===0?"FM":`FM ${index+1}`,params:[`fm${n2}`,`fmh${n2}`,`fmattack${n2}`,`fmdecay${n2}`,`fmsustain${n2}`,`fmrelease${n2}`,`fmenv${n2}`,`fmwave${n2}`]}}),{id:"zzfx",label:"ZzFX (z_* sounds)",params:["zrand","curve","slide","deltaSlide","pitchJump","pitchJumpTime","lfo","zmod","zcrush","zdelay","tremolo"]}]);function isSynthParam(name){return Object.prototype.hasOwnProperty.call(SYNTH_PARAMS,name)}function isSynthList(name){return Object.prototype.hasOwnProperty.call(SYNTH_LISTS,name)}function synthParamName(name){let lower=name.toLowerCase();if(isSynthParam(lower)||isSynthList(lower))return lower;for(let[key,spec]of Object.entries(SYNTH_PARAMS))if(spec.strudel?.some(alias=>alias.toLowerCase()===lower))return key}var SYNTH_LANE_PARAMS=Object.freeze(Object.entries(SYNTH_PARAMS).filter(entry=>entry[1].kind==="number"&&entry[1].automate===!0).map(([param2,spec])=>Object.freeze({param:param2,spec})));function normalizeSynth(input){if(input==null)return;if(!isRecord2(input))throw new FxValidationError("track synth must be an object or null");let scalars={},lists={};for(let[key,value]of Object.entries(input))if(value!=null){if(isSynthList(key)){lists[key]=normalizeList(key,value);continue}if(!isSynthParam(key))throw new FxValidationError(`synth has no parameter "${key}"${suggest(key)}`);scalars[key]=value}let out={...normalizeParams(SYNTH_PARAMS,scalars,"synth",!1)};for(let name of Object.keys(SYNTH_LISTS))lists[name]&&(out[name]=lists[name]);return Object.keys(out).length>0?Object.freeze(out):void 0}function suggest(key){let name=synthParamName(key);return name&&name!==key?` (did you mean "${name}"?)`:""}function normalizeList(name,value){let{min,max}=SYNTH_LISTS[name];if(!Array.isArray(value))throw new FxValidationError(`synth ${name} must be an array of numbers`);if(value.length===0||value.length>MAX_PARTIALS)throw new FxValidationError(`synth ${name} holds 1 to ${MAX_PARTIALS} numbers`);for(let item of value)if(typeof item!="number"||!Number.isFinite(item)||item<min||item>max)throw new FxValidationError(`synth ${name} entries must be numbers between ${min} and ${max}`);return Object.freeze([...value])}var SYNTH_PRESETS=Object.freeze({pad:{instrument:"supersaw",doc:"slow, wide detuned saws through a soft low-pass",synth:{attack:.6,decay:.5,sustain:.8,release:1.2,unison:6,detune:.25,spread:.8,lpf:1800,lpq:.8,gain:.7}},lead:{instrument:"sawtooth",doc:"bright saw with a short filter blip and delayed vibrato feel",synth:{attack:.005,decay:.2,sustain:.7,release:.12,lpf:1400,lpq:4,lpenv:2.5,lpdecay:.25,lpsustain:.3,vib:5.5,vibmod:.15,unison:2,detune:.08}},pluck:{instrument:"pulse",doc:"short percussive pulse with a fast filter envelope",synth:{attack:.001,decay:.25,sustain:0,release:.1,pw:.35,lpf:600,lpq:2,lpenv:4,lpdecay:.12,lpsustain:0}},bass:{instrument:"sawtooth",doc:"round saw bass, 24 dB low-pass with a little bite",synth:{attack:.002,decay:.3,sustain:.6,release:.06,lpf:300,lpq:2,lpenv:2,lpdecay:.15,lpsustain:.1,ftype:"24db"}},sub:{instrument:"sine",doc:"clean sine sub with a tiny pitch drop on each note",synth:{attack:.004,sustain:1,release:.08,penv:3,pattack:0,pdecay:.04,psustain:0,panchor:0}},acid:{instrument:"sawtooth",doc:"ladder low-pass with high resonance and a snappy envelope",synth:{attack:.002,decay:.2,sustain:.5,release:.05,lpf:400,lpq:18,lpenv:3.5,lpdecay:.18,lpsustain:0,ftype:"ladder",faccent:1.5}},keys:{instrument:"sine",doc:"electric-piano style 1:1 FM with a decaying modulator",synth:{attack:.002,decay:1.2,sustain:.25,release:.3,fm:2.2,fmh:1,fmdecay:.6,fmsustain:.1,fm2:.4,fmh2:14,fmdecay2:.05,fmsustain2:0}},bell:{instrument:"sine",doc:"inharmonic FM bell with a long ring",synth:{attack:.001,decay:2.5,sustain:0,release:1.5,fm:4,fmh:3.5,fmdecay:1.8,fmsustain:0}},organ:{instrument:"user",doc:"drawbar-style additive organ with a gentle vibrato",synth:{attack:.01,sustain:1,release:.08,vib:6,vibmod:.08,partials:[1,.8,.6,.5,0,.35,0,.3]}},strings:{instrument:"supersaw",doc:"softer ensemble: slow attack, gentle vibrato, darker filter",synth:{attack:.35,decay:.3,sustain:.85,release:.8,unison:4,detune:.15,spread:.7,lpf:2500,vib:5,vibmod:.1,gain:.75}},brass:{instrument:"sawtooth",doc:"filter swell on attack like a brass section",synth:{attack:.06,decay:.3,sustain:.8,release:.15,lpf:700,lpq:1.5,lpenv:2.5,lpattack:.08,lpdecay:.4,lpsustain:.5,unison:2,detune:.1}},wind:{instrument:"pink",doc:"breathy band-passed noise that swells and fades",synth:{attack:.4,sustain:1,release:.6,gain:2.5,bpf:900,bpq:2,bpenv:1,bpattack:.5,bpsustain:.5}},chip:{instrument:"pulse",doc:"8-bit square lead with slow pulse-width motion",synth:{attack:.001,sustain:.8,release:.03,pw:.25,pwrate:.8,pwsweep:.2}},zap:{instrument:"z_square",doc:"ZzFX laser zap: a square that dives in pitch",synth:{attack:.001,decay:.12,sustain:.2,release:.08,slide:-4,curve:.6}}});var ZZFX_ARRAY_LAYOUT=Object.freeze(["gain","zrand",null,"attack",null,"release","shape","curve","slide","deltaSlide","pitchJump","pitchJumpTime","lfo","noise","zmod","zcrush","zdelay","sustain","decay","tremolo","filter"]);var log="log",STRING_PARAMS=Object.freeze({exciter:{kind:"enum",values:["pick","finger","hammer","noise","bow"],default:"pick",doc:"how the string is set in motion (bow: the bowed voice)"},ring:{kind:"number",min:.05,max:60,default:3,step:log,unit:"s",automate:!0,doc:"how long a note rings (T60 at C4)",strudel:["decay"]},track:{kind:"number",min:0,max:1.5,default:.5,step:.05,doc:"higher notes ring shorter: T60 x (f/C4)^-track"},damp:{kind:"number",min:0,max:1,default:.4,step:.05,automate:!0,doc:"high-frequency loss (dark, dead strings at 1)"},stiff:{kind:"number",min:0,max:1,default:0,step:.05,doc:"inharmonicity B = 1e-6 x 400^stiff (0 off, 0.5 a wound bass string)"},pos:{kind:"number",min:.02,max:.5,default:.15,step:.01,automate:!0,doc:"pluck or strike position from the bridge (0.5 round, 0.04 nasal)"},bright:{kind:"number",min:0,max:1,default:.6,step:.05,automate:!0,doc:"excitation brightness at full velocity"},noise:{kind:"number",min:0,max:1,default:.04,step:.02,doc:"noise share of the excitation (pick scrape, finger squeak)"},release:{kind:"number",min:.005,max:10,default:.1,step:log,unit:"s",doc:"damping time after note-off"},mute:{kind:"number",min:0,max:1,default:0,step:.05,automate:!0,doc:"palm mute: shortens the ring and darkens the string"},buzz:{kind:"number",min:0,max:1,default:0,step:.05,automate:!0,doc:"bridge buzz (sitar, tanpura jawari); 0 off",strudel:["jawari"]},vel:{kind:"number",min:0,max:1,default:1,step:.05,doc:"velocity sensitivity of level and brightness (harpsichord 0.05)"},pickup:{kind:"number",min:0,max:.5,default:0,step:.01,doc:"magnetic pickup position (0 = acoustic bridge)"},vib:{kind:"number",min:0,max:12,default:0,step:.25,unit:"Hz",automate:!0,doc:"vibrato rate (a note's own vibrato overrides it)",strudel:["vib"]},vibmod:{kind:"number",min:0,max:2,default:.18,step:.02,unit:"st",automate:!0,doc:"vibrato depth in semitones",strudel:["vibmod"]},vibdelay:{kind:"number",min:0,max:2,default:.25,step:.05,unit:"s",doc:"vibrato onset delay"},body:{kind:"enum",values:["none","guitar","steel","small","bowl","gourd","skin","board","violin","bass"],default:"none",doc:"body resonance"},size:{kind:"number",min:.25,max:5,default:1,step:log,doc:"body scale: mode frequencies x 1/size (2 is a body twice as big)"},sym:{kind:"number",min:0,max:1,default:0,step:.05,doc:"sympathetic strings level"},symtune:{kind:"enum",values:["scale","open","drone"],default:"scale",doc:"what the sympathetic strings are tuned to"},unison:{kind:"number",min:1,max:8,default:1,step:1,integer:!0,doc:"strings per course",strudel:["unison"]},detune:{kind:"number",min:0,max:1,default:.1,step:.01,unit:"st",doc:"total detune spread across the course",strudel:["detune"]},spread:{kind:"number",min:0,max:1,default:.5,step:.05,doc:"stereo spread across the strings of a course",strudel:["spread"]},oct:{kind:"number",min:0,max:1,default:0,step:.05,doc:"octave string level (12-string, harpsichord 4', tres)"},octbelow:{kind:"number",min:0,max:128,default:128,step:1,integer:!0,doc:"octave strings only below this MIDI key"},voices:{kind:"number",min:1,max:32,default:8,step:1,integer:!0,doc:"polyphony cap (the oldest chord is released first)"},gain:{kind:"number",min:0,max:2,default:1,step:.05,automate:!0,doc:"output level (presets carry a calibrated trim)",strudel:["gain"]},pressure:{kind:"number",min:0,max:1,default:.5,step:.05,automate:!0,doc:"bow force within the playable range: flautando at 0, gritty at 1"},speed:{kind:"number",min:0,max:1,default:.6,step:.05,automate:!0,doc:"bow speed at full dynamics (loudness)"},attack:{kind:"number",min:.005,max:4,default:.08,step:log,unit:"s",doc:"bow-speed ramp at the start of a stroke (swells)",strudel:["attack"]},tremhz:{kind:"number",min:0,max:16,default:0,step:.5,unit:"Hz",doc:"tremolo bowing: rapid up and down strokes per second (0 off)"},sord:{kind:"number",min:0,max:1,default:0,step:.05,automate:!0,doc:"con sordino: the practice mute, darker and softer"},dyn:{kind:"number",min:0,max:1,default:1,step:.05,automate:!0,doc:"dynamics on top of velocity, drives bow speed and pressure (swells)",strudel:["expression"]}}),STRING_SIMPLE_PARAMS=Object.freeze(["ring","bright","damp","pos","mute","buzz","body","sym"]),BOW_SIMPLE_PARAMS=Object.freeze(["pressure","speed","attack","pos","vib","tremhz","sord","dyn","bright","ring","body"]);function stringParamName(word2){if(STRING_PARAMS[word2])return word2;for(let[name,spec]of Object.entries(STRING_PARAMS))if(spec.strudel?.includes(word2))return name}var STRING_LANE_PARAMS=Object.freeze(Object.entries(STRING_PARAMS).filter(entry=>entry[1].kind==="number"&&entry[1].automate===!0).map(([param2,spec])=>Object.freeze({param:param2,spec}))),BASE2={exciter:"pick",ring:3,track:.5,damp:.4,stiff:0,pos:.15,bright:.6,noise:.04,release:.1,buzz:0,vel:1,pickup:0,body:"none",size:1,sym:0,symtune:"open",unison:1,detune:0,spread:0,oct:0,octbelow:128,voices:6};function preset4(doc,styles,values){return Object.freeze({doc,styles,values:Object.freeze({...BASE2,...values})})}var BOW_BASE={...BASE2,exciter:"bow",ring:.6,damp:.5,pos:.12,release:.15,pressure:.5,speed:.6,attack:.08,vib:5.5,vibmod:.18,vibdelay:.25,body:"violin",voices:4};function bowed(doc,styles,values){return Object.freeze({doc,styles,values:Object.freeze({...BOW_BASE,...values})})}var STRING_PRESETS=Object.freeze({nylon:preset4("nylon-string classical guitar, warm fingerstyle","bachata rhythm, bossa, Mitski, ballads",{ring:3,damp:.45,stiff:.194,pos:.15,exciter:"finger",bright:.55,noise:.05,release:.12,body:"guitar",sym:.1,gain:.756}),steel:preset4("steel-string acoustic, bright pick","Neil Young, folk, jangle, bachata segunda",{ring:4,damp:.25,stiff:.425,pos:.12,exciter:"pick",bright:.7,noise:.08,body:"steel",sym:.12,gain:.41}),electric:preset4("clean electric guitar, bridge-ish pickup","angular rock, funk, jazz, Radiohead",{ring:5,damp:.3,stiff:.381,pos:.2,exciter:"pick",bright:.7,pickup:.18,gain:.211}),jangle:preset4("electric 12-string, octave courses","the Smiths, jangle rock, Byrds",{ring:5,damp:.25,stiff:.381,pos:.18,exciter:"pick",bright:.8,pickup:.15,unison:2,detune:.08,spread:.6,oct:.75,octbelow:60,voices:12,gain:.149}),ebass:preset4("electric bass, fingers","Motown, funk, soul, salsa",{ring:6,track:.3,damp:.35,stiff:.806,pos:.18,exciter:"finger",bright:.45,release:.06,pickup:.15,voices:4,gain:.207}),slap:preset4("slap bass, thumb near the neck with fret clatter","funk, disco",{ring:4,track:.3,damp:.2,stiff:.806,pos:.25,exciter:"hammer",bright:.95,release:.05,pickup:.15,buzz:.12,voices:4,gain:.198}),upright:preset4("upright bass pizzicato","jazz, salsa tumbao, Louis Armstrong",{ring:1.6,track:.4,damp:.55,stiff:.696,pos:.25,exciter:"finger",bright:.35,release:.08,body:"bass",voices:4,gain:.686}),motown:preset4("flatwound P-bass with a foam mute: short, round, thumpy","Motown, soul, 60s pop",{ring:1.2,track:.3,damp:.7,stiff:.806,pos:.2,exciter:"finger",bright:.3,release:.05,pickup:.15,mute:.3,voices:4,gain:.227}),sitar:preset4("sitar: jawari buzz and taraf sympathetic strings","raga, psychedelia",{ring:5,track:.3,damp:.25,stiff:.194,pos:.08,exciter:"pick",bright:.8,buzz:.6,release:.4,body:"gourd",sym:.35,symtune:"scale",voices:3,gain:.403}),tanpura:preset4("tanpura drone, open strings with strong jawari","raga drone, La Monte Young",{ring:9,track:.2,damp:.2,stiff:.098,pos:.05,exciter:"finger",bright:.45,buzz:.9,release:1.5,body:"gourd",size:1.25,voices:4,gain:.68}),harpsichord:preset4("harpsichord 8'+8' (oct adds the 4', pos 0.04 is the lute stop)","Bach, baroque continuo",{ring:4,track:.6,damp:.15,stiff:.098,pos:.12,exciter:"pick",bright:.9,noise:.02,release:.08,vel:.05,body:"board",unison:2,detune:.03,spread:.3,voices:24,gain:.164}),lute:preset4("renaissance lute, gut double courses","Dowland, early music, cantata continuo",{ring:2.5,damp:.5,pos:.18,exciter:"finger",bright:.45,body:"bowl",unison:2,detune:.04,spread:.3,voices:8,gain:.541}),oud:preset4("fretless oud with a plectrum","maqam, Persian, Arabic",{ring:2.5,damp:.4,pos:.12,exciter:"pick",bright:.55,body:"bowl",size:.909,unison:2,detune:.03,spread:.2,voices:6,gain:.338}),setar:preset4("Persian setar, nail-plucked, drone strings","Persian dastgah",{ring:2.5,damp:.3,pos:.1,exciter:"pick",bright:.65,body:"small",sym:.15,symtune:"drone",voices:4,gain:.415}),tar:preset4("Persian tar, skin-topped double bowl","Persian dastgah",{ring:2.2,damp:.25,pos:.1,exciter:"pick",bright:.75,body:"skin",unison:2,detune:.03,voices:6,gain:.28}),santur:preset4("santur: light mallets, four-string courses, undamped","Persian, celtic",{ring:6,track:.5,damp:.25,pos:.12,exciter:"hammer",bright:.7,release:3,body:"board",size:.833,sym:.12,symtune:"scale",unison:4,detune:.1,spread:.4,voices:24,gain:.292}),dulcimer:preset4("hammered dulcimer, softer hammers","celtic, Appalachian",{ring:5,damp:.35,pos:.13,exciter:"hammer",bright:.55,release:2.5,body:"board",unison:2,detune:.06,spread:.3,voices:24,gain:.451}),koto:preset4("koto, picks near the bridge; bends via note bend","Japanese, Ryuichi Sakamoto",{ring:3,damp:.4,pos:.08,exciter:"pick",bright:.6,release:.5,body:"board",size:1.43,voices:13,gain:.392}),harp:preset4("concert harp, plucked mid-string, open strings ring","Debussy, celtic, cantatas, film",{ring:5,track:.7,damp:.35,pos:.45,exciter:"finger",bright:.4,release:1.2,body:"board",sym:.15,symtune:"scale",voices:32,gain:.692}),banjo:preset4("5-string banjo, skin head, finger picks","bluegrass, folk",{ring:2,damp:.2,pos:.1,exciter:"pick",bright:.85,body:"skin",voices:5,gain:.376}),tres:preset4("Cuban tres, paired courses with octaves","salsa, son montuno",{ring:2.5,damp:.25,pos:.12,exciter:"pick",bright:.75,body:"small",unison:2,detune:.03,oct:.5,voices:6,gain:.238}),requinto:preset4("bachata requinto, small bright steel guitar","bachata lead",{ring:3,damp:.2,stiff:.329,pos:.1,exciter:"pick",bright:.85,body:"small",voices:6,gain:.36}),violin:bowed("solo violin","Bach, Brahms, Shostakovich, cantatas",{gain:.393}),viola:bowed("solo viola","orchestral, chamber",{vib:5.2,size:1.22,gain:.537}),cello:bowed("solo cello","Bach suites, Brahms, Shostakovich, Mitski ballads",{ring:.9,pos:.1,vib:5,vibmod:.2,size:2.4,gain:.415}),contrabass:bowed("arco double bass","orchestral bass",{ring:1.2,pos:.1,vib:4.5,vibmod:.12,body:"bass",size:1.2,voices:2,gain:.316}),fiddle:bowed("folk fiddle, straight tone, firm bow","celtic, bluegrass",{pressure:.65,pos:.1,attack:.03,vib:0,gain:.504}),erhu:bowed("erhu, skin body, wide vibrato","Chinese, film",{pressure:.45,pos:.1,vib:6,vibmod:.35,vibdelay:.15,body:"skin",size:.77,voices:2,gain:.347}),kamancheh:bowed("kamancheh spike fiddle","Persian",{pressure:.55,pos:.1,vib:6.5,vibmod:.25,vibdelay:.1,body:"skin",voices:2,gain:.43}),violins:bowed("violin section","orchestral, Shostakovich, Beethoven, Brahms",{vibmod:.15,unison:6,detune:.12,spread:.7,gain:.399}),violas:bowed("viola section","orchestral",{vib:5.2,vibmod:.15,size:1.22,unison:4,detune:.12,spread:.6,gain:.57}),cellos:bowed("cello section","orchestral, cantatas",{ring:.9,pos:.1,vib:5,vibmod:.17,size:2.4,unison:4,detune:.1,spread:.6,gain:.46}),contrabasses:bowed("double bass section","orchestral",{ring:1.2,pos:.1,vib:4.5,vibmod:.1,body:"bass",size:1.2,unison:3,detune:.08,spread:.4,voices:2,gain:.315}),pizz:preset4("pizzicato string section, plucked with the finger","orchestral, Motown strings, film",{exciter:"finger",ring:.6,damp:.5,pos:.2,bright:.45,release:.08,body:"violin",unison:4,detune:.1,spread:.6,voices:6,gain:.497}),trem:bowed("tremolo string section, rapid bowing","film, orchestral",{tremhz:13,vibmod:.1,unison:4,detune:.12,spread:.6,gain:.507})}),STRING_PRESET_NAMES=Object.freeze(Object.keys(STRING_PRESETS)),BOWED_PRESET_NAMES=Object.freeze(STRING_PRESET_NAMES.slice(STRING_PRESET_NAMES.indexOf("violin")));var DEFAULT_STRING_PRESET="nylon",STRING_ALIASES=Object.freeze({guitar:"steel",acoustic:"steel",classical:"nylon","12string":"jangle",bassguitar:"ebass",fender:"ebass",doublebass:"upright",cembalo:"harpsichord",hammered:"dulcimer",sehtar:"setar",kemence:"kamancheh",pizzicato:"pizz",tremolo:"trem","bowed-cello":"cello"});function stringPresetName(word2){let name=STRING_ALIASES[word2]??word2;return STRING_PRESETS[name]?name:void 0}function normalizeString(input){if(input==null)return;if(!isRecord2(input))throw new FxValidationError("track string must be an object or null");let values={},presetName;for(let[key,value]of Object.entries(input)){if(value==null)continue;if(key==="preset"){let name2=typeof value=="string"?stringPresetName(value):void 0;if(!name2)throw new FxValidationError(`string preset must be one of ${STRING_PRESET_NAMES.join(", ")}`);presetName=name2;continue}let name=stringParamName(key);if(!name)throw new FxValidationError(`string has no parameter "${key.slice(0,32)}"`);values[name]=value}let out={};presetName&&(out.preset=presetName);for(let[name,spec]of Object.entries(STRING_PARAMS))values[name]!==void 0&&(out[name]=normalizeParam(spec,values[name],`string ${name}`));return Object.freeze(out)}function stringPresetOf(settings){let name=settings?.preset;return typeof name=="string"&&STRING_PRESETS[name]?name:DEFAULT_STRING_PRESET}function resolveString(settings){let presetValues=STRING_PRESETS[stringPresetOf(settings)].values,out={};for(let[name,spec]of Object.entries(STRING_PARAMS)){let own=settings?.[name];out[name]=own!==void 0&&typeof own!="boolean"?own:presetValues[name]??spec.default}return Object.freeze(out)}function stringPresetTableText(){return JSON.stringify(STRING_PRESET_NAMES.map(name=>[name,STRING_PRESETS[name].values]))}var PIANO_FAMILIES=Object.freeze(["grand","upright","felt","honkytonk","prepared"]);function isPianoFamily(instrument){return PIANO_FAMILIES.includes(instrument??"")}var ELECTRIC_FAMILIES=Object.freeze(["epiano","wurli","clav"]);function isElectricFamily(instrument){return ELECTRIC_FAMILIES.includes(instrument??"")}var ORGAN_FAMILIES=Object.freeze(["tonewheel","combo","pipe"]);function isOrganFamily(instrument){return ORGAN_FAMILIES.includes(instrument??"")}var KEYS_FAMILIES=Object.freeze([...PIANO_FAMILIES,...ELECTRIC_FAMILIES,...ORGAN_FAMILIES]);var PIANO_BODIES=Object.freeze(["grand","upright","felt","honkytonk","prepared"]),unit2=(value,doc,automate=!1,step2=.05)=>({kind:"number",min:0,max:1,default:value,step:step2,...automate?{automate}:{},doc}),KEYS_PARAMS=Object.freeze({hardness:unit2(.5,"hammer felt hardness: brightness at a given velocity",!0),touch:unit2(1,"velocity sensitivity (0 plays every note at 0.8)",!0),inharm:{kind:"number",min:0,max:4,default:1,step:.1,unit:"x",doc:"inharmonicity multiplier (0 harmonic, 1 grand, 2.5 upright)"},unison:{kind:"number",min:0,max:30,default:.7,step:.5,unit:"c",doc:"detune spread of the unison strings in cents"},decay:{kind:"number",min:.1,max:4,default:1,step:.1,unit:"x",automate:!0,doc:"sustain time multiplier"},release:{kind:"number",min:.1,max:4,default:1,step:.1,unit:"x",automate:!0,doc:"damper time multiplier (how fast a released key stops)"},strike:{kind:"number",min:.04,max:.3,default:.12,step:.01,doc:"hammer position along the string"},after:unit2(.3,"aftersound share (the slow second stage of the decay)"),knock:unit2(.5,"soundboard knock and hammer thump",!0),noise:unit2(.25,"key-off and damper mechanics",!0),felt:unit2(0,"felt strip between hammers and strings",!0),prep:unit2(0,"share of keys carrying a preparation (seeded per key)"),width:unit2(.6,"keyboard stereo spread, bass left and treble right"),stretch:unit2(1,"octave stretch from the strings' own inharmonicity; 0 keeps tuning exact"),body:{kind:"enum",values:PIANO_BODIES,default:"grand",optional:!0,doc:"body EQ voicing (default: the family's own)"},vib:{kind:"number",min:0,max:64,default:0,step:.25,unit:"Hz",doc:"pitch wobble rate (tape wow); 0 is off; note vibrato replaces it",strudel:["vib","vibrato","v"]},vibmod:{kind:"number",min:0,max:24,default:.5,step:.05,unit:"st",doc:"pitch wobble depth in semitones",strudel:["vibmod","vmod"]},bark:unit2(.35,"pickup drive: growl when played hard (epiano, wurli)"),bell:unit2(.5,"tine or reed bell ping (epiano, wurli)"),tone:{kind:"number",min:0,max:12e3,default:0,step:100,unit:"Hz",automate:!0,doc:"output low-pass of the electric keys; 0 is off"},pickup:{kind:"enum",values:["neck","bridge","both","out"],default:"both",doc:"clav pickup switch; out is both pickups out of phase"},mute:unit2(0,"clav mute slider: damps the upper partials"),vibe:unit2(0,"suitcase stereo vibrato depth: antiphase left/right pan (epiano)",!0),vibehz:{kind:"number",min:.5,max:12,default:4,step:.25,unit:"Hz",doc:"suitcase vibrato rate (epiano)"},trem:unit2(0,"tremolo depth: reed piano at 5.6 Hz (wurli), pipe tremulant (pipe)",!0),sym:unit2(0,"sympathetic string resonance while the sustain pedal is down; 0 is off"),perc:{kind:"enum",values:["off","2nd","3rd"],default:"off",doc:"tonewheel percussion harmonic, single-trigger; on mutes the 1' bar"},percdecay:{kind:"enum",values:["fast","slow"],default:"fast",doc:"tonewheel percussion decay (fast 0.6 s, slow 1.8 s)"},click:unit2(.5,"tonewheel key click (contact bounce)"),scanner:{kind:"enum",values:["off","v1","v2","v3","c1","c2","c3"],default:"c3",doc:"tonewheel scanner vibrato (v1-v3) or chorus (c1-c3)"},drive:unit2(.15,"organ preamp overdrive",!0),rotary:{kind:"enum",values:["slow","fast","stop"],default:"slow",doc:"rotary speaker at the start (lane keys-rotary: 0 stop, 1 slow, 2 fast)"},voice:{kind:"enum",values:["flute","reed","bright"],default:"reed",doc:"combo register timbre: filtered square, reed pulse, bright saw"},chiff:unit2(.4,"pipe speech: the noise at each flue pipe's attack"),wind:unit2(.3,"pipe wind instability (slow pitch and level drift)"),percvol:{kind:"enum",values:["normal","soft"],default:"normal",doc:"tonewheel percussion volume: soft is about 6 dB down and keeps the drawbars at full level"}}),KEYS_PARAM_FAMILIES=Object.freeze({hardness:KEYS_FAMILIES,touch:KEYS_FAMILIES,decay:KEYS_FAMILIES,release:KEYS_FAMILIES,width:KEYS_FAMILIES,vib:KEYS_FAMILIES,vibmod:KEYS_FAMILIES,bark:["epiano","wurli"],bell:["epiano","wurli"],tone:ELECTRIC_FAMILIES,pickup:["clav"],mute:["clav"],vibe:["epiano"],vibehz:["epiano"],trem:["wurli","pipe"],perc:["tonewheel"],percdecay:["tonewheel"],percvol:["tonewheel"],click:["tonewheel"],scanner:["tonewheel"],drive:["tonewheel","combo"],rotary:["tonewheel","combo"],voice:["combo"],chiff:["pipe"],wind:["pipe"]});var ORGAN_TEXT=Object.freeze({drawbars:Object.freeze({digits:9,default:"888000000",doc:"tonewheel drawbars, nine digits 0-8: 16' 5\u2153' 8' 4' 2\u2154' 2' 1\u2157' 1\u2153' 1'"}),registers:Object.freeze({digits:5,default:"08800",doc:"combo registers, five digits 0-8: 16' 8' 4' 2\u2154' 2'"}),stops:Object.freeze({digits:0,default:"principal8 octave4 fifteenth2 mixture",doc:"pipe stops (or a registration: plenum flutes cornet reeds strings full)"})});function isOrganText(name){return Object.prototype.hasOwnProperty.call(ORGAN_TEXT,name)}var DRAWBAR_FEET=Object.freeze(["16'","5\u2153'","8'","4'","2\u2154'","2'","1\u2157'","1\u2153'","1'"]),REGISTER_FEET=Object.freeze(["16'","8'","4'","2\u2154'","2'"]),PIPE_STOPS=Object.freeze(["subbass16","bourdon16","principal8","flute8","gedackt8","gamba8","celeste8","octave4","flute4","nazard","fifteenth2","piccolo2","tierce","larigot","mixture","trombone16","trumpet8","oboe8","krummhorn8"]),PIPE_REGISTRATIONS=Object.freeze({plenum:["subbass16","principal8","octave4","fifteenth2","mixture"],flutes:["gedackt8","flute4"],cornet:["flute8","flute4","nazard","piccolo2","tierce"],reeds:["trumpet8","oboe8","nazard","tierce","larigot"],strings:["gamba8","celeste8"],full:PIPE_STOPS.filter(stop=>stop!=="celeste8")});function pipeStops(text2){let out=[];for(let word2 of text2.trim().split(/\s+/)){let names=PIPE_REGISTRATIONS[word2]??[word2];for(let name of names)out.includes(name)||out.push(name)}return out.filter(name=>PIPE_STOPS.includes(name))}function normalizeOrganText(name,value){if(typeof value!="string")throw new FxValidationError(`keys ${name} must be a string`);let spec=ORGAN_TEXT[name];if(spec.digits>0){if(!new RegExp(`^[0-8]{${spec.digits}}$`).test(value))throw new FxValidationError(`keys ${name} must be ${spec.digits} digits 0-8 (like ${spec.default})`);return value}let words=value.trim().toLowerCase().split(/\s+/).filter(Boolean);if(words.length===0)throw new FxValidationError("keys stops must name at least one stop");for(let word2 of words)if(!PIPE_STOPS.includes(word2)&&!Object.prototype.hasOwnProperty.call(PIPE_REGISTRATIONS,word2))throw new FxValidationError(`keys stops: unknown stop "${word2}" (stops ${PIPE_STOPS.join(" ")}; registrations ${Object.keys(PIPE_REGISTRATIONS).join(" ")})`);return words.join(" ")}var ORGAN_ROWS=Object.freeze({tonewheel:["drawbars","perc","percdecay","percvol","click","scanner","drive","rotary"],combo:["registers","voice","vib","vibmod","drive","rotary"],pipe:["stops","chiff","wind","trem"]}),ORGAN_PARAM_NAMES=Object.freeze(["perc","percdecay","click","scanner","drive","rotary","voice","chiff","wind","trem","percvol",...Object.keys(ORGAN_TEXT)]),ORGAN_FAMILY_DEFAULTS=Object.freeze({tonewheel:Object.freeze({drawbars:ORGAN_TEXT.drawbars.default}),combo:Object.freeze({registers:ORGAN_TEXT.registers.default,vib:6,vibmod:.12,drive:0,rotary:"stop"}),pipe:Object.freeze({stops:ORGAN_TEXT.stops.default})});var KEYS_SIMPLE=Object.freeze(["hardness","decay","release","felt"]),ELECTRIC_SIMPLE=Object.freeze({epiano:Object.freeze(["bark","bell","tone","vibe"]),wurli:Object.freeze(["bark","bell","tone","trem"]),clav:Object.freeze(["pickup","mute","tone","decay"])});var PIANO_FAMILY_DEFAULTS=Object.freeze({grand:Object.freeze({body:"grand"}),upright:Object.freeze({inharm:2.5,decay:.6,body:"upright"}),felt:Object.freeze({felt:1,hardness:.3,noise:.6,body:"felt"}),honkytonk:Object.freeze({unison:16,hardness:.7,body:"honkytonk"}),prepared:Object.freeze({prep:.6,body:"prepared"})}),ELECTRIC_FAMILY_DEFAULTS=Object.freeze({epiano:Object.freeze({width:.3,tone:6e3}),wurli:Object.freeze({width:.3,bark:.5,bell:.2,tone:5e3}),clav:Object.freeze({width:.3})}),KEYS_PRESETS=Object.freeze({grand:{instrument:"grand",keys:{},doc:"concert grand, bright and long, three-string unisons",styles:"Chopin, Beethoven, Brahms, Debussy, jazz, Glass, hyperpop"},ballad:{instrument:"grand",keys:{hardness:.3,after:.5,decay:1.3},reverb:{mix:.25,size:.7},doc:"darker grand, soft hammer, more aftersound, in a room",styles:"dark ballads, Mitski, Sakamoto, Brahms intermezzi"},upright:{instrument:"upright",keys:{},doc:"boxy, more inharmonic, shorter",styles:"soul, Motown, indie, Beach House"},felt:{instrument:"felt",keys:{},reverb:{mix:.2,size:.5},doc:"felt strip down, muted and intimate, audible mechanics",styles:"Sakamoto, Eno, Nils Frahm, The Field, Four Tet"},lofi:{instrument:"felt",keys:{vib:.3,vibmod:.05},filter:{cutoff:3500,resonance:.1},fx:{crush:{bits:10}},doc:"felt piano with tape wow, a dark filter and a little crush",styles:"lo-fi hip hop, bedroom pop, chillhop"},honkytonk:{instrument:"honkytonk",keys:{},doc:"16-cent unisons, bright saloon upright",styles:"ragtime, saloon, A. G. Cook"},prepared:{instrument:"prepared",keys:{},doc:"bolts, rubber and screws on 60% of keys (seeded per key)",styles:"Cage, Aphex-style, Oneohtrix Point Never"},epiano:{instrument:"epiano",keys:{},doc:"Rhodes-style stage tine piano: bell and bark with velocity",styles:"jazz, soul, Flying Lotus, Radiohead"},suitcase:{instrument:"epiano",keys:{vibe:.7,vibehz:4,bark:.3},doc:"tine piano with the suitcase stereo vibrato, left and right in turn",styles:"70s soul, Stevie Wonder ballads, neo-soul"},dyno:{instrument:"epiano",keys:{bell:.85,tone:9e3,hardness:.7},doc:"bright, bell-heavy tine piano",styles:"80s ballads, city pop"},wurli:{instrument:"wurli",keys:{},doc:"Wurlitzer-style reed piano, nasal and growly",styles:"soul, funk, Radiohead, Supertramp"},clav:{instrument:"clav",keys:{},doc:"clavinet, both pickups",styles:"funk, disco, reggae"},funkclav:{instrument:"clav",keys:{pickup:"out",mute:.3},doc:"clavinet with both pickups out of phase and the mute slider up",styles:"Stevie Wonder funk, Bill Withers"},tonewheel:{instrument:"tonewheel",keys:{},doc:"tonewheel organ 888000000, scanner C3, slow rotary",styles:"jazz, soul, gospel comping, Beach House"},gospel:{instrument:"tonewheel",keys:{drawbars:"888800008",perc:"3rd",rotary:"fast",drive:.35},doc:"888800008, 3rd percussion (mutes the 1'), fast rotary, driven",styles:"gospel, Motown, rock"},jazzorgan:{instrument:"tonewheel",keys:{drawbars:"888000000",perc:"3rd",percvol:"soft",scanner:"c3"},doc:"888000000 with soft fast 3rd percussion, slow rotary",styles:"Jimmy Smith jazz, soul jazz"},combo:{instrument:"combo",keys:{},doc:"Farfisa-style reed registers 08800 with vibrato",styles:"Beach House, 60s garage, Glass, Reich"},vox:{instrument:"combo",keys:{registers:"08880",voice:"bright",vib:5.5,vibmod:.1},doc:"Vox-style bright saw registers 08880",styles:"60s, Doors-ish, shoegaze drones"},pipe:{instrument:"pipe",keys:{stops:"plenum"},reverb:{mix:.35,size:.9},doc:"plenum: principal chorus, mixture and 16' in a church",styles:"Bach fugue, Bach cantata"},flutes:{instrument:"pipe",keys:{stops:"flutes",trem:.4,chiff:.5},reverb:{mix:.3,size:.8},doc:"gedackt 8' and flute 4' with tremulant",styles:"Bach chorale preludes, Eno, ambient"},cornet:{instrument:"pipe",keys:{stops:"cornet"},reverb:{mix:.3,size:.8},doc:"the cornet solo combination (8' 4' 2\u2154' 2' 1\u2157')",styles:"Bach, Buxtehude, French classical"},reeds:{instrument:"pipe",keys:{stops:"reeds"},reverb:{mix:.3,size:.85},doc:"trumpet and oboe with nazard, tierce and larigot",styles:"Messiaen"},celeste:{instrument:"pipe",keys:{stops:"strings",wind:.4},reverb:{mix:.35,size:.9},doc:"gamba and celeste: slow beating strings",styles:"Messiaen, ambient, La Monte Young drones"}}),ORGAN_ALIASES=Object.freeze({hammond:"tonewheel",b3:"tonewheel",farfisa:"combo",church:"pipe",pipeorgan:"pipe",churchorgan:"pipe"});function isKeysPreset(name){return Object.prototype.hasOwnProperty.call(KEYS_PRESETS,name)}function isKeysParam(name){return Object.prototype.hasOwnProperty.call(KEYS_PARAMS,name)}function keysParamName(name){let lower=name.toLowerCase();if(isKeysParam(lower)||isOrganText(lower))return lower;if(lower==="reg"||lower==="registration"||lower==="stop")return"stops";if(lower==="drawbar")return"drawbars";if(lower==="aftersound")return"after";if(lower==="prepared")return"prep";for(let[key,spec]of Object.entries(KEYS_PARAMS))if(spec.strudel?.some(alias=>alias.toLowerCase()===lower))return key}var KEYS_LANE_PARAMS=Object.freeze(Object.entries(KEYS_PARAMS).filter(entry=>entry[1].kind==="number"&&entry[1].automate===!0).map(([param2,spec])=>Object.freeze({param:param2,spec})).concat(Object.freeze({param:"rotary",spec:Object.freeze({kind:"number",min:0,max:2,default:1,step:1,integer:!0,doc:"rotary speed: 0 stop, 1 slow, 2 fast"})})));function rotarySpeed(value){return value==="fast"?2:value==="stop"?0:1}function normalizeKeys(input){if(input==null)return;if(!isRecord2(input))throw new FxValidationError("track keys must be an object or null");let params2={},text2={},preset5;for(let[key,value]of Object.entries(input))if(value!=null){if(key==="preset"){if(typeof value!="string"||!isKeysPreset(value))throw new FxValidationError(`keys preset must be one of ${Object.keys(KEYS_PRESETS).join(", ")}`);preset5=value;continue}if(isOrganText(key)){text2[key]=normalizeOrganText(key,value);continue}if(!isKeysParam(key)){let name=keysParamName(key);throw new FxValidationError(`keys has no parameter "${key}"${name?` (did you mean "${name}"?)`:""}`)}params2[key]=value}let values=normalizeParams(KEYS_PARAMS,params2,"keys",!1);return Object.freeze({...values,...Object.fromEntries(Object.keys(ORGAN_TEXT).filter(key=>text2[key]!==void 0).map(key=>[key,text2[key]])),...preset5?{preset:preset5}:{}})}function resolvedKeys(instrument,keys){let out={};for(let[key,spec]of Object.entries(KEYS_PARAMS))out[key]=spec.default;isPianoFamily(instrument)&&Object.assign(out,PIANO_FAMILY_DEFAULTS[instrument]),isElectricFamily(instrument)&&Object.assign(out,ELECTRIC_FAMILY_DEFAULTS[instrument]),isOrganFamily(instrument)&&Object.assign(out,ORGAN_FAMILY_DEFAULTS[instrument]);let preset5=keys?.preset?KEYS_PRESETS[keys.preset]:void 0;preset5&&Object.assign(out,preset5.keys);for(let[key,value]of Object.entries(keys??{}))key!=="preset"&&(out[key]=value);return out}var KEYS_ALIASES=Object.freeze({rhodes:"epiano",wurlitzer:"wurli",clavinet:"clav"});var SEMITONES2=Object.freeze({c:0,d:2,e:4,f:5,g:7,a:9,b:11}),NAMES=Object.freeze(["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"]);function pitchToMidi(value){if(typeof value!="string")return Number.NaN;let match=value.trim().match(/^([a-gA-G])([#b]?)(-?\d{1,2})$/);if(!match)return Number.NaN;let accidental=match[2]==="#"?1:match[2]==="b"?-1:0,midi2=(Number(match[3])+1)*12+(SEMITONES2[match[1].toLowerCase()]??0)+accidental;return midi2>=0&&midi2<=127?midi2:Number.NaN}var GRANULAR_INSTRUMENT2="granular";function isGranularInstrument(instrument){return instrument===GRANULAR_INSTRUMENT2}var GRAIN_WINDOWS=Object.freeze(["hann","tukey","gauss","tri","perc","rperc"]),SYNTH_SOURCE_PREFIX="synth:",DEFAULT_GRANULAR_SOURCE="synth:pad",GRANULAR_SOURCE_VOICE="granular:src",SYNTH_SOURCE_NOTE=60,SYNTH_SOURCE_SECONDS=4,n=(min,max,value,step2,doc,extra={})=>Object.freeze({kind:"number",min,max,default:value,step:step2,doc,...extra}),GRAIN_SYNC_VALUES=Object.freeze(["off","1/64","1/32","1/16t","1/16","1/16d","1/8t","1/8","1/8d","1/4t","1/4","1/4d","1/2","1/1"]),GRAIN_QUANT_VALUES=Object.freeze(["off","scale","chord"]),GRANULAR_PARAMS=Object.freeze({seed:n(0,2147483647,0,1,"texture variation; same seed, same grains",{integer:!0}),root:n(0,127,60,1,"the note that plays the source at its own pitch",{integer:!0}),begin:n(0,1,0,.01,"start of the region the head reads, 0..1 of the file"),end:n(0,1,1,.01,"end of the region the head reads, 0..1 of the file"),pos:n(0,1,0,.01,"where the head starts inside the region",{automate:!0}),scan:n(-4,4,1,.05,"head speed: 1 the source's own speed, 0 held, negative backwards",{unit:"x",automate:!0}),grain:n(.005,2,.08,"log","grain length",{unit:"s",automate:!0}),overlap:n(.05,32,4,.5,"grains sounding at once (density = overlap / grain)",{automate:!0}),jitter:n(0,1,.25,.05,"onset randomness, fraction of the grain period",{automate:!0}),spray:n(0,2,.01,.01,"random offset of each grain's read position",{unit:"s",automate:!0}),pitch:n(-48,48,0,1,"semitones on top of the note",{unit:"st",automate:!0}),detune:n(0,24,0,.05,"random per-grain pitch spread (\xB1 half)",{unit:"st",automate:!0}),shimmer:n(0,1,0,.05,"chance a grain plays shimint semitones up",{automate:!0}),shimint:n(-24,24,12,1,"the shimmer interval",{unit:"st"}),spread:n(0,1,.3,.05,"stereo spread of the grains",{automate:!0}),window:Object.freeze({kind:"enum",values:GRAIN_WINDOWS,default:"hann",doc:"grain envelope: hann tukey gauss tri perc rperc"}),reverse:n(0,1,0,.05,"chance a grain plays backwards",{automate:!0}),freeze:Object.freeze({kind:"boolean",default:!1,doc:"hold the read head (the cloud stops moving)"}),repeat:n(0,1,0,.05,"chance a grain step latches the head (beat repeat)",{automate:!0}),hold:n(1,16,1,1,"grain steps a latch lasts",{integer:!0}),drift:n(0,1,0,.05,"slow random walk of the head (depth)",{automate:!0}),drate:n(.01,10,.2,"log","drift rate",{unit:"Hz"}),attack:n(0,10,.01,"log","voice fade in",{unit:"s"}),release:n(0,20,.3,"log","voice fade out after the note ends",{unit:"s"}),veltone:n(0,1,0,.05,"soft notes are darker"),gain:n(0,4,1,.05,"voice level"),sync:Object.freeze({kind:"enum",values:GRAIN_SYNC_VALUES,default:"off",doc:"grain rate as a note value on the tempo map (off: grain/overlap)"}),quant:Object.freeze({kind:"enum",values:GRAIN_QUANT_VALUES,default:"off",doc:"snap grain pitches to the song scale or the sounding chord"}),mono:Object.freeze({kind:"boolean",default:!1,doc:"one voice: legato notes retarget its pitch, the cloud keeps going"}),pedal:Object.freeze({kind:"boolean",default:!1,doc:"the sustain pedal freezes the head while it is down"})}),GRANULAR_LANE_PARAMS=Object.freeze(Object.entries(GRANULAR_PARAMS).filter(entry=>entry[1].kind==="number"&&entry[1].automate===!0).map(([param2,spec])=>Object.freeze({param:param2,spec}))),GRAIN_SYNC_BEATS=Object.freeze({"1/64":1/16,"1/32":1/8,"1/16t":1/6,"1/16":1/4,"1/16d":3/8,"1/8t":1/3,"1/8":1/2,"1/8d":3/4,"1/4t":2/3,"1/4":1,"1/4d":3/2,"1/2":2,"1/1":4}),GRANULAR_PRESETS=Object.freeze({cloud:{doc:"slow-scanning soft cloud, wide",params:{grain:.12,overlap:6,jitter:.5,spray:.06,scan:.25,spread:.6,window:"hann",attack:.4,release:1.2}},hold:{doc:"held, shimmering sustain of one moment",params:{grain:.2,overlap:8,jitter:.6,spray:.03,freeze:!0,spread:.7,window:"gauss",attack:.6,release:2}},sparkle:{doc:"octave-and-fifth sparkle over a slow scan (best on a resample)",params:{grain:.15,overlap:8,jitter:.5,spray:.05,scan:.2,shimmer:.35,shimint:19,spread:.8,attack:.5,release:2.5}},swarm:{doc:"dense, detuned, fully wide",params:{grain:.09,overlap:14,jitter:.8,spray:.08,detune:.35,spread:1,scan:.5,attack:.2,release:.8}},stutter:{doc:"dry 45 ms repeats that latch and follow the music",params:{grain:.045,overlap:1,jitter:0,spray:0,scan:1,repeat:.5,hold:4,window:"perc",reverse:.25,spread:.2,attack:.002,release:.08}},microloop:{doc:"tight looping grains that slowly advance (best on a resample)",params:{grain:.06,overlap:2,jitter:0,spray:0,scan:.5,window:"tukey",spread:.1,attack:.005,release:.15}},backwards:{doc:"backwards swells (best on a resample)",params:{grain:.25,overlap:4,jitter:.3,spray:.02,reverse:1,window:"rperc",spread:.5,attack:.05,release:.6}},dust:{doc:"sparse random crackles across the source",params:{grain:.02,overlap:.4,jitter:1,spray:.4,detune:.2,spread:1,window:"perc",attack:.01,release:.5}}}),GRANULAR_PRESET_NAMES=Object.freeze(Object.keys(GRANULAR_PRESETS));function isGranularPreset(name){return Object.prototype.hasOwnProperty.call(GRANULAR_PRESETS,name)}function synthSourceNames(){return[...Object.keys(SYNTH_PRESETS),...SYNTH_SOUNDS]}function parseSynthSource(src){if(!src.startsWith(SYNTH_SOURCE_PREFIX))return;let match=/^([a-z][a-z0-9_]{0,31})(?:@(\d{1,3}|[a-gA-G][#b]?-?\d))?$/.exec(src.slice(SYNTH_SOURCE_PREFIX.length));if(!match)return;let name=match[1],at3=match[2],note2=at3===void 0?SYNTH_SOURCE_NOTE:/^\d+$/.test(at3)?Number(at3):pitchToMidi(at3);if(!(!(note2<=127)||!synthSourceNames().includes(name)))return{name,note:note2}}function normalizeGranular(input,normalizeRef){if(input==null)return;if(!isRecord2(input))throw new FxValidationError("track granular must be an object or null");let out={};if(input.src!==void 0)if(typeof input.src=="string"){if(!parseSynthSource(input.src))throw new FxValidationError(`granular src "${input.src.slice(0,40)}" must be synth:<preset>[@note] (${Object.keys(SYNTH_PRESETS).join(" ")}) or a sample`);out.src=/@[a-gA-G]/.test(input.src)?`${SYNTH_SOURCE_PREFIX}${parseSynthSource(input.src).name}@${parseSynthSource(input.src).note}`:input.src}else out.src=normalizeRef(input.src);if(input.preset!==void 0){if(typeof input.preset!="string"||!isGranularPreset(input.preset))throw new FxValidationError(`granular preset must be one of ${GRANULAR_PRESET_NAMES.join(", ")}`);out.preset=input.preset}for(let[name,spec]of Object.entries(GRANULAR_PARAMS)){let value=input[name];value!==void 0&&(out[name]=normalizeParam(spec,value,`granular ${name}`))}if(input.from!==void 0){if(typeof input.from!="string"||!/^[a-z][a-z0-9_-]{0,31}$/.test(input.from)||isGranularInstrument(input.from))throw new FxValidationError("granular from must be the instrument name grain off returns to");out.from=input.from}for(let key of Object.keys(input))if(key!=="src"&&key!=="preset"&&key!=="from"&&!Object.prototype.hasOwnProperty.call(GRANULAR_PARAMS,key))throw new FxValidationError(`granular has no parameter "${key.slice(0,32)}"`);let begin=out.begin??0;if((out.end??1)<=begin)throw new FxValidationError("granular end must be greater than begin");return Object.freeze(out)}function resolveGranular(granular){let out={src:DEFAULT_GRANULAR_SOURCE};for(let[name,spec]of Object.entries(GRANULAR_PARAMS))out[name]=spec.default;if(granular?.preset&&Object.assign(out,GRANULAR_PRESETS[granular.preset].params),granular)for(let[key,value]of Object.entries(granular))key!=="preset"&&key!=="from"&&value!==void 0&&(out[key]=value);return Object.freeze(out)}var GRANULAR_TAIL_SECONDS_MAX=10;function granularTailSeconds(granular){let s=resolveGranular(granular);return Math.min(GRANULAR_TAIL_SECONDS_MAX,s.release+1.5*s.grain)}var FX_CHAIN=Object.freeze(["filter","djf","autofilter","formant","vowel","crush","distort","stomp","head","cab","eq","wobble","bloom","swell","tremolo","gate","compressor","pan","double","phaser","chorus","leslie","postgain","delay","reverb","orbit","duck"]),MAX_ORBIT=16,GATE_PATTERNS=Object.freeze({chop:"x",eighths:"x.",offbeat:"..x.",trance:"x.xx.xx.x.xx.xx.",dotted:"x..x..x.x..x..x.",gallop:"x.xx"}),GATE_PATTERN_NAMES=Object.keys(GATE_PATTERNS),LFO_SHAPES=["sine","tri","square","saw","ramp","random"],rate=(fallback,strudel)=>({kind:"number",min:.01,max:40,default:fallback,step:.1,unit:"Hz",automate:!0,doc:"LFO rate in Hz (used when sync is 0)",...strudel?{strudel}:{}}),sync=(fallback,strudel)=>({kind:"number",min:0,max:64,default:fallback,step:.25,unit:"beats",doc:"LFO period in beats (tempo-synced); 0 uses rate in Hz",...strudel?{strudel}:{}}),mix=(fallback,strudel)=>({kind:"number",min:0,max:1,default:fallback,step:.05,automate:!0,doc:"wet/dry balance 0..1",...strudel?{strudel}:{}}),VOWEL_VALUES=Object.freeze(["a","e","i","o","u","ae","aa","oe","ue","y","uh","un","en","an","on"]),FX_SPECS=Object.freeze({autofilter:{label:"auto filter",doc:"filter whose cutoff an LFO sweeps around a center, optionally opened by the input level",simple:["type","cutoff","depth","sync","shape"],strudel:"none built in (Strudel fakes it with lpf(sine.range(..)).seg(n)); names follow lpf/lpq",params:{type:{kind:"enum",values:["lpf","hpf","bpf"],default:"lpf",doc:"filter type",strudel:["ftype-like: lpf/hpf/bpf"]},cutoff:{kind:"number",min:20,max:2e4,default:1200,step:"log",unit:"Hz",automate:!0,doc:"center cutoff",strudel:["lpf","cutoff"]},resonance:{kind:"number",min:0,max:1,default:.3,step:.05,automate:!0,doc:"resonance 0..1 (Q 0.707..8)",strudel:["lpq","resonance"]},depth:{kind:"number",min:0,max:6,default:2,step:.25,unit:"oct",automate:!0,doc:"sweep width in octaves around the center"},sync:sync(4),rate:rate(.5),shape:{kind:"enum",values:LFO_SHAPES,default:"sine",doc:"LFO shape; random is sample-and-hold, one step per cycle"},phase:{kind:"number",min:0,max:1,default:0,step:.05,doc:"LFO start phase in cycles"},follow:{kind:"number",min:-6,max:6,default:0,step:.25,unit:"oct",automate:!0,doc:"envelope follower: octaves the cutoff moves at full input level",strudel:["lpenv (per note, see synth)"]}}},djf:{label:"dj filter",doc:"one-knob filter: below 0.5 low-pass, above 0.5 high-pass, 0.5 open",simple:["value"],strudel:"djf(0..1)",params:{value:{kind:"number",min:0,max:1,default:.5,step:.02,automate:!0,doc:"0 dark (20 Hz low-pass) \u2026 0.5 open \u2026 1 thin (10 kHz high-pass)",strudel:["djf"]}}},formant:{label:"formant",doc:"formant shift at constant pitch: moves the spectral envelope (throat or gender knob), any source",simple:["shift","mix"],strudel:"none (not a Strudel concept)",params:{shift:{kind:"number",min:-12,max:12,default:0,step:.5,unit:"st",automate:!0,doc:"semitones the formants move (negative deeper, positive smaller); pitch stays"},mix:mix(1)}},vowel:{label:"vowel",doc:"formant filter bank: five band-passes per vowel",simple:["vowel","mix"],strudel:"vowel(a|e|i|o|u)",params:{vowel:{kind:"enum",values:VOWEL_VALUES,default:"a",doc:"vowel formants (a e i o u plus the extended set)",strudel:["vowel"]},mix:mix(1),to:{kind:"enum",values:VOWEL_VALUES,default:"a",optional:!0,doc:"vowel to morph toward (absent: no morph)"},morph:{kind:"number",min:0,max:1,default:0,step:.05,optional:!0,automate:!0,doc:"position between vowel (0) and to (1), log-frequency formant morph"}}},crush:{label:"bitcrush",doc:"bit-depth and sample-rate reduction",simple:["bits","coarse","mix"],strudel:"crush(bits) coarse(factor)",params:{bits:{kind:"number",min:1,max:16,default:8,step:.5,automate:!0,doc:"bit depth: 1 heavy .. 16 nearly clean",strudel:["crush"]},coarse:{kind:"number",min:1,max:64,default:1,step:1,integer:!0,doc:"sample-and-hold factor: 1 off, 2 half rate, 3 a third\u2026",strudel:["coarse"]},mix:mix(1)}},distort:{label:"distortion",doc:"waveshaper with drive, post-tone and automatic gain compensation",simple:["drive","tone","mix"],strudel:'distort("amount:postgain:type"), shape(amount)',params:{drive:{kind:"number",min:0,max:10,default:2,step:.25,automate:!0,doc:"drive 0..10 (Strudel distort amount)",strudel:["distort","dist"]},type:{kind:"enum",values:["soft","hard","cubic","diode","asym","fold","sinefold","chebyshev","scurve","shape"],default:"soft",doc:"curve: soft (tanh), hard clip, cubic, diode, asym, fold, sinefold, chebyshev, scurve, shape (Strudel shape's curve)",strudel:["distort type (3rd field)","shape \u2192 type shape"]},tone:{kind:"number",min:200,max:2e4,default:8e3,step:"log",unit:"Hz",automate:!0,doc:"low-pass after the shaper; tames fizz"},mix:mix(1),postgain:{kind:"number",min:0,max:2,default:1,step:.05,doc:"linear gain after compensation (Strudel distort postgain)",strudel:["distort postgain"]}}},stomp:{label:"stomp box",doc:"guitar pedal before the amp: fuzz (Big Muff), face (Fuzz Face), od (Tube Screamer), rat, octave (Octavia); oversampled",simple:["type","gain","tone","level"],strudel:"(no Strudel equivalent; dawn guitar rig)",params:{type:{kind:"enum",values:["fuzz","face","od","rat","octave"],default:"od",doc:"circuit: fuzz (Big Muff), face (Fuzz Face), od (Tube Screamer), rat (RAT), octave (Octavia)"},gain:{kind:"number",min:0,max:10,default:5,step:.25,automate:!0,doc:"the pedal's gain / sustain / distortion knob, 0..10"},tone:{kind:"number",min:0,max:1,default:.5,step:.05,automate:!0,doc:"dark 0 .. bright 1"},level:{kind:"number",min:-24,max:12,default:0,step:.5,unit:"dB",doc:"trim over a level-matched pedal (0 = bypass loudness)"},octave:{kind:"number",min:0,max:1,default:.7,step:.05,doc:"octave: blend of the octave-up (rectified) path"},mix:mix(1)}},head:{label:"amp head",doc:"guitar amp: preamp stages, Yeh-Smith tone stack, power amp with sag, level-matched across types; optional noise gate",simple:["type","gain","bass","mid","treble"],strudel:"(no Strudel equivalent; Strudel amp is linear gain)",params:{type:{kind:"enum",values:["clean","chime","crunch","lead","high","solid","bass"],default:"crunch",doc:"clean (blackface), chime (AC30), crunch (plexi), lead (JCM800), high (modern high gain), solid (JC-120), bass (SVT)"},gain:{kind:"number",min:0,max:10,default:5,step:.25,automate:!0,doc:"preamp gain 0..10 (level-matched: more gain, not more volume)"},bass:{kind:"number",min:0,max:10,default:5,step:.5,doc:"tone stack bass 0..10"},mid:{kind:"number",min:0,max:10,default:5,step:.5,doc:"tone stack mid 0..10"},treble:{kind:"number",min:0,max:10,default:5,step:.5,doc:"tone stack treble 0..10"},presence:{kind:"number",min:0,max:10,default:5,step:.5,doc:"power amp presence 0..10 (5 flat)"},master:{kind:"number",min:0,max:10,default:5,step:.25,automate:!0,doc:"power amp drive 0..10"},sag:{kind:"number",min:0,max:1,default:.3,step:.05,optional:!0,doc:"power supply sag 0..1 (absent: the head type's own)"},gate:{kind:"number",min:-96,max:0,default:-60,step:1,unit:"dB",optional:!0,doc:"noise gate threshold before the amp (absent: no gate; 0 dB gates all)"},level:{kind:"number",min:-24,max:12,default:0,step:.5,unit:"dB",doc:"output level after level matching"}}},cab:{label:"speaker cabinet",doc:"speaker cabinet and microphone (biquad model, no impulse response)",simple:["type","mic","mix"],strudel:"(no Strudel equivalent; dawn guitar rig)",params:{type:{kind:"enum",values:["1x12","2x12","4x12","1x10","open","8x10","1x15","di"],default:"2x12",doc:"1x12, 2x12, 4x12, 1x10, open back, 8x10 and 1x15 bass, di (no speaker)"},mic:{kind:"number",min:0,max:1,default:.3,step:.05,doc:"microphone position: 0 center (bright) .. 1 edge (dark)"},mix:mix(1)}},eq:{label:"eq",doc:"three-band tone shaping after the drive and amp: a low shelf, a peaking mid and a high shelf for air",simple:["low","mid","high"],strudel:"none (Strudel has no shelf EQ)",params:{low:{kind:"number",min:-24,max:12,default:0,step:.5,unit:"dB",automate:!0,doc:"low shelf gain (cut mud or boom, or add weight)"},lowfreq:{kind:"number",min:20,max:1e3,default:150,step:10,unit:"Hz",doc:"low shelf corner"},mid:{kind:"number",min:-24,max:12,default:0,step:.5,unit:"dB",automate:!0,doc:"peaking mid gain, about an octave and a half wide"},midfreq:{kind:"number",min:100,max:1e4,default:1e3,step:50,unit:"Hz",automate:!0,doc:"peaking mid center"},high:{kind:"number",min:-24,max:12,default:0,step:.5,unit:"dB",automate:!0,doc:"high shelf gain (air above the corner, or darken)"},highfreq:{kind:"number",min:1e3,max:2e4,default:8e3,step:100,unit:"Hz",doc:"high shelf corner"}}},wobble:{label:"wobble",doc:"held tremolo arm: slow seeded pitch wow and flutter of the whole track",simple:["depth","rate","drift"],strudel:"(no Strudel equivalent; dawn shoegaze)",params:{depth:{kind:"number",min:0,max:100,default:20,step:1,unit:"c",automate:!0,doc:"peak pitch deviation in cents"},rate:{kind:"number",min:.05,max:8,default:.5,step:.05,unit:"Hz",doc:"wobble rate"},drift:{kind:"number",min:0,max:1,default:.3,step:.05,doc:"0 periodic .. 1 wandering (seeded, so every render matches)"}}},bloom:{label:"bloom",doc:"feedback bloom: the top held note grows a singing harmonic",simple:["amount","harm","delay"],strudel:"(no Strudel equivalent; dawn shoegaze)",params:{amount:{kind:"number",min:0,max:1,default:.5,step:.05,doc:"level of the feedback partial"},harm:{kind:"number",min:1,max:4,default:2,step:1,doc:"harmonic that feeds back: 1 the note, 2 its octave, 3 the fifth above"},delay:{kind:"number",min:0,max:4,default:.6,step:.05,unit:"s",doc:"how long a note is held before it starts to feed back"},time:{kind:"number",min:.05,max:4,default:1,step:.05,unit:"s",doc:"how fast the feedback grows"}}},swell:{label:"swell",doc:"volume swell: each strum fades in, no pick attack",simple:["time","mix"],strudel:"(no Strudel equivalent; dawn shoegaze)",params:{time:{kind:"number",min:.01,max:4,default:.4,step:.01,unit:"s",doc:"rise time after each onset"},mix:mix(1)}},double:{label:"double",doc:"automatic double tracking: a seeded second take, spread left and right",simple:["time","drift","width"],strudel:"(no Strudel equivalent; dawn shoegaze)",params:{time:{kind:"number",min:5,max:60,default:22,step:1,unit:"ms",doc:"how late the second take plays"},drift:{kind:"number",min:0,max:10,default:3,step:.5,unit:"ms",doc:"how far the second take's timing wanders"},width:{kind:"number",min:0,max:1,default:.6,step:.05,doc:"0 centered .. 1 the two takes hard left and right"}}},tremolo:{label:"tremolo",doc:"volume modulation",simple:["sync","depth","shape"],strudel:"tremolosync/tremolodepth/tremoloshape/tremoloskew/tremolophase (am)",params:{sync:sync(.5,["tremolosync","tremsync"]),rate:rate(4,["tremolo"]),depth:{kind:"number",min:0,max:1,default:.5,step:.05,automate:!0,doc:"how far the level dips, 0..1",strudel:["tremolodepth","tremdepth"]},shape:{kind:"enum",values:LFO_SHAPES.filter(shape=>shape!=="random"),default:"sine",doc:"LFO shape",strudel:["tremoloshape","tremshape"]},skew:{kind:"number",min:0,max:1,default:.5,step:.05,doc:"where in the cycle the peak falls (0.5 symmetric)",strudel:["tremoloskew","tremskew"]},phase:{kind:"number",min:0,max:1,default:0,step:.05,doc:"start phase in cycles",strudel:["tremolophase","tremphase"]}}},gate:{label:"gate",doc:"tempo-synced step gate: chops a held sound to a rhythm on the song grid",simple:["pattern","step","length","depth"],strudel:"(no single Strudel equivalent; struct + clip on held notes)",params:{pattern:{kind:"enum",values:GATE_PATTERN_NAMES,default:"chop",doc:"rhythm of open (x) and shut (.) steps: chop x, eighths x., offbeat ..x., trance x.xx.xx.x.xx.xx., dotted x..x..x.x..x..x., gallop x.xx"},step:{kind:"number",min:.0625,max:4,default:.25,step:.0625,unit:"beats",doc:"length of one pattern step in beats (0.25 a 16th)"},length:{kind:"number",min:.05,max:1,default:.75,step:.05,doc:"fraction of an open step that sounds; 1 merges neighbouring open steps"},depth:{kind:"number",min:0,max:1,default:1,step:.05,automate:!0,doc:"how far shut steps dip: 1 to silence, 0 not at all"},attack:{kind:"number",min:5e-4,max:.1,default:.002,step:5e-4,unit:"s",doc:"fade-in when a step opens"},release:{kind:"number",min:5e-4,max:.2,default:.01,step:5e-4,unit:"s",doc:"fade-out when a step shuts"}}},compressor:{label:"compressor",doc:"feed-forward RMS-ish compressor with soft knee and make-up gain",simple:["threshold","ratio","makeup"],strudel:'compressor("threshold:ratio:knee:attack:release")',params:{threshold:{kind:"number",min:-60,max:0,default:-18,step:1,unit:"dB",automate:!0,doc:"level where compression starts",strudel:["compressor threshold"]},ratio:{kind:"number",min:1,max:20,default:4,step:.5,doc:"input:output above threshold",strudel:["compressorRatio"]},knee:{kind:"number",min:0,max:24,default:6,step:1,unit:"dB",doc:"soft-knee width",strudel:["compressorKnee"]},attack:{kind:"number",min:1e-4,max:1,default:.01,step:.005,unit:"s",doc:"attack time",strudel:["compressorAttack"]},release:{kind:"number",min:.01,max:2,default:.15,step:.05,unit:"s",doc:"release time",strudel:["compressorRelease"]},makeup:{kind:"number",min:0,max:24,default:5,step:.5,unit:"dB",automate:!0,doc:"gain after compression"}}},phaser:{label:"phaser",doc:"four-stage all-pass phaser",simple:["rate","depth"],strudel:"phaser/phaserdepth/phasercenter/phasersweep",params:{rate:rate(.5,["phaser","ph"]),sync:sync(0),depth:{kind:"number",min:0,max:1,default:.75,step:.05,automate:!0,doc:"notch depth (wet amount)",strudel:["phaserdepth","phd","phasdp"]},center:{kind:"number",min:100,max:1e4,default:1e3,step:"log",unit:"Hz",doc:"sweep center",strudel:["phasercenter","phc"]},sweep:{kind:"number",min:0,max:8e3,default:2e3,step:100,unit:"Hz",doc:"sweep range",strudel:["phasersweep","phs"]}}},chorus:{label:"chorus",doc:"stereo chorus: two modulated delay taps in quadrature",simple:["rate","depth","mix"],strudel:"none in superdough (SuperDirt has no chorus either); standard parameters",params:{rate:rate(.8),depth:{kind:"number",min:0,max:1,default:.4,step:.05,automate:!0,doc:"modulation depth (0..1 \u2192 0..6 ms)"},mix:mix(.5)}},leslie:{label:"leslie",doc:"rotary speaker: Doppler vibrato plus left/right amplitude rotation",simple:["mix","rate"],strudel:"leslie(wet) lrate(Hz) lsize(0..1)",params:{mix:mix(1,["leslie"]),rate:{...rate(6.7,["lrate"]),doc:"rotation in Hz: 6.7 fast, 0.7 slow"},size:{kind:"number",min:0,max:1,default:.5,step:.05,doc:"cabinet size: Doppler (pitch warble) amount",strudel:["lsize"]}}},postgain:{label:"post gain",doc:"linear gain after every insert, before the delay and reverb sends",simple:["gain"],strudel:"postgain(gain)",params:{gain:{kind:"number",min:0,max:4,default:1,step:.05,automate:!0,doc:"linear gain 0..4",strudel:["postgain","post"]}}},orbit:{label:"orbit",doc:"the bus this track plays on (1 when off); another track's duck targets it",simple:["orbit"],strudel:"orbit(n)",params:{orbit:{kind:"number",min:1,max:MAX_ORBIT,default:2,step:1,integer:!0,doc:"orbit number; tracks without this effect are on orbit 1",strudel:["orbit","o"]},shared:{kind:"boolean",default:!1,optional:!0,doc:"share one delay and one reverb with the orbit's other shared tracks, as Strudel orbits do (this track's delay/reverb mix becomes its send level)"}}},duck:{label:"duck",doc:"sidechain ducking: each note of this track dips the target orbit, then it recovers",simple:["orbit","depth","attack"],strudel:"duckorbit(n) duckdepth(0..1) duckattack(s)",params:{orbit:{kind:"number",min:1,max:MAX_ORBIT,default:1,step:1,integer:!0,doc:"target orbit to duck (never this track itself)",strudel:["duckorbit","duck"]},depth:{kind:"number",min:0,max:1,default:1,step:.05,doc:"how far the target dips: 1 to silence, 0 not at all",strudel:["duckdepth"]},attack:{kind:"number",min:.001,max:4,default:.1,step:.01,unit:"s",doc:"time the target takes to come back to full level",strudel:["duckattack","duckatt","datt"]},onset:{kind:"number",min:0,max:.5,default:.003,step:.001,unit:"s",doc:"time the dip takes to reach full depth",strudel:["duckonset"]},hold:{kind:"boolean",default:!1,optional:!0,doc:"the dip holds while each note sounds, then recovers (a vocal sidechain); off dips only at onsets"},curve:{kind:"enum",values:["linear","exp","pump"],default:"linear",optional:!0,doc:"recovery shape: linear; exp snaps back early and eases in (a compressor); pump stays down, then swells back (a hypertechno pump)",strudel:["duckcurve"]},sync:{kind:"number",min:0,max:4,default:0,step:.0625,unit:"beats",optional:!0,doc:"recovery length in beats (tempo-synced); 0 uses attack in seconds",strudel:["ducksync"]}}}}),TRACK_EFFECT_SPECS=Object.freeze({filter:{label:"filter",doc:"resonant biquad: low-pass, high-pass or band-pass",simple:["type","cutoff","resonance"],strudel:"lpf/hpf/bpf (cutoff, hcutoff, bandf) with lpq/hpq/bpq and ftype",params:{type:{kind:"enum",values:["lpf","hpf","bpf"],default:"lpf",optional:!0,doc:"lpf low-pass (default), hpf high-pass, bpf band-pass",strudel:["lpf","hpf","bpf"]},ftype:{kind:"enum",values:["12db","24db","ladder"],default:"12db",optional:!0,doc:"slope: 12db biquad (default), 24db two biquads, ladder 4-pole (low-pass only)",strudel:["ftype"]},cutoff:{kind:"number",min:20,max:2e4,default:2e3,step:"log",unit:"Hz",automate:!0,doc:"cutoff (lpf/hpf) or center (bpf) frequency",strudel:["lpf","cutoff","ctf","lp","hpf","hcutoff","bpf","bandf"]},resonance:{kind:"number",min:0,max:1,default:0,step:.05,automate:!0,doc:"resonance 0..1 (Q 0.707..8)",strudel:["lpq","resonance","hpq","hresonance","bpq","bandq"]}}},delay:{label:"delay",doc:"tempo-synced stereo delay send; ping-pong with a high-cut on the repeats by default",simple:["beats","feedback","mix"],strudel:'delay("level:time:feedback"), delaytime, delayfeedback',params:spaceEffectParameters.delay},reverb:{label:"reverb",doc:"algorithmic stereo reverb send (eight combs, four allpasses per side)",simple:["mix","size"],strudel:'room("level:size"), roomsize, roomfade, roomlp, roomdim',params:spaceEffectParameters.reverb}}),TRACK_EFFECT_NAMES=Object.freeze(Object.keys(TRACK_EFFECT_SPECS)),EFFECT_NAMES=Object.freeze(FX_CHAIN.filter(stage=>stage!=="pan")),CORE_EFFECTS=Object.freeze(["filter","autofilter","distort","tremolo","compressor","chorus","delay","reverb"]),SHOEGAZE_EFFECTS=Object.freeze(["wobble","bloom","swell","double"]);function effectSpec(name){return name in TRACK_EFFECT_SPECS?TRACK_EFFECT_SPECS[name]:FX_SPECS[name]}var TRACK_EFFECT_LANES=Object.freeze({"filter-cutoff":"filter","filter-resonance":"resonance","delay-feedback":"delay-feedback","delay-mix":"delay-mix"}),FX_NAMES=Object.freeze(FX_CHAIN.filter(stage=>Object.prototype.hasOwnProperty.call(FX_SPECS,stage)));function isFxName(value){return typeof value=="string"&&Object.prototype.hasOwnProperty.call(FX_SPECS,value)}function fxSpec(name){return FX_SPECS[name]}function normalizeFx(input){if(input==null)return;if(!isRecord2(input))throw new FxValidationError("track fx must be an object or null");let out={};for(let[name,value]of Object.entries(input)){if(!isFxName(name))throw new FxValidationError(`unknown effect "${name}" (effects: ${FX_NAMES.join(", ")})`);value!=null&&(out[name]=normalizeParams(fxSpec(name).params,value,`fx ${name}`))}let ordered={};for(let name of FX_NAMES)out[name]&&(ordered[name]=out[name]);return Object.keys(ordered).length>0?Object.freeze(ordered):void 0}var FX_LANES=Object.freeze([...[...FX_NAMES,"reverb"].flatMap(effect=>Object.entries(effectSpec(effect).params).filter(entry=>entry[1].kind==="number"&&entry[1].automate===!0).map(([param2,spec])=>Object.freeze({lane:`${effect}-${param2}`,effect,param:param2,spec}))),...SYNTH_LANE_PARAMS.map(({param:param2,spec})=>Object.freeze({lane:`synth-${param2}`,effect:"synth",param:param2,spec})),...STRING_LANE_PARAMS.map(({param:param2,spec})=>Object.freeze({lane:`string-${param2}`,effect:"string",param:param2,spec})),...KEYS_LANE_PARAMS.map(({param:param2,spec})=>Object.freeze({lane:`keys-${param2}`,effect:"keys",param:param2,spec})),...MODAL_LANE_PARAMS.map(({param:param2,spec})=>Object.freeze({lane:`modal-${param2}`,effect:"modal",param:param2,spec})),...TEXTURE_LANE_PARAMS.map(({param:param2,spec})=>Object.freeze({lane:`texture-${param2}`,effect:"texture",param:param2,spec})),...GRANULAR_LANE_PARAMS.map(({param:param2,spec})=>Object.freeze({lane:`grain-${param2}`,effect:"grain",param:param2,spec})),...WIND_LANE_PARAMS.map(({param:param2,spec})=>Object.freeze({lane:`wind-${param2}`,effect:"wind",param:param2,spec})),...SING_LANE_PARAMS.map(({param:param2,spec})=>Object.freeze({lane:`sing-${param2}`,effect:"sing",param:param2,spec})),...VOCODER_LANE_PARAMS.map(({param:param2,spec})=>Object.freeze({lane:`vocoder-${param2}`,effect:"vocoder",param:param2,spec}))]),FX_PRESETS=Object.freeze({filter:{warm:{type:"lpf",cutoff:1800,resonance:.1},dark:{type:"lpf",cutoff:600,resonance:.2},acid:{type:"lpf",ftype:"ladder",cutoff:900,resonance:.7},thin:{type:"hpf",cutoff:400,resonance:.1},telephone:{type:"bpf",cutoff:1500,resonance:.5}},djf:{dark:{value:.3},thin:{value:.7}},autofilter:{"slow-sweep":{sync:8,depth:2.5,shape:"sine",cutoff:1e3},wobble:{sync:.5,depth:2,shape:"sine",cutoff:600,resonance:.5},"s&h":{sync:.25,depth:2,shape:"random",cutoff:1500,resonance:.4},"hpf-rise":{type:"hpf",sync:16,depth:3,shape:"saw",cutoff:400},"env-follow":{sync:0,rate:.01,depth:0,follow:3,cutoff:400,resonance:.4},wah:{type:"bpf",sync:.5,depth:2,shape:"sine",cutoff:700,resonance:.6}},formant:{deep:{shift:-4},giant:{shift:-8},bright:{shift:3},tiny:{shift:7}},vowel:{a:{vowel:"a"},o:{vowel:"o"},ee:{vowel:"i"}},crush:{"8-bit":{bits:8,coarse:1},lofi:{bits:6,coarse:4,mix:.7},destroy:{bits:3,coarse:8}},distort:{warm:{drive:1.5,type:"soft",tone:6e3,mix:1},crunch:{drive:4,type:"cubic",tone:5e3},fuzz:{drive:7,type:"hard",tone:3500},fold:{drive:5,type:"fold",tone:7e3,mix:.7},shape:{drive:5,type:"shape",tone:9e3}},stomp:{muff:{type:"fuzz",gain:7,tone:.5},face:{type:"face",gain:6,tone:.5},screamer:{type:"od",gain:5,tone:.5,level:3},rat:{type:"rat",gain:6,tone:.4},octavia:{type:"octave",gain:6,tone:.6,octave:.8},boost:{type:"od",gain:0,tone:.6,level:6}},head:{blackface:{type:"clean",gain:3,treble:6},ac:{type:"chime",gain:4,treble:6},plexi:{type:"crunch",gain:5},lead:{type:"lead",gain:6,mid:6},modern:{type:"high",gain:7,bass:6,mid:3,treble:7,gate:-55},jc:{type:"solid",gain:2,treble:6},svt:{type:"bass",gain:4,bass:6}},cab:{"1x12":{type:"1x12"},"2x12":{type:"2x12"},"4x12":{type:"4x12"},open:{type:"open"},"8x10":{type:"8x10"},"1x15":{type:"1x15"},di:{type:"di"}},wobble:{glide:{depth:35,rate:.4,drift:.4},tape:{depth:12,rate:.8,drift:.6},seasick:{depth:60,rate:.25,drift:.2}},bloom:{octave:{amount:.5,harm:2,delay:.6,time:1},fifth:{amount:.4,harm:3,delay:.8,time:1.2},ebow:{amount:.8,harm:1,delay:.1,time:.6}},swell:{slow:{time:.8},violin:{time:.3}},double:{tight:{time:12,drift:1.5,width:.5},wide:{time:28,drift:3,width:.7}},tremolo:{gentle:{sync:1,depth:.3,shape:"sine"},"eighth-chop":{sync:.5,depth:.9,shape:"square"},pulse:{sync:.25,depth:.6,shape:"tri"}},compressor:{gentle:{threshold:-18,ratio:2,attack:.02,release:.2,makeup:3},punch:{threshold:-20,ratio:4,attack:.03,release:.1,makeup:6},squash:{threshold:-30,ratio:10,attack:.002,release:.08,makeup:12}},phaser:{slow:{rate:.2,depth:.7},fast:{rate:2,depth:.8}},chorus:{subtle:{rate:.6,depth:.25,mix:.35},wide:{rate:.8,depth:.5,mix:.5},seasick:{rate:3,depth:.9,mix:.6}},leslie:{fast:{rate:6.7,mix:1},slow:{rate:.7,mix:1}},delay:{"ping-pong":{beats:.75,feedback:.35,mix:.25,pingpong:!0,highcut:5e3},"dotted-eighth":{beats:.75,feedback:.4,mix:.3,pingpong:!1,highcut:6e3},slapback:{beats:.25,feedback:.1,mix:.25,pingpong:!1,highcut:8e3},dub:{beats:1.5,feedback:.6,mix:.35,pingpong:!0,highcut:2500}},reverb:{room:{mix:.2,size:.3,predelay:.01,dim:6e3},hall:{mix:.3,size:.8,fade:3.5,predelay:.03,dim:4e3},plate:{mix:.25,size:.6,fade:2,predelay:0,dim:9e3},ambient:{mix:.5,size:1,fade:8,predelay:.05,lowpass:5e3,dim:2500}},duck:{pump:{orbit:2,depth:.85,attack:.25},subtle:{orbit:2,depth:.4,attack:.12},gate:{orbit:2,depth:1,attack:.05},rave:{orbit:2,depth:.9,curve:"pump",sync:.375}}}),RIG_STAGES=Object.freeze(["stomp","head","cab"]),RIG_PRESETS2=Object.freeze({clean:{head:{type:"clean",gain:3,treble:6},cab:{type:"1x12"}},crunch:{head:{type:"crunch",gain:5},cab:{type:"4x12"}},punk:{head:{type:"crunch",gain:7,mid:6,master:6},cab:{type:"4x12",mic:.2}},ragged:{stomp:{type:"face",gain:6,tone:.6},head:{type:"chime",gain:4},cab:{type:"2x12"}},lead:{stomp:{type:"od",gain:3,tone:.5,level:3},head:{type:"lead",gain:6,mid:6},cab:{type:"4x12"}},metal:{stomp:{type:"od",gain:0,tone:.6,level:6},head:{type:"high",gain:7,bass:6,mid:3,treble:7,gate:-55},cab:{type:"4x12",mic:.2}},fuzz:{stomp:{type:"fuzz",gain:7,tone:.5},head:{type:"clean",gain:4},cab:{type:"2x12"}},octave:{stomp:{type:"octave",gain:6,tone:.6,octave:.8},head:{type:"clean",gain:3},cab:{type:"1x12"}},funk:{head:{type:"clean",gain:2,treble:7,presence:6},cab:{type:"2x12"},autofilter:{type:"bpf",sync:0,rate:.01,depth:0,follow:3,cutoff:500,resonance:.6}},wah:{head:{type:"crunch",gain:4},cab:{type:"2x12"},autofilter:{type:"bpf",sync:.5,depth:2,shape:"sine",cutoff:700,resonance:.6}},bachata:{head:{type:"clean",gain:2,mid:6,treble:7},cab:{type:"1x12",mic:.2},chorus:{rate:.8,depth:.25,mix:.3}},spring:{head:{type:"clean",gain:3,treble:6},cab:{type:"open"},reverb:{mix:.3,size:.35,fade:1.5,predelay:0,dim:3500}},bassdrive:{stomp:{type:"od",gain:4,tone:.5,mix:.6},head:{type:"bass",gain:4},cab:{type:"8x10"}},reese:{stomp:{type:"rat",gain:3,tone:.3,mix:.5},head:{type:"bass",gain:6,master:6},cab:{type:"1x15"}},jangle:{head:{type:"chime",gain:3,treble:7},cab:{type:"2x12",mic:.2},compressor:{threshold:-20,ratio:4,attack:.01,release:.15},double:{time:12,drift:1.5,width:.5}},alt:{stomp:{type:"rat",gain:6,tone:.4},head:{type:"crunch",gain:4},cab:{type:"4x12"}},shoegaze:{stomp:{type:"fuzz",gain:7,tone:.45},head:{type:"chime",gain:4},cab:{type:"2x12"},wobble:{depth:25,rate:.4,drift:.4},bloom:{amount:.4,harm:2,delay:.6,time:1},double:{time:18,drift:2.5,width:.4},postgain:{gain:.86},reverb:{mix:.35,size:.9,fade:4,predelay:.02,dim:6e3}},glide:{stomp:{type:"face",gain:5,tone:.5},head:{type:"clean",gain:4,treble:5},cab:{type:"2x12"},wobble:{depth:35,rate:.4,drift:.4},postgain:{gain:.8},reverb:{mix:.35,size:.7,fade:2.5,predelay:.01,dim:6e3}},dreampop:{head:{type:"clean",gain:2,treble:6},cab:{type:"1x12"},chorus:{rate:.6,depth:.3,mix:.35},double:{time:14,drift:2,width:.4},postgain:{gain:1.45},reverb:{mix:.4,size:.85,fade:5,predelay:.03,dim:7e3}},swell:{head:{type:"clean",gain:3,treble:5},cab:{type:"1x12"},swell:{time:.5},postgain:{gain:1.25},reverb:{mix:.45,size:.8,fade:4,predelay:.02,dim:6500}},ebow:{stomp:{type:"od",gain:3,tone:.5,level:3},head:{type:"lead",gain:5,mid:6},cab:{type:"4x12"},swell:{time:.25},bloom:{amount:.8,harm:1,delay:.1,time:.6}}}),RIG_ADDED=Object.freeze({jangle:Object.freeze(["double"])});var EXTENSIONS2=["6","m7","M7","9"];var QUALITY_INTERVALS2=Object.freeze({maj:[0,4,7],min:[0,3,7],dim:[0,3,6],sus4:[0,5,7],aug:[0,4,8],sus2:[0,2,7],5:[0,7],madd4:[0,3,5,7],mb6:[0,3,7,8],b6:[0,4,7,8],"7#9":[0,4,7,10,15],b5:[0,4,6]}),SECRET_EXTENSION2=Object.freeze({mb6:"6",b6:"6","7#9":"m7"}),EXTENSION_INTERVAL2=Object.freeze({6:9,m7:10,M7:11,9:14}),COMBINED_TYPES2=Object.freeze({"dim+sus":"5","maj+sus":"aug","min+sus":"madd4","dim+min":"mb6","dim+maj":"b6","maj+min":"7#9"});function makeChord2(root,quality,extensions=[],bass,tensions=[]){let held=new Set(extensions),own=SECRET_EXTENSION2[quality],ext=EXTENSIONS2.filter(value=>held.has(value)&&value!==own),pc=mod122(root),slash=bass===void 0?void 0:mod122(bass);return Object.freeze({root:pc,quality,extensions:Object.freeze(ext),...slash!==void 0&&slash!==pc?{bass:slash}:{},...tensions.length>0?{tensions:Object.freeze([...new Set(tensions)].sort((a,b)=>a-b))}:{}})}function chordIntervals2(chord2){let set=new Set(QUALITY_INTERVALS2[chord2.quality]);for(let ext of chord2.extensions)set.add(EXTENSION_INTERVAL2[ext]);for(let step2 of chord2.tensions??[])set.add(step2);return[...set].sort((a,b)=>a-b)}function chordPitchClasses(chord2){return chordIntervals2(chord2).map(step2=>mod122(chord2.root+step2))}var SECRET_SUFFIX2=Object.freeze({madd4:"m(add4)",mb6:"m(b6)",b6:"(b6)","7#9":"7#9"});var SUFFIXES2=[["","maj",[]],["maj","maj",[]],["M","maj",[]],["m","min",[]],["min","min",[]],["-","min",[]],["dim","dim",[]],["\xB0","dim",[]],["o","dim",[]],["aug","aug",[]],["+","aug",[]],["sus","sus4",[]],["sus4","sus4",[]],["sus2","sus2",[]],["5","5",[]],["6","maj",["6"]],["m6","min",["6"]],["6/9","maj",["6","9"]],["69","maj",["6","9"]],["m6/9","min",["6","9"]],["m69","min",["6","9"]],["7","maj",["m7"]],["dom7","maj",["m7"]],["maj7","maj",["M7"]],["M7","maj",["M7"]],["\u0394","maj",["M7"]],["\u03947","maj",["M7"]],["m7","min",["m7"]],["min7","min",["m7"]],["-7","min",["m7"]],["m(maj7)","min",["M7"]],["mM7","min",["M7"]],["m7b5","dim",["m7"]],["\xF8","dim",["m7"]],["\xF87","dim",["m7"]],["dim7","dim",["6"]],["\xB07","dim",["6"]],["o7","dim",["6"]],["aug7","aug",["m7"]],["+7","aug",["m7"]],["9","maj",["m7","9"]],["maj9","maj",["M7","9"]],["M9","maj",["M7","9"]],["m9","min",["m7","9"]],["add9","maj",["9"]],["madd9","min",["9"]],["m(add9)","min",["9"]],["7sus4","sus4",["m7"]],["7sus","sus4",["m7"]],["9sus4","sus4",["m7","9"]],["7sus2","sus2",["m7"]],["maj7sus4","sus4",["M7"]],["m(add4)","madd4",[]],["madd4","madd4",[]],["m(b6)","mb6",[]],["mb6","mb6",[]],["(b6)","b6",[]],["addb6","b6",[]],["7#9","7#9",[]],["-maj7","min",["M7"]],["mmaj7","min",["M7"]],["mMaj7","min",["M7"]],["m(maj7)","min",["M7"]],["-\u03947","min",["M7"]],["m\u03947","min",["M7"]],["add2","maj",["9"]],["2","maj",["9"]],["madd2","min",["9"]],["6add9","maj",["6","9"]],["m6add9","min",["6","9"]],["-6","min",["6"]],["-9","min",["m7","9"]],["dom9","maj",["m7","9"]],["aug(maj7)","aug",["M7"]],["augmaj7","aug",["M7"]],["+maj7","aug",["M7"]],["aug9","aug",["m7","9"]],["+9","aug",["m7","9"]],["m(maj9)","min",["M7","9"]],["mmaj9","min",["M7","9"]],["dim(maj7)","dim",["M7"]],["7(no3)","5",["m7"]],["maj7(no3)","5",["M7"]]],TENSION_SUFFIXES2=[["11","maj",["m7","9"],[17]],["m11","min",["m7","9"],[17]],["maj11","maj",["M7","9"],[17]],["add11","maj",[],[17]],["madd11","min",[],[17]],["13","maj",["m7","9"],[21]],["m13","min",["m7","9"],[21]],["maj13","maj",["M7","9"],[21]],["7b9","maj",["m7"],[13]],["7#11","maj",["m7"],[18]],["maj7#11","maj",["M7"],[18]],["M7#11","maj",["M7"],[18]],["7b13","maj",["m7"],[20]],["13b9","maj",["m7"],[13,21]]],TENSION_NAMES2=Object.freeze({13:"b9",15:"#9",17:"11",18:"#11",20:"b13",21:"13"}),SUFFIX_TABLE2=new Map([...SUFFIXES2.map(([suffix,quality,ext])=>[suffix,{quality,ext}]),...TENSION_SUFFIXES2.map(([suffix,quality,ext,tensions])=>[suffix,{quality,ext,tensions}])]),LETTER2=Object.freeze({c:0,d:2,e:4,f:5,g:7,a:9,b:11});function parsePitchClass2(text2){let match=text2.trim().match(/^([a-gA-G])(#|b|♯|♭)?$/);if(!match)return;let accidental=match[2]==="#"||match[2]==="\u266F"?1:match[2]==="b"||match[2]==="\u266D"?-1:0;return mod122(LETTER2[match[1].toLowerCase()]+accidental)}var ALTERATION_TENSION2=Object.freeze({b9:13,"#9":15,11:17,"#11":18,"+11":18,b13:20,13:21}),TOKEN2="b5|#5|\\+5|b9|#9|#11|\\+11|b13|alt|add9|add11|add13|11|13|9|6",ALTERATIONS2=new RegExp(`^(?:(?:${TOKEN2})|\\((?:${TOKEN2})(?:,(?:${TOKEN2}))*\\))+$`);function parseAlteredSuffix2(suffix){for(let cut=suffix.length-1;cut>=0;cut-=1){let base=SUFFIX_TABLE2.get(suffix.slice(0,cut));if(!base)continue;let raw=suffix.slice(cut);if(!ALTERATIONS2.test(raw))continue;let rest=raw.replace(/[(),]/g,""),tokens=rest.match(/b5|#5|\+5|b9|#9|#11|\+11|b13|alt|add9|add11|add13|11|13|9|6/g);if(!tokens||tokens.join("")!==rest)continue;let quality=base.quality,ext=new Set(base.ext),tensions=new Set(base.tensions??[]),ok=!0;for(let token of tokens)if(token==="#5"||token==="+5")quality==="maj"||quality==="aug"?quality="aug":ok=!1;else if(token==="b5")quality==="maj"||quality==="b5"?quality="b5":quality==="min"||quality==="dim"?quality="dim":ok=!1;else if(token==="alt"){quality!=="maj"&&(ok=!1),ext.add("m7");for(let step2 of[13,15,18,20])tensions.add(step2)}else if(token==="9"||token==="add9")ext.add("9");else if(token==="6")ext.add("6");else{let step2=ALTERATION_TENSION2[token.replace(/^add/,"")];step2===void 0?ok=!1:tensions.add(step2)}if(ok)return{quality,ext:[...ext],tensions:[...tensions].sort((a,b)=>a-b)}}}function parseChord2(symbol){if(typeof symbol!="string"||symbol.length>24)return;let match=symbol.trim().replace(/6\/9$/,"69").replace(/6\/9\//,"69/").match(/^([A-Ga-g])(#|b|♯|♭)?([^/]*)(?:\/(.+))?$/);if(!match)return;let root=parsePitchClass2(`${match[1]}${match[2]??""}`),entry=SUFFIX_TABLE2.get(match[3]??"")??parseAlteredSuffix2(match[3]??"");if(root===void 0||!entry)return;let bass;if(!(match[4]!==void 0&&(bass=parsePitchClass2(match[4]),bass===void 0)))return makeChord2(root,entry.quality,entry.ext,bass,entry.tensions)}var MODES2=Object.freeze({major:[0,2,4,5,7,9,11],minor:[0,2,3,5,7,8,10],dorian:[0,2,3,5,7,9,10],phrygian:[0,1,3,5,7,8,10],lydian:[0,2,4,6,7,9,11],mixolydian:[0,2,4,5,7,9,10],locrian:[0,1,3,5,6,8,10],"harmonic-minor":[0,2,3,5,7,8,11],"melodic-minor":[0,2,3,5,7,9,11],"phrygian-dominant":[0,1,4,5,7,8,10]}),MODE_NAMES2=Object.keys(MODES2),MODE_ALIASES2=Object.freeze({"":"major",maj:"major",major:"major",ionian:"major",m:"minor",min:"minor",minor:"minor",aeolian:"minor",dorian:"dorian",phrygian:"phrygian",lydian:"lydian",mixolydian:"mixolydian",mixo:"mixolydian",locrian:"locrian","harmonic-minor":"harmonic-minor","harmonic minor":"harmonic-minor",harmonic:"harmonic-minor","melodic-minor":"melodic-minor","melodic minor":"melodic-minor",melodic:"melodic-minor","jazz minor":"melodic-minor","phrygian-dominant":"phrygian-dominant","phrygian dominant":"phrygian-dominant",freygish:"phrygian-dominant",spanish:"phrygian-dominant",ajam:"major",mahur:"major",bilawal:"major"}),SCALES2=Object.freeze({"major-pentatonic":{steps:[0,2,4,7,9],mode:"major",family:"pentatonic",aliases:["pentatonic","major pentatonic","pent"]},"minor-pentatonic":{steps:[0,3,5,7,10],mode:"minor",family:"pentatonic",aliases:["minor pentatonic","m pentatonic","min pentatonic"]},blues:{steps:[0,3,5,6,7,10],mode:"minor",family:"blues",aliases:["minor blues"]},"major-blues":{steps:[0,2,3,4,7,9],mode:"major",family:"blues",aliases:["major blues"]},"yonanuki-minor":{steps:[0,2,3,7,8],mode:"minor",family:"pentatonic",aliases:["yonanuki","yonanuki minor","enka minor"]},hijaz:{steps:[0,1,4,5,7,8,10],mode:"phrygian-dominant",family:"maqam"},bayati:{steps:[0,1.5,3,5,7,8,10],mode:"phrygian",family:"maqam"},rast:{steps:[0,2,3.5,5,7,9,10.5],mode:"major",family:"maqam"},saba:{steps:[0,1.5,3,4,7,8,10],mode:"phrygian",family:"maqam"},kurd:{steps:[0,1,3,5,7,8,10],mode:"phrygian",family:"maqam"},nahawand:{steps:[0,2,3,5,7,8,11],mode:"harmonic-minor",family:"maqam"},sikah:{steps:[0,1.5,3.5,5.5,7,8.5,10.5],mode:"phrygian",family:"maqam",aliases:["sika"]},huzam:{steps:[0,1.5,3.5,4.5,7.5,8.5,10.5],mode:"phrygian",family:"maqam",aliases:["houzam"]},nikriz:{steps:[0,2,3,6,7,9,10],mode:"dorian",family:"maqam"},shur:{steps:[0,1.5,3,5,7,8,10],mode:"phrygian",family:"dastgah"},homayoun:{steps:[0,1.5,4,5,7,8,10],mode:"phrygian-dominant",family:"dastgah",aliases:["homayun"]},chahargah:{steps:[0,1.5,4,5,7,8.5,11],mode:"phrygian-dominant",family:"dastgah",aliases:["chahar-gah"]},segah:{steps:[0,1.5,3.5,5,6.5,8.5,10.5],mode:"phrygian",family:"dastgah",aliases:["sehgah","se-gah"]},nava:{steps:[0,2,3.5,5,7,8,10],mode:"minor",family:"dastgah"},yaman:{steps:[0,2,4,6,7,9,11],mode:"lydian",family:"raga",intonation:[0,203.91,386.31,611.73,701.96,884.36,1088.27],aliases:["kalyan","yaman kalyan"]},bhairav:{steps:[0,1,4,5,7,8,11],mode:"phrygian-dominant",family:"raga",intonation:[0,90.22,386.31,498.04,701.96,792.18,1088.27]},kafi:{steps:[0,2,3,5,7,9,10],mode:"dorian",family:"raga",intonation:[0,203.91,315.64,498.04,701.96,884.36,1017.6]},bhairavi:{steps:[0,1,3,5,7,8,10],mode:"phrygian",family:"raga",intonation:[0,90.22,294.13,498.04,701.96,792.18,996.09]},asavari:{steps:[0,2,3,5,7,8,10],mode:"minor",family:"raga",intonation:[0,203.91,315.64,498.04,701.96,813.69,996.09]},khamaj:{steps:[0,2,4,5,7,9,10],mode:"mixolydian",family:"raga",intonation:[0,203.91,386.31,498.04,701.96,884.36,996.09]},todi:{steps:[0,1,3,6,7,8,11],mode:"phrygian",family:"raga",intonation:[0,95,294,606,702,792,1107]},purvi:{steps:[0,1,4,6,7,8,11],mode:"phrygian-dominant",family:"raga",intonation:[0,90.22,386.31,590.22,701.96,792.18,1088.27]},marwa:{steps:[0,1,4,6,9,11],mode:"lydian",family:"raga",intonation:[0,111.73,386.31,590.22,884.36,1088.27]},darbari:{steps:[0,2,3,5,7,8,10],mode:"minor",family:"raga",intonation:[0,203.91,294.13,498.04,701.96,792.18,996.09],aliases:["darbari kanada"]},malkauns:{steps:[0,3,5,8,10],mode:"minor",family:"raga",intonation:[0,315.64,498.04,813.69,996.09]},bhupali:{steps:[0,2,4,7,9],mode:"major",family:"raga",intonation:[0,203.91,386.31,701.96,884.36]},durga:{steps:[0,2,5,7,9],mode:"major",family:"raga",intonation:[0,203.91,498.04,701.96,884.36]},"messiaen-1":{steps:[0,2,4,6,8,10],mode:"lydian",family:"messiaen",aliases:["whole-tone","whole tone","wholetone"]},"messiaen-2":{steps:[0,1,3,4,6,7,9,10],mode:"mixolydian",family:"messiaen",aliases:["octatonic","diminished","half-whole"]},"messiaen-3":{steps:[0,2,3,4,6,7,8,10,11],mode:"minor",family:"messiaen"},"messiaen-4":{steps:[0,1,2,5,6,7,8,11],mode:"harmonic-minor",family:"messiaen"},"messiaen-5":{steps:[0,1,5,6,7,11],mode:"lydian",family:"messiaen"},"messiaen-6":{steps:[0,2,4,5,6,8,10,11],mode:"major",family:"messiaen"},"messiaen-7":{steps:[0,1,2,3,5,6,7,8,9,11],mode:"harmonic-minor",family:"messiaen"},chromatic:{steps:[0,1,2,3,4,5,6,7,8,9,10,11],mode:"minor",family:"chromatic",aliases:["twelve-tone","aggregate"]},"harmonic-series":{steps:[0,2,4,6,7,9,10,11],mode:"mixolydian",family:"overtone",intonation:[0,204,386,551,702,841,969,1088],aliases:["overtone","overtone-scale","partials"]},"quarter-tone":{steps:[0,1.5,2,3.5,4,5,5.5,7,8.5,9,10.5],mode:"major",family:"quarter-tone",aliases:["quartertone","24-tone"]}}),SCALE_NAMES2=Object.keys(SCALES2),SCALE_ALIASES2=(()=>{let aliases={};for(let name of SCALE_NAMES2){let info=SCALES2[name];aliases[name]=name,aliases[name.replace(/-/g," ")]=name;for(let alias of info.aliases??[])aliases[alias]=name}return Object.freeze(aliases)})();function scaleNamed2(text2){let word2=text2.trim().toLowerCase().replace(/\s+/g," ");return SCALE_ALIASES2[word2]??SCALE_ALIASES2[word2.replace(/ /g,"-")]}function parseKey2(text2){if(typeof text2!="string"||text2.length>40)return;let match=text2.trim().match(/^([a-gA-G])(#|b|♯|♭)?\s*(m(?![a-z])|[a-zA-Z][a-zA-Z0-9 -]*)?$/);if(!match)return;let tonic=parsePitchClass2(`${match[1]}${match[2]??""}`);if(tonic===void 0)return;let word2=(match[3]??"").trim(),mode=MODE_ALIASES2[word2==="m"?"m":word2.toLowerCase()];if(mode!==void 0)return Object.freeze({tonic,mode});let scale3=scaleNamed2(word2);if(scale3!==void 0)return Object.freeze({tonic,mode:SCALES2[scale3].mode,scale:scale3})}function scaleSteps(key){return[...key.scale?SCALES2[key.scale].steps:MODES2[key.mode]]}function scaleOf2(key){return MODES2[key.mode].map(step2=>mod122(key.tonic+step2))}var VOICING_RANGE2=Object.freeze({low:48,high:79});var DEFAULT_STRUM2=1/32;var MAX_SLOP2=1/8,everyStep2=(step2,beats,hit2)=>Array.from({length:Math.round(beats/step2)},(_,index)=>({at:index*step2,...hit2(index)})),BAR_ACCENT2=[1,.84,.93,.86],CHORD_PATTERNS2=Object.freeze([{name:"eighths",description:"straight 8ths: the full chord on the beat, upper voices between",beats:4,hits:everyStep2(.5,4,i=>i%2===0?{length:.42,voices:"all",velocity:BAR_ACCENT2[i/2]}:{length:.3,voices:"upper",velocity:i===7?.76:.66}),feel:{roll:6}},{name:"sixteenths",description:"straight 16ths: full on the beat, the & lighter, e and a thin",beats:4,hits:everyStep2(.25,4,i=>{let beat2=Math.floor(i/4),place=i%4;return place===0?{length:.2,voices:"all",velocity:BAR_ACCENT2[beat2]}:place===2?{length:.16,voices:"all",velocity:.76}:{length:.13,voices:"upper",velocity:place===1?.54:.62}}),feel:{roll:4,timing:7}},{name:"offbeat",description:"short stabs on every &, programmed tight",beats:4,hits:everyStep2(1,4,()=>({length:.25,voices:"all",velocity:.9})).map(hit2=>({...hit2,at:hit2.at+.5})),feel:{tight:!0}},{name:"pop",description:"syncopated pop comp: 16th pushes, the & of 2 held over 3",beats:4,hits:[{at:0,length:.55,voices:"all",velocity:1},{at:.75,length:.2,voices:"upper",velocity:.6},{at:1.5,length:.9,voices:"all",velocity:.9},{at:2.5,length:.3,voices:"upper",velocity:.64},{at:3,length:.2,voices:"upper",velocity:.52},{at:3.5,length:.45,voices:"all",velocity:.86}],feel:{roll:6,lay:-3}},{name:"charleston",description:"jazz Charleston: a short 1, then the accented & of 2",beats:4,hits:[{at:0,length:.5,voices:"all",velocity:.86},{at:1.5,length:.42,voices:"all",velocity:.95}],feel:{roll:9,swing:.08}},{name:"bossa",description:"two-bar bossa: thumb on 1 and 3 (the 3 heavier), fingers on the clave",beats:8,hits:[...everyStep2(2,8,i=>({length:1.7,voices:[0],velocity:i%2===0?.78:.86,octave:-1,bass:i%2===0?"root":"fifth"})),...[0,1.5,3,5,6.5].map(at3=>({at:at3,length:at3===3||at3===6.5?.7:.5,voices:"upper",velocity:at3%1===0?.68:.74}))],feel:{roll:10,timing:8}},{name:"skank",description:"reggae skank: choked upper chops on 2 and 4, laid back",beats:4,hits:[1,3].map(at3=>({at:at3,length:.18,voices:"upper",velocity:at3===1?.92:.97})),feel:{roll:3,lay:8,timing:6}},{name:"gallop",description:"gallop: an 8th and two 16ths per beat",beats:4,hits:everyStep2(1,4,i=>({length:.38,voices:"all",velocity:BAR_ACCENT2[i]})).flatMap(hit2=>[hit2,{...hit2,at:hit2.at+.5,length:.18,velocity:.62},{...hit2,at:hit2.at+.75,length:.18,velocity:.7}]),feel:{roll:3,timing:6}},{name:"half-time",description:"half-time: a long rolled hit and a pickup per two bars",beats:8,hits:[{at:0,length:3.6,voices:"all",velocity:.96},{at:4,length:2.2,voices:"all",velocity:.8},{at:6.5,length:.8,voices:"upper",velocity:.56},{at:7.5,length:.45,voices:"upper",velocity:.68}],feel:{roll:11}},{name:"tresillo",description:"tresillo 3+3+2",beats:4,hits:[{at:0,length:1,voices:"all",velocity:1},{at:1.5,length:1,voices:"all",velocity:.84},{at:3,length:.6,voices:"all",velocity:.92}],feel:{roll:5}},{name:"oom-pah",description:"alternating bass and chord: low root, detached upper chord",beats:4,hits:everyStep2(1,4,i=>i%2===0?{length:.85,voices:[0],velocity:i===0?1:.9,octave:-1,bass:i===0?"root":"fifth"}:{length:.5,voices:"upper",velocity:i===1?.72:.76}),feel:{roll:4}},{name:"roll",description:"broken-chord roll up in 16ths, ringing to the half bar",beats:4,hits:[0,2].flatMap(half=>[0,1,2,3].map(step2=>({at:half+step2*.25,length:2-step2*.25,voices:[step2],velocity:(half===0?1:.92)*[.84,.64,.7,.78][step2]})))},{name:"pick",description:"broken-chord picking: low, high, middle, high in 8ths",beats:4,hits:everyStep2(.5,4,i=>({length:i%4===0?1.9:.9,voices:[[0,-1,1,-1][i%4]],velocity:[i<4?.92:.84,.7,.6,.66][i%4]})),feel:{timing:8}}]);var GUITAR_TUNINGS2=Object.freeze({standard:[40,45,50,55,59,64],dropd:[38,45,50,55,59,64],doubledropd:[38,45,50,55,59,62],dadgad:[38,45,50,55,57,62],openg:[38,43,50,55,59,62],opend:[38,45,50,54,57,62],opene:[40,47,52,56,59,64],halfdown:[39,44,49,54,58,63],nashville:[52,57,62,67,59,64],bass:[28,33,38,43],ukulele:[67,60,64,69],requinto:[45,50,55,60,64,69]}),GUITAR_TUNING_NAMES2=Object.keys(GUITAR_TUNINGS2);var STROKE_PATTERNS2=Object.freeze({down:"D",folk:"D-DU-UDU",pop:"D-DU-UD-",punk:"DDDDDDDD",funk:"xuxuDuxuxuDuxuxu",reggae:".U.U",waltz:"Ddd",jangle:"D-DUDUDU",island:"D-DU-UDU",chuck:"D-xU-UxU",soul:"..D...D."}),STROKE_PATTERN_NAMES2=Object.keys(STROKE_PATTERNS2);var PROGRESSION_PRESETS2=Object.freeze([{name:"axis",mode:"major",numerals:["I","V","vi","IV"],description:"I\u2013V\u2013vi\u2013IV, the four-chord pop loop"},{name:"sad-pop",mode:"major",numerals:["vi","IV","I","V"],description:"vi\u2013IV\u2013I\u2013V, the same loop from the relative minor"},{name:"fifties",mode:"major",numerals:["I","vi","IV","V"],description:"I\u2013vi\u2013IV\u2013V doo-wop"},{name:"ii-v-i",mode:"major",numerals:["ii","V","I","I"],sevenths:!0,description:"ii7\u2013V7\u2013Imaj7, the jazz cadence"},{name:"turnaround",mode:"major",numerals:["I","vi","ii","V"],sevenths:!0,description:"Imaj7\u2013vi7\u2013ii7\u2013V7 turnaround"},{name:"canon",mode:"major",numerals:["I","V","vi","iii","IV","I","IV","V"],description:"Pachelbel's canon"},{name:"aeolian",mode:"minor",numerals:["i","VI","III","VII"],description:"i\u2013VI\u2013III\u2013VII minor anthem"},{name:"andalusian",mode:"minor",numerals:["i","VII","VI","V"],description:"i\u2013VII\u2013VI\u2013V descending (major V)"},{name:"minor-ii-v",mode:"minor",numerals:["ii\xF8","V7","i","i"],sevenths:!0,description:"ii\xF87\u2013V7\u2013i minor cadence"},{name:"dorian-vamp",mode:"dorian",numerals:["i","IV"],sevenths:!0,description:"i7\u2013IV7 dorian vamp"},{name:"mixolydian-rock",mode:"mixolydian",numerals:["I","bVII","IV","I"],description:"I\u2013bVII\u2013IV\u2013I mixolydian rock"}]);function mod122(value){return(Math.trunc(value)%12+12)%12}var CHORD_PROCESS=["Chords (Orchid-style): pick chords from the song key's diatonic set (in C major: C Dm Em F G Am Bdim; minor keys i ii\xB0 III iv v VI VII, V major for cadences).","Move tonic (I vi iii) \u2192 predominant (IV ii) \u2192 dominant (V vii\xB0) \u2192 tonic; loops end on V or IV to lead home.","Add sevenths/9ths as color (6, m7, M7, 9 extensions); voice-lead each chord to the inversion nearest the previous one in C3\u2013G5 so common tones hold; put the root an octave or two below as bass.","Use suggest_progression to get voice-led chords and write_chords to write them (block, strum, arpeggio, harp, slop or a rhythm pattern; bassMode chords|unison|single|solo), instead of hand-placing chord notes with add_notes."].join(" ");var TUNING_LIMITS=Object.freeze({maxSteps:512,maxEdo:128,maxCents:9600,maxRatioTerm:2147483647,minRefHz:220,maxRefHz:880,maxNoteCents:1200,maxNameLength:64,maxPathLength:256}),TuningError=class extends Error{constructor(message){super(message),this.name="TuningError"}},TUNING_MAPS=Object.freeze(["linear","nearest"]);function ratioCents(ratio2){return 1200*Math.log2(ratio2)}function parseRatio(text2){let match=text2.trim().match(/^(\d+)(?:\/(\d+))?$/);if(!match)return;let top=Number(match[1]),bottom=match[2]===void 0?1:Number(match[2]);if(!(top<1||bottom<1||top>TUNING_LIMITS.maxRatioTerm||bottom>TUNING_LIMITS.maxRatioTerm))return top/bottom}function edoCents(steps2){return Array.from({length:steps2},(_,index)=>(index+1)*1200/steps2)}function fromRatios(ratios){return ratios.map(ratio2=>ratioCents(parseRatio(ratio2)))}var PYTHAGOREAN=["2187/2048","9/8","32/27","81/64","4/3","729/512","3/2","6561/4096","27/16","16/9","243/128","2/1"],JUST_5=["16/15","9/8","6/5","5/4","4/3","45/32","3/2","8/5","5/3","9/5","15/8","2/1"],JUST_7=["16/15","9/8","7/6","5/4","4/3","7/5","3/2","8/5","5/3","7/4","15/8","2/1"],WELL_TUNED_PIANO=["567/512","9/8","147/128","21/16","1323/1024","189/128","3/2","49/32","7/4","441/256","63/32","2/1"],HINDUSTANI=["16/15","9/8","6/5","5/4","4/3","45/32","3/2","8/5","5/3","16/9","15/8","2/1"],SHRUTIS=["256/243","16/15","10/9","9/8","32/27","6/5","5/4","81/64","4/3","27/20","45/32","729/512","3/2","128/81","8/5","5/3","27/16","16/9","9/5","15/8","243/128","2/1"],FIXED_PRESETS=[{name:"12-tet",family:"equal",about:"twelve equal steps per octave (12-TET), the default",cents:edoCents(12),aliases:["12edo","12-edo","12tet","12-et","equal","et","standard"]},{name:"19-edo",family:"equal",about:"19 equal steps: meantone-like thirds, 19 keys per octave",cents:edoCents(19),aliases:["19edo","19-tet","19tet"]},{name:"24-edo",family:"equal",about:"24 equal steps: quarter tones, 24 keys per octave",cents:edoCents(24),aliases:["24edo","24-tet","24tet","quarter-tone","quarter-tones"]},{name:"31-edo",family:"equal",about:"31 equal steps: near quarter-comma meantone, 31 keys per octave",cents:edoCents(31),aliases:["31edo","31-tet","31tet"]},{name:"pythagorean",family:"historical",about:"pure 3/2 fifths from E\u266D to G\u266F (the wolf between them)",cents:fromRatios(PYTHAGOREAN),ratios:PYTHAGOREAN,aliases:["pythag","3-limit"]},{name:"just",family:"just",about:"5-limit just intonation: pure 5/4 thirds and 3/2 fifths",cents:fromRatios(JUST_5),ratios:JUST_5,aliases:["ji","5-limit","just-intonation","ptolemaic"]},{name:"7-limit",family:"just",about:"7-limit just intonation: septimal 7/6, 7/5 and 7/4",cents:fromRatios(JUST_7),ratios:JUST_7,aliases:["septimal","7-limit-ji"]},{name:"well-tuned-piano",family:"just",about:"La Monte Young's Well-Tuned Piano key map (7-limit, from E\u266D, after Gann)",cents:fromRatios(WELL_TUNED_PIANO),ratios:WELL_TUNED_PIANO,root:3,aliases:["wtp","young","la-monte-young"]},{name:"pelog",family:"gamelan",about:"Javanese pelog, 7 notes (Kunst's average of 39 gamelans; every gamelan differs)",cents:[120,270,540,670,785,950,1200],approximate:!0},{name:"slendro",family:"gamelan",about:"Javanese slendro, 5 notes (Surjodiningrat's average of 30 gamelans; every gamelan differs)",cents:[231,474,717,955,1200],approximate:!0},{name:"thai",family:"equal",about:"Thai and Khmer seven-tone equidistant tuning, about 171 cents a step (Morton's theoretical norm; every ensemble differs)",cents:edoCents(7),approximate:!0,aliases:["7-edo","7edo","7-tet","khmer"]},{name:"nyamaropa",family:"african",about:"Shona mbira nyamaropa-style, 7 notes (John Kunaka's mbira after Berliner; every mbira differs)",cents:[196,377,506,676,877,1050,1200],approximate:!0,aliases:["mbira"]},{name:"hindustani",family:"indian",about:"the twelve svaras in common just ratios, from Sa",cents:fromRatios(HINDUSTANI),ratios:HINDUSTANI,aliases:["svara","sargam"]},{name:"shruti",family:"indian",about:"the 22 shrutis, 22 keys per octave",cents:fromRatios(SHRUTIS),ratios:SHRUTIS,aliases:["22-shruti","shrutis","sruti"]}];function scalePreset(name,info){if(!info.steps.some(step2=>!Number.isInteger(step2))&&!info.intonation||info.family==="quarter-tone")return;let raga=info.family==="raga",keys=[0,...(raga?fromRatios(HINDUSTANI):edoCents(12)).slice(0,11)];return info.steps.forEach((step2,index)=>{let key=Math.ceil(step2)%12;key!==0&&(keys[key]=info.intonation?.[index]??step2*100)}),{name,family:info.family==="raga"?"raga":info.family==="dastgah"?"dastgah":info.family==="overtone"?"just":"maqam",about:raga?`raga ${name} with its shruti intonation over the Hindustani just table`:info.family==="overtone"?"partials 8 to 15 of the harmonic series over the tonic, in just cents":`${info.family} ${name} quarter tones on the twelve keys (24-tone convention)`,cents:[...keys.slice(1),1200],approximate:!0}}var SCALE_PRESETS=SCALE_NAMES2.flatMap(name=>{let preset5=scalePreset(name,SCALES2[name]);return preset5?[preset5]:[]}),TUNING_PRESETS=Object.freeze([...FIXED_PRESETS,...SCALE_PRESETS]),TUNING_NAMES=Object.freeze(TUNING_PRESETS.map(preset5=>preset5.name)),PRESET_INDEX=(()=>{let index=new Map;for(let preset5 of TUNING_PRESETS){index.set(preset5.name,preset5);for(let alias of preset5.aliases??[])index.set(alias,preset5)}return index})();function tuningPreset(text2){let word2=text2.trim().toLowerCase().replace(/[\s_]+/g,"-");return PRESET_INDEX.get(word2)??PRESET_INDEX.get(word2.replace(/-/g,""))}function checkTable(cents,where2){if(cents.length<1||cents.length>TUNING_LIMITS.maxSteps)throw new TuningError(`${where2} needs 1 to ${TUNING_LIMITS.maxSteps} steps`);for(let value of cents)if(!Number.isFinite(value)||Math.abs(value)>TUNING_LIMITS.maxCents)throw new TuningError(`${where2} cents must be within \xB1${TUNING_LIMITS.maxCents}`);if(!(cents[cents.length-1]>0))throw new TuningError(`${where2} period (the last step) must be above the root`)}function isRecord3(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function projectPath(value,where2,extension){if(typeof value!="string"||value.length===0||value.length>TUNING_LIMITS.maxPathLength||value.startsWith("/")||/^[a-zA-Z]:/.test(value)||value.split(/[\\/]/).includes("..")||!value.toLowerCase().endsWith(extension))throw new TuningError(`${where2} must be a ${extension} path inside the project`);return value}function normalizeKeyMapping(input,where2){if(!isRecord3(input))throw new TuningError(`${where2} keymap must be an object`);let key=field=>{let value=input[field];if(typeof value!="number"||!Number.isInteger(value)||value<0||value>127)throw new TuningError(`${where2} keymap ${field} must be a MIDI key 0-127`);return value},size=input.size;if(typeof size!="number"||!Number.isInteger(size)||size<0||size>TUNING_LIMITS.maxSteps)throw new TuningError(`${where2} keymap size must be an integer from 0 to ${TUNING_LIMITS.maxSteps}`);let octave2=input.octave;if(typeof octave2!="number"||!Number.isInteger(octave2)||octave2<0||octave2>TUNING_LIMITS.maxSteps)throw new TuningError(`${where2} keymap octave must be a degree from 0 to ${TUNING_LIMITS.maxSteps}`);let refHz=input.refHz;if(typeof refHz!="number"||!Number.isFinite(refHz)||refHz<=0||refHz>1e5)throw new TuningError(`${where2} keymap refHz must be a positive frequency`);let map=input.map;if(!Array.isArray(map)||map.length!==size)throw new TuningError(`${where2} keymap map must list ${size} entries`);for(let entry of map)if(entry!==null&&(typeof entry!="number"||!Number.isInteger(entry)||entry<0||entry>TUNING_LIMITS.maxSteps*128))throw new TuningError(`${where2} keymap entries must be degrees or null`);let mapping={size,first:key("first"),last:key("last"),middle:key("middle"),refKey:key("refKey"),refHz,octave:octave2,map:Object.freeze([...map])};if(mapping.first>mapping.last)throw new TuningError(`${where2} keymap first key is above its last key`);if(mappedEntry(mapping,mapping.refKey)===void 0)throw new TuningError(`${where2} keymap reference key ${mapping.refKey} is unmapped`);return Object.freeze(mapping)}function normalizeTuning(input,where2){if(input==null)return;if(typeof input=="string")return normalizeTuning({name:input},where2);if(!isRecord3(input))throw new TuningError(`${where2} must be an object`);let known=new Set(["name","edo","ratios","cents","scl","kbm","keymap","ref","root","map"]);for(let field of Object.keys(input))if(!known.has(field))throw new TuningError(`${where2} has an unknown field "${field}"`);let out={},sources=["edo","ratios","cents"].filter(field=>input[field]!==void 0&&input[field]!==null);if(sources.length>1)throw new TuningError(`${where2} takes one of edo, ratios or cents, not ${sources.join(" and ")}`);if(input.name!==void 0&&input.name!==null){if(typeof input.name!="string"||input.name.trim()===""||input.name.length>TUNING_LIMITS.maxNameLength)throw new TuningError(`${where2} name must be a short string`);if(sources.length===0){let preset5=tuningPreset(input.name);if(!preset5)throw new TuningError(`${where2}: unknown tuning "${input.name}" (try ${TUNING_NAMES.slice(0,12).join(", ")}, \u2026)`);out.name=preset5.name}else out.name=input.name.trim()}if(input.edo!==void 0&&input.edo!==null){let edo=input.edo;if(typeof edo!="number"||!Number.isInteger(edo)||edo<1||edo>TUNING_LIMITS.maxEdo)throw new TuningError(`${where2} edo must be an integer from 1 to ${TUNING_LIMITS.maxEdo}`);out.edo=edo}if(input.ratios!==void 0&&input.ratios!==null){if(!Array.isArray(input.ratios))throw new TuningError(`${where2} ratios must be a list like ["9/8", "5/4", "2/1"]`);let ratios=input.ratios.map((ratio2,index)=>{let text2=typeof ratio2=="number"&&Number.isInteger(ratio2)?String(ratio2):ratio2;if(typeof text2!="string"||parseRatio(text2)===void 0)throw new TuningError(`${where2} ratio ${index+1} must be a positive ratio like "3/2"`);return text2.trim()});checkTable(ratios.map(ratio2=>ratioCents(parseRatio(ratio2))),`${where2} ratios`),out.ratios=Object.freeze(ratios)}if(input.cents!==void 0&&input.cents!==null){if(!Array.isArray(input.cents)||input.cents.some(value=>typeof value!="number"))throw new TuningError(`${where2} cents must be a list of numbers like [100, 200, 1200]`);checkTable(input.cents,`${where2} cents`),out.cents=Object.freeze([...input.cents])}if(input.scl!==void 0&&input.scl!==null&&(out.scl=projectPath(input.scl,`${where2} scl`,".scl"),out.ratios===void 0&&out.cents===void 0))throw new TuningError(`${where2} scl ${String(input.scl)} has not been read (no ratios or cents)`);if(input.kbm!==void 0&&input.kbm!==null&&(out.kbm=projectPath(input.kbm,`${where2} kbm`,".kbm"),input.keymap===void 0||input.keymap===null))throw new TuningError(`${where2} kbm ${String(input.kbm)} has not been read (no keymap)`);if(input.keymap!==void 0&&input.keymap!==null&&(out.keymap=normalizeKeyMapping(input.keymap,where2)),input.ref!==void 0&&input.ref!==null){let ref=input.ref;if(typeof ref!="number"||!Number.isFinite(ref)||ref<TUNING_LIMITS.minRefHz||ref>TUNING_LIMITS.maxRefHz)throw new TuningError(`${where2} ref (12-TET A4 in Hz) must be between ${TUNING_LIMITS.minRefHz} and ${TUNING_LIMITS.maxRefHz}`);out.ref=ref}if(input.root!==void 0&&input.root!==null){let root=input.root;if(typeof root!="number"||!Number.isInteger(root)||root<0||root>127)throw new TuningError(`${where2} root must be a MIDI key 0-127`);out.root=root}if(input.map!==void 0&&input.map!==null){if(!TUNING_MAPS.includes(input.map))throw new TuningError(`${where2} map must be ${TUNING_MAPS.join(" or ")}`);input.map!=="linear"&&(out.map=input.map)}if(out.keymap&&(out.ref!==void 0||out.root!==void 0||out.map!==void 0))throw new TuningError(`${where2}: a keymap sets its own reference and root (drop ref, root and map)`);return Object.freeze(out)}function normalizeNoteCents(input,where2){if(!(input==null||input===0)){if(typeof input!="number"||!Number.isFinite(input)||Math.abs(input)>TUNING_LIMITS.maxNoteCents)throw new TuningError(`${where2} cents must be within \xB1${TUNING_LIMITS.maxNoteCents}`);return input}}function tuningTable(tuning){if(tuning.edo!==void 0)return edoCents(tuning.edo);if(tuning.ratios)return tuning.ratios.map(ratio2=>ratioCents(parseRatio(ratio2)));if(tuning.cents)return tuning.cents;if(tuning.name)return tuningPreset(tuning.name)?.cents}var TUNING_MAX_HZ=2e4;function mappedEntry(mapping,key){let offset=key-mapping.middle;if(mapping.size===0)return{pattern:0,degree:offset};let pattern=Math.floor(offset/mapping.size),entry=mapping.map[offset-pattern*mapping.size];if(entry!=null)return{pattern,degree:entry}}function resolveTuning(song3,track2,keyText){if(!song3&&!track2)return;let own=track2?tuningTable(track2):void 0,source=own?track2:song3,table2=(source?tuningTable(source):void 0)??edoCents(12),keymap=track2?.keymap??(own?void 0:song3?.keymap),ref=track2?.ref??song3?.ref??440,presetRoot=source?.name&&!source.edo&&!source.ratios&&!source.cents?tuningPreset(source.name)?.root:void 0,tonic=parseKey2(keyText??void 0)?.tonic,root=track2?.root??song3?.root??60+(presetRoot??tonic??0),nearest2=(track2?.map??song3?.map)==="nearest",size=table2.length,period=table2[size-1],degreeCents=degree=>{let octave2=Math.floor(degree/size),index=degree-octave2*size;return octave2*period+(index===0?0:table2[index-1])},hz3=new Float64Array(128);if(keymap){let step2=keymap.octave===0?period:degreeCents(keymap.octave),centsOf=key=>{let found=mappedEntry(keymap,key);return found?found.pattern*step2+degreeCents(found.degree):void 0},refCents=centsOf(keymap.refKey);for(let key=0;key<128;key+=1){if(key<keymap.first||key>keymap.last){hz3[key]=ref*2**((key-69)/12);continue}let cents=centsOf(key);hz3[key]=cents===void 0?0:keymap.refHz*2**((cents-refCents)/1200)}}else{let rootHz=ref*2**((root-69)/12);for(let key=0;key<128;key+=1){let cents=nearest2?nearestCents(table2,(key-root)*100):degreeCents(key-root);hz3[key]=rootHz*2**(cents/1200)}}let name=source?.name??(source?.edo?`${source.edo}-edo`:source?.scl?source.scl.split("/").pop():source?"custom":"12-tet");for(let key=0;key<128;key+=1)(!Number.isFinite(hz3[key])||hz3[key]>=TUNING_MAX_HZ)&&(hz3[key]=0);return Object.freeze({hz:hz3,size,period,root:keymap?keymap.middle:root,linear:!keymap&&!nearest2,name})}function nearestCents(table2,target){let period=table2[table2.length-1],best=0,bestDistance=1/0;for(let step2 of[0,...table2.slice(0,-1)]){let octave2=Math.round((target-step2)/period);for(let candidate of[(octave2-1)*period+step2,octave2*period+step2,(octave2+1)*period+step2]){let distance=Math.abs(candidate-target);(distance<bestDistance-1e-9||Math.abs(distance-bestDistance)<=1e-9&&candidate<best)&&(best=candidate,bestDistance=distance)}}return best}function noteHz(pitch2,cents,table2){let base=table2?table2.hz[pitch2]:440*2**((pitch2-69)/12);return cents?base*2**(cents/1200):base}function keyCentsFor(table2){return pitch2=>{let hz3=table2.hz[pitch2];return hz3&&hz3>0?ratioCents(hz3/440):(pitch2-69)*100}}var AUTOTUNE_VERSION=1,AUTOTUNE_PRESETS=["hard","robot","warble","trap","pop","natural","gentle","guided","locked"],AUTOTUNE_TARGETS=["scale","chromatic","chord","notes"],AUTOTUNE_VOICES=["auto","bass","tenor","alto","soprano"],AUTOTUNE_PARAMS=Object.freeze([{name:"speed",min:0,max:400,def:25,step:5,unit:"ms",label:"Speed",help:"retune time; 0 is instant and stepped"},{name:"relax",min:0,max:1,def:.3,step:.05,unit:"",label:"Relax",help:"slower retune on held notes"},{name:"hold",min:50,max:1e3,def:150,step:10,unit:"ms",label:"Hold",help:"when a note counts as held, for relax"},{name:"flex",min:0,max:100,def:0,step:5,unit:"",label:"Flex",help:"higher only pulls notes already near a target"},{name:"glide",min:0,max:.5,def:0,step:.01,unit:"s",label:"Glide",help:"time to move between targets"},{name:"amount",min:0,max:1,def:1,step:.05,unit:"",label:"Amount",help:"correction strength"},{name:"vib",min:0,max:12,def:0,step:.5,unit:"Hz",label:"Vib",help:"added vibrato rate (0 off)"},{name:"vibmod",min:0,max:1,def:.2,step:.05,unit:"st",label:"Vib depth",help:"added vibrato depth"},{name:"center",min:0,max:1,def:1,step:.05,unit:"",label:"Center",help:"notes: move each note's middle to the written pitch"},{name:"drift",min:0,max:1,def:.5,step:.05,unit:"",label:"Drift",help:"notes: share of slow drift removed"}]),AUTOTUNE_FIELDS=["preset","to","from","key","speed","relax","hold","flex","glide","amount","vib","vibmod","center","drift","voice"],AUTOTUNE_PRESET_FIELDS=Object.freeze({hard:{speed:0,relax:0,glide:0},robot:{speed:0,relax:0,to:"chromatic"},warble:{speed:0,relax:0,vib:6.5,vibmod:.35},trap:{speed:10,relax:.2},pop:{speed:25,relax:.3},natural:{speed:60,relax:.5,flex:40},gentle:{speed:120,relax:.6,flex:20},guided:{to:"notes",center:1,drift:.5,glide:.04},locked:{to:"notes",speed:0,relax:0}}),AUTOTUNE_PRESET_HELP=Object.freeze({hard:"instant, stepped notes",robot:"stepped on every step of the tuning",warble:"hard with wide synthetic vibrato",trap:"fast and glossy",pop:"polished but sung",natural:"keeps scoops and vibrato",gentle:"barely there",guided:"notes to a written melody, vibrato kept",locked:"hard tune locked to a melody"});function fail(message){throw new FxValidationError(`autotune: ${message}`)}function word(value,words,field){return(typeof value!="string"||!words.includes(value))&&fail(`${field} must be one of ${words.join(", ")}`),value}function normalizeAutotune(input,_instrument){if(input==null)return;(typeof input!="object"||Array.isArray(input))&&fail("must be an object");let record2=input;for(let key of Object.keys(record2))AUTOTUNE_FIELDS.includes(key)||fail(`unknown field ${key}`);let out={};for(let field of AUTOTUNE_FIELDS){let value=record2[field];if(value!==void 0)if(field==="preset")out.preset=word(value,AUTOTUNE_PRESETS,field);else if(field==="to")out.to=word(value,AUTOTUNE_TARGETS,field);else if(field==="voice")out.voice=word(value,AUTOTUNE_VOICES,field);else if(field==="from")(typeof value!="string"||value.length===0||value.length>64)&&fail("from must be a track id"),out.from=value;else if(field==="key")(typeof value!="string"||parseKey2(value)===void 0)&&fail(`key ${JSON.stringify(value)} is not a key (try "A minor")`),out.key=value;else{let spec=AUTOTUNE_PARAMS.find(param2=>param2.name===field);(typeof value!="number"||!Number.isFinite(value))&&fail(`${field} must be a number`),(value<spec.min||value>spec.max)&&fail(`${field} must be ${spec.min}..${spec.max}${spec.unit?` ${spec.unit}`:""}`),out[field]=value}}Object.keys(out).length===0&&fail("give a preset or settings");let to=out.to??(out.preset?AUTOTUNE_PRESET_FIELDS[out.preset].to:void 0)??"scale";out.from!==void 0&&to!=="notes"&&fail(`from needs to: notes (this one tunes to ${to})`);let ordered={};for(let field of AUTOTUNE_FIELDS)out[field]!==void 0&&(ordered[field]=out[field]);return Object.freeze(ordered)}function resolveAutotune(input){let base=AUTOTUNE_PRESET_FIELDS[input.preset??"pop"],pick=key2=>input[key2]!==void 0?input[key2]:base[key2],to=pick("to")??"scale",def=name=>pick(name)??AUTOTUNE_PARAMS.find(param2=>param2.name===name).def,vib=def("vib"),speed=to==="notes"?input.speed??(input.preset?base.speed:void 0):def("speed"),from=input.from,key=input.key;return Object.freeze({to,...from!==void 0?{from}:{},...key!==void 0?{key}:{},...speed!==void 0?{speed}:{},relax:def("relax"),hold:def("hold"),flex:def("flex"),glide:def("glide"),amount:def("amount"),vib,vibmod:vib>0?def("vibmod"):0,center:def("center"),drift:def("drift"),voice:pick("voice")??"auto"})}function autotuneDigest(resolved){return`at${AUTOTUNE_VERSION}:${JSON.stringify(resolved)}`}var centsOfHz=hz3=>1200*Math.log2(hz3/440);function gridOf(points){let sorted=[...new Set(points.map(p=>Math.round(p*1e6)/1e6))].filter(Number.isFinite).sort((a,b)=>a-b),minStep=1/0;for(let i=1;i<sorted.length;i+=1)minStep=Math.min(minStep,sorted[i]-sorted[i-1]);return Object.freeze({points:Float64Array.from(sorted),minStep:Number.isFinite(minStep)?minStep:1200})}function keyCents(table2,key){let at3=k=>{let hz3=table2?.hz[k];return hz3&&hz3>0?ratioCents(hz3/440):(k-69)*100},base=Math.min(126,Math.max(0,Math.floor(key))),frac2=key-base;if(frac2===0)return at3(base);let gap=at3(base+1)-at3(base);return table2&&Math.abs(gap-100)>25?at3(base+1):at3(base)+gap*frac2}function chromaticGrid(table2){let points=[];for(let key=0;key<128;key+=1)if(table2){let hz3=table2.hz[key];hz3>0&&points.push(ratioCents(hz3/440))}else points.push((key-69)*100);return gridOf(points)}function scaleGrid(keyText,table2){let key=parseKey2(keyText??void 0);if(!key||table2&&(table2.size!==12||Math.abs(table2.period-1200)>1e-6))return chromaticGrid(table2);let steps2=scaleSteps(key),points=[];for(let octave2=-1;octave2<=10;octave2+=1)for(let step2 of steps2){let k=octave2*12+key.tonic+step2;k>=0&&k<=127&&points.push(keyCents(table2,k))}return gridOf(points)}function classGrid(classes,table2){let points=[];for(let key=0;key<128;key+=1)classes.includes((key%12+12)%12)&&points.push(keyCents(table2,key));return gridOf(points)}function nearestTarget(grid2,c){let p=grid2.points;if(p.length===0)return c;let lo=0,hi=p.length-1;for(;lo<hi;){let mid=lo+hi>>1;p[mid]<c?lo=mid+1:hi=mid}let above=p[lo],below=lo>0?p[lo-1]:above;return c-below<=above-c?below:above}function gapAt(grid2,t){let p=grid2.points,best=1/0;for(let i=0;i<p.length;i+=1)if(!(Math.abs(p[i]-t)>1e-6)){i>0&&(best=Math.min(best,t-p[i-1])),i+1<p.length&&(best=Math.min(best,p[i+1]-t));break}return Number.isFinite(best)?best:1200}var lp=(dtMs,tauMs)=>tauMs<=0?1:1-Math.exp(-dtMs/tauMs),smoothstep=(x,a,b)=>{let u=Math.min(1,Math.max(0,(x-a)/(b-a)));return u*u*(3-2*u)};function voicedAt(curve,f){return curve.f0[f]>0}function voicingWeight(curve,f){return smoothstep((curve.prob[f]??0)/255,.3,.7)*(1-smoothstep((curve.aperiodic[f]??255)/255,.2,.4))}function hardVoicingWeight(curve,f){return smoothstep((curve.prob[f]??0)/255,.04,.18)*(1-smoothstep((curve.aperiodic[f]??255)/255,.2,.4))}function centredAverage(curve,r){let n2=curve.f0.length,out=new Float64Array(n2).fill(NaN),f=0;for(;f<n2;){if(!voicedAt(curve,f)){f+=1;continue}let e=f;for(;e<n2&&voicedAt(curve,e);)e+=1;let sums=new Float64Array(e-f+1);for(let i=f;i<e;i+=1)sums[i-f+1]=sums[i-f]+centsOfHz(curve.f0[i]);for(let i=f;i<e;i+=1){let a=Math.max(f,i-r),b=Math.min(e-1,i+r);out[i]=(sums[b-f+1]-sums[a-f])/(b-a+1)}f=e}return out}function runningMedian(curve,r){let n2=curve.f0.length,out=new Float64Array(n2).fill(NaN),cents=new Float64Array(n2);for(let f=0;f<n2;f+=1)cents[f]=voicedAt(curve,f)?centsOfHz(curve.f0[f]):NaN;let window=[];for(let f=0;f<n2;f+=1)if(voicedAt(curve,f)){window.length=0;for(let g=Math.max(0,f-r);g<=Math.min(n2-1,f+r);g+=1)Number.isNaN(cents[g])||window.push(cents[g]);window.sort((a,b)=>a-b),out[f]=window[window.length>>1]}return out}function retuneCurve(curve,source,p){let n2=curve.f0.length,out=new Float64Array(n2).fill(NaN),dtMs=curve.hop*1e3,amount=p.amount??1,hystFloor=p.hysteresis??12,relax=p.relax??0,holdMs=p.hold??150,flex=Math.min(100,Math.max(0,p.flex??0)),zone=50*(1-flex/100),glideMs=(p.glide??0)*1e3,gridAt=typeof source=="function"?source:_seconds=>source,dynamic=typeof source=="function",selTau=p.speed<=5?0:60,hardTune=p.speed===0&&relax===0,first=gridAt(curve.t0),avg=dynamic||first.minStep<100?centredAverage(curve,Math.round(.09/curve.hop)):null,med=runningMedian(curve,Math.round(.15/curve.hop)),centre=NaN,target=NaN,shown2=NaN,corr=0,inNote=0,lastGrid;for(let f=0;f<n2;f+=1){let hz3=curve.f0[f];if(!(hz3>0)){centre=NaN,target=NaN,shown2=NaN,corr=0,inNote=0;continue}let grid2=gridAt(curve.t0+f*curve.hop),dense=grid2.minStep<100,c=centsOfHz(hz3);centre=dense&&avg?avg[f]:Number.isNaN(centre)?c:centre+(c-centre)*lp(dtMs,selTau);let nearest2=nearestTarget(grid2,centre);lastGrid!==grid2&&!Number.isNaN(target)&&Math.abs(nearestTarget(grid2,target)-target)>1e-6&&(target=nearest2,inNote=0),lastGrid=grid2;let hyst=Number.isNaN(target)||!dense?hystFloor:Math.max(hystFloor,.35*gapAt(grid2,target));if(Number.isNaN(target)?target=nearest2:nearest2!==target&&Math.abs(centre-nearest2)+hyst<Math.abs(centre-target)&&(target=nearest2,inNote=0),Number.isNaN(shown2)||glideMs<=0)shown2=target;else{let maxStep=dtMs/glideMs*100;shown2+=Math.max(-maxStep,Math.min(maxStep,target-shown2))}inNote+=dtMs;let w=amount;if(flex>0){let dist=Math.abs(centre-target);w*=dist<=zone?1:Math.max(0,1-(dist-zone)/10)}let voicing=Math.abs(c-med[f])>900?0:hardTune?hardVoicingWeight(curve,f):voicingWeight(curve,f);w*=voicing;let sustained=relax>0&&inNote>holdMs?Math.min(1,(inNote-holdMs)/holdMs):0,tau=p.speed*(1+7*relax*sustained)+(sustained>0&&p.speed===0?40*relax*sustained:0),err=(shown2-c)*w;corr+=(err-corr)*lp(dtMs,tau),out[f]=corr+voicing*addedVibrato(p.vib??0,p.vibCents??0,inNote/1e3)}return out}function addedVibrato(rate2,depth,t,delay=.2){if(rate2<=0||depth<=0)return 0;let into=t-delay;return into<=0?0:depth*Math.min(1,into/.15)*Math.sin(2*Math.PI*rate2*into)}function guideCurve(curve,notes,p){let n2=curve.f0.length,out=new Float64Array(n2).fill(NaN),center=p.center??1,driftDefault=p.drift??.5,trans=p.glide??.04,dtMs=curve.hop*1e3,sorted=[...notes].sort((a,b)=>a.start-b.start),noteOf=new Int32Array(n2).fill(-1),sums=sorted.map(()=>({s:0,n:0})),cursor=0;for(let f=0;f<n2;f+=1){let hz3=curve.f0[f];if(!(hz3>0))continue;let t=curve.t0+f*curve.hop;for(;cursor<sorted.length&&sorted[cursor].end<=t;)cursor+=1;for(let k=cursor;k<sorted.length&&sorted[k].start<=t;k+=1){let note2=sorted[k];if(t>=note2.start&&t<note2.end){noteOf[f]=k,t>note2.start+.06&&(sums[k].s+=centsOfHz(hz3),sums[k].n+=1);break}}}let mean=sums.map(s=>s.n?s.s/s.n:NaN),slowArr=new Float64Array(n2).fill(NaN);{let a=lp(dtMs,150),f=0;for(;f<n2;){let k=noteOf[f];if(k<0){f+=1;continue}let e=f;for(;e<n2&¬eOf[e]===k;)e+=1;let y=Number.isNaN(mean[k])?centsOfHz(curve.f0[f]):mean[k];for(let g=f;g<e;g+=1)y+=(centsOfHz(curve.f0[g])-y)*a,slowArr[g]=y;y=Number.isNaN(mean[k])?slowArr[e-1]:mean[k];for(let g=e-1;g>=f;g-=1)y+=(slowArr[g]-y)*a,slowArr[g]=y;f=e}}let hard=p.speed!==void 0,amount=p.amount??1,relax=p.relax??0,holdMs=p.hold??150,slow=NaN,prevK=-1,corr=0,inNote=0;for(let f=0;f<n2;f+=1){let k=noteOf[f];if(k<0){slow=NaN,prevK=-1,corr=0,inNote=0;continue}let note2=sorted[k];k!==prevK&&(inNote=0),inNote+=dtMs;let c=centsOfHz(curve.f0[f]),want;if(note2.ghost)want=0;else if(hard){let sustained=relax>0&&inNote>holdMs?Math.min(1,(inNote-holdMs)/holdMs):0,glideMs=(note2.glide??0)*1e3,tau=Math.max(p.speed*(1+7*relax*sustained),glideMs/3),err=note2.cents-c;corr=prevK<0?err:corr+(err-corr)*lp(dtMs,tau),want=corr*amount}else{slow=slowArr[f];let m=Number.isNaN(mean[k])?c:mean[k],drift=note2.drift??driftDefault;want=amount*(center*(note2.cents-m)-drift*(slow-m))}let rate2=note2.vib??p.vib??0,depth=note2.vib!==void 0?(note2.vibmod??0)*100:p.vibCents??0,delay=note2.vib!==void 0?note2.vibDelay??0:.2;out[f]=note2.ghost?0:want+addedVibrato(rate2,depth,inNote/1e3,delay),prevK=k}let voiced=f=>noteOf[f]>=0;if(!hard){let src=Float64Array.from(out);for(let f=1;f<n2;f+=1){if(!voiced(f)||!voiced(f-1)||noteOf[f]===noteOf[f-1])continue;let into=sorted[noteOf[f]],width=into.glide??trans;if(width<=0||into.ghost||sorted[noteOf[f-1]].ghost)continue;let half=Math.max(1,Math.round(width/2/curve.hop)),a=Math.max(0,f-half),b=Math.min(n2-1,f+half-1),ok=!0;for(let g=a;g<=b;g+=1)voiced(g)||(ok=!1);if(!ok)continue;let pa=centsOfHz(curve.f0[a])+src[a],pb=centsOfHz(curve.f0[b])+src[b];for(let g=a;g<=b;g+=1){let u=(g-a)/Math.max(1,b-a);out[g]=pa+(pb-pa)*u-centsOfHz(curve.f0[g])}}}for(let f=0;f<n2;f+=1)voiced(f)&&!sorted[noteOf[f]].ghost&&(out[f]=out[f]*voicingWeight(curve,f));return out}function correctionCurve(curve,targets,r,maxShift=12){let vibCents=r.vibmod*100,shift=targets.kind==="grid"?retuneCurve(curve,targets.grid,{speed:r.speed??25,relax:r.relax,hold:r.hold,flex:r.flex,glide:r.glide,amount:r.amount,vib:r.vib,vibCents}):guideCurve(curve,targets.notes,{center:r.center,drift:r.drift,glide:r.glide,...r.speed!==void 0?{speed:r.speed}:{},amount:r.amount,relax:r.relax,hold:r.hold,vib:r.vib,vibCents}),cap=maxShift*100;for(let f=0;f<shift.length;f+=1)Number.isNaN(shift[f])||(shift[f]=Math.max(-cap,Math.min(cap,shift[f])));return shift}function perSampleShift(curve,shift,frames,sampleRate){let f0=new Float64Array(frames),cents=new Float64Array(frames),n2=curve.f0.length;for(let i=0;i<frames;i+=1){let pos=(i/sampleRate-curve.t0)/curve.hop,j=Math.floor(pos);if(j<0||j>=n2)continue;let u=pos-j,fa=curve.f0[j],fb=j+1<n2?curve.f0[j+1]:fa;f0[i]=fa>0&&fb>0?fa+(fb-fa)*u:u<.5?fa:fb;let a=shift[j],b=j+1<n2?shift[j+1]:a;Number.isNaN(a)&&Number.isNaN(b)?cents[i]=0:Number.isNaN(a)?cents[i]=b:Number.isNaN(b)?cents[i]=a:cents[i]=a+(b-a)*u}return{f0,cents}}var JOB_BLOCK=16384;function*autotuneJob(x,sampleRate,curve,targets,r,psola2,maxShift=12,psolaJob){let shift=correctionCurve(curve,targets,r,maxShift),moves=!1;for(let f=0;f<shift.length&&!moves;f+=1)Math.abs(shift[f])>1e-9&&(moves=!0);if(!moves)return x;yield;let input=new Float64Array(x.length);for(let i=0;i<x.length;i+=JOB_BLOCK){let end=Math.min(x.length,i+JOB_BLOCK);for(let j=i;j<end;j+=1)input[j]=x[j];yield}let per=perSampleShift(curve,shift,x.length,sampleRate);yield;let y=psolaJob?yield*psolaJob(input,sampleRate,per):psola2(input,sampleRate,per);return yield,Float32Array.from(y)}function trackSlug(name){let slug=name.normalize("NFKD").replace(new RegExp("\\p{M}+","gu"),"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,64).replace(/-+$/g,"");return slug.length>0?slug:"track"}var DEVICE_KINDS=["fx","synth","notes"],DEVICE_HASH=/^sha256:[0-9a-f]{64}$/,DEVICE_LIMITS=Object.freeze({maxBytes:1048576,maxPages:256,maxTypes:4096,maxFunctions:8192,maxGlobals:1024,maxExports:1024,maxTables:1,maxTableSize:65536,maxLocals:4096,maxNesting:1024,maxDepth:4096,initFuel:67108864,blockFuel:4194304,notesFuel:16777216,maxEvents:64,maxNotesIn:256,maxNotesOut:1024,maxNotesTotal:65536,maxSample:16}),DEVICE_IO=Object.freeze({params:0,inLeft:64,inRight:1088,outLeft:2112,outRight:3136,eventCount:4160,events:4168,eventBytes:32,audioBytes:6216,notesIn:64,notesOut:64+40*256,noteBytes:40,notesBytes:64+40*256+40*1024}),DeviceValidationError=class extends Error{constructor(message){super(message),this.name="DeviceValidationError"}},DeviceRuntimeError=class extends Error{constructor(message){super(message),this.name="DeviceRuntimeError"}},fail2=message=>{throw new DeviceValidationError(message)},Reader=class{constructor(bytes2,pos,end){this.bytes=bytes2;this.pos=pos;this.end=end}bytes;pos;end;get done(){return this.pos>=this.end}byte(){return this.pos>=this.end&&fail2("module ends inside a section"),this.bytes[this.pos++]}u32(){let result=0,shift=0;for(let i=0;i<5;i+=1){let b=this.byte();if(result+=(b&127)*2**shift,(b&128)===0)return result>4294967295&&fail2("integer out of range"),result;shift+=7}return fail2("integer is too long")}sleb(max){for(let i=0;i<max;i+=1)if((this.byte()&128)===0)return;fail2("integer is too long")}skip(n2){this.pos+n2>this.end&&fail2("module ends inside a section"),this.pos+=n2}name(){let length=this.u32();length>1024&&fail2("name is too long");let start=this.pos;this.skip(length);let text2="";for(let i=start;i<start+length;i+=1){let b=this.bytes[i];if(b<32||b>126)return`\0${length}`;text2+=String.fromCharCode(b)}return text2}},Writer=class{buf=new Uint8Array(1024);length=0;grow(n2){if(this.length+n2<=this.buf.length)return;let size=this.buf.length*2;for(;size<this.length+n2;)size*=2;let next=new Uint8Array(size);next.set(this.buf.subarray(0,this.length)),this.buf=next}byte(...values){this.grow(values.length);for(let v of values)this.buf[this.length++]=v;return this}u32(value){do{let b=value&127;value=Math.floor(value/128),value!==0&&(b|=128),this.byte(b)}while(value!==0);return this}sleb(value){for(;;){let b=(value%128+128)%128;value=Math.floor(value/128);let done=value===0&&(b&64)===0||value===-1&&(b&64)!==0;if(this.byte(done?b:b|128),done)return this}}bytes(data){return this.grow(data.length),this.buf.set(data,this.length),this.length+=data.length,this}section(id,body2){return this.byte(id).u32(body2.length),this.bytes(body2.result())}result(){return this.buf.subarray(0,this.length)}},VALTYPES=new Set([127,126,125,124,112,111]),ORDER2={1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,12:10,10:11,11:12};function valtype(r,label){let t=r.byte();return VALTYPES.has(t)||fail2(t===123?`${label}: SIMD values (v128) are not allowed`:`${label}: unsupported value type 0x${t.toString(16)}`),t}function limits(r,label){let flag=r.byte();flag&2&&fail2(`${label}: shared memory is not allowed`),flag&4&&fail2(`${label}: 64-bit memories and tables are not allowed`),flag>1&&fail2(`${label}: unsupported limits`);let min=r.u32();return flag===1?{min,max:r.u32()}:{min}}function parse(bytes2){let head=[0,97,115,109,1,0,0,0];(bytes2.length<8||head.some((b,i)=>bytes2[i]!==b))&&fail2("not a WebAssembly module (version 1)");let out={types:[],funcs:[],globals:0,exports:[],sections:[]},top=new Reader(bytes2,8,bytes2.length),last=0;for(;!top.done;){let id=top.byte(),size=top.u32(),start=top.pos;top.skip(size);let end=top.pos;if(id===0)continue;let order=ORDER2[id];order===void 0&&fail2(id===13?"exception handling (tag section) is not allowed":`unknown section ${id}`),order<=last&&fail2(`section ${id} is out of order`),last=order;let r=new Reader(bytes2,start,end);if(out.sections.push({id,start,end}),id===1){let n2=r.u32();n2>DEVICE_LIMITS.maxTypes&&fail2("too many types");for(let i=0;i<n2;i+=1){r.byte()!==96&&fail2("only function types are allowed");let params2=Array.from({length:r.u32()},()=>valtype(r,"type")),results=Array.from({length:r.u32()},()=>valtype(r,"type"));out.types.push({params:params2,results})}}else if(id===2)r.u32()!==0&&fail2("a device may not import anything (no host functions, WASI, memory, tables or globals)");else if(id===3){let n2=r.u32();n2>DEVICE_LIMITS.maxFunctions&&fail2("too many functions");for(let i=0;i<n2;i+=1){let t=r.u32();t>=out.types.length&&fail2("function names a missing type"),out.funcs.push(t)}}else if(id===4){let n2=r.u32();n2>DEVICE_LIMITS.maxTables&&fail2(`at most ${DEVICE_LIMITS.maxTables} table`);for(let i=0;i<n2;i+=1){let t=r.byte();t!==112&&t!==111&&fail2("tables must hold funcref or externref"),limits(r,"table").min>DEVICE_LIMITS.maxTableSize&&fail2("table is too large")}}else if(id===5){r.u32()!==1&&fail2("a device defines exactly one memory");let l=limits(r,"memory");l.max===void 0&&fail2(`memory needs a maximum (at most ${DEVICE_LIMITS.maxPages} pages)`),l.max>DEVICE_LIMITS.maxPages&&fail2(`memory maximum ${l.max} pages exceeds ${DEVICE_LIMITS.maxPages} (16 MiB)`),l.min>l.max&&fail2("memory minimum exceeds its maximum"),out.memory={min:l.min,max:l.max}}else if(id===6)out.globals=r.u32(),out.globals>DEVICE_LIMITS.maxGlobals&&fail2("too many globals");else if(id===7){let n2=r.u32();n2>DEVICE_LIMITS.maxExports&&fail2("too many exports");for(let i=0;i<n2;i+=1){let name=r.name(),kind=r.byte(),index=r.u32();name.startsWith("__dawn")&&fail2(`export ${name} uses a reserved name`),out.exports.push({name,kind,index})}}else id===8?fail2("a device may not have a start function; do setup in init"):id===10&&(out.code={id,start,end})}return out}function canonicalAfter(op){return op>=141&&op<=151||op===182?32:op>=155&&op<=165||op===187?64:0}function decode(r,at3){let start=r.pos,op=r.byte(),sub=-1,memarg=()=>{r.u32()&64&&fail2(`${at3}: multiple memories are not allowed`),r.u32()},zero2=()=>{r.byte()!==0&&fail2(`${at3}: multiple memories are not allowed`)},blocktype=()=>{let b=r.bytes[r.pos];b===64||b!==void 0&&VALTYPES.has(b)?r.pos+=1:b===123?fail2(`${at3}: SIMD values (v128) are not allowed`):r.sleb(5)};if(op===2||op===3||op===4)blocktype();else if(op===12||op===13||op>=32&&op<=36||op===16||op===37||op===38||op===210)r.u32();else if(op===14){let n2=r.u32();n2>65536&&fail2(`${at3}: br_table is too long`);for(let i=0;i<=n2;i+=1)r.u32()}else if(op===17)r.u32(),r.u32();else if(op===28)r.u32()!==1&&fail2(`${at3}: typed select takes one type`),valtype(r,at3);else if(op>=40&&op<=62)memarg();else if(op===63||op===64)zero2();else if(op===65)r.sleb(5);else if(op===66)r.sleb(10);else if(op===67)r.skip(4);else if(op===68)r.skip(8);else if(op===208){let t=r.byte();t!==112&&t!==111&&fail2(`${at3}: unsupported reference type`)}else op===252?(sub=r.u32(),sub<=7||(sub===8?(r.u32(),zero2()):sub===9?r.u32():sub===10?(zero2(),zero2()):sub===11?zero2():fail2(`${at3}: table bulk operations (0xfc ${sub}) are not allowed`))):op===253?fail2(`${at3}: SIMD is not allowed (non-deterministic NaN and relaxed operations)`):op===254?fail2(`${at3}: threads and atomics are not allowed`):op===18||op===19?fail2(`${at3}: tail calls are not allowed`):op===0||op===1||op===5||op===11||op===15||op===26||op===27||op>=69&&op<=196||op===209||fail2(`${at3}: instruction 0x${op.toString(16)} is not allowed`);return{op,sub,start,end:r.pos}}function charge(w,fuel,amount){w.byte(35).u32(fuel).byte(66).sleb(amount).byte(125,36).u32(fuel),check(w,fuel)}function check(w,fuel){w.byte(35).u32(fuel).byte(66,0,83,4,64,0,11)}function rewriteBody(bytes2,start,end,type,index,rw){let at3=`function ${index}`,r=new Reader(bytes2,start,end),groups=r.u32(),locals=type.params.length,decls=new Writer;for(let i=0;i<groups;i+=1){let n2=r.u32();locals+=n2,locals>DEVICE_LIMITS.maxLocals&&fail2(`${at3}: more than ${DEVICE_LIMITS.maxLocals} locals`),decls.u32(n2).byte(valtype(r,at3))}let f32=locals,f64=locals+1,i32=locals+2,weight=1+Math.floor(locals/8),exprStart=r.pos,costs=[],fnCost=0,stack=[];for(;;){let ins=decode(r,at3),loop=stack.length>0?stack[stack.length-1]:-1;if(loop<0?fnCost+=1:costs[loop]+=1,ins.op===2||ins.op===4)stack.push(loop);else if(ins.op===3)stack.push(costs.length),costs.push(0);else if(ins.op===11){if(stack.length===0)break;stack.pop()}stack.length>DEVICE_LIMITS.maxNesting&&fail2(`${at3}: blocks nest too deeply`)}r.pos!==end&&fail2(`${at3}: code after the function's end`);let w=new Writer;w.u32(groups+3).bytes(decls.result()),w.byte(1,125,1,124,1,127),w.byte(35).u32(rw.depth).byte(65).sleb(weight).byte(106,36).u32(rw.depth),w.byte(35).u32(rw.depth).byte(65).sleb(DEVICE_LIMITS.maxDepth),w.byte(75,4,64,0,11),charge(w,rw.fuel,fnCost),w.byte(2),type.results.length===0?w.byte(64):type.results.length===1?w.byte(type.results[0]):w.sleb(rw.blockTypes.get(type.results.join(",")));let q3=new Reader(bytes2,exprStart,end),nesting=0,loopIndex=0;for(;;){let ins=decode(q3,at3),op=ins.op;if(op===15){w.byte(12).u32(nesting);continue}if(op===252&&(ins.sub===8||ins.sub===10||ins.sub===11)&&(w.byte(34).u32(i32),w.byte(35).u32(rw.fuel).byte(32).u32(i32).byte(173,66,4,136,125,36).u32(rw.fuel),check(w,rw.fuel)),w.bytes(bytes2.subarray(ins.start,ins.end)),op===2||op===4)nesting+=1;else if(op===3)nesting+=1,charge(w,rw.fuel,costs[loopIndex++]);else if(op===11){if(nesting===0)break;nesting-=1}let canon=canonicalAfter(op);canon===32?w.byte(34).u32(f32).byte(67,0,0,192,127,32).u32(f32).byte(32).u32(f32).byte(91,27):canon===64&&w.byte(34).u32(f64).byte(68,0,0,0,0,0,0,248,127,32).u32(f64).byte(32).u32(f64).byte(97,27)}return w.byte(35).u32(rw.depth).byte(65).sleb(weight).byte(107,36).u32(rw.depth),w.byte(11),w.result()}var SIGNATURES={init:"7c>7f",process:"7f>7f",render:"7f>7f",transform:"7f>7f"},ENTRY={fx:"process",synth:"render",notes:"transform"};function instrumentDevice(bytes2){bytes2 instanceof Uint8Array||fail2("a device must be bytes"),bytes2.length>DEVICE_LIMITS.maxBytes&&fail2(`module is ${bytes2.length} bytes; at most ${DEVICE_LIMITS.maxBytes}`);let m=parse(bytes2);m.memory||fail2("a device defines exactly one memory");let exported=new Map;for(let e of m.exports)exported.set(e.name,e);let memory2=exported.get("memory");(!memory2||memory2.kind!==2||memory2.index!==0)&&fail2('a device exports its memory as "memory"');let kinds=DEVICE_KINDS.filter(kind2=>exported.has(ENTRY[kind2]));kinds.length!==1&&fail2("a device exports exactly one of process (fx), render (synth) or transform (notes)");let kind=kinds[0];for(let name of["init",ENTRY[kind]]){let e=exported.get(name);(!e||e.kind!==0)&&fail2(`a device exports a function "${name}"`);let type=m.types[m.funcs[e.index]??-1];type||fail2(`export ${name} is not a defined function`),`${type.params.map(t=>t.toString(16)).join(",")}>${type.results.map(t=>t.toString(16)).join(",")}`!==SIGNATURES[name]&&fail2(name==="init"?"init takes the sample rate (f64) and returns the I/O pointer (i32)":`${name} takes an i32 and returns an i32 status`)}!m.code&&m.funcs.length>0&&fail2("module has no code section");let types=[...m.types],blockTypes=new Map;for(let t of m.funcs){let results=m.types[t].results;if(results.length<2)continue;let key=results.join(",");if(blockTypes.has(key))continue;let found=types.findIndex(x=>x.params.length===0&&x.results.join(",")===key);found<0&&(found=types.length,types.push({params:[],results})),blockTypes.set(key,found)}let rw={fuel:m.globals,depth:m.globals+1,blockTypes},out=new Writer().byte(0,97,115,109,1,0,0,0),wroteGlobals=!1,globals=()=>{if(wroteGlobals)return;wroteGlobals=!0;let g=new Writer().u32(m.globals+2),old=m.sections.find(s=>s.id===6);if(old){let r=new Reader(bytes2,old.start,old.end);r.u32(),g.bytes(bytes2.subarray(r.pos,old.end))}g.byte(126,1,66,0,11),g.byte(127,1,65,0,11),out.section(6,g)};for(let s of m.sections)if(ORDER2[s.id]>=ORDER2[6]&&globals(),s.id!==6)if(s.id===1){let w=new Writer().u32(types.length),r=new Reader(bytes2,s.start,s.end);r.u32(),w.bytes(bytes2.subarray(r.pos,s.end));for(let t of types.slice(m.types.length))w.byte(96).u32(0).u32(t.results.length).byte(...t.results);out.section(1,w)}else if(s.id===7){let w=new Writer().u32(m.exports.length+2),r=new Reader(bytes2,s.start,s.end);r.u32(),w.bytes(bytes2.subarray(r.pos,s.end));for(let[name,index]of[["__dawn_fuel",rw.fuel],["__dawn_depth",rw.depth]]){w.u32(name.length);for(let c of name)w.byte(c.charCodeAt(0));w.byte(3).u32(index)}out.section(7,w)}else if(s.id===10){let r=new Reader(bytes2,s.start,s.end),n2=r.u32();n2!==m.funcs.length&&fail2("code and function counts differ");let w=new Writer().u32(n2);for(let i=0;i<n2;i+=1){let size=r.u32(),start=r.pos;r.skip(size);let body2=rewriteBody(bytes2,start,r.pos,m.types[m.funcs[i]],i,rw);w.u32(body2.length).bytes(body2)}r.done||fail2("code section has trailing bytes"),out.section(10,w)}else out.section(s.id,new Writer().bytes(bytes2.subarray(s.start,s.end)));return globals(),Object.freeze({kind,pages:Object.freeze({...m.memory}),functions:m.funcs.length,bytes:bytes2.length,instrumented:out.result()})}function compileDevice(bytes2){let device=instrumentDevice(bytes2);WebAssembly.validate(bytes2)||fail2("module does not pass WebAssembly validation");let module;try{module=new WebAssembly.Module(device.instrumented)}catch(error){fail2(`module does not compile: ${error instanceof Error?error.message:String(error)}`.slice(0,300))}let{instrumented:_instrumented,...info}=device;return Object.freeze({...info,module})}var Device=class{constructor(compiled,sampleRate,label="device"){this.label=label;this.kind=compiled.kind;let instance;try{instance=new WebAssembly.Instance(compiled.module,{})}catch(error){throw new DeviceRuntimeError(`${label} could not start: ${error instanceof Error?error.message:String(error)}`.slice(0,300))}this.x=instance.exports;let io=this.call(this.x.init,sampleRate,DEVICE_LIMITS.initFuel,"init"),size=this.kind==="notes"?DEVICE_IO.notesBytes:DEVICE_IO.audioBytes;(io<=0||io%8!==0||io+size>this.x.memory.buffer.byteLength)&&this.die(`init returned I/O pointer ${io}; it must be 8-byte aligned, above 0 and leave ${size} bytes in memory`),this.io=io}label;kind;params=new Float64Array(8);x;io;failed;seen=0;returned=0;die(message){throw this.failed??=new DeviceRuntimeError(`${this.label}: ${message}`),this.failed}call(fn,arg,fuel,what){if(this.failed)throw this.failed;this.x.__dawn_fuel.value=BigInt(fuel),this.x.__dawn_depth.value=0;try{return fn(arg)}catch(error){throw this.x.__dawn_fuel.value<0n&&this.die(`${what} ran past its budget of ${fuel} instructions`),this.x.__dawn_depth.value>DEVICE_LIMITS.maxDepth&&this.die(`${what} recursed past the call depth limit`),error instanceof WebAssembly.RuntimeError&&this.die(`${what} trapped (${error.message})`.slice(0,300)),error instanceof RangeError&&this.die(`${what} exhausted the host stack`),error}}view(){return new DataView(this.x.memory.buffer,this.io)}block(inLeft,inRight,events,outLeft,outRight){this.kind==="notes"&&this.die("a note device has no audio block");let v=this.view();for(let i=0;i<8;i+=1)v.setFloat64(DEVICE_IO.params+8*i,finiteOr0(this.params[i]),!0);for(let i=0;i<128;i+=1)v.setFloat64(DEVICE_IO.inLeft+8*i,finiteOr0(inLeft?.[i]??0),!0),v.setFloat64(DEVICE_IO.inRight+8*i,finiteOr0(inRight?.[i]??inLeft?.[i]??0),!0),v.setFloat64(DEVICE_IO.outLeft+8*i,0,!0),v.setFloat64(DEVICE_IO.outRight+8*i,0,!0);events.length>DEVICE_LIMITS.maxEvents&&this.die("too many events in one block"),v.setInt32(DEVICE_IO.eventCount,events.length,!0),events.forEach((e,i)=>{let at3=DEVICE_IO.events+DEVICE_IO.eventBytes*i;v.setInt32(at3,e.frame,!0),v.setInt32(at3+4,e.on?1:0,!0),v.setInt32(at3+8,e.voice,!0),v.setInt32(at3+12,e.note,!0),v.setFloat64(at3+16,e.velocity,!0),v.setFloat64(at3+24,e.hz,!0)});let fn=this.kind==="fx"?this.x.process:this.x.render,status=this.call(fn,128,DEVICE_LIMITS.blockFuel,this.kind==="fx"?"process":"render");status!==0&&this.die(`${this.kind==="fx"?"process":"render"} returned status ${status}`);let after=this.view(),max=DEVICE_LIMITS.maxSample;for(let i=0;i<128;i+=1)outLeft[i]=clampSample(after.getFloat64(DEVICE_IO.outLeft+8*i,!0),max),outRight[i]=clampSample(after.getFloat64(DEVICE_IO.outRight+8*i,!0),max)}transform(notes){this.kind!=="notes"&&this.die("only a note device transforms notes"),notes.length>DEVICE_LIMITS.maxNotesIn&&this.die("too many notes in one call");let v=this.view();for(let i=0;i<8;i+=1)v.setFloat64(DEVICE_IO.params+8*i,finiteOr0(this.params[i]),!0);notes.forEach((n2,i)=>{let at3=DEVICE_IO.notesIn+DEVICE_IO.noteBytes*i;v.setFloat64(at3,n2.start,!0),v.setFloat64(at3+8,n2.length,!0),v.setFloat64(at3+16,n2.pitch,!0),v.setFloat64(at3+24,n2.velocity,!0),v.setInt32(at3+32,n2.source,!0),v.setInt32(at3+36,0,!0)}),this.seen=Math.max(this.seen,...notes.map(n2=>n2.source+1));let count2=this.call(this.x.transform,notes.length,DEVICE_LIMITS.notesFuel,"transform");count2<0&&this.die(`transform returned status ${count2}`),count2>DEVICE_LIMITS.maxNotesOut&&this.die(`transform returned ${count2} notes; at most ${DEVICE_LIMITS.maxNotesOut} per call`),this.returned+=count2,this.returned>DEVICE_LIMITS.maxNotesTotal&&this.die(`transform returned more than ${DEVICE_LIMITS.maxNotesTotal} notes in all`);let after=this.view(),out=[];for(let i=0;i<count2;i+=1){let at3=DEVICE_IO.notesOut+DEVICE_IO.noteBytes*i,note2={start:after.getFloat64(at3,!0),length:after.getFloat64(at3+8,!0),pitch:after.getFloat64(at3+16,!0),velocity:after.getFloat64(at3+24,!0),source:after.getInt32(at3+32,!0)};(!Number.isFinite(note2.start)||note2.start<0||note2.start>2**40||!Number.isFinite(note2.length)||note2.length<=0||note2.length>2**40||!Number.isFinite(note2.pitch)||note2.pitch<0||note2.pitch>127||!Number.isFinite(note2.velocity)||note2.velocity<0||note2.velocity>1||note2.source<0||note2.source>=this.seen)&&this.die(`transform returned an invalid note at index ${i}`),out.push(note2)}return out}},finiteOr0=x=>Number.isFinite(x)?x:0,clampSample=(x,max)=>Number.isFinite(x)?Math.max(-max,Math.min(max,x)):0;function editDistance(a,b){let before=[],previous=Array.from({length:b.length+1},(_,index)=>index);for(let i=1;i<=a.length;i+=1){let row2=[i];for(let j=1;j<=b.length;j+=1){let cost=a[i-1]===b[j-1]?0:1,best=Math.min(previous[j]+1,row2[j-1]+1,previous[j-1]+cost);i>1&&j>1&&a[i-1]===b[j-2]&&a[i-2]===b[j-1]&&(best=Math.min(best,before[j-2]+1)),row2.push(best)}before=previous,previous=row2}return previous[b.length]}function nearest(word2,vocabulary){let typed=word2.trim().toLowerCase();if(!typed)return;let limit=typed.length<=4?1:2,best;for(let candidate of vocabulary){let lower=candidate.toLowerCase();if(lower===typed)return;let distance=editDistance(typed,lower);distance<=limit&&(!best||distance<best.distance)&&(best={word:candidate,distance})}return best?.word}var num6=(min,max,value,doc,extra={})=>Object.freeze({kind:"number",min,max,default:value,step:(max-min)/100,doc,...extra}),audioIn=(name,doc,extra={})=>Object.freeze({name,kind:"audio",doc,...extra}),audioOut=(name="out",doc="audio out")=>Object.freeze({name,kind:"audio",doc}),controlOut=(doc,name="out")=>Object.freeze({name,kind:"control",doc}),controlIn=(name,spec,extra={})=>Object.freeze({name,kind:"control",spec,doc:spec.doc,...extra});function paramsOf(inputs2,extra={}){let out={...extra};for(let port2 of inputs2)port2.spec&&(out[port2.name]=port2.spec);return Object.freeze(out)}function node(spec){let{settings,...rest}=spec;return Object.freeze({rate:"any",process:"block",...rest,inputs:Object.freeze([...spec.inputs]),outputs:Object.freeze([...spec.outputs]),params:paramsOf(spec.inputs,settings)})}var enumParam=(values,value,doc)=>Object.freeze({kind:"enum",values,default:value,doc}),HZ={unit:"Hz",step:"log"},SEC={unit:"s"},pitch=(value=440)=>num6(0,2e4,value,"frequency in Hz (wire voice.pitch to play the note)",HZ),cutoff=(value=1e3)=>num6(20,2e4,value,"cutoff frequency in Hz",HZ),binary=(name,doc)=>node({type:name,family:name==="gt"||name==="lt"?"logic":"math",doc,inputs:[controlIn("a",num6(-1e6,1e6,0,"first operand")),controlIn("b",num6(-1e6,1e6,name==="mul"?1:0,"second operand"))],outputs:[controlOut("result")],cost:1}),unary=(name,doc,family="math")=>node({type:name,family,doc,inputs:[controlIn("in",num6(-1e6,1e6,0,"input"))],outputs:[controlOut("result")],cost:name==="pitch2hz"||name==="db2gain"?8:1}),HAND_NODES=[node({type:"osc",family:"source",doc:"oscillator: sine, saw, square, triangle or pulse, with linear FM",inputs:[controlIn("pitch",pitch(),{audioRate:!0}),controlIn("detune",num6(-1200,1200,0,"detune in cents",{unit:"ct"})),controlIn("pw",num6(.01,.99,.5,"pulse width (pulse wave)"),{smooth:!0}),audioIn("fm","linear FM: Hz added to the pitch, at audio rate",{audioRate:!0}),controlIn("level",num6(0,4,1,"output level"),{smooth:!0})],outputs:[audioOut()],settings:{wave:enumParam(["sine","saw","square","tri","pulse"],"saw","waveform (saw, square and pulse are band-limited with PolyBLEP)")},cost:12}),node({type:"noise",family:"source",doc:"seeded noise: white, pink or brown",inputs:[controlIn("level",num6(0,4,1,"output level"),{smooth:!0})],outputs:[audioOut()],settings:{color:enumParam(["white","pink","brown"],"white","noise color")},cost:6}),node({type:"svf",family:"filter",doc:"state-variable filter (TPT): low, high, band or notch",inputs:[audioIn("in","audio in"),controlIn("cutoff",cutoff(),{smooth:!0}),controlIn("q",num6(0,1,.5,"resonance 0..1"),{smooth:!0})],outputs:[audioOut()],settings:{mode:enumParam(["lp","hp","bp","notch"],"lp","filter response")},cost:14}),node({type:"onepole",family:"filter",doc:"one-pole low- or high-pass (6 dB/oct)",inputs:[audioIn("in","audio in"),controlIn("cutoff",cutoff(),{smooth:!0})],outputs:[audioOut()],settings:{mode:enumParam(["lp","hp"],"lp","filter response")},cost:4}),node({type:"adsr",family:"envelope",doc:"attack, decay, sustain, release envelope 0..1, opened by a gate",inputs:[controlIn("gate",num6(0,1,0,"gate: above 0.5 opens (wire voice.gate)")),controlIn("attack",num6(0,10,.01,"attack time",SEC)),controlIn("decay",num6(0,10,.1,"decay time",SEC)),controlIn("sustain",num6(0,1,.7,"sustain level")),controlIn("release",num6(0,10,.2,"release time",SEC))],outputs:[controlOut("envelope 0..1")],cost:4}),node({type:"ar",family:"envelope",doc:"attack-release envelope 0..1 that follows a gate",inputs:[controlIn("gate",num6(0,1,0,"gate: above 0.5 opens")),controlIn("attack",num6(0,10,.01,"attack time",SEC)),controlIn("release",num6(0,10,.2,"release time",SEC))],outputs:[controlOut("envelope 0..1")],cost:3}),node({type:"slew",family:"envelope",doc:"slew limiter: glides a control toward its input",inputs:[controlIn("in",num6(-1e6,1e6,0,"input")),controlIn("rise",num6(0,10,.05,"time to rise by one unit",SEC)),controlIn("fall",num6(0,10,.05,"time to fall by one unit",SEC))],outputs:[controlOut("slewed value")],cost:2}),node({type:"follow",family:"envelope",doc:"envelope follower: the level of an audio signal as a control",inputs:[audioIn("in","audio to follow"),controlIn("attack",num6(1e-4,1,.005,"attack time",SEC)),controlIn("release",num6(.001,4,.1,"release time",SEC))],outputs:[controlOut("level 0..1")],cost:3}),node({type:"lfo",family:"modulator",doc:"low-frequency oscillator -1..1, free in Hz or synced to beats",inputs:[controlIn("rate",num6(0,100,1,"rate in Hz (when sync is 0)",HZ)),controlIn("phase",num6(0,1,0,"phase offset in cycles")),controlIn("depth",num6(0,1,1,"output depth"))],outputs:[controlOut("-1..1")],settings:{shape:enumParam(["sine","tri","square","saw","ramp","random"],"sine","wave shape (random is seeded sample-and-hold per cycle)"),sync:num6(0,64,0,"period in beats; 0 follows rate",{unit:"beats",step:.25})},cost:3}),node({type:"sh",family:"modulator",doc:"sample and hold: latches its input when the trigger rises",inputs:[controlIn("in",num6(-1e6,1e6,0,"value to sample")),controlIn("trig",num6(0,1,0,"trigger: a rise through 0.5 samples"))],outputs:[controlOut("held value")],cost:1}),node({type:"random",family:"modulator",doc:"seeded random value 0..1, drawn per note or per block",inputs:[],outputs:[controlOut("0..1")],settings:{per:enumParam(["note","block"],"note","when a new value is drawn")},cost:1}),node({type:"const",family:"math",doc:"a constant control value",inputs:[],outputs:[controlOut("the value")],settings:{value:num6(-1e6,1e6,0,"the value")},cost:0}),binary("add","a + b"),binary("mul","a \xD7 b"),binary("min","the smaller of a and b"),binary("max","the larger of a and b"),binary("gt","1 when a > b, else 0"),binary("lt","1 when a < b, else 0"),unary("abs","|in|"),unary("not","1 when in < 0.5, else 0","logic"),unary("pitch2hz","MIDI note number to Hz (12-TET, A4 = 440)"),unary("db2gain","decibels to linear gain"),node({type:"scale",family:"math",doc:"maps in from [inmin, inmax] to [min, max], linear or exponential",inputs:[controlIn("in",num6(-1e6,1e6,0,"input")),controlIn("inmin",num6(-1e6,1e6,-1,"input range low")),controlIn("inmax",num6(-1e6,1e6,1,"input range high")),controlIn("min",num6(-1e6,1e6,0,"output range low")),controlIn("max",num6(-1e6,1e6,1,"output range high"))],outputs:[controlOut("mapped value")],settings:{curve:enumParam(["lin","exp"],"lin","lin or exp (exp needs min > 0)")},cost:3}),node({type:"clamp",family:"math",doc:"limits in to [min, max]",inputs:[controlIn("in",num6(-1e6,1e6,0,"input")),controlIn("min",num6(-1e6,1e6,0,"low limit")),controlIn("max",num6(-1e6,1e6,1,"high limit"))],outputs:[controlOut("clamped value")],cost:1}),node({type:"clock",family:"logic",doc:"tempo-synced gate: high for the first half of each cycle",inputs:[controlIn("width",num6(.01,.99,.5,"high fraction"))],outputs:[controlOut("gate 0/1")],settings:{beats:num6(.0625,64,1,"period in beats",{unit:"beats",step:.25})},rate:"global",cost:1}),node({type:"vca",family:"mix",doc:"amplifier: audio times gain (wire an envelope to gain)",inputs:[audioIn("in","audio in"),controlIn("gain",num6(0,4,1,"gain"),{audioRate:!0})],outputs:[audioOut()],cost:1}),node({type:"mix",family:"mix",doc:"four-input audio mixer with a level per input",inputs:[audioIn("a","input a"),audioIn("b","input b"),audioIn("c","input c"),audioIn("d","input d"),controlIn("la",num6(0,4,1,"level of a"),{smooth:!0}),controlIn("lb",num6(0,4,1,"level of b"),{smooth:!0}),controlIn("lc",num6(0,4,1,"level of c"),{smooth:!0}),controlIn("ld",num6(0,4,1,"level of d"),{smooth:!0})],outputs:[audioOut()],cost:4}),node({type:"xfade",family:"mix",doc:"equal-gain crossfade from a (x = 0) to b (x = 1)",inputs:[audioIn("a","input a"),audioIn("b","input b"),controlIn("x",num6(0,1,.5,"crossfade position"),{smooth:!0})],outputs:[audioOut()],cost:2}),node({type:"pan",family:"mix",doc:"equal-power pan of a mono signal to left and right",inputs:[audioIn("in","audio in"),controlIn("pan",num6(-1,1,0,"-1 left .. 1 right"),{smooth:!0})],outputs:[audioOut("left","left out"),audioOut("right","right out")],cost:3}),node({type:"voicesum",family:"mix",doc:"explicit voice sum: every voice's input, summed once for the track",inputs:[audioIn("in","per-voice audio")],outputs:[audioOut()],rate:"global",cost:1})];function splitParams(params2){let controls2=[],settings={};for(let[name,spec]of Object.entries(params2))spec.kind==="number"?controls2.push(controlIn(name,spec,{smooth:!0})):settings[name]=spec;return{controls:controls2,settings}}var PAN_STAGE=FX_CHAIN.indexOf("pan"),MIX_STAGES=new Set(["orbit","duck"]);function isStereoStage(stage){return FX_CHAIN.indexOf(stage)>PAN_STAGE}var FX_NODES=FX_CHAIN.filter(stage=>stage!=="pan"&&!MIX_STAGES.has(stage)).map(stage=>{let spec=effectSpec(stage),{controls:controls2,settings}=splitParams(spec.params),stereo=isStereoStage(stage);return node({type:`fx.${stage}`,family:"effect",doc:spec.doc,inputs:stereo?[audioIn("left","left in"),audioIn("right","right in"),...controls2]:[audioIn("in","audio in"),...controls2],outputs:stereo?[audioOut("left","left out"),audioOut("right","right out")]:[audioOut()],settings,rate:"global",process:"buffer",cost:40})}),ENGINE_TABLES=[{type:"engine.synth",doc:"the whole synth voice (oscillators, FM, unison, filters, envelopes), samplers and wavetables included",lanes:SYNTH_LANE_PARAMS,binding:{fields:["synth","wavetable","sampler"],instruments:[]},cost:120},{type:"engine.modal",doc:"modal resonators: mallets, bars, bells and plates",lanes:MODAL_LANE_PARAMS,binding:{fields:["modal"],instruments:["modal"]},cost:200},{type:"engine.string",doc:"physically modeled plucked and bowed strings",lanes:STRING_LANE_PARAMS,binding:{fields:["string"],instruments:["string"]},cost:160},{type:"engine.wind",doc:"physically modeled winds and brass",lanes:WIND_LANE_PARAMS,binding:{fields:["wind"],instruments:["wind"]},cost:160},{type:"engine.sing",doc:"the singing voice (lyrics, formants, choir)",lanes:SING_LANE_PARAMS,binding:{fields:["sing"],instruments:["sing"]},cost:400},{type:"engine.granular",doc:"granular player over a sample or the track's own source",lanes:GRANULAR_LANE_PARAMS,binding:{fields:["granular"],instruments:["granular"]},cost:300},{type:"engine.keys",doc:"modeled pianos, electric keys and organs",lanes:KEYS_LANE_PARAMS,binding:{fields:["keys"],instruments:[...KEYS_FAMILIES]},cost:250},{type:"engine.vocoder",doc:"the vocoder's built-in carrier (saw, supersaw, pulse or noise) following the notes",lanes:[],binding:{fields:["vocoder"],instruments:["vocoder"]},cost:60},{type:"engine.texture",doc:"seeded DSP textures: room, rain, wind, vinyl, tape, hum, city, crowd, data and air",lanes:TEXTURE_LANE_PARAMS,binding:{fields:["texture"],instruments:["texture"]},cost:150}],ENGINE_NODES=ENGINE_TABLES.map(table2=>node({type:table2.type,family:"engine",doc:table2.doc,inputs:[Object.freeze({name:"notes",kind:"notes",doc:"the notes to play (wire in.notes)"}),...table2.lanes.map(({param:param2,spec})=>controlIn(param2,spec))],outputs:[audioOut("out","audio out (left when stereo)"),audioOut("right","right out (equals out for a mono engine)")],settings:{instrument:Object.freeze({kind:"enum",values:table2.binding.instruments,default:table2.binding.instruments[0]??"",doc:"which instrument of this engine plays"})},rate:"global",process:"buffer",engine:Object.freeze({fields:Object.freeze([...table2.binding.fields]),instruments:Object.freeze([...table2.binding.instruments])}),cost:table2.cost})),DEVICE_CONTROLS=Array.from({length:8},(_,i)=>controlIn(`p${i+1}`,num6(0,1,0,`device control ${i+1}, read once per 128-frame block`))),DEVICE_PARAM=Object.freeze({device:enumParam([],"","the device's content hash, sha256:<64 hex digits> of its .wasm file")}),DEVICE_NODES=[node({type:"device.fx",family:"effect",doc:"a WebAssembly effect device: stereo in, stereo out",inputs:[audioIn("left","left in"),audioIn("right","right in; unwired, left feeds both"),...DEVICE_CONTROLS],outputs:[audioOut("left","left out"),audioOut("right","right out")],settings:DEVICE_PARAM,rate:"global",process:"buffer",cost:60}),node({type:"device.synth",family:"source",doc:"a WebAssembly synth device: plays the patch's notes",inputs:[Object.freeze({name:"notes",kind:"notes",doc:"the notes to play (wire in.notes)"}),...DEVICE_CONTROLS],outputs:[audioOut("out","left out"),audioOut("right","right out")],settings:DEVICE_PARAM,rate:"global",process:"buffer",cost:120}),node({type:"device.notes",family:"logic",doc:"a WebAssembly note device: rewrites the notes the whole patch plays",inputs:[Object.freeze({name:"notes",kind:"notes",doc:"the track's notes (wire in.notes)"}),...DEVICE_CONTROLS],outputs:[Object.freeze({name:"notes",kind:"notes",doc:"the rewritten notes, which every voice and device.synth plays"})],settings:DEVICE_PARAM,rate:"global",process:"buffer",cost:0})],NODE_SPECS=Object.freeze(Object.fromEntries([...HAND_NODES,...ENGINE_NODES,...FX_NODES,...DEVICE_NODES].map(spec=>[spec.type,spec]))),NODE_TYPES=Object.freeze(Object.keys(NODE_SPECS)),BOUNDARY_SPECS=Object.freeze({in:node({type:"in",family:"mix",doc:"the patch's inputs from the track",inputs:[],outputs:[Object.freeze({name:"notes",kind:"notes",doc:"the track's notes (instrument)"}),audioOut("audio","the track's audio (effect patch)"),audioOut("right","the track's right channel (stereo effect patch)"),audioOut("side","the sidechain track's audio (patch `side`)")],rate:"global",cost:0}),out:node({type:"out",family:"mix",doc:"the patch's output to the track",inputs:[audioIn("audio","audio out (mono, or left when right is wired)"),audioIn("right","right channel; unwired, audio plays on both")],outputs:[],rate:"global",cost:0}),voice:node({type:"voice",family:"source",doc:"per-voice sources, one set per playing note",inputs:[],outputs:[controlOut("the note's frequency in Hz (tuned, with glide)","pitch"),controlOut("the note's MIDI number","note"),controlOut("1 while the note is held, then 0","gate"),controlOut("velocity 0..1","velocity"),controlOut("phase 0..1 per cycle of the note's pitch","phase"),controlOut("seeded random 0..1, fixed for the note","random"),controlOut("voice slot index","index"),controlOut("seconds since the note began","age")],rate:"voice",cost:1}),song:node({type:"song",family:"source",doc:"global time and the track's automation",inputs:[],outputs:[controlOut("song position in beats","beat"),controlOut("position in the bar 0..1","bar.phase"),controlOut("tempo in BPM","tempo")],rate:"global",cost:0})}),BOUNDARY_IDS=Object.freeze(Object.keys(BOUNDARY_SPECS));function nodeSpec(type){return Object.prototype.hasOwnProperty.call(NODE_SPECS,type)?NODE_SPECS[type]:void 0}function findPort(spec,name,dir){return(dir==="in"?spec.inputs:spec.outputs).find(port2=>port2.name===name)}var PATCH_INSTRUMENT="patch",PATCH_LIMITS=Object.freeze({maxNodes:64,maxCables:128,maxMacros:16,maxPatches:32,maxDepth:3,maxVoices:32,defaultVoices:16,maxIdLength:32,maxNameLength:64,maxLabelLength:48,maxFxPatches:4});function isPatchRef(value){return"ref"in value}var PatchValidationError=class extends FxValidationError{constructor(message){super(message),this.name="PatchValidationError"}},ID=/^[a-z][a-z0-9-]*$/,NAME=/^[a-z0-9][a-z0-9-]*$/;function fail3(message){throw new PatchValidationError(message)}function suggest2(word2,vocabulary){let match=nearest(word2,vocabulary);return match?` (did you mean "${match}"?)`:""}function checkId(value,label){return(typeof value!="string"||value.length>PATCH_LIMITS.maxIdLength||!ID.test(value))&&fail3(`${label} must be [a-z][a-z0-9-]*, at most ${PATCH_LIMITS.maxIdLength} characters`),value}function checkPatchName(value,label="the name of a patch"){return(typeof value!="string"||value.length===0||value.length>PATCH_LIMITS.maxNameLength||!NAME.test(value))&&fail3(`${label} must be lowercase letters, digits and dashes, at most ${PATCH_LIMITS.maxNameLength} characters`),value}function checkLabel(value,label){if(value!==void 0)return(typeof value!="string"||value.length===0||value.length>PATCH_LIMITS.maxLabelLength)&&fail3(`${label} must be 1..${PATCH_LIMITS.maxLabelLength} characters`),value}function finite3(value,label){return(typeof value!="number"||!Number.isFinite(value))&&fail3(`${label} must be a finite number`),value}function splitPort(ref){let dot=ref.indexOf(".");return dot<0?[ref,""]:[ref.slice(0,dot),ref.slice(dot+1)]}function patchLane(macroId){return`patch-${macroId}`}function isPatchLane(value){return typeof value=="string"&&value.startsWith("patch-")&&value.length-6<=PATCH_LIMITS.maxIdLength&&ID.test(value.slice(6))}function macroAt(macro2,position){let p=Math.min(1,Math.max(0,position));return macro2.curve==="exp"?macro2.min*Math.pow(macro2.max/macro2.min,p):macro2.min+(macro2.max-macro2.min)*p}function nestedSpec(patch){let audio=(name,doc)=>({name,kind:"audio",doc}),inputs2=patch.role==="instrument"?[{name:"notes",kind:"notes",doc:"notes into the patch"}]:[audio("audio","audio in"),audio("right","right in")];(patch.side!==void 0||patch.role==="effect")&&inputs2.push(audio("side","sidechain in"));for(let macro2 of patch.macros)inputs2.push({name:macro2.id,kind:"control",spec:{kind:"number",min:macro2.min,max:macro2.max,default:macro2.default,step:(macro2.max-macro2.min)/100,doc:macro2.label??macro2.id},doc:macro2.label??macro2.id});return{type:`patch.${patch.name}`,family:"mix",doc:`the project patch ${patch.name}`,inputs:inputs2,outputs:[audio("audio","audio out"),audio("right","right out")],params:{},rate:"any",process:"block",cost:0}}function resolverFor(context){return type=>{let spec=nodeSpec(type);if(spec)return spec;if(type.startsWith("patch.")){let sub=context.library?.[type.slice(6)];return sub?nestedSpec(sub):void 0}}}function normalizeNode(input,index,resolve,context){isRecord2(input)||fail3(`node ${index+1} must be an object`);for(let key of Object.keys(input))["id","type","params","rate","label"].includes(key)||fail3(`node ${index+1} has no field "${key}"`);let id=checkId(input.id,`node ${index+1} id`);Object.prototype.hasOwnProperty.call(BOUNDARY_SPECS,id)&&fail3(`node id "${id}" is reserved for the patch boundary`),typeof input.type!="string"&&fail3(`node ${id} needs a type`);let type=input.type,spec=resolve(type);spec||(type.startsWith("patch.")&&fail3(`node ${id}: no project patch "${type.slice(6)}"${suggest2(type.slice(6),Object.keys(context.library??{}))}`),fail3(`node ${id}: unknown node type "${type}"${suggest2(type,NODE_TYPES)}`));let params2=normalizeNodeParams(id,spec,input.params,context);type.startsWith("device.")&&typeof params2?.device!="string"&&fail3(`node ${id} (${type}) needs a device: its sha256:<hash>`);let rate2=input.rate;rate2!==void 0&&rate2!=="global"&&fail3(`node ${id} rate must be "global"`),rate2==="global"&&spec.rate==="voice"&&fail3(`node ${id} (${type}) always runs per voice`);let label=checkLabel(input.label,`node ${id} label`);return Object.freeze({id,type,...params2?{params:params2}:{},...rate2==="global"&&spec.rate==="any"?{rate:"global"}:{},...label!==void 0?{label}:{}})}function normalizeNodeParams(id,spec,input,context){if(input==null)return;isRecord2(input)||fail3(`node ${id} params must be an object`);let names=Object.keys(spec.params),allowed=spec.engine?[...names,"settings"]:names;for(let key of Object.keys(input))allowed.includes(key)||fail3(`node ${id} (${spec.type}) has no param "${key}"${suggest2(key,allowed)}`);let out={};for(let[name,param2]of Object.entries(spec.params)){let value=input[name];if(value!==void 0){if(name==="instrument"&&spec.engine&&spec.engine.instruments.length===0){(typeof value!="string"||value.trim()===""||value.length>PATCH_LIMITS.maxNameLength)&&fail3(`node ${id}.instrument must be an instrument word (at most ${PATCH_LIMITS.maxNameLength} characters)`),out[name]=value.trim();continue}if(name==="device"&&spec.type.startsWith("device.")){(typeof value!="string"||!DEVICE_HASH.test(value))&&fail3(`node ${id}.device must be sha256:<64 lowercase hex digits>, the hash of the device's .wasm file`),out[name]=value;continue}try{out[name]=normalizeParam(param2,value,`${id}.${name}`)}catch(error){throw error instanceof FxValidationError&&fail3(error.message),error}}}if(spec.engine&&input.settings!==void 0){let settings=input.settings;isRecord2(settings)||fail3(`node ${id} settings must be an object`);for(let key of Object.keys(settings))spec.engine.fields.includes(key)||fail3(`node ${id} (${spec.type}) settings have no field "${key}"${suggest2(key,spec.engine.fields)}`);let checked2=context.engineSettings?context.engineSettings(spec.engine.fields,settings,`node ${id}`):settings;Object.keys(checked2).length>0&&(out.settings=Object.freeze(checked2))}return Object.keys(out).length>0?Object.freeze(out):void 0}function endpoint(ref,dir,label,nodes){(typeof ref!="string"||!ref.includes("."))&&fail3(`${label} must name node.port`);let[id,name]=splitPort(ref),spec=nodes.get(id)??BOUNDARY_SPECS[id];if((!spec||BOUNDARY_SPECS[id]&&nodes.has(id))&&fail3(`${label}: no node "${id}"${suggest2(id,[...nodes.keys(),...Object.keys(BOUNDARY_SPECS)])}`),id==="song"&&dir==="out"&&name.startsWith("lane.")){let lane=name.slice(5);return/^[a-z][a-z0-9-]*$/.test(lane)||fail3(`${label}: song.lane needs an automation lane name`),{node:id,port:{name,kind:"control",doc:`the ${lane} lane`},spec}}let port2=findPort(spec,name,dir);if(!port2){findPort(spec,name,dir==="in"?"out":"in")&&fail3(`${label}: ${id}.${name} is an ${dir==="in"?"output":"input"}, not an ${dir==="in"?"input":"output"}`);let names=(dir==="in"?spec.inputs:spec.outputs).map(candidate=>candidate.name);fail3(`${label}: no ${dir==="in"?"input":"output"} port "${name}" on ${id} (${spec.type})${suggest2(name,names)}`)}return{node:id,port:port2,spec}}function cableKindError(from,to,toRef){if(from==="notes"&&to!=="notes")return`notes cable into ${to} port ${toRef}: use a voice source (voice.note, voice.velocity)`;if(from!=="notes"&&to==="notes")return`${from} cable into notes port ${toRef}: only notes flow into notes ports`}function normalizeCable(input,index,nodes){isRecord2(input)||fail3(`cable ${index+1} must be an object`);for(let key of Object.keys(input))["id","from","to","amount"].includes(key)||fail3(`cable ${index+1} has no field "${key}"`);let id=checkId(input.id,`cable ${index+1} id`),from=endpoint(input.from,"out",`cable ${id} from`,nodes),to=endpoint(input.to,"in",`cable ${id} to`,nodes),toRef=`${to.node}.${to.port.name}`,kindError=cableKindError(from.port.kind,to.port.kind,toRef);kindError&&fail3(`cable ${id}: ${kindError}`);let amount;return input.amount!==void 0&&(to.port.kind!=="control"&&fail3(`cable ${id}: amount only scales cables into control ports (${toRef} is ${to.port.kind})`),amount=finite3(input.amount,`cable ${id} amount`),(amount<-1||amount>1)&&fail3(`cable ${id} amount must be -1..1`)),Object.freeze({id,from:`${from.node}.${from.port.name}`,to:toRef,...amount!==void 0&&amount!==1?{amount}:{}})}function targetRange(ref,label,nodes){(typeof ref!="string"||!ref.includes("."))&&fail3(`${label} must name node.port`);let[id,name]=splitPort(ref),spec=nodes.get(id);spec||fail3(`${label}: no node "${id}"${suggest2(id,[...nodes.keys()])}`);let port2=findPort(spec,name,"in");if(port2?.kind==="control"&&port2.spec)return{ref,min:port2.spec.min,max:port2.spec.max};let param2=spec.params[name];if(param2?.kind==="number")return{ref,min:param2.min,max:param2.max};let names=[...spec.inputs.filter(p=>p.kind==="control").map(p=>p.name),...Object.entries(spec.params).filter(([,p])=>p.kind==="number").map(([n2])=>n2)];fail3(`${label}: ${id}.${name} is not a control input or number param of ${spec.type}${suggest2(name,names)}`)}function normalizeMacro(input,index,nodes){isRecord2(input)||fail3(`macro ${index+1} must be an object`);for(let key of Object.keys(input))["id","label","min","max","default","curve","to"].includes(key)||fail3(`macro ${index+1} has no field "${key}"`);let id=checkId(input.id,`macro ${index+1} id`),label=checkLabel(input.label,`macro ${id} label`),min=finite3(input.min??0,`macro ${id} min`),max=finite3(input.max??1,`macro ${id} max`);max>min||fail3(`macro ${id} max must be above min`);let curve=input.curve;curve!==void 0&&curve!=="lin"&&curve!=="exp"&&fail3(`macro ${id} curve must be lin or exp`),curve==="exp"&&min<=0&&fail3(`macro ${id}: an exp curve needs min above 0`);let value=Math.min(max,Math.max(min,finite3(input.default??min,`macro ${id} default`)));Array.isArray(input.to)||fail3(`macro ${id} to must be a list`);let seen=new Set,to=input.to.map((target,at3)=>{let where2=`macro ${id} target ${at3+1}`;isRecord2(target)||fail3(`${where2} must be an object`);for(let key of Object.keys(target))["port","min","max"].includes(key)||fail3(`${where2} has no field "${key}"`);let range=targetRange(target.port,where2,nodes);seen.has(range.ref)&&fail3(`macro ${id} targets ${range.ref} twice`),seen.add(range.ref);let clamp10=v=>Math.min(range.max,Math.max(range.min,v)),lo=target.min===void 0?void 0:clamp10(finite3(target.min,`${where2} min`)),hi=target.max===void 0?void 0:clamp10(finite3(target.max,`${where2} max`));return Object.freeze({port:range.ref,...lo!==void 0?{min:lo}:{},...hi!==void 0?{max:hi}:{}})});return Object.freeze({id,...label!==void 0?{label}:{},min,max,default:value,...curve==="exp"?{curve:"exp"}:{},to:Object.freeze(to)})}function compareCables(a,b){return a.to<b.to?-1:a.to>b.to?1:a.from<b.from?-1:a.from>b.from?1:a.id<b.id?-1:a.id>b.id?1:0}function validatePatch(input,context={}){let where2=context.label??"patch";isRecord2(input)||fail3(`${where2} must be an object`);for(let key of Object.keys(input))["kind","role","name","nodes","cables","macros","voices","side","at","from"].includes(key)||fail3(`${where2} has no field "${key}"`);input.kind!=="patch"&&fail3(`${where2} kind must be "patch"`);let role=input.role??"instrument";role!=="instrument"&&role!=="effect"&&fail3(`${where2} role must be instrument or effect`);let name=checkPatchName(input.name,`${where2} name`),nodesIn=input.nodes??[],cablesIn=input.cables??[],macrosIn=input.macros??[];(!Array.isArray(nodesIn)||!Array.isArray(cablesIn)||!Array.isArray(macrosIn))&&fail3(`${name}: nodes, cables and macros must be lists`),nodesIn.length>PATCH_LIMITS.maxNodes&&fail3(`${name} holds at most ${PATCH_LIMITS.maxNodes} nodes`),cablesIn.length>PATCH_LIMITS.maxCables&&fail3(`${name} holds at most ${PATCH_LIMITS.maxCables} cables`),macrosIn.length>PATCH_LIMITS.maxMacros&&fail3(`${name} holds at most ${PATCH_LIMITS.maxMacros} macros`);let resolve=resolverFor(context),nodes=nodesIn.map((node2,index)=>normalizeNode(node2,index,resolve,context)),specs2=new Map;for(let node2 of nodes)specs2.has(node2.id)&&fail3(`${name} has two nodes with id ${node2.id}`),specs2.set(node2.id,resolve(node2.type)),role==="effect"&&specs2.get(node2.id).family==="engine"&&fail3(`node ${node2.id}: an effect patch cannot hold an engine (${node2.type})`),role==="effect"&&(node2.type==="device.synth"||node2.type==="device.notes")&&fail3(`node ${node2.id}: an effect patch cannot hold ${node2.type}; it plays notes`);let noteDevices=nodes.filter(node2=>node2.type==="device.notes");noteDevices.length>1&&fail3(`${name} holds at most one device.notes node`),noteDevices.length>0&&nodes.some(node2=>node2.type.startsWith("engine.")||node2.type.startsWith("patch."))&&fail3(`${name}: a device.notes node cannot sit beside engine.* or nested patch nodes, which play the track's own notes`);let cables=cablesIn.map((cable,index)=>normalizeCable(cable,index,specs2)),ids=new Set,pairs=new Set;for(let cable of cables){ids.has(cable.id)&&fail3(`${name} has two cables with id ${cable.id}`),ids.add(cable.id);let pair2=`${cable.from}>${cable.to}`;pairs.has(pair2)&&fail3(`${cable.from} is already wired to ${cable.to}`),pairs.add(pair2);let[source,port2]=splitPort(cable.from);role==="effect"&&(source==="voice"||source==="in"&&port2==="notes")&&fail3(`cable ${cable.id}: an effect patch has no ${cable.from}`),role==="instrument"&&source==="in"&&(port2==="audio"||port2==="right")&&fail3(`cable ${cable.id}: an instrument patch has no ${cable.from} (use in.notes)`)}cables.sort(compareCables);let macros=macrosIn.map((macro2,index)=>normalizeMacro(macro2,index,specs2)),macroIds=new Set;for(let macro2 of macros)macroIds.has(macro2.id)&&fail3(`${name} has two macros with id ${macro2.id}`),macroIds.add(macro2.id);let voices;input.voices!==void 0&&(voices=finite3(input.voices,`${name} voices`),(!Number.isInteger(voices)||voices<1||voices>PATCH_LIMITS.maxVoices)&&fail3(`${name} voices must be an integer 1..${PATCH_LIMITS.maxVoices}`));let side;input.side!==void 0&&((typeof input.side!="string"||input.side.length===0)&&fail3(`${name} side must name a track`),side=input.side),input.at!==void 0&&(input.at!=="post"||role!=="effect")&&fail3(`${name} at must be "post" (effect patches only)`);let from;input.from!==void 0&&((typeof input.from!="string"||input.from.length===0||input.from.length>128)&&fail3(`${name} from must be 1..128 characters`),from=input.from);let patch=Object.freeze({kind:"patch",role,name,nodes:Object.freeze(nodes),cables:Object.freeze(cables),macros:Object.freeze(macros),...voices!==void 0?{voices}:{},...side!==void 0?{side}:{},...input.at==="post"?{at:"post"}:{},...from!==void 0?{from}:{}});return context.library&&patchDepth(patch,context.library),patch}function validatePatchValue(input,context={}){if(isRecord2(input)&&input.ref!==void 0){for(let key of Object.keys(input))["kind","ref","macros","side"].includes(key)||fail3(`patch reference has no field "${key}"`);input.kind!=="patch"&&fail3('patch reference kind must be "patch"');let ref=checkPatchName(input.ref,"patch reference"),target=context.library?.[ref];context.library&&!target&&fail3(`no project patch "${ref}"${suggest2(ref,Object.keys(context.library))}`);let macros;if(input.macros!==void 0){isRecord2(input.macros)||fail3(`patch ${ref} macros must be an object`),macros={};let order=target?target.macros.map(macro2=>macro2.id):Object.keys(input.macros).sort();for(let key of Object.keys(input.macros))checkId(key,`patch ${ref} macro`);for(let key of order){let value=input.macros[key];if(value===void 0)continue;let macro2=target?.macros.find(candidate=>candidate.id===key),n2=finite3(value,`patch ${ref} macro ${key}`);macros[key]=macro2?Math.min(macro2.max,Math.max(macro2.min,n2)):n2}}let side;return input.side!==void 0&&((typeof input.side!="string"||input.side.length===0)&&fail3(`patch ${ref} side must name a track`),side=input.side),Object.freeze({kind:"patch",ref,...macros&&Object.keys(macros).length>0?{macros:Object.freeze(macros)}:{},...side!==void 0?{side}:{}})}return validatePatch(input,context)}function resolvePatch(value,library={}){return isPatchRef(value)?library[value.ref]:value}function patchDepth(patch,library,stack=[patch.name]){let depth=0;for(let node2 of patch.nodes){if(!node2.type.startsWith("patch."))continue;let name=node2.type.slice(6);stack.includes(name)&&fail3(`patch ${[...stack,name].join(" -> ")} nests itself`);let sub=library[name];sub||fail3(`node ${node2.id}: no project patch "${name}"`),depth=Math.max(depth,1+patchDepth(sub,library,[...stack,name]))}return depth>PATCH_LIMITS.maxDepth&&fail3(`patch ${patch.name} nests ${depth} deep (at most ${PATCH_LIMITS.maxDepth})`),depth}var compareText=(a,b)=>a<b?-1:a>b?1:0;function findCycles(patch){let order=new Set(patch.nodes.map(node2=>node2.id)),cycles=[],breaks=[],live2=patch.cables.filter(cable=>order.has(splitPort(cable.from)[0])&&order.has(splitPort(cable.to)[0]));for(let guard=0;guard<=live2.length;guard+=1){let loops=stronglyConnected(patch.nodes.map(n2=>n2.id),live2).filter(component=>component.length>1||live2.some(cable=>splitPort(cable.from)[0]===component[0]&&splitPort(cable.to)[0]===component[0]));if(loops.length===0)break;let broken=new Set;for(let loop of loops){let members=new Set(loop);guard===0&&cycles.push([...loop].sort());let head=[...loop].sort(compareText)[0],edge=live2.filter(cable=>splitPort(cable.to)[0]===head&&members.has(splitPort(cable.from)[0])).sort((a,b)=>compareText(a.to,b.to)||compareText(a.from,b.from)||compareText(a.id,b.id))[0];broken.add(edge.id),breaks.push(edge.id)}live2=live2.filter(cable=>!broken.has(cable.id))}return cycles.sort((a,b)=>a[0]<b[0]?-1:1),{cycles,breaks:breaks.sort()}}function stronglyConnected(ids,cables){let next=new Map(ids.map(id=>[id,[]]));for(let cable of cables)next.get(splitPort(cable.from)[0])?.push(splitPort(cable.to)[0]);let counter=0,index=new Map,low=new Map,stack=[],onStack=new Set,out=[],visit=id=>{index.set(id,counter),low.set(id,counter),counter+=1,stack.push(id),onStack.add(id);for(let to of next.get(id)??[])index.has(to)?onStack.has(to)&&low.set(id,Math.min(low.get(id),index.get(to))):(visit(to),low.set(id,Math.min(low.get(id),low.get(to))));if(low.get(id)===index.get(id)){let component=[],member;do member=stack.pop(),onStack.delete(member),component.push(member);while(member!==id);out.push(component)}};for(let id of ids)index.has(id)||visit(id);return out}function validateLibrary(input,context={}){if(input==null)return Object.freeze({});isRecord2(input)||fail3("score patches must be an object");let names=Object.keys(input).sort();names.length>PATCH_LIMITS.maxPatches&&fail3(`a project holds at most ${PATCH_LIMITS.maxPatches} patches`);let raw={};for(let name of names){checkPatchName(name,`project patch "${name}"`);let value=input[name];isRecord2(value)||fail3(`project patch ${name} must be an object`),value.name!==void 0&&value.name!==name&&fail3(`project patch ${name} is named ${String(value.name)}`),value.side!==void 0&&fail3(`project patch ${name}: side names a track, so set it on the track's patch`),raw[name]={...value,name}}let done={},visit=(name,stack)=>{if(done[name])return done[name];stack.includes(name)&&fail3(`patch ${[...stack,name].join(" -> ")} nests itself`);let value=raw[name],nodes=Array.isArray(value.nodes)?value.nodes:[];for(let node2 of nodes)if(isRecord2(node2)&&typeof node2.type=="string"&&node2.type.startsWith("patch.")){let sub=node2.type.slice(6);raw[sub]&&visit(sub,[...stack,name])}return done[name]=validatePatch(value,{...context,library:done,label:`project patch ${name}`}),done[name]};for(let name of names)visit(name,[]);let out={};for(let name of names)out[name]=done[name];return Object.freeze(out)}function patchSides(patch,fx){let out=[];patch?.side!==void 0&&out.push(patch.side);for(let stage of fx??[])stage.side!==void 0&&out.push(stage.side);return out}var ENGINE_FIELDS=[...new Set(Object.values(NODE_SPECS).flatMap(spec=>spec.engine?.fields??[]))].sort();function engineTrack(track2,node2){let out={...track2};delete out.patch,delete out.fxPatch,delete out.clips;for(let field of ENGINE_FIELDS)delete out[field];let word2=node2.params?.instrument;out.instrument=typeof word2=="string"&&word2!==PATCH_INSTRUMENT?word2:"sine";let settings=node2.params?.settings;if(isRecord2(settings))for(let[field,value]of Object.entries(settings))out[field]=value;return out}function engineTracks(track2,library={}){let value=track2.patch;if(track2.instrument!==PATCH_INSTRUMENT||!value)return[track2];let out=[],walk=(patch,depth)=>{if(!(!patch||depth>PATCH_LIMITS.maxDepth))for(let node2 of patch.nodes)node2.type.startsWith("engine.")?out.push(engineTrack(track2,node2)):node2.type.startsWith("patch.")&&walk(library[node2.type.slice(6)],depth+1)};return walk(resolvePatch(value,library),0),out}function soundingTracks(score){return score.tracks.some(track2=>track2.instrument===PATCH_INSTRUMENT)?score.tracks.flatMap(track2=>track2.instrument===PATCH_INSTRUMENT&&track2.patch?[track2,...engineTracks(track2,score.patches??{})]:[track2]):score.tracks}var specs=new Map;function registerTrackRefs(field,spec){specs.set(field,spec),registerTrackRefDrop(field,spec.drop)}function resolveTrackRef(score,idOrSlug){let byId=score.tracks.find(track2=>track2.id===idOrSlug);if(byId)return byId;let slug=trackSlug(idOrSlug);return score.tracks.find(track2=>trackSlug(track2.name)===slug)}registerTrackRefs("vocoder",{refs:track2=>track2.vocoder?.src!==void 0?[{trackId:track2.vocoder.src,kind:"audio"}]:[],drop:(track2,removedId)=>{if(track2.vocoder?.src!==removedId)return track2;let{src:_src,...rest}=track2.vocoder;return{...track2,vocoder:rest}}});registerTrackRefs("autotune.from",{refs:track2=>track2.autotune?.from!==void 0?[{trackId:track2.autotune.from,kind:"notes"}]:[],drop:(track2,removedId)=>{if(track2.autotune?.from!==removedId)return track2;let{from:_from,...autotune}=track2.autotune;return{...track2,autotune}}});registerTrackRefs("patch.side",{refs:track2=>patchSides(track2.patch,track2.fxPatch).map(trackId=>({trackId,kind:"audio"})),drop:(track2,removedId)=>{let next=track2;if(track2.patch?.side===removedId){let{side:_side,...rest}=track2.patch;next={...next,patch:rest}}return track2.fxPatch?.some(stage=>stage.side===removedId)&&(next={...next,fxPatch:track2.fxPatch.map(stage=>{if(stage.side!==removedId)return stage;let{side:_side,...rest}=stage;return rest})}),next}});var TEMPO_RAMPS=["linear","exp"],TIME_LIMITS=Object.freeze({maxTempoEvents:256,maxMeterChanges:256,maxFermatas:256,maxFermataBeats:64,maxFermataSeconds:16.777,minBpm:20,maxBpm:300,maxTick:67108864,maxBeatsPerBar:16,maxBars:256,beatUnits:Object.freeze([1,2,4,8,16,32]),minRate:.125,maxRate:8,maxPerformedNotes:16384}),TimeValidationError=class extends Error{constructor(message){super(message),this.name="TimeValidationError"}};function normalizeSongTime(input,label="time"){if(input==null)return;let record2=recordOf(input,label,["tempo","meter","fermatas"]),tempo=normalizeList2(record2.tempo,`${label}.tempo`,TIME_LIMITS.maxTempoEvents,normalizeTempoEvent,event=>event.tick),meter=normalizeList2(record2.meter,`${label}.meter`,TIME_LIMITS.maxMeterChanges,normalizeMeterChange,change=>change.bar),fermatas=normalizeList2(record2.fermatas,`${label}.fermatas`,TIME_LIMITS.maxFermatas,normalizeFermata,fermata=>fermata.tick);if(!(!tempo&&!meter&&!fermatas))return Object.freeze({...tempo?{tempo}:{},...meter?{meter}:{},...fermatas?{fermatas}:{}})}function checkSongTime(time,ticksPerBeat,score){if(score&&time?.fermatas){let map=new TimeMap({...score,ticksPerBeat,time});for(let fermata of time.fermatas){let span4=fermataSpan({...score,ticksPerBeat,time},fermata.tick),held=map.seconds(fermata.tick+span4)-map.seconds(fermata.tick);if(held>TIME_LIMITS.maxFermataSeconds+1e-9)throw new TimeValidationError(`fermata at beat ${fermata.tick/ticksPerBeat} holds ${held.toFixed(1)} s; at most ${TIME_LIMITS.maxFermataSeconds} s (MIDI tempo limit), so use fewer beats or a faster tempo`)}}for(let change of time?.meter??[]){let ticks=barTicksOf(change.beatsPerBar,change.beatUnit??4,ticksPerBeat);if(!Number.isInteger(ticks))throw new TimeValidationError(`time.meter bar ${change.bar}: ${change.beatsPerBar}/${change.beatUnit??4} is not a whole number of ticks at ${ticksPerBeat} ticks per beat`)}}function normalizeTrackTime(input,label="track time"){if(input==null)return;let record2=recordOf(input,label,["rate","phase","cycle","steps"]),out={};if(record2.rate!==void 0){let rate2=record2.rate;if(typeof rate2!="number"||!Number.isFinite(rate2)||rate2<TIME_LIMITS.minRate||rate2>TIME_LIMITS.maxRate)throw new TimeValidationError(`${label} rate must be between ${TIME_LIMITS.minRate} and ${TIME_LIMITS.maxRate}`);rate2!==1&&(out.rate=rate2)}if(record2.phase!==void 0){let phase=record2.phase;if(typeof phase!="number"||!Number.isInteger(phase)||Math.abs(phase)>TIME_LIMITS.maxTick)throw new TimeValidationError(`${label} phase must be an integer tick within \xB1${TIME_LIMITS.maxTick}`);phase!==0&&(out.phase=phase)}if(record2.cycle!==void 0){let cycle=record2.cycle;if(typeof cycle!="number"||!Number.isInteger(cycle)||cycle<1||cycle>TIME_LIMITS.maxTick)throw new TimeValidationError(`${label} cycle must be an integer between 1 and ${TIME_LIMITS.maxTick} ticks`);out.cycle=cycle}if(record2.steps!==void 0){if(out.rate!==void 0)throw new TimeValidationError(`${label} takes rate or steps, not both`);if(out.cycle===void 0)throw new TimeValidationError(`${label} steps need a cycle`);out.steps=normalizePhaseSteps(record2.steps,out.cycle,`${label} steps`)}return Object.keys(out).length>0?Object.freeze(out):void 0}function normalizePhaseSteps(input,cycle,label){let record2=recordOf(input,label,["shift","hold","drift"]),int=(value,min,max)=>typeof value=="number"&&Number.isInteger(value)&&value>=min&&value<=max;if(!int(record2.shift,1,cycle))throw new TimeValidationError(`${label} shift must be an integer between 1 and the cycle (${cycle} ticks)`);if(!int(record2.hold,0,64))throw new TimeValidationError(`${label} hold must be 0..64 cycles`);if(!int(record2.drift,1,64))throw new TimeValidationError(`${label} drift must be 1..64 cycles`);return Object.freeze({shift:record2.shift,hold:record2.hold,drift:record2.drift})}function normalizeTempoEvent(input,label){let record2=recordOf(input,label,["tick","bpm","ramp"]),tick=record2.tick;if(typeof tick!="number"||!Number.isInteger(tick)||tick<1||tick>TIME_LIMITS.maxTick)throw new TimeValidationError(`${label} tick must be an integer between 1 and ${TIME_LIMITS.maxTick} (tick 0 is tempoBpm)`);let bpm=record2.bpm;if(typeof bpm!="number"||!Number.isFinite(bpm)||bpm<TIME_LIMITS.minBpm||bpm>TIME_LIMITS.maxBpm)throw new TimeValidationError(`${label} bpm must be between ${TIME_LIMITS.minBpm} and ${TIME_LIMITS.maxBpm}`);let ramp=record2.ramp;if(ramp!=null&&!TEMPO_RAMPS.includes(ramp))throw new TimeValidationError(`${label} ramp must be one of ${TEMPO_RAMPS.join(", ")}`);return Object.freeze({tick,bpm,...typeof ramp=="string"?{ramp}:{}})}function normalizeMeterChange(input,label){let record2=recordOf(input,label,["bar","beatsPerBar","beatUnit"]),bar=record2.bar;if(typeof bar!="number"||!Number.isInteger(bar)||bar<0||bar>=TIME_LIMITS.maxBars)throw new TimeValidationError(`${label} bar must be an integer between 0 and ${TIME_LIMITS.maxBars-1}`);let beatsPerBar=record2.beatsPerBar;if(typeof beatsPerBar!="number"||!Number.isInteger(beatsPerBar)||beatsPerBar<1||beatsPerBar>TIME_LIMITS.maxBeatsPerBar)throw new TimeValidationError(`${label} beatsPerBar must be an integer between 1 and ${TIME_LIMITS.maxBeatsPerBar}`);let beatUnit=record2.beatUnit??4;if(typeof beatUnit!="number"||!TIME_LIMITS.beatUnits.includes(beatUnit))throw new TimeValidationError(`${label} beatUnit must be one of ${TIME_LIMITS.beatUnits.join(", ")}`);return Object.freeze({bar,beatsPerBar,...beatUnit!==4?{beatUnit}:{}})}function normalizeFermata(input,label){let record2=recordOf(input,label,["tick","beats"]),tick=record2.tick;if(typeof tick!="number"||!Number.isInteger(tick)||tick<0||tick>TIME_LIMITS.maxTick)throw new TimeValidationError(`${label} tick must be an integer between 0 and ${TIME_LIMITS.maxTick}`);let beats=record2.beats;if(typeof beats!="number"||!Number.isFinite(beats)||beats<=0||beats>TIME_LIMITS.maxFermataBeats)throw new TimeValidationError(`${label} beats must be above 0 and at most ${TIME_LIMITS.maxFermataBeats}`);return Object.freeze({tick,beats})}function normalizeList2(input,label,max,normalize,keyOf2){if(input==null)return;if(!Array.isArray(input)||input.length>max)throw new TimeValidationError(`${label} must be an array of at most ${max} entries`);if(input.length===0)return;let items=input.map((value,index)=>normalize(value,`${label}[${index}]`)).sort((a,b)=>keyOf2(a)-keyOf2(b));for(let index=1;index<items.length;index+=1)if(keyOf2(items[index])===keyOf2(items[index-1]))throw new TimeValidationError(`${label} has two entries at ${keyOf2(items[index])}`);return Object.freeze(items)}function recordOf(input,label,keys){if(typeof input!="object"||input===null||Array.isArray(input))throw new TimeValidationError(`${label} must be an object`);for(let key of Object.keys(input))if(!keys.includes(key))throw new TimeValidationError(`${label} has unknown field ${key}`);return input}function barTicksOf(beatsPerBar,beatUnit,ticksPerBeat){return beatsPerBar*ticksPerBeat*4/beatUnit}var meterCache=new WeakMap;function meterSegments(score){let cached=meterCache.get(score);if(cached)return cached;let current={bar:0,tick:0,beatsPerBar:score.beatsPerBar,beatUnit:4,barTicks:score.beatsPerBar*score.ticksPerBeat},segments=[];for(let change of score.time?.meter??[]){let beatUnit=change.beatUnit??4,next={bar:change.bar,tick:current.tick+(change.bar-current.bar)*current.barTicks,beatsPerBar:change.beatsPerBar,beatUnit,barTicks:barTicksOf(change.beatsPerBar,beatUnit,score.ticksPerBeat)};change.bar>0&&segments.push(Object.freeze(current)),current=next}segments.push(Object.freeze(current));let frozen=Object.freeze(segments);return meterCache.set(score,frozen),frozen}function barStartTick(score,bar){if(!score.time?.meter)return bar*score.beatsPerBar*score.ticksPerBeat;let segments=meterSegments(score),segment=segments[0];for(let candidate of segments){if(candidate.bar>bar)break;segment=candidate}return segment.tick+(bar-segment.bar)*segment.barTicks}function loopTicksOf(score){return score.time?.meter?barStartTick(score,score.bars):score.bars*score.beatsPerBar*score.ticksPerBeat}function barAt(score,tick){let segments=meterSegments(score),segment=segments[0];for(let candidate of segments){if(candidate.tick>tick)break;segment=candidate}let within=Math.floor((tick-segment.tick)/segment.barTicks),start=segment.tick+within*segment.barTicks;return{...segment,bar:segment.bar+within,tick:start,offset:tick-start}}function fermataSpan(score,tick){let tpb=score.ticksPerBeat;return score.time?.meter?Math.max(tpb,clickTicksOf(barAt(score,tick),tpb)):tpb}function clickTicksOf(segment,ticksPerBeat){let unit4=ticksPerBeat*4/segment.beatUnit;return segment.beatUnit>=8&&segment.beatsPerBar>3&&segment.beatsPerBar%3===0?unit4*3:unit4}function constant(segment){return segment.ramp===void 0||segment.beats<=0||Math.abs(segment.to-segment.from)<1e-9}function segmentSeconds(segment,beats){let{from,to}=segment;if(constant(segment))return 60*beats/from;let span4=segment.beats;if(segment.ramp==="linear"){let slope=(to-from)/span4;return 60/slope*Math.log1p(slope*beats/from)}let k=Math.log(to/from)/span4;return 60/(from*k)*-Math.expm1(-k*beats)}function segmentBeats(segment,seconds2){let{from,to}=segment;if(constant(segment))return seconds2*from/60;let span4=segment.beats;if(segment.ramp==="linear"){let slope=(to-from)/span4;return from/slope*Math.expm1(seconds2*slope/60)}let k=Math.log(to/from)/span4;return-Math.log1p(-seconds2*from*k/60)/k}function segmentBpm(segment,beats){let{from,to}=segment;if(constant(segment))return from;let x=Math.min(1,Math.max(0,beats/segment.beats));return segment.ramp==="linear"?from+(to-from)*x:from*Math.pow(to/from,x)}var TimeMap=class{ticksPerBeat;startBpm;pieces;spans=new Map;constructor(score){this.ticksPerBeat=score.ticksPerBeat,this.startBpm=score.tempoBpm;let tpb=score.ticksPerBeat,events=score.time?.tempo??[],segments=[],previousTick=0,previousBpm=score.tempoBpm;for(let event of events)segments.push({start:previousTick,segment:event.ramp?{origin:previousTick,beats:(event.tick-previousTick)/tpb,from:previousBpm,to:event.bpm,ramp:event.ramp}:{origin:previousTick,beats:0,from:previousBpm,to:previousBpm,ramp:void 0}}),previousTick=event.tick,previousBpm=event.bpm;segments.push({start:previousTick,segment:{origin:previousTick,beats:0,from:previousBpm,to:previousBpm,ramp:void 0}});let fermatas=score.time?.fermatas??[],spans=this.spans;for(let fermata of fermatas)spans.set(fermata.tick,fermataSpan(score,fermata.tick));let starts=new Set(segments.map(entry=>entry.start));for(let fermata of fermatas)starts.add(fermata.tick),starts.add(fermata.tick+spans.get(fermata.tick));let ticks=[...starts].sort((a,b)=>a-b),stretchAt=tick=>{let stretch=1;for(let fermata of fermatas)fermata.tick<=tick&&tick<fermata.tick+spans.get(fermata.tick)&&(stretch*=1+fermata.beats);return stretch},pieces=[],segmentIndex=0,lastPiece;for(let tick of ticks){for(;segmentIndex+1<segments.length&&segments[segmentIndex+1].start<=tick;)segmentIndex+=1;let segment=segments[segmentIndex].segment,piece={tick,seconds:lastPiece?this.secondsInPiece(lastPiece,tick):0,stretch:stretchAt(tick),segment,base:segmentSeconds(segment,(tick-segment.origin)/tpb)};pieces.push(piece),lastPiece=piece}this.pieces=Object.freeze(pieces)}secondsInPiece(piece,tick){let segment=piece.segment,plain=constant(segment)?(tick-piece.tick)/this.ticksPerBeat*(60/segment.from):segmentSeconds(segment,(tick-segment.origin)/this.ticksPerBeat)-piece.base;return piece.seconds+(piece.stretch===1?plain:plain*piece.stretch)}pieceAt(tick){let pieces=this.pieces,low=0,high=pieces.length-1;for(;low<high;){let middle=low+high+1>>1;pieces[middle].tick<=tick?low=middle:high=middle-1}return pieces[low]}seconds(tick){if(tick<=0){let first=this.pieces[0];return tick===0?0:tick/this.ticksPerBeat*60/first.segment.from}let piece=this.pieceAt(tick);return tick===piece.tick?piece.seconds:this.secondsInPiece(piece,tick)}tick(seconds2){if(seconds2<=0)return seconds2===0?0:seconds2*this.startBpm/60*this.ticksPerBeat;let pieces=this.pieces,low=0,high=pieces.length-1;for(;low<high;){let middle=low+high+1>>1;pieces[middle].seconds<=seconds2?low=middle:high=middle-1}let piece=pieces[low],into=(seconds2-piece.seconds)/piece.stretch;if(into<=0)return piece.tick;let segment=piece.segment;return constant(segment)?piece.tick+into*segment.from/60*this.ticksPerBeat:segment.origin+segmentBeats(segment,into+piece.base)*this.ticksPerBeat}bpm(tick){if(tick<0)return this.startBpm;let piece=this.pieceAt(tick),segment=piece.segment;return segmentBpm(segment,(tick-segment.origin)/this.ticksPerBeat)/piece.stretch}tempoAt(tick){if(tick<0)return this.startBpm;let segment=this.pieceAt(tick).segment;return segmentBpm(segment,(tick-segment.origin)/this.ticksPerBeat)}holdAt(tick){let piece=this.pieceAt(tick);if(piece.tick!==tick||piece.stretch===1)return 0;let end=tick+(this.spans.get(tick)??this.ticksPerBeat),span4=this.seconds(end)-piece.seconds;return span4-span4/piece.stretch}},mapCache=new WeakMap;function timeMapFor(score){if(!score.time?.tempo&&!score.time?.fermatas)return;let cached=mapCache.get(score);if(cached!==void 0)return cached??void 0;let map=new TimeMap(score);return mapCache.set(score,map),map}function secondsAtTick(score,tick){let map=timeMapFor(score);return map?map.seconds(tick):tick/score.ticksPerBeat*60/score.tempoBpm}function tickAtSeconds(score,seconds2){let map=timeMapFor(score);return map?map.tick(seconds2):seconds2*score.tempoBpm/60*score.ticksPerBeat}function loopSecondsOf(score){let map=timeMapFor(score);return map?map.seconds(loopTicksOf(score)):score.time?.meter?loopTicksOf(score)/score.ticksPerBeat*60/score.tempoBpm:score.bars*score.beatsPerBar*60/score.tempoBpm}function slowestBpmOf(score){if(!score.time?.tempo&&!score.time?.fermatas)return score.tempoBpm;let bpm=score.tempoBpm;for(let event of score.time.tempo??[])bpm=Math.min(bpm,event.bpm);let stretch=1;for(let fermata of score.time.fermatas??[])stretch=Math.max(stretch,1+fermata.beats);return bpm/stretch}function hasTempoMap(score){return timeMapFor(score)!==void 0}function rebuild(time,patch){let next={...time??{}};for(let[key,value]of Object.entries(patch))value===void 0||value.length===0?delete next[key]:next[key]=value;return normalizeSongTime(next)}function timeWithinSong(score){let time=score.time;if(!time)return time;let end=loopTicksOf(score),tempo=[];for(let event of time.tempo??[]){let previous=tempo[tempo.length-1]?.tick??0;event.tick<end?tempo.push(event):event.tick===end&&event.ramp&&end-1>previous&&tempo.push({...event,tick:end-1})}let meter=(time.meter??[]).filter(m=>m.bar<score.bars),fermatas=(time.fermatas??[]).filter(f=>f.tick<end);return tempo.every((e,i)=>e===time.tempo?.[i])&&tempo.length===(time.tempo??[]).length&&meter.length===(time.meter??[]).length&&fermatas.length===(time.fermatas??[]).length?time:rebuild(time,{tempo,meter,fermatas})}function withMeterChange(time,bar,meter){let changes=(time?.meter??[]).filter(m=>m.bar!==bar);return rebuild(time,{meter:meter?[...changes,{bar,beatsPerBar:meter.beatsPerBar,...meter.beatUnit!==void 0&&meter.beatUnit!==4?{beatUnit:meter.beatUnit}:{}}]:changes})}var placedCache=new WeakMap;function performedNotes(score){if(!score.tracks.some(track2=>track2.time))return score.notes;let cached=placedCache.get(score);if(cached)return cached;let loop=loopTicksOf(score),times=new Map;for(let track2 of score.tracks)track2.time&×.set(track2.id,track2.time);let out=[],repeats=0;for(let note2 of score.notes){let time=times.get(note2.trackId);if(!time){out.push(note2);continue}let rate2=time.rate??1,phase=time.phase??0,cycle=time.cycle??loop;if(note2.startTick>=cycle)continue;if(time.steps){repeats=placeStepped(note2,cycle,phase,time.steps,loop,out,repeats);continue}let period=cycle/rate2,offset=phase+note2.startTick/rate2,first=Math.ceil((0-offset)/period-1e-9),last=Math.floor((loop-offset)/period-1e-9);for(let k=first;k<=last&&!(repeats>=TIME_LIMITS.maxPerformedNotes);k+=1){let startTick=offset+k*period;startTick<0||startTick>=loop||(out.push({...note2,startTick,durationTicks:note2.durationTicks/rate2}),repeats+=1)}}out.sort((a,b)=>a.startTick-b.startTick||(a.trackId<b.trackId?-1:a.trackId>b.trackId?1:0)||a.pitch-b.pitch||(a.id<b.id?-1:a.id>b.id?1:0));let frozen=Object.freeze(out);return placedCache.set(score,frozen),frozen}function placeStepped(note2,cycle,phase,steps2,loop,out,repeats){let held=steps2.hold*cycle,drifting=steps2.drift*cycle,song3=held+drifting,track2=song3+steps2.shift,squeeze=drifting/(drifting+steps2.shift),songTick=tau=>{let step2=Math.floor(tau/track2),within=tau-step2*track2;return step2*song3+(within<held?within:held+(within-held)*squeeze)},first=Math.floor(-phase*track2/song3/cycle)-2;for(let k=first;!(repeats>=TIME_LIMITS.maxPerformedNotes);k+=1){let tau=k*cycle+note2.startTick,startTick=songTick(tau)+phase;if(startTick>=loop)break;if(startTick<0)continue;let within=tau-Math.floor(tau/track2)*track2;out.push({...note2,startTick,durationTicks:note2.durationTicks*(within<held?1:squeeze)}),repeats+=1}return repeats}function hasTrackTime(score){return score.tracks.some(track2=>track2.time!==void 0)}var EXPRESSION_LIMITS=Object.freeze({maxBendPoints:32,maxBendCents:4800,maxVibratoRate:20,maxVibratoDepth:1200,maxVibratoDelay:10,maxGlideSeconds:10,maxPedalEvents:1024,maxHumanizeTimingMs:250,maxHumanizePercent:100,maxSeed:2147483647}),ARTICULATIONS2=["staccato","legato","accent","tenuto","marcato","ghost"],ARTICULATION_EFFECTS=Object.freeze({staccato:{length:.5,scale:1,add:0,doc:"half length"},legato:{length:1,scale:1,add:0,doc:"held into the next note with a short overlap"},accent:{length:1,scale:1,add:.2,doc:"velocity +0.2"},tenuto:{length:1,scale:1,add:.05,doc:"full length, velocity +0.05"},marcato:{length:2/3,scale:1,add:.3,doc:"two-thirds length, velocity +0.3"},ghost:{length:.5,scale:.4,add:0,doc:"half length, velocity \xD70.4"}});var GLIDE_MODES=["legato","mono","poly"],DEFAULT_GLIDE_SECONDS2=.06,PEDAL_STATES=["down","half","up"],SOSTENUTO_STATES=["down","up"],VELOCITY_CURVES=["linear","soft","hard","fixed"],DEFAULT_FIXED_VELOCITY2=.8,HALF_PEDAL_TAU=.5,VIBRATO_FADE_SECONDS=.15,ExpressionValidationError=class extends Error{constructor(message){super(message),this.name="ExpressionValidationError"}};function finite4(value,label,min,max){if(typeof value!="number"||!Number.isFinite(value)||value<min||value>max)throw new ExpressionValidationError(`${label} must be a number ${min}..${max}`);return value}function record(value,label){if(typeof value!="object"||value===null||Array.isArray(value))throw new ExpressionValidationError(`${label} must be an object`);return value}function onlyKeys(value,keys,label){for(let key of Object.keys(value))if(!keys.includes(key))throw new ExpressionValidationError(`${label} has an unknown field ${key.slice(0,32)}`)}function normalizeArticulation(value){if(value==null)return;let name=typeof value=="string"?value.trim().toLowerCase():"",found=ARTICULATIONS2.find(candidate=>candidate===name||candidate.slice(0,4)===name);if(!found)throw new ExpressionValidationError(`articulation must be one of ${ARTICULATIONS2.join(", ")}`);return found}function normalizeNoteGlide(value){if(value!=null)return finite4(value,"note glide",0,EXPRESSION_LIMITS.maxGlideSeconds)}function normalizeBend(value){if(value==null)return;if(!Array.isArray(value)||value.length>EXPRESSION_LIMITS.maxBendPoints)throw new ExpressionValidationError(`bend must be an array of at most ${EXPRESSION_LIMITS.maxBendPoints} points`);if(value.length===0)return;let points=value.map(item=>{let point=record(item,"bend point");return onlyKeys(point,["at","cents"],"bend point"),Object.freeze({at:finite4(point.at,"bend at",0,1),cents:finite4(point.cents,"bend cents",-EXPRESSION_LIMITS.maxBendCents,EXPRESSION_LIMITS.maxBendCents)})});return points.sort((a,b)=>a.at-b.at),Object.freeze(points)}function normalizeVibrato(value){if(value==null)return;let input=record(value,"vibrato");onlyKeys(input,["rate","depth","delay"],"vibrato");let rate2=finite4(input.rate??5.5,"vibrato rate",.01,EXPRESSION_LIMITS.maxVibratoRate),depth=finite4(input.depth??20,"vibrato depth",0,EXPRESSION_LIMITS.maxVibratoDepth),delay=input.delay===void 0?0:finite4(input.delay,"vibrato delay",0,EXPRESSION_LIMITS.maxVibratoDelay);return Object.freeze({rate:rate2,depth,...delay>0?{delay}:{}})}function normalizeNoteDrift(value){if(value!=null)return finite4(value,"note drift",0,1)}function normalizeNoteExpression(input){let articulation=normalizeArticulation(input.articulation),glide=normalizeNoteGlide(input.glide),bend=normalizeBend(input.bend),vibrato=normalizeVibrato(input.vibrato),humanize=normalizeNoteHumanize(input.humanize),drift=normalizeNoteDrift(input.drift);return{...articulation?{articulation}:{},...glide!==void 0?{glide}:{},...bend?{bend}:{},...vibrato?{vibrato}:{},...humanize?{humanize}:{},...drift!==void 0?{drift}:{}}}function normalizeNoteHumanize(value){if(value==null)return;let input=record(value,"humanize");onlyKeys(input,["timing","velocity","length"],"humanize");let amount=(key,max)=>finite4(input[key]??0,`humanize ${key}`,0,max),timing=amount("timing",EXPRESSION_LIMITS.maxHumanizeTimingMs),velocity=amount("velocity",EXPRESSION_LIMITS.maxHumanizePercent),length=amount("length",EXPRESSION_LIMITS.maxHumanizePercent);return Object.freeze({...timing>0?{timing}:{},...velocity>0?{velocity}:{},...length>0?{length}:{}})}function normalizeTrackGlide(value){if(value==null)return;if(typeof value=="number")return Object.freeze({time:finite4(value,"glide time",0,EXPRESSION_LIMITS.maxGlideSeconds),mode:"legato"});let input=record(value,"glide");onlyKeys(input,["time","mode"],"glide");let time=finite4(input.time??DEFAULT_GLIDE_SECONDS2,"glide time",0,EXPRESSION_LIMITS.maxGlideSeconds),mode=input.mode??"legato";if(!GLIDE_MODES.includes(mode))throw new ExpressionValidationError(`glide mode must be one of ${GLIDE_MODES.join(", ")}`);return Object.freeze({time,mode})}function normalizePedal(value,maxTick,label="pedal",states=PEDAL_STATES){if(value==null)return;if(!Array.isArray(value)||value.length>EXPRESSION_LIMITS.maxPedalEvents)throw new ExpressionValidationError(`${label} must be an array of at most ${EXPRESSION_LIMITS.maxPedalEvents} events`);let byTick=new Map;for(let item of value){let event=record(item,`${label} event`);onlyKeys(event,["tick","state"],`${label} event`);let tick=event.tick;if(typeof tick!="number"||!Number.isInteger(tick)||tick<0||tick>maxTick)throw new ExpressionValidationError(`${label} tick must be an integer 0..${maxTick}`);if(!states.includes(event.state))throw new ExpressionValidationError(`${label} state must be one of ${states.join(", ")}`);byTick.set(tick,Object.freeze({tick,state:event.state}))}if(byTick.size!==0)return Object.freeze([...byTick.values()].sort((a,b)=>a.tick-b.tick))}function normalizeVelocityCurve(value){if(value==null)return;let input=typeof value=="string"?{curve:value}:record(value,"velocityCurve");onlyKeys(input,["curve","fixed"],"velocityCurve");let curve=input.curve;if(!VELOCITY_CURVES.includes(curve))throw new ExpressionValidationError(`velocityCurve must be one of ${VELOCITY_CURVES.join(", ")}`);if(curve!=="linear"){if(curve==="fixed")return Object.freeze({curve,fixed:finite4(input.fixed??DEFAULT_FIXED_VELOCITY2,"velocityCurve fixed",0,1)});if(input.fixed!==void 0)throw new ExpressionValidationError("velocityCurve fixed is only used by the fixed curve");return Object.freeze({curve})}}function normalizeHumanize(value){if(value==null)return;let input=record(value,"humanize");onlyKeys(input,["timing","velocity","length","seed"],"humanize");let timing=finite4(input.timing??0,"humanize timing",0,EXPRESSION_LIMITS.maxHumanizeTimingMs),velocity=finite4(input.velocity??0,"humanize velocity",0,EXPRESSION_LIMITS.maxHumanizePercent),length=finite4(input.length??0,"humanize length",0,EXPRESSION_LIMITS.maxHumanizePercent),seed=input.seed??1;if(typeof seed!="number"||!Number.isInteger(seed)||seed<0||seed>EXPRESSION_LIMITS.maxSeed)throw new ExpressionValidationError(`humanize seed must be an integer 0..${EXPRESSION_LIMITS.maxSeed}`);if(!(timing===0&&velocity===0&&length===0))return Object.freeze({...timing>0?{timing}:{},...velocity>0?{velocity}:{},...length>0?{length}:{},seed})}function normalizeTrackPerformance(input,maxTick){let glide=normalizeTrackGlide(input.glide),pedal=normalizePedal(input.pedal,maxTick),velocityCurve=normalizeVelocityCurve(input.velocityCurve),humanize=normalizeHumanize(input.humanize);return{...glide?{glide}:{},...pedal?{pedal}:{},...velocityCurve?{velocityCurve}:{},...humanize?{humanize}:{}}}function curveVelocity(curve,velocity){let v=Math.max(0,Math.min(1,velocity));return curve?curve.curve==="soft"?Math.sqrt(v):curve.curve==="hard"?v*v:curve.fixed??DEFAULT_FIXED_VELOCITY2:v}function pedalStateAt(pedal,tick){let state="up";for(let event of pedal??[]){if(event.tick>tick)break;state=event.state}return state}function slicePedal(events,pieces,carry=!0){if(!events||events.length===0)return events;let byTick=new Map,put2=(tick,state)=>byTick.set(tick,Object.freeze({tick,state}));for(let{from,to,offset}of pieces){let state="up";if(carry)for(let event of events){if(event.tick>=from)break;state=event.state}(state!=="up"||byTick.size>0)&&put2(offset,state);for(let event of events)event.tick<from||event.tick>=to||(put2(event.tick-from+offset,event.state),state=event.state);state!=="up"&&Number.isFinite(to)&&put2(offset+to-from,"up")}let out=[...byTick.values()].sort((a,b)=>a.tick-b.tick),kept=[],last="up";for(let event of out)event.state!==last&&(kept.push(event),last=event.state);return kept.length>0?Object.freeze(kept):void 0}function slicePedals(track2,pieces){if(!track2.pedal&&!track2.softPedal&&!track2.sostenuto)return track2;let out={...track2};for(let[field,carry]of[["pedal",!0],["softPedal",!0],["sostenuto",!1]]){if(!track2[field])continue;let next=slicePedal(track2[field],pieces,carry);next?out[field]=next:delete out[field]}return out}function performanceTimingFor(score){return{tempoBpm:score.tempoBpm,ticksPerBeat:score.ticksPerBeat,endTick:loopTicksOf(score),...hasTempoMap(score)?{secondsAt:tick=>secondsAtTick(score,tick)}:{}}}function tunedTiming(timing,score,track2){let tuning=resolveTuning(score.tuning,track2?.tuning,score.key);return tuning?{...timing,keyCents:keyCentsFor(tuning)}:timing}function intervalFor(keyCents2){let keys=keyCents2?(a,b)=>keyCents2(a.pitch)-keyCents2(b.pitch):(a,b)=>(a.pitch-b.pitch)*100;return(a,b)=>keys(a,b)+((a.cents??0)-(b.cents??0))}function hasNoteExpression(note2){return note2.articulation!==void 0||note2.glide!==void 0||note2.bend!==void 0||note2.vibrato!==void 0||note2.humanize!==void 0}function hasTrackPerformance(track2){return track2!==void 0&&(track2.glide!==void 0||track2.pedal!==void 0||track2.sostenuto!==void 0||track2.velocityCurve!==void 0||track2.humanize!==void 0)}function seeded(seed){let hash=2166136261;for(let index=0;index<seed.length;index+=1)hash^=seed.charCodeAt(index),hash=Math.imul(hash,16777619)>>>0;let state=hash;return()=>{state=state+1831565813>>>0;let value=Math.imul(state^state>>>15,1|state);return value=value+Math.imul(value^value>>>7,61|value)^value,((value^value>>>14)>>>0)/4294967296}}function triangular(random2){return random2()+random2()-1}var ACCENTED=new Set(["accent","marcato"]);function performNotes(track2,notes,timing){if(!hasTrackPerformance(track2)&&!notes.some(hasNoteExpression))return notes;let{tempoBpm,ticksPerBeat}=timing,secondsPerTick=60/(tempoBpm*ticksPerBeat),{secondsAt}=timing,span4=secondsAt?(from,to)=>secondsAt(to)-secondsAt(from):(from,to)=>(to-from)*secondsPerTick,localSecondsPerTick=tick=>secondsAt?secondsAt(tick+1)-secondsAt(tick):secondsPerTick,ordered=[...notes].sort((a,b)=>a.startTick-b.startTick||a.pitch-b.pitch||(a.id<b.id?-1:a.id>b.id?1:0)),onsets2=[...new Set(ordered.map(note2=>note2.startTick))],nextOnset=tick=>{let lo=0,hi=onsets2.length;for(;lo<hi;){let mid=lo+hi>>>1;onsets2[mid]>tick?hi=mid:lo=mid+1}return onsets2[lo]},working=ordered.map(note2=>{let effect=note2.articulation?ARTICULATION_EFFECTS[note2.articulation]:void 0,duration=note2.durationTicks,velocity=note2.velocity;if(effect&&(duration=Math.max(1,duration*effect.length),velocity=Math.max(0,Math.min(1,velocity*effect.scale+effect.add)),note2.articulation==="legato")){let overlap=ticksPerBeat/16,next=nextOnset(note2.startTick),end=note2.startTick+duration;next!==void 0&&next-end<=ticksPerBeat?duration=Math.max(duration,next-note2.startTick+overlap):duration+=overlap}return{note:note2,start:note2.startTick,duration,velocity,shift:0,stretch:1,bendLength:duration}}),trackHumanize=track2?.humanize,seed=trackHumanize?.seed??1,humanizing=working.some(item=>(item.note.humanize??trackHumanize)!==void 0&&Object.keys(item.note.humanize??trackHumanize??{}).some(key=>key!=="seed"));humanizing&&(working=working.map(item=>{let ticksPerMs=1/(localSecondsPerTick(item.start)*1e3),humanize=item.note.humanize??trackHumanize;if(!humanize)return item;let random2=seeded(`${seed}:${item.note.id}`),shift=triangular(random2)*(humanize.timing??0)*ticksPerMs,velocity=item.velocity+triangular(random2)*(humanize.velocity??0)/100,stretch=1+triangular(random2)*(humanize.length??0)/100;return{...item,shift,stretch,velocity:Math.max(0,Math.min(1,velocity))}}));let pedal=track2?.pedal;if(pedal){let ups=pedal.filter(event=>event.state==="up");working=working.map(item=>{let release=item.start+item.duration,state=pedalStateAt(pedal,release);if(state==="up")return item;let lift=ups.find(event=>event.tick>release)?.tick??timing.endTick,end=Math.max(release,Math.min(lift,timing.endTick)),halfAt=state==="half"?release:pedal.find(event=>event.state==="half"&&event.tick>release&&event.tick<end)?.tick,damp;if(halfAt!==void 0){let tauTicks=HALF_PEDAL_TAU/localSecondsPerTick(halfAt);end=Math.min(end,halfAt+5*tauTicks),damp={from:span4(item.start,halfAt),tau:HALF_PEDAL_TAU}}let restrike=working.find(other=>other!==item&&other.note.pitch===item.note.pitch&&other.start>item.start&&other.start<end);return restrike&&(end=Math.max(release,restrike.start)),{...item,duration:end-item.start,pedalled:end>release,...damp?{damp}:{}}})}let sostenuto=track2?.sostenuto;if(sostenuto){let spans=[],open;for(let event of sostenuto)event.state==="down"&&open===void 0?open=event.tick:event.state==="up"&&open!==void 0&&(spans.push({down:open,lift:event.tick,pitches:new Set}),open=void 0);open!==void 0&&spans.push({down:open,lift:timing.endTick,pitches:new Set});let caughtBy=working.map(item=>{let keyUp=item.start+item.bendLength;return spans.filter(span5=>{let held=item.start<=span5.down&&span5.down<keyUp;return held&&span5.pitches.add(item.note.pitch),held})});working=working.map((item,index)=>{let keyUp=item.start+item.bendLength,lift=-1/0;for(let span5 of caughtBy[index])lift=Math.max(lift,span5.lift);for(let span5 of spans)span5.pitches.has(item.note.pitch)&&span5.down<item.start&&item.start<span5.lift&&(lift=Math.max(lift,span5.lift));if(lift===-1/0)return item;let current=item.start+item.duration,end=Math.max(current,Math.min(lift,timing.endTick));if(end<=current)return item;let restrike=working.find(other=>other!==item&&other.note.pitch===item.note.pitch&&other.start>item.start&&other.start<end);return restrike&&(end=Math.max(current,restrike.start)),{...item,duration:end-item.start,pedalled:end>keyUp||item.pedalled===!0}})}let performed=glideAndMono(track2,working,span4,ticksPerBeat,intervalFor(timing.keyCents));if(humanizing&&working.some(item=>item.shift!==0||item.stretch!==1)&&(performed=performed.map(item=>{let start=Math.max(0,item.start+item.shift),end=item.pedalled?item.start+item.duration:start+item.duration*item.stretch;return{...item,start,duration:Math.max(1,end-start)}}),track2?.glide?.mode==="legato"||track2?.glide?.mode==="mono")){let byStart=[...performed].sort((a,b)=>a.start-b.start);for(let k=0;k+1<byStart.length;k+=1){let item=byStart[k],next=byStart[k+1];item.start+item.duration>next.start&&(item.duration=Math.max(1,next.start-item.start))}}let curve=track2?.velocityCurve;return performed.map(item=>{let velocity=curveVelocity(curve,item.velocity),performance2=item.performance;return item.start!==item.note.startTick||item.duration!==item.note.durationTicks||velocity!==item.note.velocity||performance2!==void 0?Object.freeze({...item.note,startTick:item.start,durationTicks:item.duration,velocity,...performance2?{performance:performance2}:{}}):item.note})}function segmentFor(item,offset,target,from,glide,span4,vibratoFrom,curve){let{note:note2}=item;return{offset,length:span4(item.start,item.start+item.bendLength),target,from,glide,...curve&&glide>0?{curve}:{},...note2.bend?{bend:note2.bend}:{},...note2.vibrato?{vibrato:note2.vibrato}:{},vibratoFrom}}function performanceFor(segments,damp,accent=!1){let pitched=segments.some(segment=>segment.glide>0||segment.target!==0||segment.bend!==void 0||segment.vibrato!==void 0);if(!pitched&&!damp&&!accent)return;let cursor=0;return Object.freeze({...pitched?{cents:t=>(t<segments[cursor].offset&&(cursor=0),cursor=segmentIndexAt(segments,t,cursor),centsOfSegment(segments[cursor],t))}:{},...accent?{accent:!0}:{},...damp?{damp:Object.freeze({...damp})}:{},replaceVibrato:segments.some(segment=>segment.vibrato!==void 0),replacePitchEnvelope:segments.some(segment=>segment.bend!==void 0),replaceSlide:segments.some(segment=>segment.glide>0||segment.target!==0)})}function bendAt(points,x){let previous={at:0,cents:0};points[0]&&points[0].at===0&&(previous=points[0]);for(let point of points){if(point.at>=x){if(point.at===previous.at)return point.cents;let mix3=(x-previous.at)/(point.at-previous.at);return previous.cents+(point.cents-previous.cents)*mix3}previous=point}return previous.cents}function vibratoAt(vibrato,t){let into=t-(vibrato.delay??0);if(into<=0||vibrato.depth===0)return 0;let fade=Math.min(1,into/VIBRATO_FADE_SECONDS);return vibrato.depth*fade*Math.sin(2*Math.PI*vibrato.rate*into)}function segmentIndexAt(segments,t,from=0){let index=from;for(;index+1<segments.length&&segments[index+1].offset<=t;)index+=1;return index}function reachedCents(segment,t){return centsOfSegment({...segment,vibrato:void 0},t)}function centsOfSegment(segment,t){let local=t-segment.offset,cents=segment.target;return segment.glide>0&&segment.curve==="exp"&&local<segment.glide?cents=segment.from+(segment.target-segment.from)*(1-Math.exp(-3*Math.max(0,local)/segment.glide))/(1-Math.exp(-3)):segment.glide>0&&local<segment.glide&&(cents=segment.from+(segment.target-segment.from)*local/segment.glide),segment.bend&&(cents+=bendAt(segment.bend,segment.length>0?Math.min(1,local/segment.length):1)),segment.vibrato&&(cents+=vibratoAt(segment.vibrato,t-segment.vibratoFrom)),cents}function glideAndMono(track2,working,span4,ticksPerBeat,interval){let trackGlide=track2?.glide,mode=trackGlide?.mode,curve=mode==="legato"||mode==="mono"?"exp":void 0,glideOf=item=>item.note.glide??trackGlide?.time??0,accented=item=>item.note.articulation!==void 0&&ACCENTED.has(item.note.articulation),single=(item,from,glide=0)=>{let segments=[segmentFor(item,0,0,from??0,from===void 0?0:glide,span4,0,curve)],performance2=performanceFor(segments,item.damp,accented(item));return{...item,...performance2?{performance:performance2}:{}}};if(mode==="legato"||mode==="mono"){let line=[];for(let item of[...working].sort((a,b)=>a.start-b.start||b.note.pitch-a.note.pitch)){let last=line[line.length-1];last&&last.start===item.start||line.push({...item})}let out=[],monoSegment,index=0;for(;index<line.length;){let first=line[index];if(mode==="mono"){let next=line[index+1];next&&first.start+first.duration>next.start&&(first.duration=Math.max(1,next.start-first.start));let previous=line[index-1],glide=glideOf(first),from;if(previous&&glide>0){let at3=span4(previous.start,first.start),reached=monoSegment?reachedCents(monoSegment,at3):0;from=interval(previous.note,first.note)+reached}let voice=from===void 0?single(first):single(first,from,glide);monoSegment=segmentFor(first,0,0,from??0,from===void 0?0:glide,span4,0,curve),out.push(voice),index+=1;continue}let chain=[first];for(;index+chain.length<line.length;){let last=chain[chain.length-1],next=line[index+chain.length],end2=last.start+last.duration,slide=(next.note.glide??0)>0&&next.start-end2<=ticksPerBeat/4;if(end2<=next.start&&!slide||next.note.glide===0)break;chain.push(next)}let after=line[index+chain.length],tail=chain[chain.length-1];if(after&&tail.start+tail.duration>after.start&&(tail.duration=Math.max(1,after.start-tail.start)),chain.length===1){out.push(single(first)),index+=1;continue}let segments=[];chain.forEach((item,k)=>{let offset=span4(first.start,item.start),target=interval(item.note,first.note),prior=segments[k-1],from=prior?reachedCents(prior,offset):0,segment=segmentFor(item,offset,target,from,k===0?0:glideOf(item),span4,offset,curve),sounding=k+1<chain.length?span4(item.start,chain[k+1].start):segment.length;segments.push({...segment,length:Math.min(segment.length,sounding)})});let end=tail.start+tail.duration,merged={...first,duration:end-first.start,stretch:1,pedalled:tail.pedalled??!1,...tail.damp?{damp:{from:tail.damp.from+span4(first.start,tail.start),tau:tail.damp.tau}}:{}},performance2=performanceFor(segments,merged.damp,chain.some(accented));out.push({...merged,...performance2?{performance:performance2}:{}}),index+=chain.length}return out}let chords=new Map;for(let item of working){let chord2=chords.get(item.start);chord2?chord2.push(item):chords.set(item.start,[item])}let starts=[...chords.keys()].sort((a,b)=>a-b);for(let chord2 of chords.values())chord2.sort((a,b)=>a.note.pitch-b.note.pitch);return working.map(item=>{let glide=glideOf(item);if(glide<=0)return single(item);let at3=starts.indexOf(item.start),previous=at3>0?chords.get(starts[at3-1]):void 0;if(!previous)return single(item);let rank=chords.get(item.start).indexOf(item),source=previous[Math.min(rank,previous.length-1)];return single(item,interval(source.note,item.note),glide)})}var MASTER_UNITS=Object.freeze(["trim","eq","tone","mseq","glue","multiband","tape","width","clip","limiter"]),MASTER_LIMITS=Object.freeze({minTarget:-40,maxTarget:-3,maxTargetGain:48,safeCeiling:-1}),db=(min,max,fallback,doc,step2=.5)=>({kind:"number",min,max,default:fallback,step:step2,unit:"dB",doc}),hz2=(min,max,fallback,doc)=>({kind:"number",min,max,default:fallback,step:"log",unit:"Hz",doc}),q2=doc=>({kind:"number",min:.1,max:10,default:1,step:.1,doc}),TONE_BANDS=Object.freeze([["b31",31.5],["b63",63],["b125",125],["b250",250],["b500",500],["b1k",1e3],["b2k",2e3],["b4k",4e3],["b8k",8e3],["b16k",16e3]]);function toneReach(sampleRate){let out=[];return TONE_BANDS.forEach(([,centre],index)=>{centre<=sampleRate*.45&&out.push(index)}),out}var MULTIBAND_BANDS=Object.freeze(["low","mid","high","air"]),ms=(min,max,fallback,doc,step2=1)=>({kind:"number",min,max,default:fallback,step:step2,unit:"ms",doc}),ratio=(fallback,doc)=>({kind:"number",min:1,max:10,default:fallback,step:.1,doc}),MULTIBAND_DEFAULTS={low:[-20,2,30,160,"below the low crossover: kick and sub"],mid:[-20,1.5,20,200,"low crossover to mid crossover: body and chords"],high:[-24,1.5,8,120,"mid crossover to high crossover: presence, voice and harshness"],air:[-30,2,3,80,"above the high crossover: hats, sibilance and air"]};function multibandParams(){let params2={lowfreq:hz2(40,400,120,"crossover between the low and mid bands"),midfreq:hz2(400,4e3,1e3,"crossover between the mid and high bands"),highfreq:hz2(2e3,16e3,6e3,"crossover between the high and air bands")};for(let band of MULTIBAND_BANDS){let[threshold,r,attack,release,doc]=MULTIBAND_DEFAULTS[band];params2[`${band}threshold`]=db(-60,0,threshold,`${band} band (${doc}): level where compression starts`,1),params2[`${band}ratio`]=ratio(r,`${band} band input:output above threshold`),params2[`${band}attack`]=ms(.5,100,attack,`${band} band attack`,.5),params2[`${band}release`]=ms(20,1e3,release,`${band} band release`,10),params2[`${band}gain`]=db(-12,12,0,`${band} band gain after compression`)}return params2.knee=db(0,12,6,"soft-knee width of every band",1),params2.range=db(0,24,6,"most gain reduction any band may apply",.5),params2}var MASTER_SPECS=Object.freeze({trim:{label:"trim",doc:"gain staging: sets the raw mix to a loudness before the other units, so glue and tape see the same level however loud the tracks are",simple:["lufs"],params:{lufs:{kind:"number",min:-40,max:-6,default:-16,step:.5,unit:"LUFS",doc:"integrated loudness the mix is set to before eq, glue and tape"},monitor:{kind:"number",min:0,max:40,default:0,step:.5,unit:"dB",doc:"fixed gain progressive monitoring windows use in place of the loudness trim (they cannot measure the song); 0 leaves them untrimmed"},dcblock:{kind:"boolean",default:!1,doc:"remove DC and sub-5 Hz drift (first-order high-pass) before the units, so it does not eat headroom"}}},eq:{label:"EQ",doc:"low shelf, two bells and a high shelf; 0 dB bands are skipped",simple:["low","bell1","bell2","high"],params:{low:db(-12,12,0,"low shelf gain"),lowfreq:hz2(20,1e3,100,"low shelf corner"),bell1:db(-12,12,0,"first bell gain"),bell1freq:hz2(40,16e3,400,"first bell center"),bell1q:q2("first bell width: higher is narrower"),bell2:db(-12,12,0,"second bell gain"),bell2freq:hz2(200,18e3,3e3,"second bell center"),bell2q:q2("second bell width: higher is narrower"),high:db(-12,12,0,"high shelf gain"),highfreq:hz2(1e3,2e4,1e4,"high shelf corner")}},tone:{label:"tone",doc:"tonal balance: an octave graphic EQ (bells, with shelves for the 31 Hz and 16 kHz octaves) solved so each octave centre gets exactly its gain (balance matching toward a target curve)",simple:TONE_BANDS.map(([key])=>key),params:Object.fromEntries(TONE_BANDS.map(([key,centre])=>[key,db(-8,8,0,`gain at ${centre} Hz`,.1)]))},mseq:{label:"M/S EQ",doc:"mid/side shelves and bells: shapes the center and the sides apart, so the top can widen without moving the lead or the bass; 0 dB bands are skipped",simple:["midlow","midhigh","sidelow","sidehigh"],params:{midlow:db(-12,12,0,"mid low shelf gain"),midlowfreq:hz2(20,1e3,100,"mid low shelf corner"),midbell:db(-12,12,0,"mid bell gain"),midbellfreq:hz2(200,18e3,2500,"mid bell center"),midbellq:q2("mid bell width: higher is narrower"),midhigh:db(-12,12,0,"mid high shelf gain"),midhighfreq:hz2(1e3,2e4,1e4,"mid high shelf corner"),sidelow:db(-12,12,0,"side low shelf gain"),sidelowfreq:hz2(20,1e3,200,"side low shelf corner"),sidebell:db(-12,12,0,"side bell gain"),sidebellfreq:hz2(200,18e3,3e3,"side bell center"),sidebellq:q2("side bell width: higher is narrower"),sidehigh:db(-12,12,0,"side high shelf gain"),sidehighfreq:hz2(1e3,2e4,6e3,"side high shelf corner")}},glue:{label:"glue",doc:"stereo-linked bus compressor that holds the mix together",simple:["threshold","ratio","attack","release","makeup","auto"],params:{threshold:db(-40,0,-18,"level where compression starts",1),ratio:{kind:"number",min:1,max:10,default:2,step:.5,doc:"input:output above threshold (2 and 4 are the classic bus settings)"},attack:{kind:"number",min:.1,max:30,default:10,step:.5,unit:"ms",doc:"how fast it clamps down; slower lets transients through"},release:{kind:"number",min:50,max:1200,default:300,step:50,unit:"ms",doc:"how fast it lets go; set it to breathe with the tempo"},knee:db(0,12,6,"soft-knee width",1),makeup:db(0,24,0,"gain after compression (on top of auto)"),auto:{kind:"boolean",default:!0,doc:"automatic make-up (half the reduction at 0 dBFS) so on/off compares near level-matched"},mix:{kind:"number",min:0,max:1,default:1,step:.05,doc:"dry/wet: below 1 is parallel compression"},hpf:{kind:"number",min:0,max:400,default:0,step:10,unit:"Hz",doc:"sidechain high-pass so the bass does not pump the mix; 0 is off"}}},multiband:{label:"multiband",doc:"four-band compressor: Linkwitz-Riley crossovers that sum flat, a stereo-linked RMS detector, soft knee and range per band",simple:["lowfreq","midfreq","highfreq","lowthreshold","midthreshold","highthreshold","airthreshold"],params:multibandParams()},tape:{label:"tape",doc:"tape-style saturation: soft clipping with bias, peaks held in place",simple:["drive","mix"],params:{drive:db(0,24,6,"push into the curve: denser and louder"),bias:{kind:"number",min:0,max:.5,default:.1,step:.05,doc:"asymmetry: adds even harmonics"},tone:hz2(2e3,2e4,2e4,"high-frequency roll-off after the curve; 20000 is off"),mix:{kind:"number",min:0,max:1,default:1,step:.05,doc:"dry/wet"}}},width:{label:"width",doc:"mid/side stereo width with mono bass below a cutoff",simple:["width","mono"],params:{width:{kind:"number",min:0,max:2,default:1,step:.05,doc:"side level: 0 is mono, 1 unchanged, 2 twice as wide"},mono:{kind:"number",min:0,max:300,default:120,step:10,unit:"Hz",doc:"below this the mix is mono (keeps bass centered); 0 is off"}}},clip:{label:"clip",doc:"soft clipper before the limiter: shaves transient peaks so the limiter holds less and sections keep their shape",simple:["drive","ceiling","softness"],params:{drive:db(0,18,3,"push into the clipper (louder, more clipped)"),ceiling:{kind:"number",min:-12,max:0,default:-1,step:.1,unit:"dBFS",doc:"level the clipper never exceeds"},softness:{kind:"number",min:0,max:1,default:.5,step:.05,doc:"0 clips hard at the ceiling; 1 starts rounding 6 dB below it"},oversample:{kind:"boolean",default:!1,doc:"run the curve at 4x so its harmonics do not fold back as aliasing"},target:{kind:"boolean",default:!1,doc:"the loudness target drives into the clipper (the limiter keeps its own gain) instead of into the limiter"}}},limiter:{label:"limiter",doc:"true-peak brickwall limiter with lookahead",simple:["ceiling","gain","release"],params:{ceiling:{kind:"number",min:-12,max:0,default:-1,step:.1,unit:"dBTP",doc:"highest true peak out"},gain:db(0,24,0,"drive into the limiter (a target sets it itself)"),release:{kind:"number",min:1,max:1e3,default:100,step:10,unit:"ms",doc:"recovery time; short is louder, long is cleaner"},lookahead:{kind:"number",min:.5,max:10,default:5,step:.5,unit:"ms",doc:"how early gain reduction starts before a peak"},truepeak:{kind:"boolean",default:!0,doc:"catch peaks between samples (4x oversampled detection)"},dcblock:{kind:"boolean",default:!1,doc:"remove the offset the limiter's own gain leaves (5 Hz high-pass after it; the ceiling is trimmed after that)"}}}}),LOUDNESS_TARGETS=Object.freeze({streaming:{lufs:-14,ceiling:-1,doc:"Spotify, YouTube, Tidal and Amazon play back near -14"},apple:{lufs:-16,ceiling:-1,doc:"Apple Music Sound Check level"},podcast:{lufs:-16,ceiling:-1,doc:"spoken word"},broadcast:{lufs:-23,ceiling:-1,doc:"EBU R 128 broadcast level"},club:{lufs:-8,ceiling:-2,limiter:"loud",doc:"club and DJ masters: trance, DnB, techno"},loud:{lufs:-6,ceiling:-2,limiter:"brick",doc:"loud hyperpop, gabber and hardcore masters"},classical:{lufs:-20,ceiling:-1,doc:"classical: keeps the dynamics"},ambient:{lufs:-18,ceiling:-1,doc:"ambient and drone"}}),LOUDNESS_TARGET_NAMES=Object.freeze(Object.keys(LOUDNESS_TARGETS));var MASTER_PRESETS=Object.freeze({trim:{quiet:{lufs:-20},staged:{lufs:-16},hot:{lufs:-12}},tone:{flat:{},tilt:{b31:1,b63:.8,b125:.5,b250:.2,b2k:-.2,b4k:-.5,b8k:-.8,b16k:-1},smile:{b31:1,b63:1,b125:.5,b2k:-.5,b4k:-.5,b16k:1}},mseq:{open:{sidehigh:2.5,sidehighfreq:6e3},tight:{sidelow:-3,sidelowfreq:250},presence:{midbell:1,midbellfreq:2500,midbellq:.7},"wide-top":{sidehigh:3,sidehighfreq:6e3},"tight-low":{sidelow:-4,sidelowfreq:200}},multiband:{gentle:{},tame:{highthreshold:-28,highratio:2,airthreshold:-34,airratio:3},dense:{lowthreshold:-24,midthreshold:-24,midratio:2,highthreshold:-28,highratio:2}},eq:{air:{high:2,highfreq:12e3},warm:{low:1.5,lowfreq:120,high:-1.5,highfreq:8e3},"mud-cut":{bell1:-2.5,bell1freq:300,bell1q:1.2},smile:{low:2,high:2,bell1:-1.5,bell1freq:800,bell1q:.7}},glue:{gentle:{threshold:-16,ratio:2,attack:30,release:300},glue:{threshold:-20,ratio:4,attack:10,release:100},pump:{threshold:-26,ratio:10,attack:.1,release:200,hpf:0}},tape:{warm:{drive:3,bias:.15,tone:16e3},hot:{drive:9,bias:.2,tone:14e3},crush:{drive:18,bias:.3,tone:9e3}},width:{narrow:{width:.7,mono:150},wide:{width:1.4,mono:120},vinyl:{width:1,mono:150}},clip:{gentle:{drive:2,softness:.7},rave:{drive:5,softness:.4},hard:{drive:8,softness:0}},limiter:{transparent:{release:300,lookahead:5},loud:{release:60,lookahead:2},brick:{release:20,lookahead:1}}});function isMasterUnit(name){return MASTER_UNITS.includes(name)}function masterActive(master){return master!==void 0&&(master.target!==void 0||MASTER_UNITS.some(unit4=>master[unit4]!==void 0))}function normalizeMaster(input){if(input==null)return;if(!isRecord2(input))throw new FxValidationError("master must be an object");for(let key of Object.keys(input))if(key!=="target"&&!isMasterUnit(key))throw new FxValidationError(`master has no "${key}"; use ${[...MASTER_UNITS,"target"].join(", ")}`);let out={};for(let unit4 of MASTER_UNITS){let value=input[unit4];value!=null&&(out[unit4]=normalizeParams(MASTER_SPECS[unit4].params,value,`master ${unit4}`))}let target=input.target;if(target!=null){if(typeof target!="number"||!Number.isFinite(target)||target<MASTER_LIMITS.minTarget||target>MASTER_LIMITS.maxTarget)throw new FxValidationError(`master target must be ${MASTER_LIMITS.minTarget}..${MASTER_LIMITS.maxTarget} LUFS`);out.target=target}return Object.keys(out).length>0?Object.freeze(out):void 0}var VOX_PHONES=Object.freeze(["iy","ih","eh","ae","aa","ah","ao","uh","uw","er","ax","ey","ay","aw","oy","ow","w","y","r","l","m","n","ng","s","z","sh","zh","f","v","th","dh","hh","p","b","t","d","k","g","ch","jh","q","dx"]),PHONE_SET=new Set(VOX_PHONES),VOX_ENGINES=Object.freeze(["formant","espeak-ng","kokoro","piper","openutau","say"]),VOX_FITS=Object.freeze(["psola","world","none"]),VOX_LIMITS=Object.freeze({maxPhones:12,maxParams:8,maxVoiceLength:64,maxDynPoints:16});var NOTE_VOX_KEYS=Object.freeze(["ph","lang","cons","lead","shift","breath","dyn","p"]),TRACK_VOX_KEYS=Object.freeze(["engine","voice","lang","fit","p"]),VoxValidationError=class extends Error{constructor(message){super(message),this.name="VoxValidationError"}},fail4=message=>{throw new VoxValidationError(message)};function numberIn(value,min,max,label){return typeof value!="number"||!Number.isFinite(value)?fail4(`${label} must be a number`):value<min||value>max?fail4(`${label} must be ${min}..${max}`):value}var LANG=/^[a-z]{2,3}(?:-[a-z0-9]{2,8})*$/i;function lang(value,label){return typeof value!="string"||value.length>16||!LANG.test(value)?fail4(`${label} must be a language tag like en-us`):value.toLowerCase()}function parsePhones(value,label="vox ph"){let list=typeof value=="string"?value.trim().split(/\s+/).filter(Boolean):Array.isArray(value)?value:fail4(`${label} must be phones like "hh eh l"`);return list.length===0?fail4(`${label} needs at least one phone`):list.length>VOX_LIMITS.maxPhones?fail4(`${label} takes at most ${VOX_LIMITS.maxPhones} phones`):list.map(raw=>{if(typeof raw!="string")return fail4(`${label} phones are strings`);let phone=raw.toLowerCase().replace(/[0-2]$/,"");return PHONE_SET.has(phone)?phone:fail4(`${label} "${raw.slice(0,8)}" is not a phone (ARPAbet: hh eh l ow \u2026)`)})}function params(value,label){if(!isRecord2(value))return fail4(`${label} must be an object of numbers`);let keys=Object.keys(value).sort();if(keys.length>VOX_LIMITS.maxParams)return fail4(`${label} takes at most ${VOX_LIMITS.maxParams} params`);let out={};for(let key of keys){if(!/^[a-z][a-z0-9]{0,15}$/i.test(key))return fail4(`${label} key "${key.slice(0,16)}" is not a param name`);out[key]=numberIn(value[key],-1e3,1e3,`${label}.${key}`)}return out}function normalizeNoteVox(input,label="vox"){if(input==null)return;if(!isRecord2(input))return fail4(`${label} must be an object`);for(let key of Object.keys(input))NOTE_VOX_KEYS.includes(key)||fail4(`${label} has no field "${key.slice(0,16)}" (${NOTE_VOX_KEYS.join(" ")})`);let out={};if(input.ph!==void 0&&(out.ph=Object.freeze(parsePhones(input.ph,`${label} ph`))),input.lang!==void 0&&(out.lang=lang(input.lang,`${label} lang`)),input.cons!==void 0){let cons=input.cons;isRecord2(cons)?(Object.keys(cons).some(key=>key!=="s")&&fail4(`${label} cons takes { s } seconds`),out.cons=Object.freeze({s:numberIn(cons.s,0,1,`${label} cons.s`)})):out.cons=numberIn(cons,0,.9,`${label} cons`)}if(input.lead!==void 0&&(out.lead=numberIn(input.lead,0,.25,`${label} lead`)),input.shift!==void 0&&(out.shift=numberIn(input.shift,-.25,.25,`${label} shift`)),input.breath!==void 0&&(out.breath=numberIn(input.breath,.05,1,`${label} breath`)),input.dyn!==void 0){(!Array.isArray(input.dyn)||input.dyn.length===0)&&fail4(`${label} dyn must be a list of { at, v } points`);let dyn=input.dyn;dyn.length>VOX_LIMITS.maxDynPoints&&fail4(`${label} dyn takes at most ${VOX_LIMITS.maxDynPoints} points`);let last=-1;out.dyn=Object.freeze(dyn.map((point,index)=>{if(!isRecord2(point)||Object.keys(point).some(k=>k!=="at"&&k!=="v"))return fail4(`${label} dyn[${index}] must be { at, v }`);let at3=numberIn(point.at,0,1,`${label} dyn[${index}].at`);return at3<last&&fail4(`${label} dyn points must be in time order`),last=at3,Object.freeze({at:at3,v:numberIn(point.v,0,1,`${label} dyn[${index}].v`)})}))}return input.p!==void 0&&(out.p=Object.freeze(params(input.p,`${label} p`))),Object.keys(out).length>0?Object.freeze(out):void 0}function normalizeTrackVox(input,label="vox"){if(input==null)return;if(!isRecord2(input))return fail4(`${label} must be an object`);for(let key of Object.keys(input))TRACK_VOX_KEYS.includes(key)||fail4(`${label} has no field "${key.slice(0,16)}" (${TRACK_VOX_KEYS.join(" ")})`);let engine2=input.engine??"formant";VOX_ENGINES.includes(engine2)||fail4(`${label} engine must be one of ${VOX_ENGINES.join(" ")}`);let voice=input.voice??`${String(engine2)}:default`;(typeof voice!="string"||voice.length===0||voice.length>VOX_LIMITS.maxVoiceLength||/\s/.test(voice))&&fail4(`${label} voice must be 1..${VOX_LIMITS.maxVoiceLength} characters without spaces`);let out={engine:engine2,voice};return input.lang!==void 0&&(out.lang=lang(input.lang,`${label} lang`)),input.fit!==void 0&&(VOX_FITS.includes(input.fit)||fail4(`${label} fit must be one of ${VOX_FITS.join(" ")}`),out.fit=input.fit),input.p!==void 0&&(out.p=Object.freeze(params(input.p,`${label} p`))),Object.freeze(out)}var STYLE_ID=/^[a-z0-9][a-z0-9-]{0,63}$/;var SongStyleError=class extends Error{name="SongStyleError"};function fail5(message){throw new SongStyleError(`style ${message}`)}function styleId(value,label){return(typeof value!="string"||!STYLE_ID.test(value))&&fail5(`${label} must be a style id like "deep-house"`),value}function normalizeSongStyle(value){if(value==null)return;(typeof value!="object"||Array.isArray(value))&&fail5("must be an object { id, seed, bars }");let record2=value;for(let key of Object.keys(record2))["id","seed","bars","blend"].includes(key)||fail5(`has no "${key}"; use id, seed, bars, blend`);let id=styleId(record2.id,"id"),seed=record2.seed;(typeof seed!="number"||!Number.isInteger(seed)||seed<0||seed>2147483647)&&fail5("seed must be an integer 0..2147483647");let bars=record2.bars;(typeof bars!="number"||!Number.isInteger(bars)||bars<1||bars>256)&&fail5("bars must be an integer 1..256");let blend2;if(record2.blend!==void 0&&record2.blend!==null){let raw=record2.blend;(typeof raw!="object"||Array.isArray(raw))&&fail5("blend must be { id, weight }");let part=raw,weight=part.weight;(typeof weight!="number"||!Number.isFinite(weight)||weight<0||weight>1)&&fail5("blend weight must be 0..1"),blend2=Object.freeze({id:styleId(part.id,"blend id"),weight})}return Object.freeze({id,seed,bars,...blend2?{blend:blend2}:{}})}var SCORE_STEPS=Object.freeze([]),steps=SCORE_STEPS;function checked(list){return list.forEach((step2,index)=>{let from=1-list.length+index;if(step2.from!==from)throw new Error(`score step ${index} reads version ${step2.from}, not ${from}`);if(!step2.reason.trim()||!step2.hint.trim())throw new Error(`score step from ${step2.from} needs a reason and a hint`);if(/\n/u.test(step2.reason)||/\n/u.test(step2.hint))throw new Error(`score step from ${step2.from}: one line each`)}),list}checked(SCORE_STEPS);function oldestScoreVersion(){return 1-steps.length}var ScoreVersionError=class extends Error{fault;constructor(fault,message){super(message),this.name="ScoreVersionError",this.fault=fault}};function shown(version){return typeof version=="string"||typeof version=="number"||typeof version=="boolean"||typeof version=="bigint"?String(version).slice(0,40):"[object]"}function scoreStepsFrom(version){if(typeof version!="number"||!Number.isSafeInteger(version))throw new ScoreVersionError("invalid",`unsupported score version: ${shown(version)}`);if(version>1)throw new ScoreVersionError("newer",`unsupported score version: ${version} \xB7 this dawn reads up to 1 \xB7 update dawn`);let oldest=oldestScoreVersion();if(version<oldest)throw new ScoreVersionError("older",`unsupported score version: ${version} \xB7 the first is ${oldest}`);return steps.slice(version-oldest)}function upgradeScore(score){if(score.version===void 0)return{score,from:1,steps:[]};let from=score.version,needed=scoreStepsFrom(from);if(needed.length===0)return{score,from:1,steps:needed};let next=score;for(let step2 of needed){let out=step2.up(next);if(typeof out!="object"||out===null||Array.isArray(out))throw new ScoreVersionError("invalid",`the step from score version ${step2.from} did not return a score`);next={...out,version:step2.from+1}}return{score:next,from,steps:needed}}var CALIBRATION_LATEST=1,DEFAULT_TICKS_PER_BEAT=480,SCORE_LIMITS=Object.freeze({maxTracks:64,maxNotes:4096,maxIdLength:64,maxNameLength:96,maxInstrumentLength:64,maxAutomationPoints:256,maxVolume:1,maxTempoBpm:300,minTempoBpm:20,maxBars:256,maxSections:64,maxSectionNameLength:32,maxFormEntries:128,maxFormRepeat:16,maxSectionTranspose:24,maxSectionGain:2,maxBeatsPerBar:16,maxTicksPerBeat:4096,maxTick:67108864,minFilterCutoff:20,maxFilterCutoff:2e4,maxFilterResonance:1,minDelayBeats:.0625,maxDelayBeats:4,maxDelayFeedback:.9,maxDelayMix:1,maxReverbMix:1,minReverbSize:0,maxReverbSize:1,maxFxLanes:64,maxPatchNodes:64,maxPatchCables:128,maxPatchMacros:16,maxPatches:32,maxPatchDepth:3,maxSamplerVoices:64,maxSamplerVoiceNameLength:32,maxSamplePathLength:256,maxSampleUrlLength:1024,maxSampleGain:2,maxSampleSpeed:8,maxChokeGroupLength:32,maxSampleClip:16,maxSampleAccelerate:8,maxSampleSquiz:32,minSampleBpm:20,maxSampleBpm:400,maxSampleLenBeats:1024,maxSampleShift:24,maxSampleFadeSeconds:2,maxResampleSeconds:600,maxSampleFileBytes:50*1024*1024,maxSampleSeconds:600,maxSampleCacheBytes:512*1024*1024,maxClipsPerTrack:256,maxTakesPerTrack:64,maxClipGain:4,maxClipFadeSeconds:2,maxClipSeconds:520,maxClipTextLength:2e3,maxLyricLength:32,maxTakeNudgeMs:250,maxTtsVoiceLength:64,singVoices:8,singVoicesPerTrack:48,maxSayCuts:512,maxTakePpm:1e3,minVocoderBands:4,maxVocoderBands:40,maxVocoderFormant:24,maxVocoderTracks:8,maxAutotuneSpeedMs:400,maxAutotuneHoldMs:1e3,maxAutotuneGlideSeconds:.5,maxAutotuneVibHz:12,maxAutotuneShift:12}),WAVETABLE_INSTRUMENT2="wavetable",WARP_MODES=Object.freeze(["none","asym","bendp","bendm","bendmp","sync","quant"]),BUILTIN_TABLE_PREFIX="builtin:",WAVETABLE_PARAMS=Object.freeze({wt:[0,1,0],wtenv:[-1,1,0],wtattack:[0,10,.01],wtdecay:[0,10,.1],wtsustain:[0,1,1],wtrelease:[0,10,.1],wtrate:[0,50,0],wtdepth:[0,1,0],warp:[0,1,0],wtphaserand:[0,1,0]}),BUILTIN_TABLE=/^builtin:[a-z][a-z0-9_-]{0,31}$/;function isLocalTableSrc(src){return!src.startsWith(PACK_PREFIX)&&!src.startsWith(BUILTIN_TABLE_PREFIX)&&/\.wav$/i.test(src)&&isSafeRelativePath(src)}function isWavetableInstrument(instrument){return typeof instrument=="string"&&instrument.trim().toLowerCase()===WAVETABLE_INSTRUMENT2}function wavetableOf(track2){return track2.wavetable??DEFAULT_WAVETABLE}var DEFAULT_WAVETABLE=Object.freeze({table:Object.freeze({src:`${BUILTIN_TABLE_PREFIX}basic`})});function normalizeWavetable(input){if(input==null)return;if(!isRecord4(input))throw new ScoreValidationError("track wavetable must be an object or null","invalid-track");let table2=input.table,ref;if(isRecord4(table2)&&typeof table2.src=="string"&&table2.src.startsWith(BUILTIN_TABLE_PREFIX)){if(!BUILTIN_TABLE.test(table2.src)||Object.keys(table2).length!==1)throw new ScoreValidationError("wavetable table builtin:<name> takes no other fields","invalid-track");ref=Object.freeze({src:table2.src})}else if(ref=normalizeSampleRef(table2,"wavetable table"),!isPackRef(ref.src)&&!isLocalTableSrc(ref.src))throw new ScoreValidationError("wavetable table must be builtin:<name>, pack:<pack>/<sound>[:<n>] or a project .wav path","invalid-track");let out={table:ref};for(let name of Object.keys(WAVETABLE_PARAMS)){let value=input[name];if(value===void 0)continue;let[min,max,fallback]=WAVETABLE_PARAMS[name];if(typeof value!="number"||!Number.isFinite(value))throw new ScoreValidationError(`wavetable ${name} must be a number ${min}..${max}`,"invalid-track");let clamped=Math.max(min,Math.min(max,value));clamped!==fallback&&(out[name]=clamped)}if(input.warpmode!==void 0){if(!WARP_MODES.includes(input.warpmode))throw new ScoreValidationError(`wavetable warpmode must be one of ${WARP_MODES.join(", ")}`,"invalid-track");input.warpmode!=="none"&&(out.warpmode=input.warpmode)}for(let key of Object.keys(input))if(key!=="table"&&key!=="warpmode"&&!Object.prototype.hasOwnProperty.call(WAVETABLE_PARAMS,key))throw new ScoreValidationError(`wavetable has an unknown field ${key.slice(0,32)}`,"invalid-track");return Object.freeze(out)}var SAMPLER_INSTRUMENT2="sampler",SAMPLER_FIRST_SLOT2=36,ScoreValidationError=class extends Error{code;constructor(message,code="invalid-score"){super(message),this.name="ScoreValidationError",this.code=code}};var SAMPLE_FIT_MODES=Object.freeze(["repitch","beats","tones"]),SAMPLE_UNITS=Object.freeze(["r","c","s"]),REVERB_IR_BUILTINS=Object.freeze(["room","hall","plate","reverse","gate","spring"]);function normalizeReverbIr(input){let ref=typeof input=="string"?{src:input}:input;if(isRecord4(ref)&&typeof ref.src=="string"){let bare=REVERB_IR_BUILTINS.includes(ref.src);if(bare||ref.src.startsWith(BUILTIN_TABLE_PREFIX)){let name=bare?ref.src:ref.src.slice(BUILTIN_TABLE_PREFIX.length);if(!REVERB_IR_BUILTINS.includes(name)||Object.keys(ref).length!==1)throw new ScoreValidationError(`track reverb ir builtin must be one of ${REVERB_IR_BUILTINS.map(n2=>`builtin:${n2}`).join(", ")} with no other fields`,"invalid-track");return Object.freeze({src:`${BUILTIN_TABLE_PREFIX}${name}`})}}return normalizeSampleRef(ref,"reverb ir")}var AUTOMATION_LANES=Object.freeze({volume:{field:"volumeAutomation",min:0,max:SCORE_LIMITS.maxVolume},pan:{field:"panAutomation",min:-1,max:1},filter:{field:"filterAutomation",min:SCORE_LIMITS.minFilterCutoff,max:SCORE_LIMITS.maxFilterCutoff},resonance:{field:"resonanceAutomation",min:0,max:SCORE_LIMITS.maxFilterResonance},"delay-feedback":{field:"delayFeedbackAutomation",min:0,max:SCORE_LIMITS.maxDelayFeedback},"delay-mix":{field:"delayMixAutomation",min:0,max:SCORE_LIMITS.maxDelayMix},wt:{field:"wtAutomation",min:0,max:1}}),FX_LANE_RANGES=new Map(FX_LANES.map(({lane,spec})=>[lane,{min:spec.min,max:spec.max}])),PATCH_LANE_RANGE=Object.freeze({min:0,max:1});function fxLaneRange(lane){return FX_LANE_RANGES.get(lane)??(isPatchLane(lane)?PATCH_LANE_RANGE:void 0)}var AUTOMATION_PARAMETERS=Object.freeze([...Object.keys(AUTOMATION_LANES),...FX_LANES.map(({lane})=>lane)]);var TrackScore=class _TrackScore{version=1;tempoBpm;beatsPerBar;bars;ticksPerBeat;key;tuning;tracks;notes;sections;form;loopSection;patches;constructor(data={}){let tempoBpm=data.tempoBpm??120,beatsPerBar=data.beatsPerBar??4,bars=data.bars??4,ticksPerBeat=data.ticksPerBeat??DEFAULT_TICKS_PER_BEAT,key=data.key??null;if(!Number.isFinite(tempoBpm)||tempoBpm<SCORE_LIMITS.minTempoBpm||tempoBpm>SCORE_LIMITS.maxTempoBpm)throw new ScoreValidationError(`tempoBpm must be between ${SCORE_LIMITS.minTempoBpm} and ${SCORE_LIMITS.maxTempoBpm}`,"invalid-score");if(!Number.isInteger(beatsPerBar)||beatsPerBar<1||beatsPerBar>SCORE_LIMITS.maxBeatsPerBar)throw new ScoreValidationError(`beatsPerBar must be an integer between 1 and ${SCORE_LIMITS.maxBeatsPerBar}`,"invalid-score");if(!Number.isInteger(bars)||bars<1||bars>SCORE_LIMITS.maxBars)throw new ScoreValidationError(`bars must be an integer between 1 and ${SCORE_LIMITS.maxBars}`,"invalid-score");if(!Number.isInteger(ticksPerBeat)||ticksPerBeat<1||ticksPerBeat>SCORE_LIMITS.maxTicksPerBeat)throw new ScoreValidationError(`ticksPerBeat must be an integer between 1 and ${SCORE_LIMITS.maxTicksPerBeat}`,"invalid-score");if(key!==null&&(typeof key!="string"||key.length>SCORE_LIMITS.maxNameLength))throw new ScoreValidationError("key must be null or a short string","invalid-score");let time=timeOrThrow(()=>{let normalized=normalizeSongTime(data.time);return checkSongTime(normalized,ticksPerBeat,{tempoBpm,beatsPerBar,bars}),normalized}),tuning=tuningOrThrow(()=>normalizeTuning(data.tuning,"song tuning"),"invalid-score"),patches=patchOrThrow(()=>validateLibrary(data.patches,{engineSettings:normalizeEngineSettings})),tracks=normalizeTracks(data.tracks??[],patches),notes=normalizeNotes(data.notes??[]),trackIds=new Set(tracks.map(track2=>track2.id)),orphan=notes.find(note2=>!trackIds.has(note2.trackId));if(orphan)throw new ScoreValidationError(`note ${orphan.id} is on track ${orphan.trackId}, which does not exist`,"invalid-note");this.tuning=tuning;let master;try{master=normalizeMaster(data.master)}catch(error){throw error instanceof FxValidationError?new ScoreValidationError(error.message,"invalid-score"):error}master&&(this.master=master);let style2;try{style2=normalizeSongStyle(data.style)}catch(error){throw error instanceof SongStyleError?new ScoreValidationError(error.message,"invalid-score"):error}style2&&(this.style=style2);let sections=normalizeSections(data.sections??[]),form=normalizeForm(data.form??[],sections);if(sections.length>0&&time?.meter?.some((change,index)=>index>0||change.bar>0))throw new ScoreValidationError("sections need one meter: remove the meter changes (time.meter) or the sections","invalid-score");this.tempoBpm=tempoBpm,this.beatsPerBar=beatsPerBar,this.bars=bars,this.ticksPerBeat=ticksPerBeat,this.key=key,time&&(this.time=time),this.tracks=freezeArray(tracks),this.notes=freezeArray(notes),this.patches=patches,this.sections=freezeArray(sections),this.form=freezeArray(form);let loop=normalizeLoopRange(data.loop),looped=normalizeLoopSection(data.loopSection,sections);this.loopSection=loop?void 0:looped,loop&&(this.loop=loop);let calibration=normalizeCalibration(data.calibration);calibration&&(this.calibration=calibration),Object.freeze(this)}addNote(note2){return addNote(this,note2)}removeNote(noteId){return removeNote(this,noteId)}withTracks(tracks){let ids=new Set(tracks.map(track2=>track2.id));return new _TrackScore({...this.toJSON(),tracks,notes:this.notes.filter(note2=>ids.has(note2.trackId))})}withLoop(loop){return new _TrackScore({...this.toJSON(),loop,...loop?{loopSection:null}:{}})}withTempo(tempoBpm){return new _TrackScore({...this.toJSON(),tempoBpm})}withSections(sections,form=[],loopSection=this.loopSection){return new _TrackScore({...this.toJSON(),sections,form,loopSection:loopSection??null,...loopSection?{loop:null}:{}})}withBars(bars){let time=bars<this.bars?timeWithinSong({tempoBpm:this.tempoBpm,beatsPerBar:this.beatsPerBar,ticksPerBeat:this.ticksPerBeat,bars,...this.time?{time:this.time}:{}}):this.time;return new _TrackScore({...this.toJSON(),bars,time:time??null})}withKey(key){return new _TrackScore({...this.toJSON(),key})}withTuning(tuning){return new _TrackScore({...this.toJSON(),tuning})}withMeter(beatsPerBar){let time=this.time?.meter?.some(change=>change.bar===0)?withMeterChange(this.time,0,null):this.time;return new _TrackScore({...this.toJSON(),beatsPerBar,time:time??null})}withTime(time){return new _TrackScore({...this.toJSON(),time:time??null})}withCalibration(calibration){return new _TrackScore({...this.toJSON(),calibration})}withMaster(master){return new _TrackScore({...this.toJSON(),master})}withStyle(style2){return new _TrackScore({...this.toJSON(),style:style2})}toJSON(){return{version:1,tempoBpm:this.tempoBpm,beatsPerBar:this.beatsPerBar,bars:this.bars,ticksPerBeat:this.ticksPerBeat,key:this.key,...this.time?{time:this.time}:{},...this.tuning?{tuning:this.tuning}:{},tracks:this.tracks,notes:this.notes,...this.master?{master:this.master}:{},...this.style?{style:this.style}:{},...this.sections.length>0?{sections:this.sections}:{},...this.form.length>0?{form:this.form}:{},...this.loopSection===void 0?{}:{loopSection:this.loopSection},...this.loop?{loop:this.loop}:{},...this.calibration?{calibration:this.calibration}:{},...Object.keys(this.patches).length>0?{patches:this.patches}:{}}}};function addNote(score,input){if(!(score instanceof TrackScore))throw new ScoreValidationError("addNote requires a TrackScore");let note2=normalizeNote(input);if(score.notes.some(candidate=>candidate.id===note2.id))throw new ScoreValidationError(`note id already exists: ${note2.id}`,"duplicate-note");if(score.notes.length>=SCORE_LIMITS.maxNotes)throw new ScoreValidationError(`score cannot contain more than ${SCORE_LIMITS.maxNotes} notes`,"score-limit");return new TrackScore({...score.toJSON(),notes:[...score.notes,note2]})}function removeNote(score,noteId){if(!(score instanceof TrackScore))throw new ScoreValidationError("removeNote requires a TrackScore");if(typeof noteId!="string"||noteId.length===0||noteId.length>SCORE_LIMITS.maxIdLength)throw new ScoreValidationError("noteId must be a non-empty short string","invalid-note");return score.notes.some(note2=>note2.id===noteId)?new TrackScore({...score.toJSON(),notes:score.notes.filter(note2=>note2.id!==noteId)}):score}function isSamplerInstrument(instrument){return typeof instrument=="string"&&instrument.trim().toLowerCase()===SAMPLER_INSTRUMENT2}function samplerVoiceSlots(sampler){let slots=new Map;return sampler.mode!=="oneshot"||Object.keys(sampler.voices).sort(compareCodePoints).forEach((name,index)=>slots.set(name,SAMPLER_FIRST_SLOT2+index)),slots}function compareCodePoints(a,b){return a<b?-1:a>b?1:0}function isTrackAudible(score,trackId){let track2=score.tracks.find(candidate=>candidate.id===trackId);return track2?.muted?!1:!score.tracks.some(candidate=>candidate.solo===!0)||track2?.solo===!0}function scoreFromJSON(value){if(!isRecord4(value))throw new ScoreValidationError("score must be an object");try{value=upgradeScore(value).score}catch(error){throw error instanceof ScoreVersionError?new ScoreValidationError(error.message):error}if(!isRecord4(value))throw new ScoreValidationError("score must be an object");let data={tracks:optionalArray(value.tracks).map(parseTrack),notes:optionalArray(value.notes).map(parseNote)},trackIds=new Set(data.tracks.map(track2=>track2.id));data.notes=normalizeNotes(data.notes).filter(note2=>trackIds.has(note2.trackId));let tempoBpm=optionalNumber(value.tempoBpm),beatsPerBar=optionalNumber(value.beatsPerBar),bars=optionalNumber(value.bars),ticksPerBeat=optionalNumber(value.ticksPerBeat),key=optionalNullableString(value.key);return tempoBpm!==void 0&&(data.tempoBpm=tempoBpm),beatsPerBar!==void 0&&(data.beatsPerBar=beatsPerBar),bars!==void 0&&(data.bars=bars),ticksPerBeat!==void 0&&(data.ticksPerBeat=ticksPerBeat),key!==void 0&&(data.key=key),value.time!==void 0&&value.time!==null&&(data.time=value.time),value.tuning!==void 0&&(data.tuning=value.tuning),value.master!==void 0&&value.master!==null&&(data.master=value.master),value.style!==void 0&&value.style!==null&&(data.style=value.style),value.sections!==void 0&&(data.sections=optionalArray(value.sections)),value.form!==void 0&&(data.form=optionalArray(value.form)),value.loopSection!==void 0&&(data.loopSection=value.loopSection),value.loop!==void 0&&(data.loop=value.loop),migrateHiddenLoop(data),value.calibration!==void 0&&(data.calibration=value.calibration),value.patches!==void 0&&(data.patches=value.patches),new TrackScore(data)}var SECTION_NAME=/^[^\u0000-\u001f\u007f]+$/u;function normalizeSections(inputs2){if(!Array.isArray(inputs2)||inputs2.length>SCORE_LIMITS.maxSections)throw new ScoreValidationError(`score cannot contain more than ${SCORE_LIMITS.maxSections} sections`,"score-limit");let seen=new Set;return inputs2.map((input,index)=>{if(!isRecord4(input))throw new ScoreValidationError(`section ${index} must be an object`);let name=typeof input.name=="string"?input.name.trim().replace(/\s+/gu," "):"";if(name.length===0||name.length>SCORE_LIMITS.maxSectionNameLength||!SECTION_NAME.test(name))throw new ScoreValidationError(`section ${index} needs a name of 1..${SCORE_LIMITS.maxSectionNameLength} characters`);let folded=name.toLowerCase();if(seen.has(folded))throw new ScoreValidationError(`duplicate section name: ${name}`);seen.add(folded);let startBar=input.startBar,bars=input.bars;if(typeof startBar!="number"||!Number.isInteger(startBar)||startBar<0||startBar>=SCORE_LIMITS.maxBars)throw new ScoreValidationError(`section ${name} startBar must be an integer 0..${SCORE_LIMITS.maxBars-1}`);if(typeof bars!="number"||!Number.isInteger(bars)||bars<1||startBar+bars>SCORE_LIMITS.maxBars)throw new ScoreValidationError(`section ${name} bars must be an integer 1..${SCORE_LIMITS.maxBars-startBar}`);let out={name,startBar,bars};if(input.mute!==void 0){if(!Array.isArray(input.mute)||input.mute.length>SCORE_LIMITS.maxTracks||input.mute.some(id=>typeof id!="string"||id.length===0))throw new ScoreValidationError(`section ${name} mute must be a list of track ids`);let mute=[...new Set(input.mute)];mute.length>0&&(out.mute=freezeArray(mute))}if(input.vary!==void 0){if(!isRecord4(input.vary))throw new ScoreValidationError(`section ${name} vary must map track ids to variations`);let entries=Object.entries(input.vary);if(entries.length>SCORE_LIMITS.maxTracks)throw new ScoreValidationError(`section ${name} vary has too many tracks`);let vary={};for(let[trackId,raw]of entries.sort(([a],[b])=>a<b?-1:a>b?1:0)){if(!isRecord4(raw)||trackId.length===0)throw new ScoreValidationError(`section ${name} vary.${trackId} must be an object`);let variation={};if(raw.transpose!==void 0){let t=raw.transpose;if(typeof t!="number"||!Number.isInteger(t)||Math.abs(t)>SCORE_LIMITS.maxSectionTranspose)throw new ScoreValidationError(`section ${name} vary.${trackId}.transpose must be an integer -${SCORE_LIMITS.maxSectionTranspose}..${SCORE_LIMITS.maxSectionTranspose}`);t!==0&&(variation.transpose=t)}if(raw.gain!==void 0){let g=raw.gain;if(typeof g!="number"||!Number.isFinite(g)||g<0||g>SCORE_LIMITS.maxSectionGain)throw new ScoreValidationError(`section ${name} vary.${trackId}.gain must be 0..${SCORE_LIMITS.maxSectionGain}`);g!==1&&(variation.gain=g)}Object.keys(variation).length>0&&(vary[trackId]=Object.freeze(variation))}Object.keys(vary).length>0&&(out.vary=Object.freeze(vary))}return Object.freeze(out)}).map((section,index)=>({section,index})).sort((a,b)=>a.section.startBar-b.section.startBar||a.index-b.index).map(({section})=>section)}function normalizeCalibration(value){if(!(value==null||value===0)){if(typeof value!="number"||!Number.isInteger(value)||value<0||value>CALIBRATION_LATEST)throw new ScoreValidationError(`calibration must be an integer 0..${CALIBRATION_LATEST}`,"invalid-score");return value}}function normalizeLoopRange(value){if(value==null)return;let range=value,{startBar,bars}=range;if(typeof value!="object"||typeof startBar!="number"||typeof bars!="number"||!Number.isInteger(startBar)||!Number.isInteger(bars)||startBar<0||bars<1||startBar+bars>SCORE_LIMITS.maxBars)throw new ScoreValidationError(`loop must be {startBar, bars}: whole bars from 0, 1..${SCORE_LIMITS.maxBars}`,"invalid-score");return Object.freeze({startBar,bars})}function migrateHiddenLoop(data){if(data.loop||typeof data.loopSection!="string"||data.loopSection.trim().toLowerCase()!=="loop")return;let sections=data.sections??[],hidden=sections.find(section=>typeof section?.name=="string"&§ion.name.trim().toLowerCase()==="loop");!hidden||!Number.isInteger(hidden.startBar)||!Number.isInteger(hidden.bars)||(data.loop={startBar:hidden.startBar,bars:hidden.bars},data.loopSection=null,data.sections=sections.filter(section=>section!==hidden),data.form&&(data.form=data.form.filter(entry=>entry?.section?.trim?.().toLowerCase()!=="loop")))}function normalizeLoopSection(value,sections){if(value==null)return;if(typeof value!="string")throw new ScoreValidationError("loopSection must be a section name or null","invalid-score");let key=value.trim().replace(/\s+/gu," ").toLowerCase();return sections.find(section=>section.name.toLowerCase()===key)?.name}function normalizeForm(inputs2,sections){if(!Array.isArray(inputs2)||inputs2.length>SCORE_LIMITS.maxFormEntries)throw new ScoreValidationError(`form cannot contain more than ${SCORE_LIMITS.maxFormEntries} entries`,"score-limit");let byName=new Map(sections.map(section=>[section.name.toLowerCase(),section]));return inputs2.map((input,index)=>{let record2=typeof input=="string"?{section:input}:input;if(!isRecord4(record2)||typeof record2.section!="string")throw new ScoreValidationError(`form entry ${index} must name a section`);let section=byName.get(record2.section.trim().toLowerCase());if(!section)throw new ScoreValidationError(`form entry ${index} names an unknown section: ${record2.section}`);let repeat=record2.repeat??1;if(typeof repeat!="number"||!Number.isInteger(repeat)||repeat<1||repeat>SCORE_LIMITS.maxFormRepeat)throw new ScoreValidationError(`form entry ${index} repeat must be an integer 1..${SCORE_LIMITS.maxFormRepeat}`);return Object.freeze(repeat===1?{section:section.name}:{section:section.name,repeat})})}function normalizeTracks(inputs2,library={}){if(!Array.isArray(inputs2)||inputs2.length>SCORE_LIMITS.maxTracks)throw new ScoreValidationError(`score cannot contain more than ${SCORE_LIMITS.maxTracks} tracks`,"score-limit");let seen=new Set,tracks=inputs2.map(input=>{let track2=normalizeTrack(input,library);if(seen.has(track2.id))throw new ScoreValidationError(`track id already exists: ${track2.id}`,"duplicate-track");return seen.add(track2.id),track2}),vocoderError=vocoderScoreError(tracks,SCORE_LIMITS.maxVocoderTracks);if(vocoderError)throw new ScoreValidationError(vocoderError,"invalid-track");for(let track2 of tracks){let from=track2.autotune?.from;if(from!==void 0&&(from===track2.id||!seen.has(from)))throw new ScoreValidationError(from===track2.id?`track ${track2.id} autotune.from cannot be the track itself`:`track ${track2.id} autotune.from: unknown track "${from}"`,"invalid-track")}return tracks}function normalizeTrack(input,library={}){if(!isRecord4(input))throw new ScoreValidationError("track must be an object","invalid-track");let id=boundedString(input.id,"track id",SCORE_LIMITS.maxIdLength,"invalid-track"),name=boundedString(input.name??id,"track name",SCORE_LIMITS.maxNameLength,"invalid-track"),instrument=boundedString(input.instrument??"sine","instrument",SCORE_LIMITS.maxInstrumentLength,"invalid-track"),muted=input.muted??!1;if(typeof muted!="boolean")throw new ScoreValidationError("track muted must be boolean","invalid-track");let volume=input.volume??1,pan2=input.pan??0;if(typeof volume!="number"||!Number.isFinite(volume)||volume<0||volume>1)throw new ScoreValidationError("track volume must be between 0 and 1","invalid-track");if(typeof pan2!="number"||!Number.isFinite(pan2)||pan2<-1||pan2>1)throw new ScoreValidationError("track pan must be between -1 and 1","invalid-track");let volumeAutomation=normalizeAutomation(input.volumeAutomation,"volumeAutomation",0,SCORE_LIMITS.maxVolume),panAutomation=normalizeAutomation(input.panAutomation,"panAutomation",-1,1),solo=input.solo??!1;if(typeof solo!="boolean")throw new ScoreValidationError("track solo must be boolean","invalid-track");let filter=normalizeFilter(input.filter),delay=normalizeDelay(input.delay),filterAutomation=normalizeAutomation(input.filterAutomation,"filterAutomation",SCORE_LIMITS.minFilterCutoff,SCORE_LIMITS.maxFilterCutoff),lane=parameter=>{let{field,min,max}=AUTOMATION_LANES[parameter];return normalizeAutomation(input[field],field,min,max)},resonanceAutomation=lane("resonance"),delayFeedbackAutomation=lane("delay-feedback"),delayMixAutomation=lane("delay-mix"),wtAutomation=lane("wt"),reverb=normalizeReverb(input.reverb),fx=fxOrThrow(()=>normalizeFx(input.fx)),fxAutomation=normalizeFxAutomation(input.fxAutomation),synth=fxOrThrow(()=>normalizeSynth(input.synth)),keys=fxOrThrow(()=>normalizeKeys(input.keys)),wavetable=normalizeWavetable(input.wavetable),modal2=fxOrThrow(()=>normalizeModal(input.modal));if(modal2&&instrument!==MODAL_INSTRUMENT2)throw new ScoreValidationError(`track ${id} has modal settings but its instrument is "${instrument}"`,"invalid-track");let texture=fxOrThrow(()=>normalizeTexture(input.texture));if(texture&&instrument!==TEXTURE_INSTRUMENT2)throw new ScoreValidationError(`track ${id} has texture settings but its instrument is "${instrument}"`,"invalid-track");let guitar=normalizeGuitar(input.guitar),wind2=fxOrThrow(()=>normalizeWind(input.wind));if(wind2&&instrument!==WIND_INSTRUMENT2)throw new ScoreValidationError(`track ${id} has wind settings but its instrument is "${instrument}"`,"invalid-track");let sing2=fxOrThrow(()=>normalizeSing(input.sing));if(sing2&&instrument!==SING_INSTRUMENT2)throw new ScoreValidationError(`track ${id} has sing settings but its instrument is "${instrument}"`,"invalid-track");let vox=voxOrThrow(()=>normalizeTrackVox(input.vox,`track ${id} vox`),"invalid-track"),sampler=normalizeSampler(input.sampler),takes=normalizeTakes(input.takes,id),vocoder=fxOrThrow(()=>normalizeVocoder(input.vocoder)),clips=normalizeClips(input.clips,id,takes),autotune=fxOrThrow(()=>normalizeAutotune(input.autotune,instrument)),rhythm=normalizeRhythm(input.rhythm,id),time=timeOrThrow(()=>normalizeTrackTime(input.time,`track ${id} time`),"invalid-track"),performance2;try{performance2=normalizeTrackPerformance(input,SCORE_LIMITS.maxTick)}catch(error){throw error instanceof ExpressionValidationError?new ScoreValidationError(`track ${id} ${error.message}`,"invalid-track"):error}let tuning=tuningOrThrow(()=>normalizeTuning(input.tuning,`track ${id} tuning`),"invalid-track"),softPedal,sostenuto;try{softPedal=normalizePedal(input.softPedal,SCORE_LIMITS.maxTick,"softPedal"),sostenuto=normalizePedal(input.sostenuto,SCORE_LIMITS.maxTick,"sostenuto",SOSTENUTO_STATES)}catch(error){throw error instanceof ExpressionValidationError?new ScoreValidationError(`track ${id} ${error.message}`,"invalid-track"):error}let patch=normalizeTrackPatch(input.patch,id,instrument,library),fxPatch=normalizeFxPatches(input.fxPatch,id,library),string=fxOrThrow(()=>normalizeString(input.string)),granular=fxOrThrow(()=>normalizeGranular(input.granular,ref=>normalizeSampleRef(ref,"granular src")))??(isGranularInstrument(instrument)?Object.freeze({}):void 0),kit2;if(input.kit!==void 0&&input.kit!==null){let found=typeof input.kit=="string"?synthKit(input.kit):void 0;if(!found)throw new ScoreValidationError(`track ${id} kit must be one of ${SYNTH_KIT_NAMES.join(", ")}`,"invalid-track");if(!isDrumInstrument(instrument))throw new ScoreValidationError(`track ${id} has a kit but its instrument is "${instrument}"`,"invalid-track");kit2=found.name}if(isSamplerInstrument(instrument)&&!sampler)throw new ScoreValidationError(`track ${id} instrument "sampler" needs a sampler`,"invalid-track");if(sampler&&!isSamplerInstrument(instrument)&&!isGranularInstrument(instrument))throw new ScoreValidationError(`track ${id} has a sampler but its instrument is "${instrument}"`,"invalid-track");return Object.freeze({id,name,instrument,muted,volume,pan:pan2,volumeAutomation,panAutomation,...solo?{solo}:{},...filter?{filter}:{},...delay?{delay}:{},...filterAutomation.length>0?{filterAutomation}:{},...resonanceAutomation.length>0?{resonanceAutomation}:{},...delayFeedbackAutomation.length>0?{delayFeedbackAutomation}:{},...delayMixAutomation.length>0?{delayMixAutomation}:{},...reverb?{reverb}:{},...fx?{fx}:{},...fxAutomation?{fxAutomation}:{},...synth?{synth}:{},...wavetable?{wavetable}:{},...wtAutomation.length>0?{wtAutomation}:{},...sampler?{sampler}:{},...rhythm?{rhythm}:{},...kit2?{kit:kit2}:{},...time?{time}:{},...performance2,...tuning?{tuning}:{},...string?{string}:{},...granular?{granular}:{},...keys?{keys}:{},...modal2?{modal:modal2}:{},...texture?{texture}:{},...softPedal?{softPedal}:{},...sostenuto?{sostenuto}:{},...guitar?{guitar}:{},...wind2?{wind:wind2}:{},...sing2?{sing:sing2}:{},...vox?{vox}:{},...clips?{clips}:{},...takes?{takes}:{},...vocoder?{vocoder}:{},...autotune?{autotune}:{},...patch?{patch}:{},...fxPatch?{fxPatch}:{}})}function patchContext(library={},label){return{library,engineSettings:normalizeEngineSettings,...label!==void 0?{label}:{}}}function normalizeEngineSettings(fields,settings,label){let out={};for(let field of fields){let value=settings[field];if(value===void 0)continue;let normalized=(()=>{try{if(field==="synth")return normalizeSynth(value);if(field==="wavetable")return normalizeWavetable(value);if(field==="sampler")return normalizeSampler(value);if(field==="modal")return normalizeModal(value);if(field==="texture")return normalizeTexture(value);if(field==="string")return normalizeString(value);if(field==="wind")return normalizeWind(value);if(field==="sing")return normalizeSing(value);if(field==="keys")return normalizeKeys(value);if(field==="vocoder")return normalizeVocoder(value);if(field==="granular")return normalizeGranular(value,ref=>normalizeSampleRef(ref,"granular src"))}catch(error){throw error instanceof FxValidationError||error instanceof ScoreValidationError?new PatchValidationError(`${label} ${field}: ${error.message}`):error}throw new PatchValidationError(`${label}: no engine field "${field}"`)})();normalized!==void 0&&(out[field]=normalized)}return Object.freeze(out)}function normalizeTrackPatch(input,id,instrument,library){if(input==null)return;if(instrument!==PATCH_INSTRUMENT)throw new ScoreValidationError(`track ${id} has a patch but its instrument is "${instrument}"`,"invalid-track");let value=patchOrThrow(()=>validatePatchValue(input,patchContext(library,`track ${id} patch`)));if(!isPatchRef(value)&&value.role!=="instrument")throw new ScoreValidationError(`track ${id} patch must be an instrument patch (it is an ${value.role} patch)`,"invalid-track");if(isPatchRef(value)&&library[value.ref]?.role!=="instrument")throw new ScoreValidationError(`track ${id} patch: project patch ${value.ref} is an effect patch`,"invalid-track");return value}function normalizeFxPatches(input,id,library){if(input==null)return;if(!Array.isArray(input)||input.length>PATCH_LIMITS.maxFxPatches)throw new ScoreValidationError(`track ${id} fxPatch must be a list of at most ${PATCH_LIMITS.maxFxPatches} effect patches`,"invalid-track");let names=new Set,out=input.map((value,index)=>{let patch=patchOrThrow(()=>validatePatch(value,patchContext(library,`track ${id} fxPatch ${index+1}`)));if(patch.role!=="effect")throw new ScoreValidationError(`track ${id} fxPatch ${patch.name} must be an effect patch`,"invalid-track");if(names.has(patch.name))throw new ScoreValidationError(`track ${id} has two effect patches named ${patch.name}`,"invalid-track");return names.add(patch.name),patch});return out.length>0?Object.freeze(out):void 0}function normalizeGuitar(input){if(input==null)return;let fail6=message=>{throw new ScoreValidationError(`track guitar ${message}`,"invalid-track")};(typeof input!="object"||Array.isArray(input))&&fail6("must be an object or null");let out={},record2=input;for(let key of Object.keys(record2))["tune","capo","hand","ring","position"].includes(key)||fail6(`has no field "${key.slice(0,32)}"`);let tune=record2.tune;if(tune!=null)if(typeof tune=="string"){let name=tune.toLowerCase().replace(/[\s_-]/g,"");GUITAR_TUNING_NAMES2.includes(name)||fail6(`tune must be one of ${GUITAR_TUNING_NAMES2.join(", ")} or a list of pitches`),out.tune=name}else Array.isArray(tune)&&tune.length>=3&&tune.length<=12&&tune.every(p=>Number.isInteger(p)&&p>=0&&p<=127)?out.tune=Object.freeze([...tune]):fail6("tune must be a tuning name or 3..12 MIDI pitches");let int=(key,min,max)=>{let value=record2[key];value!=null&&((typeof value!="number"||!Number.isInteger(value)||value<min||value>max)&&fail6(`${key} must be an integer ${min}..${max}`),out[key]=value)};int("capo",0,12),int("hand",3,6);let ring=record2.ring;return ring!=null&&((typeof ring!="number"||!Number.isFinite(ring)||ring<0||ring>1)&&fail6("ring must be 0..1"),out.ring=Math.round(ring*1e3)/1e3),int("position",0,12),Object.keys(out).length>0?Object.freeze(out):void 0}function normalizeRhythm(input,trackId){if(input==null)return;if(!Array.isArray(input)||input.length>RHYTHM_LIMITS.maxRows)throw new ScoreValidationError(`track ${trackId} rhythm must be an array of at most ${RHYTHM_LIMITS.maxRows} rows`,"invalid-track");if(input.length===0)return;let rows=input.map((row2,index)=>{try{return normalizeRhythmRow(row2,`track ${trackId} rhythm[${index}]`)}catch(error){throw new ScoreValidationError(error instanceof Error?error.message:String(error),"invalid-track")}});if(new Set(rows.map(row2=>row2.voice)).size!==rows.length)throw new ScoreValidationError(`track ${trackId} rhythm has two rows for one voice`,"invalid-track");return Object.freeze(rows)}function timeOrThrow(run,code="invalid-score"){try{return run()}catch(error){throw error instanceof TimeValidationError?new ScoreValidationError(error.message,code):error}}function tuningOrThrow(run,code){try{return run()}catch(error){throw error instanceof TuningError?new ScoreValidationError(error.message,code):error}}function fxOrThrow(run){try{return run()}catch(error){throw error instanceof FxValidationError?new ScoreValidationError(error.message,"invalid-track"):error}}function normalizeFxAutomation(input){if(input==null)return;if(!isRecord4(input))throw new ScoreValidationError("track fxAutomation must be an object","invalid-track");let keys=Object.keys(input);if(keys.length>SCORE_LIMITS.maxFxLanes)throw new ScoreValidationError(`track fxAutomation holds at most ${SCORE_LIMITS.maxFxLanes} lanes`,"score-limit");for(let key of keys)if(fxLaneRange(key)===void 0)throw new ScoreValidationError(`unknown fx automation lane "${key}"`,"invalid-track");let out={};for(let{lane,spec}of FX_LANES){if(input[lane]===void 0)continue;let points=normalizeAutomation(input[lane],`fxAutomation ${lane}`,spec.min,spec.max);points.length>0&&(out[lane]=points)}for(let lane of keys.filter(isPatchLane).sort()){let points=normalizeAutomation(input[lane],`fxAutomation ${lane}`,0,1);points.length>0&&(out[lane]=points)}return Object.keys(out).length>0?Object.freeze(out):void 0}function trackEffectExtras(name,input,keys){let params2=TRACK_EFFECT_SPECS[name].params,subset={},values={};for(let key of keys)subset[key]=params2[key],input[key]!==void 0&&(values[key]=input[key]);return{...fxOrThrow(()=>normalizeParams(subset,values,`track ${name}`))}}var VOICE_NAME=/^[A-Za-z][A-Za-z0-9_]*$/,SAMPLE_RR_GROUP=/^[A-Za-z0-9_]{1,32}$/,SHA256_HEX=/^[0-9a-f]{64}$/;function normalizeSampler(input){if(input==null)return;if(!isRecord4(input))throw new ScoreValidationError("track sampler must be an object or null","invalid-track");let mode=input.mode??"oneshot";if(mode!=="oneshot"&&mode!=="keyed")throw new ScoreValidationError('sampler mode must be "oneshot" or "keyed"',"invalid-track");if(!isRecord4(input.voices))throw new ScoreValidationError("sampler voices must be an object of name \u2192 sample","invalid-track");let names=Object.keys(input.voices);if(names.length===0||names.length>SCORE_LIMITS.maxSamplerVoices)throw new ScoreValidationError(`sampler must have between 1 and ${SCORE_LIMITS.maxSamplerVoices} voices`,"score-limit");let voices={};for(let name of names.sort(compareCodePoints)){if(name.length>SCORE_LIMITS.maxSamplerVoiceNameLength||!VOICE_NAME.test(name))throw new ScoreValidationError(`sampler voice name "${name.slice(0,40)}" must match ${VOICE_NAME.source} and be at most ${SCORE_LIMITS.maxSamplerVoiceNameLength} characters`,"invalid-track");voices[name]=normalizeSampleRef(input.voices[name],name)}return Object.freeze({voices:Object.freeze(voices),mode})}function normalizeSampleRef(input,name){let label=`sampler voice ${name}`;if(!isRecord4(input))throw new ScoreValidationError(`${label} must be an object`,"invalid-track");let src=input.src,packRef=typeof src=="string"&&src.startsWith(PACK_PREFIX);if(typeof src!="string"||src.length===0||src.length>SCORE_LIMITS.maxSamplePathLength||(packRef?!isPackRef(src):!isSafeRelativePath(src)))throw new ScoreValidationError(packRef?`${label} src must be pack:<pack>/<sound>[:<n>], at most ${SCORE_LIMITS.maxSamplePathLength} characters`:`${label} src must be a project-relative path without "..", at most ${SCORE_LIMITS.maxSamplePathLength} characters`,"invalid-track");let ref={src};if(input.sha256!==void 0){if(typeof input.sha256!="string"||!SHA256_HEX.test(input.sha256))throw new ScoreValidationError(`${label} sha256 must be 64 lowercase hex characters`,"invalid-track");ref.sha256=input.sha256}if(input.url!==void 0){if(!packRef||!isPinnedSampleUrl(input.url))throw new ScoreValidationError(`${label} url must be an https URL without credentials, at most ${SCORE_LIMITS.maxSampleUrlLength} characters, on a pack: sound`,"invalid-track");ref.url=input.url}if(input.license!==void 0){if(typeof input.license!="string"||!/^[\x20-\x7e]{1,64}$/.test(input.license))throw new ScoreValidationError(`${label} license must be a short label such as CC0-1.0`,"invalid-track");ref.license=input.license}if(input.root!==void 0){if(typeof input.root!="number"||!Number.isInteger(input.root)||input.root<0||input.root>127)throw new ScoreValidationError(`${label} root must be a MIDI integer between 0 and 127`,"invalid-track");ref.root=input.root}let begin=input.begin===void 0?0:input.begin,end=input.end===void 0?1:input.end;if(typeof begin!="number"||typeof end!="number"||!Number.isFinite(begin)||!Number.isFinite(end)||begin<0||end>1||begin>=end)throw new ScoreValidationError(`${label} begin/end must be fractions with 0 \u2264 begin < end \u2264 1`,"invalid-track");if(input.begin!==void 0&&(ref.begin=begin),input.end!==void 0&&(ref.end=end),input.gain!==void 0&&(ref.gain=boundedNumber(input.gain,`${label} gain`,0,SCORE_LIMITS.maxSampleGain)),input.speed!==void 0){let speed=boundedNumber(input.speed,`${label} speed`,-SCORE_LIMITS.maxSampleSpeed,SCORE_LIMITS.maxSampleSpeed);if(speed===0)throw new ScoreValidationError(`${label} speed cannot be 0`,"invalid-track");ref.speed=speed}if(input.loop!==void 0){if(typeof input.loop!="boolean")throw new ScoreValidationError(`${label} loop must be boolean`,"invalid-track");ref.loop=input.loop}if(input.choke!==void 0){if(typeof input.choke!="string"||input.choke.length===0||input.choke.length>SCORE_LIMITS.maxChokeGroupLength||!VOICE_NAME.test(input.choke))throw new ScoreValidationError(`${label} choke must be a short group name`,"invalid-track");ref.choke=input.choke}if(input.loopBegin!==void 0||input.loopEnd!==void 0){let loopBegin=input.loopBegin===void 0?begin:input.loopBegin,loopEnd=input.loopEnd===void 0?end:input.loopEnd;if(typeof loopBegin!="number"||typeof loopEnd!="number"||!Number.isFinite(loopBegin)||!Number.isFinite(loopEnd)||loopBegin<begin||loopEnd>end||loopBegin>=loopEnd)throw new ScoreValidationError(`${label} loopBegin/loopEnd must be fractions with begin \u2264 loopBegin < loopEnd \u2264 end`,"invalid-track");input.loopBegin!==void 0&&(ref.loopBegin=loopBegin),input.loopEnd!==void 0&&(ref.loopEnd=loopEnd)}if(input.clip!==void 0){let clip=boundedNumber(input.clip,`${label} clip`,0,SCORE_LIMITS.maxSampleClip);if(clip===0)throw new ScoreValidationError(`${label} clip must be greater than 0`,"invalid-track");ref.clip=clip}if(input.unit!==void 0){if(!SAMPLE_UNITS.includes(input.unit))throw new ScoreValidationError(`${label} unit must be "r", "c" or "s"`,"invalid-track");ref.unit=input.unit}if(input.fit!==void 0){if(typeof input.fit!="boolean")throw new ScoreValidationError(`${label} fit must be boolean`,"invalid-track");ref.fit=input.fit}if(input.accelerate!==void 0&&(ref.accelerate=boundedNumber(input.accelerate,`${label} accelerate`,-SCORE_LIMITS.maxSampleAccelerate,SCORE_LIMITS.maxSampleAccelerate)),input.squiz!==void 0&&(ref.squiz=boundedNumber(input.squiz,`${label} squiz`,1,SCORE_LIMITS.maxSampleSquiz)),input.bpm!==void 0&&(ref.bpm=boundedNumber(input.bpm,`${label} bpm`,SCORE_LIMITS.minSampleBpm,SCORE_LIMITS.maxSampleBpm)),input.fitmode!==void 0){if(!SAMPLE_FIT_MODES.includes(input.fitmode))throw new ScoreValidationError(`${label} fitmode must be "repitch", "beats" or "tones"`,"invalid-track");ref.fitmode=input.fitmode}if(input.len!==void 0){let len=boundedNumber(input.len,`${label} len`,0,SCORE_LIMITS.maxSampleLenBeats);if(len===0)throw new ScoreValidationError(`${label} len must be greater than 0`,"invalid-track");ref.len=len}if(input.vel!==void 0){let vel=input.vel;if(!Array.isArray(vel)||vel.length!==2||!vel.every(v=>Number.isInteger(v)&&v>=0&&v<=127)||vel[0]>vel[1])throw new ScoreValidationError(`${label} vel must be [lo, hi], MIDI velocities 0..127 with lo \u2264 hi`,"invalid-track");ref.vel=Object.freeze([vel[0],vel[1]])}if(input.rr!==void 0){if(typeof input.rr!="string"||!SAMPLE_RR_GROUP.test(input.rr))throw new ScoreValidationError(`${label} rr must be a round-robin group name (letters, digits, _; at most 32)`,"invalid-track");ref.rr=input.rr}if(ref.fitmode!==void 0&&ref.fitmode!=="repitch"&&ref.bpm===void 0&&ref.len===void 0&&ref.fit!==!0)throw new ScoreValidationError(`${label} fitmode ${ref.fitmode} needs bpm, len or fit`,"invalid-track");return input.shift!==void 0&&(ref.shift=boundedNumber(input.shift,`${label} shift`,-SCORE_LIMITS.maxSampleShift,SCORE_LIMITS.maxSampleShift)),input.formant!==void 0&&(ref.formant=boundedNumber(input.formant,`${label} formant`,-SCORE_LIMITS.maxSampleShift,SCORE_LIMITS.maxSampleShift)),input.fadeTime!==void 0&&(ref.fadeTime=boundedNumber(input.fadeTime,`${label} fadeTime`,0,SCORE_LIMITS.maxSampleFadeSeconds)),input.fadeInTime!==void 0&&(ref.fadeInTime=boundedNumber(input.fadeInTime,`${label} fadeInTime`,0,SCORE_LIMITS.maxSampleFadeSeconds)),input.from!==void 0&&(ref.from=normalizeProvenance(input.from,`${label} from`)),Object.freeze(ref)}var PROVENANCE_SOURCE=/^(?:track:[A-Za-z0-9_-]{1,64}|orbit:[0-9]{1,2}|master)$/;function normalizeProvenance(input,label){if(!isRecord4(input)||typeof input.source!="string"||!PROVENANCE_SOURCE.test(input.source)||typeof input.score!="string"||!SHA256_HEX.test(input.score))throw new ScoreValidationError(`${label} must be { source: track:<id>|orbit:<n>|master, score: <sha256> }`,"invalid-track");let from={source:input.source,score:input.score};if(input.section!==void 0){if(typeof input.section!="string"||input.section.length===0||input.section.length>64)throw new ScoreValidationError(`${label} section must be a section name`,"invalid-track");from.section=input.section}if(input.bars!==void 0){let bars=input.bars;if(!Array.isArray(bars)||bars.length!==2||!bars.every(b=>Number.isInteger(b)&&b>=1&&b<=1e5)||bars[0]>bars[1])throw new ScoreValidationError(`${label} bars must be [a, b] with 1 \u2264 a \u2264 b`,"invalid-track");from.bars=[bars[0],bars[1]]}return Object.freeze({source:from.source,...from.section!==void 0?{section:from.section}:{},...from.bars!==void 0?{bars:Object.freeze(from.bars)}:{},score:from.score})}var PACK_PREFIX="pack:",PACK_REF=/^pack:([a-z0-9][a-z0-9._-]{0,63})\/([A-Za-z0-9][A-Za-z0-9_.~+-]{0,127})(?::([0-9]{1,4}|[A-Ga-g](?:#|s|b)?-?[0-9]))?$/;function isPackRef(src){return PACK_REF.test(src)}function isPinnedSampleUrl(value){if(typeof value!="string"||value.length===0||value.length>SCORE_LIMITS.maxSampleUrlLength||/[\u0000-\u0020]/.test(value))return!1;let url;try{url=new URL(value)}catch{return!1}return url.username!==""||url.password!==""?!1:url.protocol==="https:"||url.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(url.hostname)}function isSafeRelativePath(path){return path.startsWith("/")||/[\\\u0000-\u001f]/.test(path)||/^[A-Za-z]:/.test(path)?!1:path.split("/").every(segment=>segment!==""&&segment!=="."&&segment!=="..")}function normalizeReverb(input){if(input==null)return;if(!isRecord4(input))throw new ScoreValidationError("track reverb must be an object or null","invalid-track");let mix3=boundedNumber(input.mix,"track reverb mix",0,SCORE_LIMITS.maxReverbMix),size=boundedNumber(input.size??.5,"track reverb size",SCORE_LIMITS.minReverbSize,SCORE_LIMITS.maxReverbSize),extras2=trackEffectExtras("reverb",input,["fade","lowpass","dim","predelay","center"]),ir=input.ir===void 0||input.ir===null?void 0:normalizeReverbIr(input.ir);return Object.freeze({mix:mix3,size,...extras2,...ir?{ir}:{}})}function normalizeFilter(input){if(input==null)return;if(!isRecord4(input))throw new ScoreValidationError("track filter must be an object or null","invalid-track");let cutoff2=boundedNumber(input.cutoff,"track filter cutoff",SCORE_LIMITS.minFilterCutoff,SCORE_LIMITS.maxFilterCutoff),resonance=boundedNumber(input.resonance??0,"track filter resonance",0,SCORE_LIMITS.maxFilterResonance),extras2=trackEffectExtras("filter",input,["type","ftype"]);return extras2.ftype==="12db"&&delete extras2.ftype,extras2.type==="lpf"&&delete extras2.type,Object.freeze({cutoff:cutoff2,resonance,...extras2})}function normalizeDelay(input){if(input==null)return;if(!isRecord4(input))throw new ScoreValidationError("track delay must be an object or null","invalid-track");let beats=boundedNumber(input.beats,"track delay beats",SCORE_LIMITS.minDelayBeats,SCORE_LIMITS.maxDelayBeats),feedback=boundedNumber(input.feedback??.3,"track delay feedback",0,SCORE_LIMITS.maxDelayFeedback),mix3=boundedNumber(input.mix??.35,"track delay mix",0,SCORE_LIMITS.maxDelayMix),extras2=trackEffectExtras("delay",input,["time","pingpong","highcut"]);return extras2.time===0&&delete extras2.time,Object.freeze({beats,feedback,mix:mix3,...extras2})}function boundedNumber(value,label,min,max){if(typeof value!="number"||!Number.isFinite(value)||value<min||value>max)throw new ScoreValidationError(`${label} must be between ${min} and ${max}`,"invalid-track");return value}function normalizeAutomation(input,label,minValue,maxValue){if(input===void 0)return Object.freeze([]);if(!Array.isArray(input)||input.length>SCORE_LIMITS.maxAutomationPoints)throw new ScoreValidationError(`${label} must contain at most ${SCORE_LIMITS.maxAutomationPoints} points`,"score-limit");let points=input.map(candidate=>{if(!isRecord4(candidate))throw new ScoreValidationError(`${label} point must be an object`,"invalid-track");let tick=candidate.tick,value=candidate.value;if(typeof tick!="number"||!Number.isInteger(tick)||tick<0||tick>SCORE_LIMITS.maxTick)throw new ScoreValidationError(`${label} point tick must be an integer between 0 and ${SCORE_LIMITS.maxTick}`,"invalid-track");if(typeof value!="number"||!Number.isFinite(value)||value<minValue||value>maxValue)throw new ScoreValidationError(`${label} point value must be between ${minValue} and ${maxValue}`,"invalid-track");return Object.freeze({tick,value})});points.sort((a,b)=>a.tick-b.tick);for(let index=1;index<points.length;index+=1)if(points[index].tick===points[index-1].tick)throw new ScoreValidationError(`${label} points cannot share a tick`,"invalid-track");return freezeArray(points)}var noteCap=SCORE_LIMITS.maxNotes;function withNoteCap(cap,fn){let previous=noteCap;noteCap=Math.max(previous,cap);try{return fn()}finally{noteCap=previous}}function normalizeNotes(inputs2){if(!Array.isArray(inputs2)||inputs2.length>noteCap)throw new ScoreValidationError(`score cannot contain more than ${noteCap} notes`,"score-limit");let seen=new Set;return inputs2.map(input=>{let note2=normalizeNote(input);if(seen.has(note2.id))throw new ScoreValidationError(`note id already exists: ${note2.id}`,"duplicate-note");return seen.add(note2.id),note2}).sort(compareNotes)}function normalizeNote(input){if(!isRecord4(input))throw new ScoreValidationError("note must be an object","invalid-note");let id=boundedString(input.id,"note id",SCORE_LIMITS.maxIdLength,"invalid-note"),trackId=boundedString(input.trackId,"note trackId",SCORE_LIMITS.maxIdLength,"invalid-note"),startTick=input.startTick??input.start,durationTicks=input.durationTicks??input.duration;if(typeof startTick!="number"||!Number.isInteger(startTick)||startTick<0||startTick>SCORE_LIMITS.maxTick)throw new ScoreValidationError(`note ${id} startTick must be an integer between 0 and ${SCORE_LIMITS.maxTick}`,"invalid-note");if(typeof durationTicks!="number"||!Number.isInteger(durationTicks)||durationTicks<1||durationTicks>SCORE_LIMITS.maxTick)throw new ScoreValidationError(`note ${id} durationTicks must be an integer between 1 and ${SCORE_LIMITS.maxTick}`,"invalid-note");if(startTick+durationTicks>SCORE_LIMITS.maxTick)throw new ScoreValidationError(`note ${id} must end by tick ${SCORE_LIMITS.maxTick}`,"invalid-note");let pitch2=input.pitch;if(typeof pitch2!="number"||!Number.isInteger(pitch2)||pitch2<0||pitch2>127)throw new ScoreValidationError(`note ${id} pitch must be a MIDI integer between 0 and 127`,"invalid-note");if(typeof input.velocity!="number"||!Number.isFinite(input.velocity)||input.velocity<0||input.velocity>1)throw new ScoreValidationError(`note ${id} velocity must be between 0 and 1`,"invalid-note");let expression2;try{expression2=normalizeNoteExpression(input)}catch(error){throw error instanceof ExpressionValidationError?new ScoreValidationError(`note ${id} ${error.message}`,"invalid-note"):error}let cents=tuningOrThrow(()=>normalizeNoteCents(input.cents,`note ${id}`),"invalid-note"),lyric=normalizeLyric(input.lyric,id),vowel=input.vowel===void 0||input.vowel===null?void 0:vowelOrThrow(input.vowel,id),vox=voxOrThrow(()=>normalizeNoteVox(input.vox,`note ${id} vox`),"invalid-note");return Object.freeze({id,trackId,startTick,durationTicks,pitch:pitch2,velocity:input.velocity,...expression2,...cents!==void 0?{cents}:{},...lyric!==void 0?{lyric}:{},...vowel!==void 0?{vowel}:{},...vox!==void 0?{vox}:{}})}function voxOrThrow(run,code){try{return run()}catch(error){throw error instanceof VoxValidationError?new ScoreValidationError(error.message,code):error}}function parseTrack(value){if(!isRecord4(value))throw new ScoreValidationError("track must be an object","invalid-track");return value}function parseNote(value){if(!isRecord4(value))throw new ScoreValidationError("note must be an object","invalid-note");return value}function compareNotes(a,b){return a.startTick-b.startTick||compareIds(a.trackId,b.trackId)||a.pitch-b.pitch||compareIds(a.id,b.id)}var ID_COLLATION=" _-,;:!?.'\"()[]{}@*/\\&#%`^+<=>|~$0123456789abcdefghijklmnopqrstuvwxyz",PRINTABLE_ASCII=/^[\x20-\x7e]*$/;function compareIds(a,b){if(a===b)return 0;let asciiA=PRINTABLE_ASCII.test(a),asciiB=PRINTABLE_ASCII.test(b);if(asciiA!==asciiB)return asciiA?-1:1;if(!asciiA)return a<b?-1:1;let length=Math.min(a.length,b.length);for(let i=0;i<length;i+=1){let rank=ID_COLLATION.indexOf(a[i].toLowerCase())-ID_COLLATION.indexOf(b[i].toLowerCase());if(rank!==0)return rank}if(a.length!==b.length)return a.length-b.length;for(let i=0;i<length;i+=1)if(a[i]!==b[i])return a[i]===a[i].toLowerCase()?-1:1;return 0}function boundedString(value,label,max,code){if(typeof value!="string"||value.length===0||value.length>max)throw new ScoreValidationError(`${label} must be a non-empty string of at most ${max} characters`,code);return value}function optionalNumber(value){return value===void 0?void 0:typeof value=="number"?value:Number.NaN}function optionalNullableString(value){return value==null||typeof value=="string"?value:"\0invalid"}function optionalArray(value){if(value===void 0)return[];if(!Array.isArray(value))throw new ScoreValidationError("array field is malformed");return value}function isRecord4(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function freezeArray(items){return Object.freeze([...items])}var MAX_CLIP_LABEL_LENGTH=128;function clipError(message){return new ScoreValidationError(message,"invalid-track")}function clipNumber(value,label,min,max){if(value!==void 0){if(typeof value!="number"||!Number.isFinite(value)||value<min||value>max)throw clipError(`${label} must be a number ${min}..${max}`);return value}}function clipTick(value,label){if(typeof value!="number"||!Number.isInteger(value)||value<0||value>SCORE_LIMITS.maxTick)throw clipError(`${label} must be an integer tick 0..${SCORE_LIMITS.maxTick}`);return value}function clipString(value,label,max){if(value!==void 0){if(typeof value!="string"||value.length===0||value.length>max)throw clipError(`${label} must be 1..${max} characters`);return value}}function clipBool(value,label){if(value!==void 0){if(typeof value!="boolean")throw clipError(`${label} must be a boolean`);return value||void 0}}function clipSrc(value,label){let packRef=typeof value=="string"&&value.startsWith(PACK_PREFIX);if(typeof value!="string"||value.length===0||value.length>SCORE_LIMITS.maxSamplePathLength||(packRef?!isPackRef(value):!isSafeRelativePath(value)))throw clipError(`${label} src must be a project-relative path without ".." or pack:<pack>/<sound>, at most ${SCORE_LIMITS.maxSamplePathLength} characters`);return value}function clipSha(value,label){if(typeof value!="string"||!SHA256_HEX.test(value))throw clipError(`${label} sha256 must be 64 lowercase hex characters`);return value}function increasingTimes(value,label){if(!Array.isArray(value)||value.length>SCORE_LIMITS.maxSayCuts)throw clipError(`${label} must be an array of at most ${SCORE_LIMITS.maxSayCuts} times`);let previous=-1/0;return value.map((time,index)=>{if(typeof time!="number"||!Number.isFinite(time)||time<0||time>SCORE_LIMITS.maxClipSeconds)throw clipError(`${label}[${index}] must be seconds 0..${SCORE_LIMITS.maxClipSeconds}`);if(time<=previous)throw clipError(`${label} must be strictly increasing`);return previous=time,time})}function normalizeClipSay(input,label){if(input==null)return;if(!isRecord4(input))throw clipError(`${label} say must be an object`);let engine2=input.engine;if(engine2!=="say"&&engine2!=="espeak-ng"&&engine2!=="piper")throw clipError(`${label} say.engine must be say, espeak-ng or piper`);let voice=clipString(input.voice,`${label} say.voice`,SCORE_LIMITS.maxTtsVoiceLength);if(voice===void 0)throw clipError(`${label} say.voice is required`);let license=clipString(input.license,`${label} say.license`,MAX_CLIP_LABEL_LENGTH);if(license===void 0)throw clipError(`${label} say.license is required`);let rate2=clipNumber(input.rate,`${label} say.rate`,80,400),cuts=increasingTimes(input.cuts,`${label} say.cuts`),vowels=increasingTimes(input.vowels,`${label} say.vowels`);if(cuts.length!==vowels.length)throw clipError(`${label} say.cuts and say.vowels must be the same length`);cuts.forEach((cut,index)=>{if(cut>vowels[index])throw clipError(`${label} say.cuts[${index}] must be <= say.vowels[${index}]`)});let unvoiced;if(input.unvoiced!==void 0){if(!Array.isArray(input.unvoiced))throw clipError(`${label} say.unvoiced must be an array of indices`);let previous=-1;unvoiced=input.unvoiced.map(index=>{if(typeof index!="number"||!Number.isInteger(index)||index<=previous||index>=cuts.length)throw clipError(`${label} say.unvoiced must be increasing indices below ${cuts.length}`);return previous=index,index})}let oct=clipNumber(input.oct,`${label} say.oct`,-3,3);if(oct!==void 0&&!Number.isInteger(oct))throw clipError(`${label} say.oct must be an integer -3..3`);let soft=clipNumber(input.soft,`${label} say.soft`,0,1),sung;if(input.sung!==void 0){if(!isRecord4(input.sung))throw clipError(`${label} say.sung must be { src, sha256, key }`);let key=clipString(input.sung.key,`${label} say.sung.key`,MAX_CLIP_LABEL_LENGTH);if(key===void 0)throw clipError(`${label} say.sung.key is required`);sung=Object.freeze({src:clipSrc(input.sung.src,`${label} say.sung`),sha256:clipSha(input.sung.sha256,`${label} say.sung`),key})}return Object.freeze({engine:engine2,voice,...rate2!==void 0?{rate:rate2}:{},license,cuts:Object.freeze(cuts),vowels:Object.freeze(vowels),...unvoiced&&unvoiced.length>0?{unvoiced:Object.freeze(unvoiced)}:{},...oct!==void 0?{oct}:{},...soft!==void 0?{soft}:{},...sung?{sung}:{}})}function normalizeTakes(input,trackId){if(input==null)return;if(!Array.isArray(input))throw clipError(`track ${trackId} takes must be an array`);if(input.length>SCORE_LIMITS.maxTakesPerTrack)throw new ScoreValidationError(`track ${trackId} takes holds at most ${SCORE_LIMITS.maxTakesPerTrack} takes`,"score-limit");let names=new Set,takes=input.map((value,index)=>{if(!isRecord4(value))throw clipError(`track ${trackId} takes[${index}] must be an object`);let name=clipString(value.name,`track ${trackId} takes[${index}] name`,SCORE_LIMITS.maxNameLength);if(name===void 0)throw clipError(`track ${trackId} takes[${index}] name is required`);if(names.has(name))throw clipError(`track ${trackId} take name ${name} is duplicated`);names.add(name);let label=`track ${trackId} take ${name}`,offset=clipNumber(value.offset,`${label} offset`,0,SCORE_LIMITS.maxClipSeconds);if(offset===void 0)throw clipError(`${label} offset is required`);let latency=clipNumber(value.latency,`${label} latency`,-1,1);if(latency===void 0)throw clipError(`${label} latency is required`);let inTick=clipTick(value.inTick,`${label} inTick`),outTick=clipTick(value.outTick,`${label} outTick`);if(inTick>=outTick)throw clipError(`${label} inTick must be before outTick`);let latencyAssumed=clipBool(value.latencyAssumed,`${label} latencyAssumed`),ppm=clipNumber(value.ppm,`${label} ppm`,-SCORE_LIMITS.maxTakePpm,SCORE_LIMITS.maxTakePpm),fit=clipNumber(value.fit,`${label} fit`,0,1),warn=clipString(value.warn,`${label} warn`,MAX_CLIP_LABEL_LENGTH),nudge=clipNumber(value.nudge,`${label} nudge`,-SCORE_LIMITS.maxTakeNudgeMs,SCORE_LIMITS.maxTakeNudgeMs);return Object.freeze({name,src:clipSrc(value.src,label),sha256:clipSha(value.sha256,label),startTick:clipTick(value.startTick,`${label} startTick`),offset,latency,...latencyAssumed?{latencyAssumed}:{},...ppm!==void 0?{ppm}:{},...fit!==void 0?{fit}:{},...warn!==void 0?{warn}:{},...nudge!==void 0?{nudge}:{},inTick,outTick})});return takes.length>0?Object.freeze(takes):void 0}function normalizeClips(input,trackId,takes){if(input==null)return;if(!Array.isArray(input))throw clipError(`track ${trackId} clips must be an array`);if(input.length>SCORE_LIMITS.maxClipsPerTrack)throw new ScoreValidationError(`track ${trackId} clips holds at most ${SCORE_LIMITS.maxClipsPerTrack} clips`,"score-limit");let takeNames=new Set((takes??[]).map(take=>take.name)),ids=new Set,clips=input.map((value,index)=>{if(!isRecord4(value))throw clipError(`track ${trackId} clips[${index}] must be an object`);let id=clipString(value.id,`track ${trackId} clips[${index}] id`,SCORE_LIMITS.maxIdLength);if(id===void 0)throw clipError(`track ${trackId} clips[${index}] id is required`);if(ids.has(id))throw clipError(`track ${trackId} clip id ${id} is duplicated`);ids.add(id);let label=`track ${trackId} clip ${id}`,max=SCORE_LIMITS.maxClipSeconds,offset=clipNumber(value.offset,`${label} offset`,0,max),dur=clipNumber(value.dur,`${label} dur`,0,max);if(dur===0)throw clipError(`${label} dur must be above 0`);if((offset??0)+(dur??0)>max)throw clipError(`${label} offset + dur must be at most ${max} seconds`);let gain=clipNumber(value.gain,`${label} gain`,0,SCORE_LIMITS.maxClipGain),fadeMax=SCORE_LIMITS.maxClipFadeSeconds,fadeInTime=clipNumber(value.fadeInTime,`${label} fadeInTime`,0,fadeMax),fadeTime=clipNumber(value.fadeTime,`${label} fadeTime`,0,fadeMax);if(dur!==void 0&&(fadeInTime??0)+(fadeTime??0)>dur)throw clipError(`${label} fadeInTime + fadeTime must fit within dur`);let rev=clipBool(value.rev,`${label} rev`),take=clipString(value.take,`${label} take`,SCORE_LIMITS.maxNameLength);if(take!==void 0&&!takeNames.has(take))throw clipError(`${label} take ${take} does not exist on the track`);let mute=clipBool(value.mute,`${label} mute`),text2=clipString(value.text,`${label} text`,SCORE_LIMITS.maxClipTextLength),say=normalizeClipSay(value.say,label);return Object.freeze({id,src:clipSrc(value.src,label),sha256:clipSha(value.sha256,label),startTick:clipTick(value.startTick,`${label} startTick`),...offset!==void 0?{offset}:{},...dur!==void 0?{dur}:{},...gain!==void 0?{gain}:{},...fadeInTime!==void 0?{fadeInTime}:{},...fadeTime!==void 0?{fadeTime}:{},...rev?{rev}:{},...take!==void 0?{take}:{},...mute?{mute}:{},...text2!==void 0?{text:text2}:{},...say?{say}:{}})});return clips.length>0?Object.freeze(clips):void 0}function vowelOrThrow(input,noteId){try{return normalizeVowel(input)}catch(error){throw error instanceof FxValidationError?new ScoreValidationError(`note ${noteId} ${error.message}`,"invalid-note"):error}}function normalizeLyric(input,noteId){if(input!=null){if(typeof input!="string"||input.length===0||input.length>SCORE_LIMITS.maxLyricLength||/\s/.test(input))throw new ScoreValidationError(`note ${noteId} lyric must be 1..${SCORE_LIMITS.maxLyricLength} characters without whitespace`,"invalid-note");return input}}function patchOrThrow(make){try{return make()}catch(error){throw error instanceof PatchValidationError||error instanceof FxValidationError?new ScoreValidationError(error.message,"invalid-track"):error}}var trackRefDrops;function registerTrackRefDrop(field,drop){(trackRefDrops??=new Map).set(field,drop)}var SYL_ONSETS2=new Set("bl br cl cr dr fl fr gl gr pl pr sc sk sl sm sn sp st sw tr tw dw thr shr chr phr phl spl spr str scr squ skr".split(" ")),SYL_SILENT_E_HEADS2="some home life time love fire side care where there here more one make lone like name game base wide grace face place space stone bone".split(" ");var CLIP_VOICE_PREFIX="clip:";var GUIDE_INSTRUMENT="vocal";function isGuideInstrument(instrument){return instrument===GUIDE_INSTRUMENT}var DEFAULT_CLIP_FADE=.005,CLIP_EDGE_FADE=.005;function clipSongTick(clip,time){if(!time)return clip.startTick;let rate2=time.rate??1;return Math.max(0,(time.phase??0)+clip.startTick/rate2)}function clipLength(clip,fileSeconds=SCORE_LIMITS.maxClipSeconds){let rest=Math.max(0,fileSeconds-(clip.offset??0));return clip.dur===void 0?rest:Math.min(clip.dur,rest)}function resolveClipLengths(score,seconds2){let changed=!1,tracks=score.tracks.map(track2=>{if(!track2.clips?.some(clip=>clip.dur===void 0))return track2;let clips=track2.clips.map(clip=>{if(clip.dur!==void 0)return clip;let file=seconds2(track2.id,clip);if(file===void 0||!(file>0))return clip;let dur=Math.round(Math.max(0,file-(clip.offset??0))*1e6)/1e6;return dur>0?(changed=!0,{...clip,dur}):clip});return{...track2,clips}});return changed?new TrackScore({...score.toJSON(),tracks}):score}function clipSpan(score,clip,fileSeconds,time){let start=secondsAtTick(score,clipSongTick(clip,time));return{start,end:start+clipLength(clip,fileSeconds)}}function bakeClipTime(track2){if(!track2.clips||!track2.time)return track2;let time=track2.time;return{...track2,clips:track2.clips.map(clip=>({...clip,startTick:Math.round(clipSongTick(clip,time))}))}}function sliceClips(clips,pieces,time){if(!clips||clips.length===0)return;let joined=[];for(let piece of pieces){let last=joined.at(-1);last&&last.to===piece.from&&last.offset+(last.to-last.from)===piece.offset&&(last.mute??!1)===(piece.mute??!1)&&(last.gain??1)===(piece.gain??1)?joined[joined.length-1]={...last,to:piece.to}:joined.push(piece)}let out=[],ids=new Map;for(let piece of joined){if(piece.mute||piece.to<=piece.from)continue;let pieceStart=secondsAtTick(time,piece.from),pieceEnd=secondsAtTick(time,piece.to);for(let clip of clips){let{start,end}=clipSpan(time,clip);if(start>=pieceEnd||end<=pieceStart||clip.startTick>=piece.to)continue;let cut=cutClip(clip,start,end,pieceStart,pieceEnd,piece.seam===!0);if(!cut)continue;let pass2=(ids.get(clip.id)??0)+1;ids.set(clip.id,pass2);let gain=piece.gain===void 0?cut.gain:Math.min(SCORE_LIMITS.maxClipGain,(cut.gain??1)*piece.gain);out.push({...cut,id:pass2===1?clip.id:clipPassId(clip.id,pass2),startTick:clip.startTick>=piece.from?piece.offset+(clip.startTick-piece.from):piece.offset,...gain===void 0||gain===1?{}:{gain}})}}return out.length>0?out:void 0}function clipPassId(id,pass2){let suffix=`~${pass2}`;return`${id.slice(0,SCORE_LIMITS.maxIdLength-suffix.length)}${suffix}`}function cutClip(clip,start,end,from,to,seam=!1){let head=Math.max(0,from-start),tail=Math.max(0,end-to);if(head<1e-9&&tail<1e-9)return clip;let length=end-start-head-tail;if(length<.001)return;let offset=clip.offset??0,nextOffset=clip.rev?clip.dur===void 0?offset:offset+tail:offset+head,rounded=value=>Math.round(value*1e6)/1e6,fit=(fade,cut)=>Math.min(cut?CLIP_EDGE_FADE:fade??DEFAULT_CLIP_FADE,length/2),fadeInTime=seam&&head>1e-9?0:fit(clip.fadeInTime,head>1e-9),fadeTime=fit(clip.fadeTime,tail>1e-9);return{...clip,...nextOffset>0?{offset:rounded(nextOffset)}:{},dur:rounded(length),...head>1e-9||clip.fadeInTime!==void 0?{fadeInTime}:{},...tail>1e-9||clip.fadeTime!==void 0?{fadeTime}:{}}}function seededRandom(seed){let hash=2166136261;for(let index=0;index<seed.length;index+=1)hash^=seed.charCodeAt(index),hash=Math.imul(hash,16777619)>>>0;let state=hash;return()=>{state=state+1831565813>>>0;let value=Math.imul(state^state>>>15,1|state);return value=value+Math.imul(value^value>>>7,61|value)^value,((value^value>>>14)>>>0)/4294967296}}var MAX_IMPULSE_SECONDS=10,TWIDDLES=new Map;function twiddles(n2){let table2=TWIDDLES.get(n2);if(table2)return table2;let cos=new Float64Array(n2>>1),sin=new Float64Array(n2>>1);for(let k=0;k<n2>>1;k+=1)cos[k]=Math.cos(2*Math.PI*k/n2),sin[k]=Math.sin(2*Math.PI*k/n2);let rev=new Uint32Array(n2);for(let i=1,j=0;i<n2;i+=1){let bit=n2>>1;for(;j&bit;bit>>=1)j^=bit;j^=bit,rev[i]=j}return table2={cos,sin,rev},TWIDDLES.set(n2,table2),table2}function fftInPlace(re,im,inverse2=!1){let n2=re.length,{cos,sin,rev}=twiddles(n2);for(let i=1;i<n2;i+=1){let j=rev[i];if(i<j){let tr=re[i];re[i]=re[j],re[j]=tr;let ti=im[i];im[i]=im[j],im[j]=ti}}let sign=inverse2?1:-1;for(let length=2;length<=n2;length<<=1){let half=length>>1,stride=n2/length;for(let start=0;start<n2;start+=length)for(let k=0;k<half;k+=1){let wr=cos[k*stride],wi=sign*sin[k*stride],a=start+k,b=a+half,xr=re[b]*wr-im[b]*wi,xi=re[b]*wi+im[b]*wr;re[b]=re[a]-xr,im[b]=im[a]-xi,re[a]+=xr,im[a]+=xi}}}function nextPow2(value){let n2=1;for(;n2<value;)n2<<=1;return n2}function partitionSize(impulseLength){return Math.min(32768,Math.max(512,nextPow2(impulseLength)>>3))}function addConvolved(rawL,rawR,scale3,outL,outR,gain,gainAt){for(let index=0;index<rawL.length;index+=1){let g=(gainAt?gainAt(index):gain)*scale3;outL[index]+=rawL[index]*g,outR[index]+=rawR[index]*g}}function convolveRaw(input,impulse,rawL,rawR){let length=input.length,irLength=impulse.left.length;if(length===0||irLength===0)return 0;let block=partitionSize(irLength),n2=block*2,partitions=Math.ceil(irLength/block),gRe=[],gIm=[];for(let p=0;p<partitions;p+=1){let re=new Float64Array(n2),im=new Float64Array(n2),start=p*block,end=Math.min(irLength,start+block);for(let i=start;i<end;i+=1)re[i-start]=impulse.left[i],im[i-start]=impulse.right[i];fftInPlace(re,im),gRe.push(re),gIm.push(im)}let xRe=Array.from({length:partitions},()=>new Float64Array(n2)),xIm=Array.from({length:partitions},()=>new Float64Array(n2)),accRe=new Float64Array(n2),accIm=new Float64Array(n2),blocks=Math.ceil(length/block),scale3=1/n2;for(let k=0;k<blocks;k+=1){let slot=k%partitions,re=xRe[slot],im=xIm[slot],base=(k-1)*block;for(let i=0;i<n2;i+=1){let at3=base+i;re[i]=at3>=0&&at3<length?input[at3]:0,im[i]=0}fftInPlace(re,im),accRe.fill(0),accIm.fill(0);for(let p=0;p<partitions&&p<=k;p+=1){let source=(slot-p+partitions)%partitions,ar2=xRe[source],ai=xIm[source],br=gRe[p],bi=gIm[p];for(let i=0;i<n2;i+=1){let r=ar2[i],m=ai[i];accRe[i]+=r*br[i]-m*bi[i],accIm[i]+=r*bi[i]+m*br[i]}}fftInPlace(accRe,accIm,!0);let outStart=k*block,count2=Math.min(block,length-outStart);for(let i=0;i<count2;i+=1)rawL[outStart+i]=accRe[block+i],rawR[outStart+i]=accIm[block+i]}return scale3}var BUILTIN_IMPULSES=Object.freeze({room:{title:"small room",seconds:.7,damp:6e3,early:7,attack:0},hall:{title:"concert hall",seconds:2.8,damp:4500,early:5,attack:.06},plate:{title:"plate",seconds:1.8,damp:9e3,early:0,attack:0},reverse:{title:"reverse",seconds:1.2,damp:7e3,early:0,attack:0,shape:"rise"},gate:{title:"gated",seconds:.45,damp:8e3,early:6,attack:.005,shape:"gate"},spring:{title:"spring tank",seconds:2.2,damp:4500,early:0,attack:0,shape:"spring"}}),BUILTIN_CACHE=new Map;function builtinImpulse(name,sampleRate){if(!Object.prototype.hasOwnProperty.call(BUILTIN_IMPULSES,name))return;let key=`${name}@${sampleRate}`,cached=BUILTIN_CACHE.get(key);if(cached)return cached;let spec=BUILTIN_IMPULSES[name],length=Math.max(1,Math.round(spec.seconds*sampleRate));if("shape"in spec){let impulse2=normalizeImpulse(`builtin:${name}`,shapedSide(name,"L",spec,sampleRate),shapedSide(name,"R",spec,sampleRate));return BUILTIN_CACHE.set(key,impulse2),impulse2}let sides=["L","R"].map(side=>{let random2=seededRandom(`dawg-ir:${name}:${side}`),out=new Float64Array(length),decay=Math.log(1e3)/spec.seconds,state=0;for(let index=0;index<length;index+=1){let t=index/sampleRate,progress=t/spec.seconds,cutoff2=16e3*(spec.damp/16e3)**progress,coefficient=1-Math.exp(-2*Math.PI*Math.min(cutoff2,sampleRate*.45)/sampleRate);state+=coefficient*(random2()*2-1-state);let build=spec.attack>0?Math.min(1,t/spec.attack):1;out[index]=state*Math.exp(-decay*t)*build}for(let tap=0;tap<spec.early;tap+=1){let at3=Math.floor((.004+random2()*.036)*sampleRate);at3<length&&(out[at3]+=(random2()<.5?-1:1)*(.9-tap*.08))}return out}),impulse=normalizeImpulse(`builtin:${name}`,sides[0],sides[1]);return BUILTIN_CACHE.set(key,impulse),impulse}function shapedSide(name,side,spec,sampleRate){let random2=seededRandom(`dawg-ir:${name}:${side}`),length=Math.max(16,Math.round(spec.seconds*sampleRate)),out=new Float64Array(length),coefficient=1-Math.exp(-2*Math.PI*Math.min(spec.damp,sampleRate*.45)/sampleRate),fadeOut=Math.min(length>>2,Math.round(.003*sampleRate)),state=0;for(let index=0;index<length;index+=1){let x=(index+.5)/length,t=index/sampleRate;state+=coefficient*(random2()*2-1-state);let env;spec.shape==="rise"?env=Math.exp(4*(x-1)):spec.shape==="gate"?env=Math.min(1,t/Math.max(1e-4,spec.attack))*(1-.3*x):env=.35*Math.exp(-Math.log(1e3)*t/spec.seconds),spec.shape!=="spring"&&index>=length-fadeOut&&(env*=(length-index)/fadeOut),out[index]=state*env}for(let tap=0;tap<spec.early;tap+=1){let at3=Math.floor((.004+random2()*.036)*sampleRate);at3<length&&(out[at3]+=(random2()<.5?-1:1)*(.5-tap*.05))}if(spec.shape==="spring"){let period=(.031+.004*random2())*sampleRate,chirp=.025,decay=Math.log(1e3)/spec.seconds;for(let echo=0;echo*period<length;echo+=1){let start=Math.round(echo*period),level2=Math.exp(-decay*start/sampleRate),phase=random2()*2*Math.PI;for(let k=0;k<chirp*sampleRate&&start+k<length;k+=1){let u=k/(chirp*sampleRate),hz3=4e3*(300/4e3)**u;phase+=2*Math.PI*hz3/sampleRate,out[start+k]+=level2*Math.sin(phase)*Math.sin(Math.PI*u)}}}return out}function sampleImpulse(id,mono,sourceRate,sampleRate){let length=Math.max(1,Math.min(Math.round(mono.length*sampleRate/sourceRate),Math.round(MAX_IMPULSE_SECONDS*sampleRate))),out=new Float64Array(length),step2=sourceRate/sampleRate;for(let index=0;index<length;index+=1){let position=index*step2,base=Math.floor(position),a=mono[Math.min(mono.length-1,base)]??0,b=mono[Math.min(mono.length-1,base+1)]??0;out[index]=a+(b-a)*(position-base)}return normalizeImpulse(id,out,out)}function normalizeImpulse(id,left,right){let energy=0;for(let index=0;index<left.length;index+=1)energy+=left[index]*left[index]+right[index]*right[index];let scale3=energy>0?1/Math.sqrt(energy/2):0,l=new Float64Array(left.length),r=new Float64Array(right.length);for(let index=0;index<left.length;index+=1)l[index]=left[index]*scale3,r[index]=right[index]*scale3;return Object.freeze({id,left:l,right:r})}function nextPow22(value){let n2=1;for(;n2<value;)n2<<=1;return n2}function frameSize(seconds2,sampleRate){return nextPow22(Math.max(2,seconds2*sampleRate))}function hann(n2){let w=new Float64Array(n2);for(let i=0;i<n2;i+=1)w[i]=.5-.5*Math.cos(2*Math.PI*i/n2);return w}var HANN_SQUARED_OLA_QUARTER=1.5;function sampleAt(x,index){return index>=0&&index<x.length?x[index]:0}function princarg(phase){return phase-2*Math.PI*Math.round(phase/(2*Math.PI))}function frameCount(length,n2,hop){return Math.max(0,Math.floor((length-n2)/hop)+1)}function analyse(x,at3,window,re,im){let n2=window.length;for(let i=0;i<n2;i+=1)re[i]=sampleAt(x,at3+i)*window[i],im[i]=0;fftInPlace(re,im)}function inverse(re,im){fftInPlace(re,im,!0);let scale3=1/re.length;for(let i=0;i<re.length;i+=1)re[i]=re[i]*scale3,im[i]=im[i]*scale3}var ONSET_MIN_GAP_SECONDS=.03,ONSET_LEAD_SECONDS=.001;function detectOnsets(x,sampleRate,sensitivity=1){let n2=nextPow22(.021*sampleRate),hop=n2/4,half=n2/2,w=hann(n2),frames=frameCount(x.length,n2,hop),flux=new Float64Array(frames),prev=new Float64Array(half+1),cur=new Float64Array(half+1),re=new Float64Array(n2),im=new Float64Array(n2);for(let m=0;m<frames;m+=1){analyse(x,m*hop,w,re,im);let f=0;for(let k=0;k<=half;k+=1){cur[k]=Math.log1p(100*Math.hypot(re[k],im[k]));let lo=k>0?prev[k-1]:prev[k],hi=k<half?prev[k+1]:prev[k],d=cur[k]-Math.max(lo,prev[k],hi);d>0&&(f+=d)}flux[m]=m===0?0:f;let swap=prev;prev=cur,cur=swap}let mean=0;for(let m=0;m<frames;m+=1)mean+=flux[m];mean/=Math.max(1,frames);let onsets2=[],minGap=Math.round(ONSET_MIN_GAP_SECONDS*sampleRate),radius=8,local=[];loudStart(x,sampleRate)&&onsets2.push(0);for(let m=1;m<frames-1;m+=1){let v=flux[m],isPeak=!0;for(let j=Math.max(0,m-3);j<=Math.min(frames-1,m+3);j+=1)if(flux[j]>v||flux[j]===v&&j<m){isPeak=!1;break}if(!isPeak)continue;local.length=0;for(let j=Math.max(0,m-radius);j<=Math.min(frames-1,m+radius);j+=1)local.push(flux[j]);local.sort((a,b)=>a-b);let median=local[local.length>>1];if(v<(median*1.5+mean*.5)/sensitivity)continue;let at3=refineOnset(x,sampleRate,m*hop+half);onsets2.length>0&&at3-onsets2[onsets2.length-1]<minGap||onsets2.push(at3)}return onsets2}function loudStart(x,sampleRate){let peak=0;for(let i=0;i<x.length;i+=1)peak=Math.max(peak,Math.abs(x[i]));if(peak===0)return!1;let head=Math.min(x.length,Math.round(.005*sampleRate));for(let i=0;i<head;i+=1)if(Math.abs(x[i])>.1*peak)return!0;return!1}function refineOnset(x,sampleRate,coarse){let from=Math.max(1,Math.round(coarse-.03*sampleRate)),to=Math.min(x.length,Math.round(coarse+.015*sampleRate));if(to<=from)return coarse;let block=Math.max(1,Math.round(.001*sampleRate)),back=10,start=Math.max(1,from-back*block),blocks=Math.ceil((to-start)/block),raw=new Float64Array(blocks),diff=new Float64Array(blocks);for(let i=start;i<to;i+=1){let b=Math.floor((i-start)/block);raw[b]=Math.max(raw[b],Math.abs(x[i])),diff[b]=Math.max(diff[b],Math.abs(x[i]-x[i-1]))}let peakRaw=0,peakDiff=0;for(let b=0;b<blocks;b+=1)peakRaw=Math.max(peakRaw,raw[b]),peakDiff=Math.max(peakDiff,diff[b]);if(peakRaw===0)return coarse;let first=Math.floor((from-start)/block),best=-1,bestScore=0,bestDiff=!1,bestBg=0;for(let b=Math.max(1,first);b<blocks;b+=1){let bgRaw=0,bgDiff=0;for(let k=Math.max(0,b-back);k<b;k+=1)bgRaw=Math.max(bgRaw,raw[k]),bgDiff=Math.max(bgDiff,diff[k]);let rawScore=raw[b]/(bgRaw+.02*peakRaw),diffScore=peakDiff>0?diff[b]/(bgDiff+.02*peakDiff):0,score=Math.max(rawScore,diffScore);score>bestScore&&(bestScore=score,best=b,bestDiff=diffScore>rawScore,bestBg=bestDiff?bgDiff:bgRaw)}if(best<0)return coarse;let level2=bestDiff?diff[best]:raw[best],threshold=bestBg+.25*(level2-bestBg),lo=Math.max(1,start+(best-1)*block),hi=Math.min(to,start+(best+1)*block),at3=start+best*block;for(let i=lo;i<hi;i+=1)if(Math.abs(bestDiff?x[i]-x[i-1]:x[i])>threshold){at3=i;break}return Math.max(0,at3-Math.round(ONSET_LEAD_SECONDS*sampleRate))}function hermite4(xm1,x0,x1,x2,t){let c1=.5*(x1-xm1),c2=xm1-2.5*x0+2*x1-.5*x2;return(((.5*(x2-xm1)+1.5*(x0-x1))*t+c2)*t+c1)*t+x0}function hermiteAt(x,pos){let i=Math.floor(pos),n2=x.length,at3=k=>k>=0&&k<n2?x[k]:0;return hermite4(at3(i-1),at3(i),at3(i+1),at3(i+2),pos-i)}function clamp(x,lo,hi){return x<lo?lo:x>hi?hi:x}function allpassDelay(a,w){if(w<1e-9)return(1-a)/(1+a);let s=Math.sin(w),c=Math.cos(w),num9=Math.atan2(-s,a+c),den=Math.atan2(-a*s,1+a*c),phase=num9-den;for(;phase>0;)phase-=2*Math.PI;for(;phase<=-2*Math.PI;)phase+=2*Math.PI;return-phase/w}function thiranFor(d,w=0){let a=(1-d)/(1+d);if(w<1e-9)return a;let s=Math.sin(w),c=Math.cos(w);for(let i=0;i<4;i+=1){let f=allpassDelay(a,w)-d;if(Math.abs(f)<1e-10)break;let p=a+c,q3=1+a*c,df=-(s/(p*p+s*s)+s/(q3*q3+a*a*s*s))/w;if(df===0)break;a=clamp(a-f/df,-.9,.9)}return a}var ENVELOPE_LIFTER_SECONDS=.002,ENVELOPE_ITERATIONS=16,PERIOD_FRACTION=.25;function envelopeScratch(n2){return Object.freeze({re:new Float64Array(n2),im:new Float64Array(n2),log:new Float64Array(n2/2+1)})}function cepstralEnvelope(mag,n2,lifter,out,scratch=envelopeScratch(n2),iterations=0,periodRange){let half=n2/2,{re,im,log:log2}=scratch,peak=0;for(let k=0;k<=half;k+=1)peak=Math.max(peak,mag[k]);let floor=peak*1e-6+1e-12;for(let k=0;k<=half;k+=1)log2[k]=Math.log(mag[k]+floor);let cut=Math.max(4,Math.min(half,Math.round(lifter)));for(let pass2=0;pass2<=iterations;pass2+=1){for(let k=0;k<n2;k+=1)re[k]=log2[k<=half?k:n2-k],im[k]=0;if(inverse(re,im),pass2===0&&periodRange){let[lo,hi]=periodRange,q3=Math.max(2,Math.round(lo));for(let i=q3;i<=Math.min(half,Math.round(hi));i+=1)re[i]>re[q3]&&(q3=i);cut=Math.max(4,Math.min(cut,Math.round(q3*PERIOD_FRACTION)))}for(let q3=cut;q3<=n2-cut;q3+=1)re[q3]=0,im[q3]=0;if(fftInPlace(re,im),pass2<iterations)for(let k=0;k<=half;k+=1)log2[k]=Math.max(log2[k],re[k])}for(let k=0;k<=half;k+=1)out[k]=Math.exp(re[k]);return out}var HARMONIC_PEAK_FLOOR=10**(-9/20);function peakEnvelope(mag,half,out,smooth,peaks,range=1e-4){let top=0;for(let k=0;k<=half;k+=1)top=Math.max(top,mag[k]);peaks.length=0;let floor=top*range;for(let k=2;k<=half-2;k+=1){let v=mag[k];v>floor&&v>=smooth[k]*HARMONIC_PEAK_FLOOR&&v>mag[k-1]&&v>=mag[k+1]&&v>mag[k-2]&&v>=mag[k+2]&&peaks.push(k)}if(peaks.length<2)return out.set(smooth.subarray(0,half+1)),out;let at3=i=>{let k=peaks[i],a=Math.log(mag[k-1]+1e-30),b=Math.log(mag[k]+1e-30),c=Math.log(mag[k+1]+1e-30),d=a-2*b+c,delta=d<0?Math.max(-.5,Math.min(.5,.5*(a-c)/d)):0;return[k+delta,b-.25*(a-c)*delta]},j=0,[x0,y0]=at3(0),[x1,y1]=at3(1);for(let k=0;k<=half;k+=1){for(;j+2<peaks.length&&x1<=k;)j+=1,[x0,y0]=[x1,y1],[x1,y1]=at3(j+1);let t=Math.max(0,Math.min(1,(k-x0)/(x1-x0)));out[k]=Math.exp(y0+(y1-y0)*t)}return out}var SHIFT_FRAME_SECONDS=.085,SHIFT_YIELD_HOPS=16,FORMANT_LEVEL_CAP=4,MAX_FORMANT_GAIN=16;function*stretchForShift(x,sampleRate,rho,outLength,formantRatio,options){let n2=frameSize(options.frame??SHIFT_FRAME_SECONDS,sampleRate),hs=n2/4,half=n2/2,w=hann(n2),norm=1/HANN_SQUARED_OLA_QUARTER,keep=rho>1?Math.floor(half/rho):half,lifter=Math.max(4,Math.round((options.lifter??ENVELOPE_LIFTER_SECONDS)*sampleRate)),periodRange=[sampleRate/800,sampleRate/50],out=new Float64Array(outLength+n2),reA=new Float64Array(n2),imA=new Float64Array(n2),reB=new Float64Array(n2),imB=new Float64Array(n2),mag=new Float64Array(half+1),phA=new Float64Array(half+1),syn=new Float64Array(half+1),next=new Float64Array(half+1),omega=new Float64Array(half+1),env=new Float64Array(half+1),scratch=envelopeScratch(n2),smooth=new Float64Array(half+1),envPeaks=[],peaks=[];for(let m=0;m*hs<outLength;m+=1){m%SHIFT_YIELD_HOPS===SHIFT_YIELD_HOPS-1&&(yield);let at3=Math.round((m*hs+half)/rho-half);analyse(x,at3,w,reA,imA),analyse(x,at3-hs,w,reB,imB);for(let k=0;k<=half;k+=1){mag[k]=Math.hypot(reA[k],imA[k]),phA[k]=Math.atan2(imA[k],reA[k]);let phB=Math.atan2(imB[k],reB[k]),bin=2*Math.PI*k*hs/n2;omega[k]=bin+princarg(phA[k]-phB-bin)}if(formantRatio!==void 0&&cepstralEnvelope(mag,n2,lifter,env,scratch,options.iterations??ENVELOPE_ITERATIONS,options.adaptive===!1?void 0:periodRange),formantRatio!==void 0&&options.envelope!=="cepstral"&&(smooth.set(env),peakEnvelope(mag,half,env,smooth,envPeaks)),m===0)syn.set(phA);else{peaks.length=0;for(let k=2;k<=half-2;k+=1){let v=mag[k];v>mag[k-1]&&v>=mag[k+1]&&v>mag[k-2]&&v>=mag[k+2]&&peaks.push(k)}if(peaks.length===0)for(let k=0;k<=half;k+=1)syn[k]=syn[k]+omega[k];else{for(let p of peaks)next[p]=syn[p]+omega[p];let j=0;for(let k=0;k<=half;k+=1){for(;j+1<peaks.length&&Math.abs(peaks[j+1]-k)<Math.abs(peaks[j]-k);)j+=1;let p=peaks[j];k!==p&&(next[k]=next[p]+phA[k]-phA[p])}syn.set(next)}}let before=0,after=0;for(let k=0;k<=half;k+=1){let a=k>keep?0:mag[k];if(before+=a*a,formantRatio!==void 0&&a>0){let src=k*rho/formantRatio,i0=Math.floor(src),target=i0+1<=half?env[i0]+(env[i0+1]-env[i0])*(src-i0):env[half]*.001;a*=Math.min(target/env[k],MAX_FORMANT_GAIN)}after+=a*a,reA[k]=a*Math.cos(syn[k]),imA[k]=a*Math.sin(syn[k]),k>0&&k<half&&(reA[n2-k]=reA[k],imA[n2-k]=-imA[k])}if(imA[0]=0,imA[half]=0,formantRatio!==void 0&&after>0){let gain=Math.min(Math.sqrt(before/after),FORMANT_LEVEL_CAP);for(let k=0;k<n2;k+=1)reA[k]=reA[k]*gain,imA[k]=imA[k]*gain}inverse(reA,imA);let o0=m*hs;for(let i=0;i<n2;i+=1)out[o0+i]=out[o0+i]+reA[i]*w[i]*norm}return out}function*pitchShiftJob(x,sampleRate,semitones,options={}){let length=x.length,out=new Float32Array(length);if(semitones===0&&options.formant===void 0){for(let i=0;i<length;i+=1)out[i]=x[i];return out}let rho=2**(semitones/12),formantRatio=options.formant===void 0?void 0:2**(options.formant/12),midLength=Math.ceil(length*rho)+4,y=yield*stretchForShift(x,sampleRate,rho,midLength,formantRatio,options);for(let i=0;i<length;i+=1){let pos=i*rho,j=Math.floor(pos);out[i]=hermite4(sampleAt(y,j-1),sampleAt(y,j),sampleAt(y,j+1),sampleAt(y,j+2),pos-j)}return out}var FIT_CACHE_BYTES=64*1024*1024,LIVE_SYNC_FIT_SECONDS=8,SLICE_FADE_SECONDS=.002,VOCODER_FRAME_SECONDS=.085,CHUNK=64,cache=new Map,cachedBytes=0,onsetCache=new Map,pending=new Map,live=!1,missed=!1,timer,listeners=new Set;function fittedBuffer(key,window,sampleRate,map,algorithm,onsetKey,length=map.length){let hit2=cache.get(key);if(hit2)return cache.delete(key),cache.set(key,hit2),hit2;let work=()=>fitWork(window,sampleRate,map,algorithm,length,()=>{let known=onsetCache.get(onsetKey);if(known)return known;let found=detectOnsets(window,sampleRate);return onsetCache.set(onsetKey,found),found}),workFrames=Math.max(window.length,Math.min(length,map.length));if(live&&workFrames>LIVE_SYNC_FIT_SECONDS*sampleRate){if(missed=!0,!pending.has(key)){for(let[old,entry]of pending)entry.window===onsetKey&&pending.delete(old);pending.set(key,{job:work(),window:onsetKey}),schedule()}return}pending.delete(key);let out=drain(work());return remember(key,out),out}var LIVE_SYNC_SHIFT_SECONDS=.1;function shiftedBuffer(key,buffer,sampleRate,semitones,formant){let hit2=cache.get(key);if(hit2)return cache.delete(key),cache.set(key,hit2),hit2;let work=()=>pitchShiftJob(buffer,sampleRate,semitones,{...formant===void 0?{}:{formant}});if(live&&buffer.length>LIVE_SYNC_SHIFT_SECONDS*sampleRate){missed=!0,pending.has(key)||(pending.set(key,{job:work(),window:key}),schedule());return}pending.delete(key);let out=drain(work());return remember(key,out),out}function liveFitActive(){return live}function deferLiveJob(key,job,done){missed=!0,!pending.has(key)&&(pending.set(key,{job:job(),window:key,done}),schedule())}function drain(job){for(;;){let step2=job.next();if(step2.done)return step2.value}}function schedule(){timer||(timer=setTimeout(()=>{timer=void 0;let next=pending.entries().next();if(next.done)return;let[key,{job,done}]=next.value,until=performance.now()+8;for(;;){let step2=job.next();if(step2.done){pending.delete(key),done?done(step2.value):remember(key,step2.value);for(let listener of listeners)listener();break}if(performance.now()>until)break}pending.size>0&&schedule()},0))}function remember(key,out){if(!(out.byteLength>FIT_CACHE_BYTES)){cache.set(key,out),cachedBytes+=out.byteLength;for(let[old,buffer]of cache){if(cachedBytes<=FIT_CACHE_BYTES)break;cache.delete(old),cachedBytes-=buffer.byteLength}}}function*fitWork(window,sampleRate,map,algorithm,limit,onsets2){let length=Math.max(1,Math.round(Math.min(limit,map.length)));if(algorithm==="repitch"){let out=new Float32Array(length);for(let e=0;e<length;e+=1)out[e]=hermiteRead(window,map.at(e)),e%(CHUNK*1024)===0&&(yield);return out}return algorithm==="beats"?(yield,beatsFit(window,sampleRate,onsets2(),map,length)):yield*tonesFit(window,sampleRate,map,length)}function beatsFit(x,sampleRate,onsets2,map,length){let out=new Float32Array(length),marks=[0,...onsets2.filter(v=>v>0&&v<x.length),x.length],fade=Math.max(1,Math.round(SLICE_FADE_SECONDS*sampleRate)),lead=Math.round(ONSET_LEAD_SECONDS*sampleRate),place=v=>v===0||v===x.length?Math.round(map.outAt(v)):Math.round(map.outAt(Math.min(x.length,v+lead)))-lead;for(let s=0;s+1<marks.length;s+=1){let a=marks[s],b=marks[s+1],oa=Math.max(0,place(a)),ob=Math.min(length,place(b)),span4=Math.min(ob-oa,b-a);if(span4<=0)continue;let tail=Math.min(fade,span4),head=a===0?0:Math.min(Math.max(1,lead),span4-tail);for(let i=0;i<span4&&oa+i<length;i+=1){let g=(i>=span4-tail?(span4-i)/tail:1)*(i<head?(i+1)/(head+1):1);out[oa+i]=out[oa+i]+x[a+i]*g}}return out}function*tonesFit(x,sampleRate,map,length){let n2=frameSize(VOCODER_FRAME_SECONDS,sampleRate),hs=n2/4,half=n2/2,w=hann(n2),norm=1/HANN_SQUARED_OLA_QUARTER,out=new Float64Array(length+n2),reA=new Float64Array(n2),imA=new Float64Array(n2),reB=new Float64Array(n2),imB=new Float64Array(n2),mag=new Float64Array(half+1),phA=new Float64Array(half+1),syn=new Float64Array(half+1),next=new Float64Array(half+1),omega=new Float64Array(half+1),prevPh=new Float64Array(half+1),lastAt=0,peaks=[];for(let m=0;m*hs<length;m+=1){m%CHUNK===CHUNK-1&&(yield);let at3=Math.round(map.at(m*hs+half)-half),back=at3-lastAt,reuse=m>0&&back>=hs/4&&back<=half;if(!reuse){analyse(x,at3-hs,w,reB,imB);for(let k=0;k<=half;k+=1)prevPh[k]=Math.atan2(imB[k],reB[k])}let ha=reuse?back:hs;analyse(x,at3,w,reA,imA);for(let k=0;k<=half;k+=1){mag[k]=Math.hypot(reA[k],imA[k]),phA[k]=Math.atan2(imA[k],reA[k]);let bin=2*Math.PI*k/n2;omega[k]=(bin*ha+princarg(phA[k]-prevPh[k]-bin*ha))*(hs/ha),prevPh[k]=phA[k]}if(lastAt=at3,m===0)syn.set(phA);else{peaks.length=0;for(let k=2;k<=half-2;k+=1){let v=mag[k];v>mag[k-1]&&v>=mag[k+1]&&v>mag[k-2]&&v>=mag[k+2]&&peaks.push(k)}if(peaks.length===0)for(let k=0;k<=half;k+=1)syn[k]=syn[k]+omega[k];else{for(let p of peaks)next[p]=syn[p]+omega[p];let j=0;for(let k=0;k<=half;k+=1){for(;j+1<peaks.length&&Math.abs(peaks[j+1]-k)<Math.abs(peaks[j]-k);)j+=1;let p=peaks[j];k!==p&&(next[k]=next[p]+phA[k]-phA[p])}syn.set(next)}}for(let k=0;k<=half;k+=1){let a=mag[k];reA[k]=a*Math.cos(syn[k]),imA[k]=a*Math.sin(syn[k]),k>0&&k<half&&(reA[n2-k]=reA[k],imA[n2-k]=-imA[k])}imA[0]=0,imA[half]=0,inverse(reA,imA);let o0=m*hs;for(let i=0;i<n2;i+=1)out[o0+i]=out[o0+i]+reA[i]*w[i]*norm}let result=new Float32Array(length);for(let i=0;i<length;i+=1)result[i]=out[i];return result}function windowAt(mono,from,to,rate2,reverse){let frames=Math.max(1,Math.floor((to-from)/rate2)),out=new Float32Array(frames),last=mono.length-1;for(let i=0;i<frames;i+=1){let position=reverse?to-1-i*rate2:from+i*rate2;if(position<=0)out[i]=mono[0];else if(position>=last)out[i]=mono[last];else{let base=Math.floor(position),a=mono[base];out[i]=a+(mono[base+1]-a)*(position-base)}}return out}function hermiteRead(x,pos){let i=Math.floor(pos);return hermite4(sampleAt(x,i-1),sampleAt(x,i),sampleAt(x,i+1),sampleAt(x,i+2),pos-i)}var MiB=1024*1024,GiB=1024*MiB,DEFAULT_PACKS_CACHE_BYTES=2*GiB,DEFAULT_ASSETS_CACHE_BYTES=1*GiB,DEFAULT_MEMORY_CACHE_BYTES=SCORE_LIMITS.maxSampleCacheBytes;var DEFAULT_RENDER_CACHE_BYTES=4*GiB,DEFAULT_VOICE_CACHE_BYTES=2*GiB;function besselI0(x){let sum=1,term=1;for(let k=1;k<50&&(term*=(x/(2*k))**2,sum+=term,!(term<1e-12*sum));k+=1);return sum}function halfbandTaps(length=47,beta=8){let taps=new Float64Array(length),mid=(length-1)/2,i0b=besselI0(beta);for(let n2=0;n2<length;n2+=1){let k=n2-mid,sinc=k===0?.5:Math.sin(Math.PI*k/2)/(Math.PI*k),r=k/mid,w=besselI0(beta*Math.sqrt(Math.max(0,1-r*r)))/i0b;taps[n2]=k!==0&&k%2===0?0:sinc*w}return taps}function phaseOf(taps,parity){let kept=[],offsets=[];for(let n2=parity;n2<taps.length;n2+=2)taps[n2]!==0&&(kept.push(taps[n2]),offsets.push((n2-parity)/2));return{taps:Float64Array.from(kept),offsets:Int32Array.from(offsets)}}function ringSize(length){let size=4;for(;size<length+2;)size*=2;return size}var Decimate2=class{taps;offsets;history;mask;write=0;constructor(taps=halfbandTaps(47,8)){let kept=[],offsets=[];for(let n2=0;n2<taps.length;n2+=1)taps[n2]!==0&&(kept.push(taps[n2]),offsets.push(n2));this.taps=Float64Array.from(kept),this.offsets=Int32Array.from(offsets),this.history=new Float64Array(ringSize(taps.length)),this.mask=this.history.length-1}process(a,b){let h=this.history,m=this.mask;h[this.write]=a;let newest=this.write;this.write=this.write+1&m,h[this.write]=b,this.write=this.write+1&m;let acc=0;for(let i=0;i<this.taps.length;i+=1)acc+=this.taps[i]*h[newest-this.offsets[i]&m];return acc}reset(){this.history.fill(0)}},Interpolate2=class{even;odd;history;mask;write=0;constructor(taps=halfbandTaps(47,8)){this.even=phaseOf(taps,0),this.odd=phaseOf(taps,1),this.history=new Float64Array(ringSize(taps.length+1>>1)),this.mask=this.history.length-1}process(x,out){let h=this.history,m=this.mask;h[this.write]=x;let newest=this.write;this.write=this.write+1&m,out[0]=2*branch(this.even,h,newest,m),out[1]=2*branch(this.odd,h,newest,m)}reset(){this.history.fill(0)}};function branch(phase,history,newest,mask){let acc=0,{taps,offsets}=phase;for(let i=0;i<taps.length;i+=1)acc+=taps[i]*history[newest-offsets[i]&mask];return acc}var Oversample2x=class{up;down;pair=new Float64Array(2);constructor(taps=halfbandTaps(47,8)){this.up=new Interpolate2(taps),this.down=new Decimate2(taps)}static latency(taps=47){return(taps-1)/2}process(x,fn){let pair2=this.pair;return this.up.process(x,pair2),this.down.process(fn(pair2[0]),fn(pair2[1]))}reset(){this.up.reset(),this.down.reset()}},Oversample4x=class{outerUp;outerDown;inner;pair=new Float64Array(2);constructor(outer=halfbandTaps(127,10),inner=halfbandTaps(47,8)){this.outerUp=new Interpolate2(outer),this.outerDown=new Decimate2(outer),this.inner=new Oversample2x(inner)}process(x,fn){let pair2=this.pair;this.outerUp.process(x,pair2);let a=this.inner.process(pair2[0],fn),b=this.inner.process(pair2[1],fn);return this.outerDown.process(a,b)}reset(){this.outerUp.reset(),this.outerDown.reset(),this.inner.reset()}};var PITCH_TRACKER_VERSION=2,TRACK_RATE=16e3,PITCH_HOP_SECONDS=.005,PITCH_VOICES={auto:{fmin:70,fmax:1400},bass:{fmin:55,fmax:400},tenor:{fmin:90,fmax:600},alto:{fmin:140,fmax:900},soprano:{fmin:200,fmax:1400}},PITCH_VOICE_NAMES=Object.keys(PITCH_VOICES);function emptyCurve(hop=PITCH_HOP_SECONDS){return{t0:0,hop,f0:new Float32Array(0),prob:new Uint8Array(0),aperiodic:new Uint8Array(0)}}var HALFBAND=halfbandTaps(47,8);function halve(x){let n2=Math.floor(x.length/2),y=new Float64Array(n2),mid=(HALFBAND.length-1)/2,taps=[],offsets=[];for(let k=0;k<HALFBAND.length;k+=1)HALFBAND[k]!==0&&(taps.push(HALFBAND[k]),offsets.push(k-mid));let len=x.length;for(let j=0;j<n2;j+=1){let c=2*j,acc=0;for(let k=0;k<taps.length;k+=1){let i=c+offsets[k];i>=0&&i<len&&(acc+=taps[k]*x[i])}y[j]=acc}return y}function gcd(a,b){for(;b;)[a,b]=[b,a%b];return a}function besselI02(x){let sum=1,term=1;for(let k=1;k<50&&(term*=(x/(2*k))**2,sum+=term,!(term<1e-12*sum));k+=1);return sum}var POLY_TABLES=new Map;function polyTable(from,to){let key=`${from}:${to}`,cached=POLY_TABLES.get(key);if(cached)return cached;let g=gcd(from,to),up=to/g,down=from/g,cut=.45*Math.min(from,to)/from,half=Math.ceil(12/(2*cut)),beta=8,i0b=besselI02(beta),phases2=[];for(let p=0;p<up;p+=1){let frac2=p/up,taps=new Float64Array(2*half),sum=0;for(let k=0;k<2*half;k+=1){let t=k-half+1-frac2,arg=2*cut*t,sinc=arg===0?1:Math.sin(Math.PI*arg)/(Math.PI*arg),r=t/half,w=Math.abs(r)>=1?0:besselI02(beta*Math.sqrt(1-r*r))/i0b;taps[k]=sinc*w,sum+=taps[k]}for(let k=0;k<taps.length;k+=1)taps[k]/=sum;phases2.push(taps)}let table2={up,down,half,phases:phases2};return POLY_TABLES.set(key,table2),table2}function polyphase(x,from,to){if(from===to)return x;let{up,down,half,phases:phases2}=polyTable(from,to),n2=Math.floor(x.length*up/down),y=new Float64Array(n2),len=x.length;for(let j=0;j<n2;j+=1){let num9=j*down,i=Math.floor(num9/up),taps=phases2[num9-i*up],acc=0,base=i-half+1;for(let k=0;k<taps.length;k+=1){let s=base+k;s>=0&&s<len&&(acc+=taps[k]*x[s])}y[j]=acc}return y}function resampleForTracking(x,sampleRate){let rate2=Math.round(sampleRate),y=x;for(;rate2>=2*TRACK_RATE&&rate2%2===0;)y=halve(y),rate2/=2;return polyphase(y,rate2,TRACK_RATE)}var THRESHOLDS=100,BETA=(()=>{let w=new Float64Array(THRESHOLDS),s=0;for(let i=0;i<THRESHOLDS;i+=1){let t=(i+.5)/THRESHOLDS;w[i]=t*(1-t)**17,s+=w[i]}for(let i=0;i<THRESHOLDS;i+=1)w[i]/=s;return w})(),MAX_CANDIDATES=6,SUBHARMONIC_MARGIN=.12,SUBHARMONIC_RAW=6,SUBHARMONIC_COMB=.3,REGISTER_CENTS=1700,HANN=new Map;function hannOf(n2){let w=HANN.get(n2);if(!w){w=new Float64Array(n2);for(let i=0;i<n2;i+=1)w[i]=.5-.5*Math.cos(2*Math.PI*i/n2);HANN.set(n2,w)}return w}function harmonicEnergies(y,start,size,rate2,lag){let w=hannOf(size),f=rate2/lag,top=Math.min(4e3,rate2*.45),count2=Math.max(0,Math.ceil(top/f)-1),out=new Float64Array(count2);for(let k=1;k*f<top;k+=1){let om=2*Math.PI*k*f/rate2,c=2*Math.cos(om),q1=0,q22=0;for(let i=0;i<size;i+=1){let q0=(y[start+i]??0)*w[i]+c*q1-q22;q22=q1,q1=q0}out[k-1]=q1*q1+q22*q22-c*q1*q22}return out}function combRatio(e,div){let eNon=0,nNon=0,eMul=0,nMul=0;for(let k=1;k<=e.length;k+=1)k%div===0?(eMul+=e[k-1],nMul+=1):(eNon+=e[k-1],nNon+=1);return!nMul||!nNon||eMul<=0?1:eNon/nNon/(eMul/nMul)}var STEP_FRAMES=100;function trackPitch(x,sampleRate,options={}){let steps2=trackPitchSteps(x,sampleRate,options);for(;;){let r=steps2.next();if(r.done)return r.value}}async function trackPitchAsync(x,sampleRate,options={},progress){let steps2=trackPitchSteps(x,sampleRate,options);for(;;){let r=steps2.next();if(r.done)return r.value;progress?.(r.value),await new Promise(resolve=>setImmediate(resolve))}}function*trackPitchSteps(x,sampleRate,options={}){let range=PITCH_VOICES[options.voice??"auto"],fmin=options.fmin??range.fmin,fmax=options.fmax??range.fmax,gateDb=options.gateDb??45,comb=options.comb!==!1,rate2=TRACK_RATE,hopS=Math.max(1,Math.round((options.hop??PITCH_HOP_SECONDS)*rate2)),hop=hopS/rate2,tauMax=Math.ceil(rate2/fmin),tauMin=Math.max(2,Math.floor(rate2/fmax)),W2=Math.max(256,1<<Math.ceil(Math.log2(tauMax*1.6))),tauRef=Math.min(tauMax,rate2/220),centre=(W2+tauRef)/2,pad=Math.floor(centre/hopS)*hopS,t0=(centre-pad)/rate2,src=resampleForTracking(x,sampleRate);if(src.length===0)return emptyCurve(hop);let frames=Math.max(0,Math.floor((pad+src.length-centre)/hopS)+1),y=new Float64Array(pad+src.length+W2+tauMax+2);y.set(src,pad);let N=1;for(;N<W2+tauMax+1;)N<<=1;let re=new Float64Array(N),im=new Float64Array(N),pr=new Float64Array(N),pi=new Float64Array(N),sq=new Float64Array(y.length+1);for(let i=0;i<y.length;i+=1)sq[i+1]=sq[i]+y[i]*y[i];let d=new Float64Array(tauMax+2),dn=new Float64Array(tauMax+2),all=[],maxRms=0;for(let f=0;f<frames;f+=1){let s=f*hopS;re.fill(0),im.fill(0);for(let i=0;i<W2;i+=1)re[i]=y[s+i];for(let i=0;i<W2+tauMax;i+=1)im[i]=y[s+i];fftInPlace(re,im);for(let k=0;k<N;k+=1){let k2=N-k&N-1,ar2=.5*(re[k]+re[k2]),ai=.5*(im[k]-im[k2]),br=.5*(im[k]+im[k2]),bi=-.5*(re[k]-re[k2]);pr[k]=ar2*br+ai*bi,pi[k]=ar2*bi-ai*br}fftInPlace(pr,pi,!0);let e0=Math.max(0,sq[s+W2]-sq[s]);d[0]=0,dn[0]=1;let run=0;for(let tau=1;tau<=tauMax;tau+=1){let et=sq[s+tau+W2]-sq[s+tau],r=pr[tau]/N,v=Math.max(0,e0+et-2*r);d[tau]=v,run+=v,dn[tau]=run>0?v*tau/run:1}let rms=Math.sqrt(e0/W2);rms>maxRms&&(maxRms=rms);let mins=[];for(let tau=tauMin;tau<tauMax;tau+=1)if(dn[tau]<dn[tau-1]&&dn[tau]<=dn[tau+1]){let a=dn[tau-1],b=dn[tau],c=dn[tau+1],den=a-2*b+c,off=den>0?.5*(a-c)/den:0;mins.push({tau:tau+Math.max(-.5,Math.min(.5,off)),v:b-.25*(a-c)*off,raw:d[tau]})}let tauList=[],pList=[],apList=[];if(mins.length){let probs=new Float64Array(mins.length),gi=0;for(let i=1;i<mins.length;i+=1)mins[i].v<mins[gi].v&&(gi=i);for(let t=0;t<THRESHOLDS;t+=1){let thr=(t+1)/THRESHOLDS,chosen=-1;for(let i=0;i<mins.length;i+=1)if(mins[i].v<thr){chosen=i;break}chosen>=0?probs[chosen]+=BETA[t]:probs[gi]+=BETA[t]*.01}let energies=new Map,combOf=(i,div)=>{let e=energies.get(i);return e||(e=harmonicEnergies(y,s,W2,rate2,mins[i].tau),energies.set(i,e)),combRatio(e,div)};for(let i=0;i<mins.length;i+=1)for(let div of[2,3]){let want=mins[i].tau/div;for(let m=0;m<mins.length;m+=1){if(m===i||Math.abs(mins[m].tau-want)>want*.04)continue;let short=mins[m],long=mins[i];(short.v<long.v+SUBHARMONIC_MARGIN||comb&&probs[i]>0&&short.raw<SUBHARMONIC_RAW*long.raw&&combOf(i,div)<SUBHARMONIC_COMB)&&(probs[m]+=probs[i],probs[i]=0,short.v=Math.min(short.v,long.v))}}let order=[...mins.keys()].sort((a,b)=>probs[b]-probs[a]||a-b).slice(0,MAX_CANDIDATES);for(let i of order)probs[i]<=0||(tauList.push(mins[i].tau),pList.push(probs[i]),apList.push(mins[i].v))}let pv=0;for(let q3 of pList)pv+=q3;let apMin=apList.length?Math.min(...apList):1,ramp=Math.max(0,Math.min(1,(.5-apMin)/.3));all.push({tau:tauList,p:pList,ap:apList,rms,v:Math.min(.995,Math.max(pv,ramp))}),(f+1)%STEP_FRAMES===0&&f+1<frames&&(yield(f+1)/frames)}let gate=maxRms*10**(-gateDb/20);for(let fr of all)fr.rms<=gate&&(fr.p=fr.p.map(p=>p*.02),fr.v*=.02);let centsOf=tau=>1200*Math.log2(rate2/tau/440),confident=[];for(let fr of all)if(!(fr.rms<=gate)){for(let i=0;i<fr.tau.length;i+=1)if(fr.ap[i]<.08){confident.push(centsOf(fr.tau[i]));break}}if(confident.length>=20){confident.sort((a,b)=>a-b);let median=confident[confident.length>>1];for(let fr of all)fr.p=fr.p.map((p,i)=>Math.abs(centsOf(fr.tau[i])-median)>REGISTER_CENTS?p*.15:p)}let path=viterbi(all,centsOf),hz3=new Float64Array(frames),prob=new Uint8Array(frames),aperiodic=new Uint8Array(frames).fill(255);for(let f=0;f<frames;f+=1){let fr=all[f],k=path[f],p=0;for(let v of fr.p)p+=v;prob[f]=toByte(p),k>=0&&(hz3[f]=rate2/fr.tau[k],aperiodic[f]=toByte(fr.ap[k]))}return foldOctaves(hz3),{t0,hop,f0:Float32Array.from(hz3),prob,aperiodic}}function toByte(value){return Math.round(Math.min(1,Math.max(0,value))*255)}function foldOctaves(hz3){let n2=hz3.length,src=Float64Array.from(hz3),R=10,win=[];for(let f=0;f<n2;f+=1){if(!(src[f]>0))continue;win.length=0;for(let g=Math.max(0,f-R);g<=Math.min(n2-1,f+R);g+=1)src[g]>0&&win.push(Math.log2(src[g]));win.sort((a,b)=>a-b);let med=win[win.length>>1],l=Math.log2(src[f]);Math.abs(l-med)*1200>900&&(hz3[f]=2**(l-Math.round(l-med)))}}function viterbi(frames,centsOf){let n2=frames.length,SWITCH=Math.log(.02),STAY_U=Math.log(.98),JUMP=250,back=[],prevScore=[],prevCents=[];for(let f=0;f<n2;f+=1){let fr=frames[f],k=fr.tau.length,sum=0;for(let p of fr.p)sum+=p;let pv=fr.v,emitU=Math.log(Math.max(1e-6,1-pv)),score=new Array(k+1).fill(-1/0),bp=new Int8Array(k+1).fill(-1),cents=fr.tau.map(centsOf);for(let j=0;j<=k;j+=1){let emit=j<k?Math.log(Math.max(1e-9,pv*fr.p[j]/Math.max(1e-12,sum))):emitU;if(f===0){score[j]=emit;continue}let pk=prevScore.length-1;for(let i=0;i<=pk;i+=1){let t;if(i===pk&&j===k)t=STAY_U;else if(i===pk||j===k)t=SWITCH;else{let dc=(cents[j]-prevCents[i])/JUMP;t=-.5*dc*dc}let s=prevScore[i]+t+emit;s>score[j]&&(score[j]=s,bp[j]=i)}}back.push(bp),prevScore=score,prevCents=cents}let path=new Array(n2),best=0;for(let j=1;j<prevScore.length;j+=1)prevScore[j]>prevScore[best]&&(best=j);for(let f=n2-1;f>=0;f-=1){let k=frames[f].tau.length;path[f]=best===k?-1:best,best=back[f][best]}return path}var ANALYSIS_CACHE_BYTES=64*1024*1024,ANALYSIS_MEMORY_ENTRIES=64;function analysisFileName(sha256,voice){return`${sha256}.${voice}.v${PITCH_TRACKER_VERSION}.f0`}var memory=new Map;function remember2(key,curve){for(memory.delete(key),memory.set(key,curve);memory.size>ANALYSIS_MEMORY_ENTRIES;)memory.delete(memory.keys().next().value)}function cachedPitchCurve(sha256,voice="auto"){let key=analysisFileName(sha256,voice),hit2=memory.get(key);return hit2&&remember2(key,hit2),hit2}var UNVOICED_PERIOD=.004;function pitchMarks(x,sampleRate,f0){let n2=x.length,up=Math.max(1,Math.round(UNVOICED_PERIOD*sampleRate)),polarity=new Int8Array(n2).fill(1);for(let a=0;a<n2;){if(!(f0[a]>0)){a+=1;continue}let b=a,s3=0;for(;b<n2&&f0[b]>0;)s3+=x[b]**3,b+=1;s3<0&&polarity.fill(-1,a,b),a=b}let marks=[],i=0;for(;i<n2;){let hz3=f0[i];if(!(hz3>0)){marks.push(i),i+=up;continue}let period=sampleRate/hz3,last=marks.length?marks[marks.length-1]:-1,afterVoiced=last>=0&&f0[last]>0,lo=Math.max(0,Math.round(i-(afterVoiced?period/4:0))),hi=Math.min(n2-1,Math.round(i+(afterVoiced?period/4:period))),sign=polarity[i],best=lo;for(let j=lo+1;j<=hi;j+=1)sign*x[j]>sign*x[best]&&(best=j);if(last>=0&&best<=last&&(best=last+Math.max(1,Math.round(period/2))),best>=n2)break;marks.push(best);let next=f0[best]>0?sampleRate/f0[best]:period;i=best+Math.max(1,Math.round(next))}return Int32Array.from(marks)}function psola(x,sampleRate,curve,options={}){let n2=x.length,offset=Math.max(0,Math.min(n2,Math.round(options.offset??0))),length=Math.max(0,Math.round(options.length??n2-offset)),out=new Float64Array(length),marks=options.marks??pitchMarks(x,sampleRate,curve.f0);if(marks.length===0||length===0)return out;let formant=Math.min(2,Math.max(.5,options.formant??1)),up=UNVOICED_PERIOD*sampleRate,end=offset+length,k=0,t=marks[0];for(;t<end+up;){for(;k+1<marks.length&&Math.abs(marks[k+1]-t)<=Math.abs(marks[k]-t);)k+=1;let m=marks[k],hz3=curve.f0[m],voiced=hz3>0,period=voiced?sampleRate/hz3:up,gap=k+1<marks.length?marks[k+1]-m:0,pin=gap>=period*.5&&gap<=period*1.5?gap:period,at3=Math.min(n2-1,Math.max(0,Math.round(t))),ratio2=voiced?2**((curve.cents[at3]||0)/1200):1,pout=pin/ratio2,left=k>0?Math.min(period*1.5,Math.max(2,m-marks[k-1])):period,right=k+1<marks.length?Math.min(period*1.5,Math.max(2,marks[k+1]-m)):period,f=voiced?formant:1,gain=voiced?Math.min(2,pout*f/pin):1,lo=Math.max(offset,Math.ceil(t-left/f)),hi=Math.min(end-1,Math.floor(t+right/f));for(let o=lo;o<=hi;o+=1){let j=(o-t)*f,w=j<0?.5*(1+Math.cos(Math.PI*j/left)):.5*(1+Math.cos(Math.PI*j/right));out[o-offset]+=hermiteAt(x,m+j)*w*gain}if(t=!voiced&&k+1<marks.length?marks[k+1]:t+pout,k+1>=marks.length&&t>m+2*period)break}return out}var CURVE_ENTRIES=64,curves=new Map,anonymous=new WeakMap,pending2=new Set;function keyOf(buffer){return buffer.id??buffer.sha256}function lookup(buffer,voice){let key=keyOf(buffer);if(key===void 0)return anonymous.get(buffer.mono)?.get(voice);let name=`${key}|${voice}`,hit2=curves.get(name);if(hit2)return curves.delete(name),curves.set(name,hit2),hit2;if(buffer.id===void 0&&buffer.sha256!==void 0){let cached=cachedPitchCurve(buffer.sha256,voice);return cached&&store(buffer,voice,cached),cached}}function store(buffer,voice,curve){let key=keyOf(buffer);if(key===void 0){let byVoice=anonymous.get(buffer.mono)??new Map;byVoice.set(voice,curve),anonymous.set(buffer.mono,byVoice);return}let name=`${key}|${voice}`;for(curves.delete(name),curves.set(name,curve);curves.size>CURVE_ENTRIES;)curves.delete(curves.keys().next().value)}var builtinPitchEngine=Object.freeze({version:`yin${PITCH_TRACKER_VERSION}-psola1`,curve(buffer,voice,options){let hit2=lookup(buffer,voice);if(hit2)return hit2;let x=Float64Array.from(buffer.mono);if(!options?.defer){let curve=trackPitch(x,buffer.sampleRate,{voice});return store(buffer,voice,curve),curve}let name=`${keyOf(buffer)??"anon"}|${voice}`;pending2.has(name)||(pending2.add(name),trackPitchAsync(x,buffer.sampleRate,{voice}).then(curve=>{pending2.delete(name),store(buffer,voice,curve)},()=>pending2.delete(name)))},psola:(x,sampleRate,curve)=>psola(x,sampleRate,curve)});var chunks=new Map,sourceTables=new WeakMap,count=0,clock=0,bytes=0,byteCap=67108864,ZERO_CHUNK=new Float32Array(4099),kernels=new Map;function bankLevel(step2){let r=step2<0?-step2:step2;if(r<=1+1e-9)return 0;let level2=Math.ceil(12*Math.log2(r)-1e-6);return level2>60?60:level2}function besselI03(x){let sum=1,term=1,q3=x*x/4;for(let k=1;k<64&&(term*=q3/(k*k),sum+=term,!(term<sum*1e-17));k+=1);return sum}function bankKernel(level2){let h=kernels.get(level2);if(h)return h;let r=2**(level2/12),taps=Math.min(511,Math.ceil(96*r));taps%2===0&&(taps+=1);let transition=62/(2.285*2*Math.PI*(taps-1)),fc=Math.max(.01,.5/r-transition/2);h=new Float64Array(taps);let mid=(taps-1)/2,norm=besselI03(6.75526),sum=0;for(let i=0;i<taps;i+=1){let m=i-mid,sinc=m===0?2*fc:Math.sin(2*Math.PI*fc*m)/(Math.PI*m),ratio2=m/mid,w=besselI03(6.75526*Math.sqrt(1-ratio2*ratio2))/norm;h[i]=sinc*w,sum+=h[i]}for(let i=0;i<taps;i+=1)h[i]=h[i]/sum;return kernels.set(level2,h),h}function fill(source,level2,index){let out=new Float32Array(4099),data=source.data,n2=data.length,first=index*4096-1;if(level2===0){for(let i=0;i<out.length;i+=1){let k=first+i;out[i]=k>=0&&k<n2?data[k]:0}return out}let h=bankKernel(level2),taps=h.length,mid=taps-1>>1;for(let i=0;i<out.length;i+=1){let lo=first+i-mid,from=0,to=taps;lo<0&&(from=-lo),lo+to>n2&&(to=n2-lo);let acc=0;for(let j=from;j<to;j+=1)acc+=h[j]*data[lo+j];out[i]=acc}return out}function bankChunk(source,level2,index){if(index<0||index*4096>source.data.length+2)return ZERO_CHUNK;let table2=sourceTables.get(source);if(!table2){let id=`${source.id}\0${source.rate}`;table2=chunks.get(id),table2||chunks.set(id,table2=new Map),sourceTables.set(source,table2)}let key=level2*2**32+index;clock+=1;let hit2=table2.get(key);if(hit2)return hit2.used=clock,hit2.chunk;let chunk=fill(source,level2,index);return table2.set(key,{chunk,used:clock}),count+=1,bytes+=chunk.byteLength,bytes>byteCap&&evict(),chunk}function evict(){let all=[];for(let table2 of chunks.values())for(let[key,entry]of table2)all.push({table:table2,key,used:entry.used});all.sort((a,b)=>a.used-b.used);for(let{table:table2,key}of all){if(bytes<=byteCap||count<=1)break;bytes-=table2.get(key).chunk.byteLength,table2.delete(key),count-=1}}function seedHash(text2){let hash=2166136261;for(let index=0;index<text2.length;index+=1)hash^=text2.charCodeAt(index),hash=Math.imul(hash,16777619)>>>0;return hash>>>0}function fmix32(h){return h^=h>>>16,h=Math.imul(h,2246822507),h^=h>>>13,h=Math.imul(h,3266489909),h^=h>>>16,h>>>0}function unit3(seed,index,slot){let a=fmix32((seed^Math.imul(index|0,2654435761))>>>0);return fmix32((a^Math.imul(slot+1,2146121005))>>>0)/4294967296}var WINDOW_SHAPES=Object.freeze(["hann","tukey","gauss","tri","perc","rperc"]),WINDOW_TABLE=2048;function shapeAt(shape,u){switch(shape){case"hann":return .5-.5*Math.cos(2*Math.PI*u);case"tukey":return u<.25?.5-.5*Math.cos(Math.PI*u/.25):u>1-.25?.5-.5*Math.cos(Math.PI*(1-u)/.25):1;case"gauss":{let g=Math.exp(-.5*((u-.5)/.15)**2),e=Math.exp(-.5*(.5/.15)**2);return(g-e)/(1-e)}case"tri":return 1-Math.abs(2*u-1);case"perc":return(u<.02?u/.02:1)*(1-u)**3;case"rperc":return(u>.98?(1-u)/.02:1)*u**3}}function windowTable(shape){let table2=new Float64Array(WINDOW_TABLE+1);for(let i=0;i<=WINDOW_TABLE;i+=1)table2[i]=shapeAt(shape,i/WINDOW_TABLE);return table2}var cache2=new Map;function grainWindow(shape){let entry=cache2.get(shape);if(!entry){let table2=windowTable(shape),sq=0;for(let i=0;i<WINDOW_TABLE;i+=1)sq+=table2[i]*table2[i];entry=Object.freeze({table:table2,meanSq:sq/WINDOW_TABLE}),cache2.set(shape,entry)}return entry}function tickAtSample(context,index){return context.warp?context.warp.tick(index):index/context.samplesPerTick}function tempoAtSample(context,index){return context.warp?context.warp.bpm(context.warp.tick(index)):context.tempoBpm}function interpolateAutomation(points,tick,fallback){if(points.length===0||!Number.isFinite(tick))return fallback;let first=points[0];if(tick<first.tick)return fallback;let last=points[points.length-1];if(tick>=last.tick)return last.value;let index=1;if(points.length>8){let end=points.length-1;for(;index<end;){let middle=index+end>>>1;points[middle].tick<tick?index=middle+1:end=middle}}else for(;index<points.length-1&&tick>points[index].tick;)index+=1;let right=points[index],left=points[index-1],span4=right.tick-left.tick,ratio2=span4<=0?1:(tick-left.tick)/span4;return left.value+(right.value-left.value)*ratio2}var Param=class{constructor(fallback,points,samplesPerTick,warp2){this.fallback=fallback;this.samplesPerTick=samplesPerTick;this.warp=warp2;this.points=points??[],this.automated=this.points.length>0}fallback;samplesPerTick;warp;automated;points;at(index){return this.automated?interpolateAutomation(this.points,this.warp?this.warp.tick(index):index/this.samplesPerTick,this.fallback):this.fallback}};function fxReader(track2,effect,values,context){return{number(name){return values[name]},text(name){return values[name]},param(name){return new Param(values[name],track2.fxAutomation?.[`${effect}-${name}`],context.samplesPerTick,context.warp)}}}function clamp2(value,min,max){return Math.min(max,Math.max(min,value))}function resonanceQ(resonance){return .707+clamp2(resonance,0,1)*7.293}var Biquad=class{b0=1;b1=0;b2=0;a1=0;a2=0;z1=0;z2=0;set(type,cutoff2,q3,sampleRate){let frequency=clamp2(cutoff2,20,sampleRate*.45),omega=2*Math.PI*frequency/sampleRate,alpha=Math.sin(omega)/(2*q3),cos=Math.cos(omega),a0=1+alpha;type==="lpf"?(this.b0=(1-cos)/2/a0,this.b1=(1-cos)/a0,this.b2=this.b0):type==="hpf"?(this.b0=(1+cos)/2/a0,this.b1=-(1+cos)/a0,this.b2=this.b0):(this.b0=alpha/a0,this.b1=0,this.b2=-alpha/a0),this.a1=-2*cos/a0,this.a2=(1-alpha)/a0}process(input){let output2=this.b0*input+this.z1;return this.z1=this.b1*input-this.a1*output2+this.z2,this.z2=this.b2*input-this.a2*output2,output2}},Svf=class{constructor(type){this.type=type}type;k=Math.SQRT2;a1=1;a2=0;a3=0;ic1=0;ic2=0;set(cutoff2,q3,sampleRate){let frequency=clamp2(cutoff2,20,sampleRate*.45),g=Math.tan(Math.PI*frequency/sampleRate);this.k=1/Math.max(.1,q3),this.a1=1/(1+g*(g+this.k)),this.a2=g*this.a1,this.a3=g*this.a2}process(input){let v3=input-this.ic2,v1=this.a1*this.ic1+this.a2*v3,v2=this.ic2+this.a2*this.ic1+this.a3*v3;return this.ic1=2*v1-this.ic1,this.ic2=2*v2-this.ic2,this.type==="lpf"?v2:this.type==="hpf"?input-this.k*v1-v2:this.k*v1}},OnePole=class{coefficient=0;state=0;constructor(cutoff2,sampleRate){this.set(cutoff2,sampleRate)}set(cutoff2,sampleRate){this.coefficient=1-Math.exp(-2*Math.PI*clamp2(cutoff2,1,sampleRate*.49)/sampleRate)}process(input){return this.state+=this.coefficient*(input-this.state),this.state}};function hashUnit(value,seed=0){let state=(Math.floor(value)^Math.imul(seed,2654435761))>>>0;return state=Math.imul(state^state>>>16,2246822507)>>>0,state=Math.imul(state^state>>>13,3266489909)>>>0,((state^state>>>16)>>>0)/4294967296}function lfo(shape,phase,seed=0){let cycle=phase-Math.floor(phase);switch(shape){case"tri":return 1-4*Math.abs(cycle-.5);case"square":return cycle<.5?1:-1;case"saw":return 1-2*cycle;case"ramp":return 2*cycle-1;case"random":return hashUnit(phase,seed)*2-1;default:return Math.sin(2*Math.PI*phase)}}function lfoHz(sync2,rate2,tempoBpm){return sync2>0?tempoBpm/60/sync2:rate2}var Phasor=class{phase;increment=0;constructor(start){this.phase=start}setHz(hz3,sampleRate){this.increment=hz3/sampleRate}next(){let value=this.phase;return this.phase+=this.increment,value}};function readFractional(buffer,write,delay){let length=buffer.length,position=write-delay,base=Math.floor(position),fraction=position-base,a=buffer[(base%length+length)%length],b=buffer[((base+1)%length+length)%length];return a+(b-a)*fraction}function dbToGain(db2){return 10**(db2/20)}var ZZFX_SOUNDS=Object.freeze(["z_sine","z_triangle","z_sawtooth","z_square","z_tan","z_noise"]);function isZzfxSound(sound){return ZZFX_SOUNDS.includes(sound)}function wave(sound,phase,held){let p=phase-Math.floor(phase);switch(sound){case"z_triangle":return 1-4*Math.abs(p-.5);case"z_sawtooth":return 2*p-1;case"z_square":return p<.5?1:-1;case"z_tan":return clamp2(Math.tan(Math.PI*p),-1,1);case"z_noise":return held;default:return Math.sin(2*Math.PI*p)}}function renderZzfx(out,count2,params2){let{sampleRate,random:random2}=params2,base=params2.frequency*(1+params2.zrand*(random2()*2-1)),curve=Math.max(0,params2.curve),hold=Math.max(1,Math.round((1+params2.zcrush*99)*(sampleRate/44100))),phase=0,held=random2()*2-1,crushed=0,lastCycle=0;for(let index=0;index<count2;index+=1){let t=index/sampleRate,local=params2.lfo>0?t%params2.lfo:t,frequency=params2.slideOff?base:base+500*params2.slide*local+250*params2.deltaSlide*local*local;params2.pitchJumpTime>0&&local>=params2.pitchJumpTime&&(frequency+=params2.pitchJump),params2.zmod>0&&(frequency*=1+.5*Math.sin(2*Math.PI*params2.zmod*t)),params2.cents&&(frequency*=2**(params2.cents(t)/1200)),frequency=clamp2(frequency,0,sampleRate/2);let increment=frequency/sampleRate;params2.noise>0&&(increment*=1+params2.noise*(random2()*2-1)),phase+=increment;let cycle=Math.floor(phase*2);cycle!==lastCycle&&(lastCycle=cycle,held=random2()*2-1);let value=wave(params2.sound,phase,held);curve!==1&&(value=curve===0?Math.sign(value):Math.sign(value)*Math.abs(value)**curve),params2.tremolo>0&¶ms2.lfo>0&&(value*=1-params2.tremolo*(.5+.5*Math.sin(2*Math.PI*t/params2.lfo))),index%hold===0&&(crushed=value),out[index]=hold>1?crushed:value}if(params2.zdelay>0){let lag=Math.round(params2.zdelay*sampleRate);for(let index=count2-1;index>=lag;index-=1)out[index]=out[index]+.5*out[index-lag]}}var resolvers=[];function registerOscillatorResolver(resolver){resolvers.unshift(resolver)}function resolveOscillator(sound){let name=sound.trim().toLowerCase();for(let resolver of resolvers){let factory=resolver(name);if(factory)return factory}return BUILT_IN[name]}function polyBlep(t,dt){if(dt<=0)return 0;if(t<dt){let x=t/dt;return x+x-x*x-1}if(t>1-dt){let x=(t-1)/dt;return x*x+x+x+1}return 0}function frac(value){return value-Math.floor(value)}function sawtooth(phase,increment){let t=frac(phase);return 2*t-1-polyBlep(t,Math.abs(increment))}function pulse(phase,increment,width){let t=frac(phase),dt=Math.abs(increment),w=Math.min(.99,Math.max(.01,width)),value=t<w?1:-1;return value+=polyBlep(t,dt),value-=polyBlep(frac(t-w+1),dt),value-(2*w-1)}function triangle(phase){return 1-4*Math.abs(frac(phase)-.5)}function legacyWaveFor(instrument){let name=instrument.trim().toLowerCase();return name.includes("square")?phase=>phase-Math.floor(phase)<.5?1:-1:name.includes("saw")?phase=>2*(phase-Math.floor(phase))-1:name.includes("triangle")?phase=>1-4*Math.abs(phase-Math.floor(phase)-.5):name.includes("bass")?phase=>Math.tanh(.9*Math.sin(2*Math.PI*phase)+.25*Math.sin(4*Math.PI*phase)):name.includes("piano")||name.includes("pluck")?phase=>{let harmonic=Math.sin(4*Math.PI*phase)*.28+Math.sin(6*Math.PI*phase)*.12;return Math.tanh(Math.sin(2*Math.PI*phase)+harmonic)}:phase=>Math.sin(2*Math.PI*phase)}function harmonicSeries(sound,partials){let count2=partials?.length??1,out=[];for(let index=0;index<count2;index+=1){let h=index+1,user=partials?.[index]??1,base=1;sound==="sawtooth"||sound==="saw"||sound==="supersaw"?base=1/h:sound==="square"||sound==="pulse"?base=h%2===1?1/h:0:sound==="triangle"&&(base=h%2===1?(h-1)/2%2===0?1/(h*h):-1/(h*h):0),out.push(base*user)}return out}function additive(init){let amplitudes=harmonicSeries(init.sound,init.partials??[1]),phases2=init.phases??[],norm=Math.max(1,amplitudes.reduce((sum,value)=>sum+Math.abs(value),0)),count2=amplitudes.length;return(phase,increment)=>{let sum=0,limit=Math.abs(increment)>0?.5/Math.abs(increment):count2;for(let index=0;index<count2&&index+1<limit;index+=1){let a=amplitudes[index];a!==0&&(sum+=a*Math.sin(2*Math.PI*((index+1)*phase+(phases2[index]??0))))}return sum/norm}}function pinkNoise(random2){let b0=0,b1=0,b2=0,b3=0,b4=0,b5=0,b6=0;return()=>{let white=random2()*2-1;b0=.99886*b0+white*.0555179,b1=.99332*b1+white*.0750759,b2=.969*b2+white*.153852,b3=.8665*b3+white*.3104856,b4=.55*b4+white*.5329522,b5=-.7616*b5-white*.016898;let value=b0+b1+b2+b3+b4+b5+b6+white*.5362;return b6=white*.115926,value*.2}}function makePinkNoise(random2){return pinkNoise(random2)}var BUILT_IN=Object.freeze({sine:init=>init.partials?additive(init):phase=>Math.sin(2*Math.PI*phase),sawtooth:init=>init.partials?additive(init):sawtooth,saw:init=>init.partials?additive(init):sawtooth,supersaw:init=>init.partials?additive(init):sawtooth,square:init=>init.partials?additive(init):(phase,increment)=>pulse(phase,increment,.5),pulse:init=>(phase,increment)=>pulse(phase,increment,init.width()),triangle:init=>init.partials?additive(init):triangle,user:init=>additive(init),piano:()=>legacyWaveFor("piano"),pluck:()=>legacyWaveFor("pluck"),bass:()=>legacyWaveFor("bass"),white:init=>()=>(init.random()*2-1)*.6,pink:init=>pinkNoise(init.random),brown:init=>{let state=0;return()=>(state=(state+.02*(init.random()*2-1))/1.02,state*6.1)},crackle:init=>{let chance=Math.min(1,init.density*1e3/init.sampleRate);return()=>{let hit2=init.random()<chance,value=init.random()*2-1;return hit2?value:0}},z_sine:()=>phase=>Math.sin(2*Math.PI*phase),z_triangle:()=>triangle,z_sawtooth:()=>sawtooth,z_square:()=>(phase,increment)=>pulse(phase,increment,.5),z_tan:()=>phase=>Math.max(-1,Math.min(1,Math.tan(Math.PI*(phase-Math.floor(phase))))),z_noise:init=>()=>init.random()*2-1}),BUILT_IN_SOUNDS=Object.freeze(Object.keys(BUILT_IN));var VOICE_LEVEL=.28,NOISE_SOUNDS=new Set(["white","pink","brown","crackle"]);function canonicalSound(instrument){let name=instrument.trim().toLowerCase();return SOUND_ALIASES[name]??name}function usesSynthVoice(track2){if(!track2)return!1;if(track2.synth)return!0;let sound=canonicalSound(track2.instrument);return LEGACY_SOUNDS.includes(sound)?!1:resolveOscillator(sound)!==void 0}function controls(track2,tick){let synth=track2.synth??{},lanes=track2.fxAutomation,lane=name=>lanes?.[`synth-${name}`];return{has:name=>synth[name]!==void 0||(lane(name)?.length??0)>0,number:(name,fallback)=>{let stored=synth[name],base=typeof stored=="number"?stored:fallback??SYNTH_PARAMS[name].default,points=lane(name);return points&&points.length>0?interpolateAutomation(points,tick,base):base},text:name=>{let stored=synth[name];return typeof stored=="string"?stored:SYNTH_PARAMS[name].default},list:name=>{let stored=synth[name];return Array.isArray(stored)?stored:void 0},follow:name=>{let points=lane(name);if(!points||points.length===0)return;let stored=synth[name],base=typeof stored=="number"?stored:SYNTH_PARAMS[name].default;return at3=>interpolateAutomation(points,at3,base)}}}function attackDecay(t,a,d,s){if(t<a)return t/a;let u=t-a;return u<d?1-(1-s)*u/d:s}var Envelope=class{constructor(a,d,s,r,gate){this.a=a;this.d=d;this.s=s;this.r=r;this.gate=gate;this.gateLevel=attackDecay(gate,a,d,s)}a;d;s;r;gate;gateLevel;at(t){if(t<this.gate)return attackDecay(t,this.a,this.d,this.s);if(this.r<=0)return 0;let u=t-this.gate;return u>=this.r?0:this.gateLevel*(1-u/this.r)}};function envelopeFor(c,prefix,suffix,gate){return new Envelope(c.number(`${prefix}attack${suffix}`),c.number(`${prefix}decay${suffix}`),c.number(`${prefix}sustain${suffix}`),c.number(`${prefix}release${suffix}`),gate)}function synthTailSeconds(track2){if(!usesSynthVoice(track2))return 0;let stored=track2.synth?.release,tail=typeof stored=="number"?stored:SYNTH_PARAMS.release.default;for(let point of track2.fxAutomation?.["synth-release"]??[])tail=Math.max(tail,point.value);return tail}var FILTERS=[{prefix:"lp",type:"lpf",param:"lpf"},{prefix:"hp",type:"hpf",param:"hpf"},{prefix:"bp",type:"bpf",param:"bpf"}],BUTTERWORTH_Q1=.5412,BUTTERWORTH_Q2=1.3066,NoteFilter=class{constructor(type,slope,cutoff2,q3,depth,anchor,envelope2,sampleRate,cutoffAt,qAt){this.type=type;this.slope=slope;this.cutoff=cutoff2;this.q=q3;this.depth=depth;this.anchor=anchor;this.envelope=envelope2;this.sampleRate=sampleRate;this.cutoffAt=cutoffAt;this.qAt=qAt;this.svfFirst=new Svf(type),this.svfSecond=new Svf(type)}type;slope;cutoff;q;depth;anchor;envelope;sampleRate;cutoffAt;qAt;first=new Biquad;second=new Biquad;svfFirst;svfSecond;ladder=new Float64Array(4);ladderG=0;ladderK=0;get isSvf(){return this.depth<0}get isLadder(){return this.slope==="ladder"&&this.type==="lpf"}update(t){let e=this.depth===0?0:this.envelope.at(t),cutoff2=this.cutoffAt?this.cutoffAt(t):this.cutoff,frequency=clamp2(cutoff2*2**(this.depth*(e-this.anchor)),20,this.sampleRate*.45),q3=Math.max(.1,this.qAt?this.qAt(t):this.q);if(this.isLadder){this.ladderG=1-Math.exp(-2*Math.PI*frequency/this.sampleRate),this.ladderK=3.9*clamp2((q3-.707)/11.3,0,1);return}if(this.isSvf){this.slope==="24db"?(this.svfFirst.set(frequency,BUTTERWORTH_Q1,this.sampleRate),this.svfSecond.set(frequency,q3*BUTTERWORTH_Q2/.707,this.sampleRate)):this.svfFirst.set(frequency,q3,this.sampleRate);return}if(this.slope==="24db"){this.first.set(this.type,frequency,BUTTERWORTH_Q1,this.sampleRate),this.second.set(this.type,frequency,q3*BUTTERWORTH_Q2/.707,this.sampleRate);return}this.first.set(this.type,frequency,q3,this.sampleRate)}process(input){if(this.isLadder){let stages=this.ladder,g=this.ladderG,driven=Math.tanh(input-this.ladderK*stages[3]);return stages[0]+=g*(driven-stages[0]),stages[1]+=g*(stages[0]-stages[1]),stages[2]+=g*(stages[1]-stages[2]),stages[3]+=g*(stages[2]-stages[3]),stages[3]*(1+.5*this.ladderK)}if(this.isSvf){let once2=this.svfFirst.process(input);return this.slope==="24db"?this.svfSecond.process(once2):once2}let once=this.first.process(input);return this.slope==="24db"?this.second.process(once):once}};function noteFilters(c,gate,sampleRate,accent=!1,tickAt4){let out=[];for(let{prefix,type,param:param2}of FILTERS){let written=c.number(`${prefix}env`);if(!c.has(param2)&&written===0)continue;let boost=accent&&prefix==="lp"?c.number("faccent"):0,depth=written+boost,cutoff2=c.number(param2),q3=c.number(`${prefix}q`),slope=type==="lpf"?c.text("ftype"):"12db",anchor=c.number("fanchor"),cutoffLane=tickAt4?c.follow(param2):void 0,qLane=tickAt4?c.follow(`${prefix}q`):void 0,cutoffAt=cutoffLane&&tickAt4?t=>cutoffLane(tickAt4(t)):void 0,qAt=qLane&&tickAt4?t=>qLane(tickAt4(t)):void 0;out.push(()=>new NoteFilter(type,slope,cutoff2,q3,depth,anchor,boost>0?new Envelope(c.number(`${prefix}attack`),c.number(`${prefix}decay`)/2,c.number(`${prefix}sustain`),c.number(`${prefix}release`),gate):envelopeFor(c,prefix,"",gate),sampleRate,cutoffAt,qAt))}return out}function fmOperators(c,gate){let out=[];for(let op=1;op<=FM_OPERATORS;op+=1){let n2=op===1?"":String(op),index=c.number(`fm${n2}`);index<=0||out.push({index,ratio:c.number(`fmh${n2}`),envelope:envelopeFor(c,"fm",n2,gate),exp:c.text(`fmenv${n2}`)==="exp",wave:c.text(`fmwave${n2}`)})}return out}function modulatorWave(wave2,phase){let t=phase-Math.floor(phase);return wave2==="sawtooth"?2*t-1:wave2==="square"?t<.5?1:-1:wave2==="triangle"?1-4*Math.abs(t-.5):Math.sin(2*Math.PI*phase)}function renderSynthNote(left,right,note2,track2,start,length,context,gainAt){let{sampleRate,samples,samplesPerTick}=context,c=controls(track2,note2.startTick),tickAt4=t=>note2.startTick+t*sampleRate/samplesPerTick,sound=canonicalSound(track2.instrument),gate=length/sampleRate,release=Math.max(0,c.number("release")),end=Math.min(samples,start+length+Math.ceil(release*sampleRate));if(end<=start)return;let random2=seededRandom(`${note2.id}:${note2.startTick+(context.seedTick??0)}:synth`),amp=envelopeFor(c,"","",gate),velocity=clamp2(note2.velocity,0,1),gain=c.number("gain"),performance2=note2.performance,cents=performance2?.cents,damp=performance2?.damp,dampAt=t=>damp&&t>damp.from?Math.exp(-(t-damp.from)/damp.tau):1,base=noteHz(note2.pitch,note2.cents,context.tuning);if(!(base>0))return;if(isZzfxSound(sound)&&!context.oscillatorFor){let count2=end-start,raw=new Float64Array(count2);renderZzfx(raw,count2,{sound,sampleRate,frequency:base,zrand:c.number("zrand"),curve:c.number("curve"),slide:c.number("slide"),deltaSlide:c.number("deltaSlide"),pitchJump:c.number("pitchJump"),pitchJumpTime:c.number("pitchJumpTime"),lfo:c.number("lfo"),noise:c.number("noise"),zmod:c.number("zmod"),zcrush:c.number("zcrush"),zdelay:c.number("zdelay"),tremolo:c.number("tremolo"),random:random2,...cents?{cents}:{},...performance2?.replaceSlide?{slideOff:!0}:{}});let filters=noteFilters(c,gate,sampleRate,performance2?.accent===!0,tickAt4).map(make=>make());for(let elapsed=0;elapsed<count2;elapsed+=1){let t=elapsed/sampleRate;if(elapsed%32===0)for(let filter of filters)filter.update(t);let value=raw[elapsed];for(let filter of filters)value=filter.process(value);let level2=amp.at(t)*velocity*gain*VOICE_LEVEL*gainAt(note2.startTick+elapsed/samplesPerTick);damp&&(level2*=dampAt(t)),left[start+elapsed]+=value*level2,right&&(right[start+elapsed]+=value*level2)}return}let vib=performance2?.replaceVibrato?0:c.number("vib"),vibmod=c.number("vibmod"),penv=performance2?.replacePitchEnvelope?0:c.number("penv"),pitchEnv=penv===0?void 0:new Envelope(c.number("pattack"),c.number("pdecay"),c.number("psustain"),c.number("prelease"),gate),panchor=c.has("panchor")?c.number("panchor"):c.number("psustain"),pcurve=c.number("pcurve"),supersaw=sound==="supersaw",unison=Math.max(1,Math.round(c.has("unison")?c.number("unison"):supersaw?5:1)),detune=c.number("detune"),spread=right?c.number("spread"):0,voiceRatios=[],voicePans=[],phases2=[];for(let v=0;v<unison;v+=1){let position=unison===1?0:v/(unison-1)-.5;voiceRatios.push(2**(detune*position/12));let theta=(clamp2(spread*position*2,-1,1)+1)*Math.PI/4;voicePans.push([Math.cos(theta)*Math.SQRT2,Math.sin(theta)*Math.SQRT2]),phases2.push(unison===1&&!supersaw?0:random2())}let unisonGain=1/Math.sqrt(unison),factory=context.oscillatorFor?.(note2)??resolveOscillator(sound)??resolveOscillator("sine"),pw=c.number("pw"),pwrate=c.number("pwrate"),pwsweep=c.number("pwsweep"),width=pw,partials=c.list("partials"),phaseList=c.list("phases"),noteTime=0,oscillators=[];for(let v=0;v<unison;v+=1)oscillators.push(factory({sound,sampleRate,random:random2,...partials?{partials}:{},...phaseList?{phases:phaseList}:{},width:()=>width,density:c.number("density"),param:name=>track2.synth?.[name],time:()=>noteTime}));let noise2=NOISE_SOUNDS.has(sound)?0:c.number("noise"),pink=noise2>0?makePinkNoise(random2):void 0,fm=fmOperators(c,gate),fmPhases=fm.map(()=>new Float64Array(unison)),filterMakers=noteFilters(c,gate,sampleRate,performance2?.accent===!0,tickAt4),filtersL=filterMakers.map(make=>make()),filtersR=right?filterMakers.map(make=>make()):[];for(let index=start;index<end;index+=1){let elapsed=index-start,t=elapsed/sampleRate;if(noteTime=t,elapsed%32===0){for(let filter of filtersL)filter.update(t);for(let filter of filtersR)filter.update(t)}let semitones=0;if(vib>0&&(semitones+=vibmod*Math.sin(2*Math.PI*vib*t)),pitchEnv){let e=pitchEnv.at(t);pcurve>=1&&(e=e*e*e),semitones+=penv*(e-panchor)}cents&&(semitones+=cents(t)/100);let frequency=semitones===0?base:base*2**(semitones/12);pwsweep>0&&(width=clamp2(pw+pwsweep*.5*(1-4*Math.abs(pwrate*t%1-.5)),.01,.99));let sampleL=0,sampleR=0;for(let v=0;v<unison;v+=1){let increment=frequency*voiceRatios[v]/sampleRate,offset=0;for(let op=0;op<fm.length;op+=1){let operator=fm[op],modPhases=fmPhases[op],e=operator.envelope.at(t);operator.exp&&(e*=e),offset+=operator.index*e*modulatorWave(operator.wave,modPhases[v])/(2*Math.PI),modPhases[v]=modPhases[v]+increment*operator.ratio}let value=oscillators[v](phases2[v]+offset,increment);phases2[v]=phases2[v]+increment,right?(sampleL+=value*voicePans[v][0],sampleR+=value*voicePans[v][1]):sampleL+=value}if(sampleL*=unisonGain,sampleR*=unisonGain,pink){let n2=pink();sampleL=sampleL*(1-noise2)+n2*noise2,sampleR=sampleR*(1-noise2)+n2*noise2}for(let filter of filtersL)sampleL=filter.process(sampleL);for(let filter of filtersR)sampleR=filter.process(sampleR);let level2=amp.at(t)*velocity*gain*VOICE_LEVEL*gainAt(note2.startTick+elapsed/samplesPerTick);damp&&(level2*=dampAt(t)),left[index]+=sampleL*level2,right&&(right[index]+=sampleR*level2)}}function isStereoVoice(track2){if(!track2||!usesSynthVoice(track2))return!1;let c=controls(track2,0),sound=canonicalSound(track2.instrument),unison=c.has("unison")?c.number("unison"):sound==="supersaw"?5:1,lanes=track2.fxAutomation,laneMax=name=>Math.max(0,...(lanes?.[`synth-${name}`]??[]).map(p=>p.value)),spread=Math.max(c.number("spread"),laneMax("spread"));return Math.max(unison,laneMax("unison"))>1&&spread>0}function sampleWarpFor(score,sampleRate){let map=timeMapFor(score);if(!map)return;let grid2=new Float64Array(0),known=new Uint8Array(0),edge=block=>{if(block>=grid2.length){let size=Math.max(block+1,grid2.length*2,1024),nextGrid=new Float64Array(size),nextKnown=new Uint8Array(size);nextGrid.set(grid2),nextKnown.set(known),grid2=nextGrid,known=nextKnown}return known[block]===0&&(grid2[block]=map.tick(block*WARP_BLOCK/sampleRate),known[block]=1),grid2[block]};return Object.freeze({sample:tick=>map.seconds(tick)*sampleRate,tick:index=>{if(!(index>=0)||index>MAX_GRID_SAMPLES)return map.tick(index/sampleRate);let block=Math.floor(index/WARP_BLOCK),into=index-block*WARP_BLOCK,from=edge(block);return into===0?from:from+(edge(block+1)-from)*into/WARP_BLOCK},bpm:tick=>map.bpm(tick)})}var WARP_BLOCK=64,MAX_GRID_SAMPLES=2**29;function warpedSpan(warp2,startTick,durationTicks){let from=warp2.sample(startTick),to=warp2.sample(startTick+durationTicks);return{start:Math.max(0,Math.floor(from)),length:Math.max(1,Math.floor(to-from))}}function beatFitMap(warp2,timing,startTick,frames,perBeat){let{tempoBpm,ticksPerBeat,sampleRate}=timing;if(!warp2){let ratio2=perBeat/(sampleRate*60/tempoBpm);return Object.freeze({length:frames/ratio2,at:e=>e*ratio2,outAt:p=>p/ratio2})}let origin=warp2.sample(startTick),outAt=p=>warp2.sample(startTick+p/perBeat*ticksPerBeat)-origin;return Object.freeze({length:outAt(frames),at:e=>(warp2.tick(origin+e)-startTick)/ticksPerBeat*perBeat,outAt})}function spanFitMap(frames,held){let ratio2=frames/Math.max(1,held);return Object.freeze({length:held,at:e=>e*ratio2,outAt:p=>p/ratio2})}var CONTROL_FRAMES=32,MAX_GRAINS=64,MAX_OVERLAP=32,MAX_VOICES=16,STEAL_SECONDS=.005,CHUNK_MASK=4095,Grain=class{start=0;len=0;pos=0;step=0;gl=0;gr=0};function granularVoice(init){let{source,sr,seed}=init,lanes=init.lanes??[],p=lanes.length>0?{...init.settings}:init.settings,live2=p,data=source.data,srcRate=source.rate,n0=Math.max(1,data.length),begin=Math.max(0,Math.min(Math.floor(p.begin*n0),n0-1)),region=Math.max(begin+1,Math.min(Math.ceil(p.end*n0),n0))-begin,releaseFrames=Math.max(1,Math.round(p.release*sr)),attackFrames=Math.max(1,Math.round(p.attack*sr)),maxGrainFrames=Math.round(2*sr),tailFrames=releaseFrames+Math.round(Math.min(2,p.grain)*sr*1.5),total=init.gateFrames+tailFrames,spawnEnd=init.gateFrames+releaseFrames,win=grainWindow(p.window),table2=win.table,grainSec=Math.max(.005,Math.min(2,p.grain)),overlap=Math.max(.05,Math.min(MAX_OVERLAP,p.overlap)),period=grainSec*sr/overlap,len=Math.max(16,Math.min(maxGrainFrames,Math.round(grainSec*sr))),winGain=Math.min(1,1/Math.sqrt(Math.max(1e-9,overlap*win.meanSq))),frameStep=srcRate/sr,scanStep=p.freeze?0:p.scan*frameStep,grid2=init.grid,gridPeriod=init.gridPeriod??(at3=>grid2(at3+1)-grid2(at3));function shape(){grainSec=Math.max(.005,Math.min(2,p.grain)),grid2?(period=Math.max(1,gridPeriod(k)),overlap=Math.max(.05,grainSec*sr/period),overlap>MAX_OVERLAP&&(overlap=MAX_OVERLAP,grainSec=MAX_OVERLAP*period/sr)):(overlap=Math.max(.05,Math.min(MAX_OVERLAP,p.overlap)),period=grainSec*sr/overlap),len=Math.max(16,Math.min(maxGrainFrames,Math.round(grainSec*sr))),winGain=Math.min(1,1/Math.sqrt(Math.max(1e-9,overlap*win.meanSq)))}let grains=[],pool=[],t=0,scanned=0,k=0,nextGrid=grid2?grid2(0):0;grid2&&shape();let latch=0,latched=0,lp2=0,lpR=0,lpA=p.veltone>0?1-Math.exp(-2*Math.PI*Math.min(.45*sr,18e3*2**(-6*p.veltone*(1-init.velocity)))/sr):1,amp=init.velocity*p.gain,blockL=new Float64Array(CONTROL_FRAMES),blockR=new Float64Array(CONTROL_FRAMES);function driftAt(sec){let driftDepth=.5*p.drift*region;if(driftDepth===0)return 0;let x=sec*p.drate,i=Math.floor(x),f=x-i,a=2*unit3(seed,i,7)-1,b=2*unit3(seed,i+1,7)-1,s=.5-.5*Math.cos(Math.PI*f);return driftDepth*(a+(b-a)*s)}function spawn(){grid2&&shape();let sec=nextGrid/sr;latch>0?latch-=1:(latched=scanned,p.repeat>0&&unit3(seed,k,6)<p.repeat&&(latch=p.hold-1));let head=latched,onset=nextGrid+p.jitter*unit3(seed,k,0)*period,raw=p.pitch+p.detune*(unit3(seed,k,2)-.5)+(unit3(seed,k,5)<p.shimmer?p.shimint:0),semis=init.quant?init.quant(raw,nextGrid):raw,step0=init.baseRate*2**(semis/12)*frameStep,center=begin+p.pos*region+head+driftAt(sec)+p.spray*srcRate*(2*unit3(seed,k,1)-1);center=begin+((center-begin)%region+region)%region;let span4=step0*len,back=unit3(seed,k,4)<p.reverse,theta=(1+p.spread*(2*unit3(seed,k,3)-1))*Math.PI/4;if(grains.length<MAX_GRAINS){let g=pool.pop()??new Grain;g.start=Math.round(onset),g.len=len,g.pos=back?center+span4/2:center-span4/2,g.step=back?-step0:step0,g.gl=Math.cos(theta)*Math.SQRT2*winGain,g.gr=Math.sin(theta)*Math.SQRT2*winGain,grains.push(g)}k+=1,nextGrid=grid2?grid2(k):nextGrid+period}function envelope2(i){let a=i<attackFrames?i/attackFrames:1,e;if(i<init.gateFrames)e=a;else{let r=1-(i-init.gateFrames)/releaseFrames;e=r>0?a*r:0}let damp=init.damp;if(damp){let sec=i/sr;sec>damp.from&&(e*=Math.exp(-(sec-damp.from)/damp.tau))}return e}function renderGrains(from,n2,centsMul){blockL.fill(0,0,n2),blockR.fill(0,0,n2);let to=from+n2;for(let gi=grains.length-1;gi>=0;gi-=1){let g=grains[gi];if(g.start>=to)continue;let a=g.start>from?g.start:from,gEnd=g.start+g.len,b=gEnd<to?gEnd:to,step2=g.step*centsMul,level2=bankLevel(step2),pos=g.pos,ci=Math.floor(pos)>>12,chunk=bankChunk(source,level2,ci),wScale=WINDOW_TABLE/g.len,gl=g.gl,gr=g.gr;for(let i=a;i<b;i+=1){let ip=Math.floor(pos),c=ip>>12;c!==ci&&(ci=c,chunk=bankChunk(source,level2,ci));let o=(ip&CHUNK_MASK)+1,f=pos-ip,xm1=chunk[o-1],x0=chunk[o],x1=chunk[o+1],x2=chunk[o+2],c1=.5*(x1-xm1),c2=xm1-2.5*x0+2*x1-.5*x2,sample=(((.5*(x2-xm1)+1.5*(x0-x1))*f+c2)*f+c1)*f+x0,u=(i-g.start)*wScale,wi=Math.floor(u),w=table2[wi]+(table2[wi+1]-table2[wi])*(u-wi),s=sample*w,j=i-from;blockL[j]=blockL[j]+s*gl,blockR[j]=blockR[j]+s*gr,pos+=step2}if(g.pos=pos,gEnd<=to){let last=grains.pop();last!==g&&(grains[gi]=last),pool.push(g)}}}let pedalDown=!1;return{totalFrames:total,process(outL,outR,offset,frames){let done=0;for(;done<frames;){if(t>=total)return!1;let n2=Math.min(CONTROL_FRAMES-t%CONTROL_FRAMES,frames-done,total-t);if(init.held&&t%CONTROL_FRAMES===0&&(pedalDown=init.held(t)),lanes.length>0&&t%CONTROL_FRAMES===0){for(let lane of lanes)live2[lane.name]=lane.at(t);grid2||shape(),scanStep=p.freeze?0:p.scan*frameStep}for(;nextGrid<t+n2&&t<spawnEnd;)spawn();let cents=init.cents?init.cents(t/sr):0,centsMul=cents===0?1:2**(cents/1200);renderGrains(t,n2,centsMul),pedalDown||(scanned+=scanStep*n2);for(let i=0;i<n2;i+=1){let l=blockL[i],r=blockR[i];lpA<1&&(lp2+=lpA*(l-lp2),lpR+=lpA*(r-lpR),l=lp2,r=lpR);let e=envelope2(t+i)*amp,at3=offset+done+i;outL[at3]=outL[at3]+l*e,outR[at3]=outR[at3]+r*e}t+=n2,done+=n2}return t<total}}}var synthSources=new Map,MAX_SYNTH_SOURCES=16,LOOP_HOP_SECONDS=.01,LOOP_START_DB=-6,LOOP_END_DB=-30,LOOP_MAX_GAIN_DB=30,LOOP_FADE_SECONDS=.05;function synthSource(name,note2,sampleRate,synth){let preset5=SYNTH_PRESETS[name],params2=preset5?preset5.synth:synth,id=`synth:${name}@${note2}:${sampleRate}${!preset5&&synth?`:${JSON.stringify(synth)}`:""}`,cached=synthSources.get(id);if(cached)return cached;let frames=Math.round(SYNTH_SOURCE_SECONDS*sampleRate),track2={id:"granular-source",name:"granular source",instrument:preset5?preset5.instrument:name,muted:!1,volume:1,pan:0,...params2?{synth:params2}:{}},left=new Float64Array(frames),ticksPerBeat=480;renderSynthNote(left,void 0,{id:"granular-source",trackId:track2.id,startTick:0,durationTicks:ticksPerBeat*8,pitch:note2,velocity:1},track2,0,frames,{sampleRate,samples:frames,samplesPerTick:sampleRate*.5/ticksPerBeat,tempoBpm:120,ticksPerBeat},()=>1);let data=heldLoop(left,sampleRate),source=Object.freeze({id,rate:sampleRate,data});for(synthSources.set(id,source);synthSources.size>MAX_SYNTH_SOURCES;){let oldest=synthSources.keys().next().value;synthSources.delete(oldest)}return source}function heldLoop(render,sampleRate){let frames=render.length,hop=Math.max(1,Math.round(LOOP_HOP_SECONDS*sampleRate)),hops=Math.max(1,Math.floor(frames/hop)),rms=new Float64Array(hops),loudest=0;for(let h=0;h<hops;h+=1){let sum=0;for(let i=h*hop;i<(h+1)*hop;i+=1)sum+=render[i]*render[i];rms[h]=Math.sqrt(sum/hop),rms[h]>loudest&&(loudest=rms[h])}if(loudest===0)return new Float32Array(frames);let startLevel=loudest*10**(LOOP_START_DB/20),endLevel=loudest*10**(LOOP_END_DB/20),first=0;for(;first<hops-1&&rms[first]<startLevel;)first+=1;let last=hops-1;for(;last>first&&rms[last]<endLevel;)last-=1;let begin=first*hop,stop=Math.min(frames,(last+1)*hop),fade=Math.max(1,Math.min(Math.round(LOOP_FADE_SECONDS*sampleRate),Math.floor((stop-begin)/4))),loop=Math.max(1,stop-begin-fade),maxGain=10**(LOOP_MAX_GAIN_DB/20),levelled=new Float64Array(loop+fade);for(let i=0;i<loop+fade;i+=1){let frame=begin+i,x=frame/hop-.5,h0=Math.max(0,Math.min(hops-1,Math.floor(x))),h1=Math.min(hops-1,h0+1),f=Math.max(0,Math.min(1,x-h0)),env=rms[h0]+(rms[h1]-rms[h0])*f,gain=env>0?Math.min(maxGain,loudest/env):maxGain;levelled[i]=(render[frame]??0)*gain}let seamless=new Float64Array(loop);for(let i=0;i<loop;i+=1)seamless[i]=levelled[i];for(let i=0;i<fade&&i<loop;i+=1){let u=(i+.5)/fade;seamless[i]=levelled[i]*Math.sin(u*Math.PI/2)+levelled[loop+i]*Math.cos(u*Math.PI/2)}let copies=Math.max(1,Math.ceil(frames/loop)),out=new Float32Array(loop*copies),peak=0;for(let i=0;i<loop;i+=1)peak=Math.max(peak,Math.abs(seamless[i]));let g=peak>0?.7/peak:0;for(let c=0;c<copies;c+=1)for(let i=0;i<loop;i+=1)out[c*loop+i]=seamless[i]*g;return out}function granularSampleKey(trackId){return`${trackId}\0${GRANULAR_SOURCE_VOICE}`}function granularSource(track2,sampleRate,bank){let src=resolveGranular(track2.granular).src,stored=track2.granular?.root;if(typeof src=="string"){let parsed=parseSynthSource(src)??parseSynthSource(DEFAULT_GRANULAR_SOURCE);return{source:synthSource(parsed.name,parsed.note,sampleRate,track2.synth),root:stored??parsed.note}}let decoded=bank.voices.get(granularSampleKey(track2.id));if(!decoded||decoded.frames===0)return;let ref=src;return{source:{id:decoded.sha256,rate:decoded.sampleRate,data:decoded.mono},root:stored??ref.root??60}}function granularSeeds(notes,seed,trackId){let seen=new Map;return notes.map(note2=>{let at3=`${note2.pitch}:${note2.startTick}`,occurrence=seen.get(at3)??0;return seen.set(at3,occurrence+1),seedHash(`${seed}:${trackId}:${at3}:${occurrence}`)})}function spanOf(note2,context){if(context.warp)return warpedSpan(context.warp,note2.startTick,note2.durationTicks);let{tempoBpm,sampleRate}=context,tpb=context.ticksPerBeat;return{start:Math.max(0,Math.floor(note2.startTick/tpb*60/tempoBpm*sampleRate)),length:Math.max(1,Math.floor(note2.durationTicks/tpb*60/tempoBpm*sampleRate))}}function renderGranularTrack(left,right,notes,track2,context,bank){let resolved=granularSource(track2,context.sampleRate,bank);if(!resolved)return;let settings=resolveGranular(track2.granular),sr=context.sampleRate,seeds=granularSeeds(notes,settings.seed,track2.id),rootHz=noteHz(resolved.root,void 0,context.tuning),tail=Math.round(granularTailSeconds(track2.granular)*sr),plans2=notes.map((note2,index)=>{let{start,length}=spanOf(note2,context);return{note:note2,seed:seeds[index],start,length,end:start+length+tail,cut:1/0}}),chains=new Map;if(settings.mono&&plans2.length>1){let sorted=[...plans2].sort((a,b)=>a.start-b.start),heads=[],head;for(let plan2 of sorted){if(head&&plan2.start<head.start+head.length){chains.get(head).push(plan2),head.length=Math.max(head.length,plan2.start+plan2.length-head.start),head.end=head.start+head.length+tail;continue}head&&head.end>plan2.start&&(head.cut=plan2.start),head=plan2,chains.set(plan2,[plan2]),heads.push(plan2)}plans2=heads}let order=plans2.map((_,index)=>index).sort((a,b)=>plans2[a].start-plans2[b].start||a-b),active=[];for(let index of order){let plan2=plans2[index];for(let i=active.length-1;i>=0;i-=1)Math.min(active[i].end,active[i].cut)<=plan2.start&&active.splice(i,1);if(active.length>=MAX_VOICES){let at3=active.findIndex(candidate=>candidate.start+candidate.length<=plan2.start);at3<0&&(at3=0);let victim=active.splice(at3,1)[0];victim.cut=plan2.start}active.push(plan2)}let stealFrames=Math.max(1,Math.round(STEAL_SECONDS*sr)),block=4096,outL=new Float64Array(block),outR=new Float64Array(block),volume=Math.max(0,Math.min(1,track2.volume??1)),lane=track2.volumeAutomation??[],tickOf=frame=>context.warp?context.warp.tick(frame):frame/Math.max(1e-9,context.samplesPerTick),frameOf2=tick=>context.warp?context.warp.sample(tick):tick*context.samplesPerTick,grainLanes=GRANULAR_LANE_PARAMS.flatMap(({param:param2})=>{let points=track2.fxAutomation?.[`grain-${param2}`];return points&&points.length>0?[{param:param2,points}]:[]}),syncBeats=settings.sync==="off"?void 0:GRAIN_SYNC_BEATS[settings.sync],allowed=settings.quant==="off"?void 0:quantPitchClasses(context.score,settings.quant,context.quantChord),pedal=settings.pedal?track2.pedal:void 0;for(let plan2 of plans2){let{note:note2}=plan2;if(plan2.start>=left.length)continue;let hz3=noteHz(note2.pitch,note2.cents,context.tuning),performance2=note2.performance,chain=chains.get(plan2),startTick=note2.startTick,startFrame=plan2.start,cents=performance2?.cents;if(chain&&chain.length>1){let steps2=chain.map(item=>({from:(item.start-startFrame)/sr,cents:1200*Math.log2(noteHz(item.note.pitch,item.note.cents,context.tuning)/hz3),perf:item.note.performance?.cents,offset:(item.start-startFrame)/sr}));cents=t=>{let at3=0;for(;at3+1<steps2.length&&steps2[at3+1].from<=t;)at3+=1;let step2=steps2[at3];return step2.cents+(step2.perf?step2.perf(t-step2.offset):0)}}let lanes=grainLanes.map(({param:param2,points})=>{let fallback=settings[param2];return{name:param2,at:frame=>interpolateAutomation(points,tickOf(startFrame+frame),fallback)}}),grid2,gridPeriod;if(syncBeats!==void 0){let stepTicks=syncBeats*context.ticksPerBeat,at3=startTick/stepTicks,k0=Math.round(at3);if(Math.abs(at3-k0)<1e-9)grid2=k=>frameOf2((k0+k)*stepTicks)-startFrame;else{let first=Math.floor(at3)+1,point=k=>frameOf2((first+k)*stepTicks)-startFrame;grid2=k=>k===0?0:point(k-1),gridPeriod=k=>k===0?point(1)-point(0):point(k)-point(k-1)}}let quant=allowed?(semis,frame)=>snapSemis(note2.pitch,semis,allowed(tickOf(startFrame+frame))):void 0,held=pedal&&pedal.length>0?frame=>pedalStateAt(pedal,tickOf(startFrame+frame))==="down":void 0,voice=granularVoice({source:resolved.source,sr,settings,baseRate:hz3/rootHz,velocity:Math.max(0,Math.min(1,note2.velocity)),gateFrames:plan2.length,...cents?{cents}:{},...performance2?.damp?{damp:performance2.damp}:{},seed:plan2.seed,...lanes.length>0?{lanes}:{},...grid2?{grid:grid2}:{},...gridPeriod?{gridPeriod}:{},...quant?{quant}:{},...held?{held}:{}}),stop=Math.min(left.length,plan2.start+voice.totalFrames,plan2.cut===1/0?1/0:plan2.cut+stealFrames);for(let at3=plan2.start;at3<stop;at3+=block){let n2=Math.min(block,stop-at3);outL.fill(0,0,n2),outR.fill(0,0,n2);let alive=voice.process(outL,outR,0,n2);for(let i=0;i<n2;i+=1){let frame=at3+i,tick=context.warp?context.warp.tick(frame):note2.startTick+(frame-plan2.start)/Math.max(1e-9,context.samplesPerTick),g=volume*(lane.length>0?interpolateAutomation(lane,tick,1):1);frame>=plan2.cut&&(g*=Math.max(0,1-(frame-plan2.cut)/stealFrames)),left[frame]=left[frame]+outL[i]*g,right[frame]=right[frame]+outR[i]*g}if(!alive)break}}}function harmonicTrack(track2){if(track2.muted===!0||track2.granular!==void 0||track2.instrument==="kit"||track2.kit!==void 0)return!1;if(track2.sampler||track2.instrument==="sampler"){let sampler=track2.sampler;if(!sampler||sampler.mode!=="keyed"||Object.values(sampler.voices).some(ref=>ref.from!==void 0))return!1}return!0}var timelines=new WeakMap;function chordTimeline(score){let known=timelines.get(score);if(known)return known;let harmonic=new Set(score.tracks.filter(harmonicTrack).map(track2=>track2.id)),events=new Map,add=(tick,pc,delta)=>{let row2=events.get(tick);row2||events.set(tick,row2=new Array(12).fill(0)),row2[pc]=row2[pc]+delta};for(let note2 of score.notes){if(!harmonic.has(note2.trackId)||note2.durationTicks<=0)continue;let pc=(note2.pitch%12+12)%12;add(note2.startTick,pc,1),add(note2.startTick+note2.durationTicks,pc,-1)}let counts2=new Array(12).fill(0),ticks=[],sets=[];for(let tick of[...events.keys()].sort((a,b)=>a-b)){let row2=events.get(tick);for(let pc=0;pc<12;pc+=1)counts2[pc]=counts2[pc]+row2[pc];ticks.push(tick),sets.push(counts2.flatMap((count2,pc)=>count2>0?[pc]:[]))}let timeline=Object.freeze({ticks,sets});return timelines.set(score,timeline),timeline}function chordAt(timeline,tick){let{ticks,sets}=timeline,lo=0,hi=ticks.length-1,found=-1;for(;lo<=hi;){let mid=lo+hi>>1;ticks[mid]<=tick?(found=mid,lo=mid+1):hi=mid-1}return found<0?[]:sets[found]}function chordDigest(timeline,from=-1/0,to=1/0){let parts=[chordAt(timeline,from).join(".")];for(let i=0;i<timeline.ticks.length;i+=1){let tick=timeline.ticks[i];tick>from&&tick<to&&parts.push(`${Number.isFinite(from)?tick-from:tick}:${timeline.sets[i].join(".")}`)}return`chord:${parts.join(",")}`}function quantPitchClasses(score,mode,source){let key=parseKey2(score.key??void 0),scale3=key?scaleOf2(key):[0,1,2,3,4,5,6,7,8,9,10,11];if(mode==="scale")return()=>scale3;let timeline=chordTimeline(source?.score??score),offset=source?.tick??0;return tick=>{let set=chordAt(timeline,tick+offset);return set.length>0?set:scale3}}function snapSemis(pitch2,semis,classes){let target=pitch2+semis,base=Math.round(target),best=base,bestDistance=1/0;for(let d=0;d<=6;d+=1)for(let candidate of d===0?[base]:[base-d,base+d]){if(!classes.includes((candidate%12+12)%12))continue;let distance=Math.abs(candidate-target);distance<bestDistance&&(best=candidate,bestDistance=distance)}return best-pitch2}var GRANULAR_ENGINE=Object.freeze({id:"granular",field:"granular",render(dry,dryR,notes,track2,context,bank){let right=dryR??new Float64Array(dry.length);if(renderGranularTrack(dry,right,notes,track2,context,bank),!dryR)for(let i=0;i<dry.length;i+=1)dry[i]=.5*(dry[i]+right[i])},tailSeconds:track2=>granularTailSeconds(track2.granular),stereo:()=>!0,assetDigests(track2,bank,score){let src=track2.granular?.src,digests=[];if(src!==void 0&&typeof src!="string"){let decoded=bank.voices.get(granularSampleKey(track2.id));digests.push(decoded?decoded.sha256:"missing")}return score&&resolveGranular(track2.granular).quant==="chord"&&digests.push(chordDigest(chordTimeline(score))),digests}});var AUTOTUNE_CACHE_BYTES=128*1024*1024,LIVE_SYNC_AUTOTUNE_SECONDS=.25,AUTOTUNE_SPAN_MARGIN_SECONDS=.05,engine=builtinPitchEngine;var cache3=new Map,cachedBytes2=0,counters={hits:0,misses:0,tuned:0};function bytesOf(audio){return audio.mono.byteLength+(audio.left?.byteLength??0)+(audio.right?.byteLength??0)}function remember3(key,out){let size=bytesOf(out);if(size>AUTOTUNE_CACHE_BYTES)return;let old=cache3.get(key);old&&(cache3.delete(key),cachedBytes2-=bytesOf(old)),cache3.set(key,out),cachedBytes2+=size;for(let[stale,audio]of cache3){if(cachedBytes2<=AUTOTUNE_CACHE_BYTES)break;cache3.delete(stale),cachedBytes2-=bytesOf(audio)}}var bufferIds=new WeakMap,bufferSerial=0;function bufferId(buffer){if(buffer.id)return`id:${buffer.id}`;if(buffer.sha256)return`${buffer.sha256}:${buffer.mono.length}`;let id=bufferIds.get(buffer.mono);return id===void 0&&bufferIds.set(buffer.mono,id=`buf#${bufferSerial+=1}`),id}function fnv(text2){let h=2166136261;for(let i=0;i<text2.length;i+=1)h=Math.imul(h^text2.charCodeAt(i),16777619)>>>0;return h.toString(16).padStart(8,"0")}function guideTrack(score,track2,r){return r.from===void 0?track2:score.tracks.find(other=>other.id===r.from)}function guideNotes(score,guide){let table2=resolveTuning(score.tuning,guide.tuning,score.key),out=[];for(let note2 of score.notes){if(note2.trackId!==guide.id||note2.durationTicks<=0)continue;let start=secondsAtTick(score,note2.startTick),end=secondsAtTick(score,note2.startTick+note2.durationTicks);out.push({start,end,cents:centsOfHz(noteHz(note2.pitch,note2.cents,table2)),...note2.drift!==void 0?{drift:note2.drift}:{},...note2.articulation==="ghost"?{ghost:!0}:{},...note2.glide!==void 0?{glide:note2.glide}:{},...note2.vibrato?{vib:note2.vibrato.rate,vibmod:note2.vibrato.depth/100,...note2.vibrato.delay?{vibDelay:note2.vibrato.delay}:{}}:{}})}return out.sort((a,b)=>a.start-b.start||a.cents-b.cents)}function guideDigest(notes){return`guide:${notes.length}:${fnv(notes.map(n2=>`${n2.start.toFixed(6)}-${n2.end.toFixed(6)}@${n2.cents.toFixed(3)}${n2.drift!==void 0?`d${n2.drift}`:""}${n2.ghost?"g":""}${n2.glide!==void 0?`l${n2.glide}`:""}${n2.vib!==void 0?`v${n2.vib}/${n2.vibmod}/${n2.vibDelay??0}`:""}`).join(","))}`}function tableDigest(table2){return table2?`tun:${fnv(Array.from(table2.hz,hz3=>hz3.toFixed(6)).join(","))}`:"12tet"}function autotuneKeyTuning(score,track2){let keyText=track2.autotune?.key;if(!keyText||score.tuning||track2.tuning)return;let scale3=parseKey2(keyText)?.scale;return scale3&&tuningPreset(scale3)?scale3:void 0}function tableFor(score,track2,r){let preset5=autotuneKeyTuning(score,track2);return preset5?resolveTuning({name:preset5},void 0,r.key):resolveTuning(score.tuning,track2.tuning,score.key)}function chordSource(score,track2,r){let excluded=new Set([track2.id]);r.from!==void 0&&excluded.add(r.from);for(let other of score.tracks)(other.instrument==="vocal"||other.autotune)&&excluded.add(other.id);return{score:score.withTracks(score.tracks.map(other=>excluded.has(other.id)?{...other,muted:!0}:other)),excluded:[...excluded].sort()}}var plans=new WeakMap;function plan(score,track2,r){let known=plans.get(score);known||plans.set(score,known=new Map);let memo=`${track2.id}|${autotuneDigest(r)}|${JSON.stringify(track2.tuning??null)}`,hit2=known.get(memo);if(hit2)return hit2;let made=buildPlan(score,track2,r);return known.set(memo,made),made}function buildPlan(score,track2,r){let table2=tableFor(score,track2,r);if(r.to==="chromatic")return{kind:"static",digest:`chromatic:${tableDigest(table2)}`,targets:{kind:"grid",grid:chromaticGrid(table2)}};if(r.to==="scale"){let keyText=r.key??score.key;return{kind:"static",digest:`scale:${keyText??""}:${tableDigest(table2)}`,targets:{kind:"grid",grid:scaleGrid(keyText,table2)}}}if(r.to==="chord"){let source=chordSource(score,track2,r),timeline=chordTimeline(source.score),fallback=scaleGrid(r.key??score.key,table2),grids2=new Map;return{kind:"timed",digest:`chord:${fnv(`${source.excluded.join(",")}|${chordDigest(timeline)}`)}:${r.key??score.key??""}:${tableDigest(table2)}`,build:p=>({kind:"grid",grid:seconds2=>{let song3=p.start+(seconds2-p.offset)/p.rate,classes=chordAt(timeline,tickAtSeconds(score,song3));if(classes.length===0)return fallback;let id=classes.join("."),grid2=grids2.get(id);return grid2||grids2.set(id,grid2=classGrid(classes,table2)),grid2}})}}let guide=guideTrack(score,track2,r),notes=guide?guideNotes(score,guide):[];return{kind:"timed",digest:guideDigest(notes),build:p=>{let out=[];for(let n2 of notes)out.push({...n2,start:p.offset+(n2.start-p.start)*p.rate,end:p.offset+(n2.end-p.start)*p.rate});return{kind:"notes",notes:out}}}}function autotuneStemDigests(track2,score){if(!track2.autotune)return[];let r=resolveAutotune(track2.autotune);return[`autotune:${engine?.version??"none"}`,plan(score,track2,r).digest]}function atRate(curve,rate2){if(rate2===1)return curve;let f0=new Float32Array(curve.f0.length);for(let f=0;f<f0.length;f+=1){let hz3=curve.f0[f];f0[f]=hz3>0?hz3*rate2:0}return{...curve,f0}}function sliceCurve(curve,from,to){let n2=curve.f0.length,a=Math.max(0,Math.floor((from-curve.t0)/curve.hop)-1),b=Math.min(n2,Math.ceil((to-curve.t0)/curve.hop)+2);if(a===0&&b===n2&&from===0)return curve;let take=x=>Array.prototype.slice.call(x,a,Math.max(a,b));return{t0:curve.t0+a*curve.hop-from,hop:curve.hop,f0:Float32Array.from(take(curve.f0)),prob:Uint8Array.from(take(curve.prob)),aperiodic:Uint8Array.from(take(curve.aperiodic))}}function untuned(buffer){return{mono:buffer.mono,...buffer.left?{left:buffer.left}:{},...buffer.right?{right:buffer.right}:{},from:0}}function autotuneSpan(score,track2,buffer,placement,extraKey="",span4){let settings=track2.autotune,pitch2=engine;if(!settings||!pitch2)return untuned(buffer);let r=resolveAutotune(settings),targetPlan=plan(score,track2,r),timed=targetPlan.kind==="timed",sr=buffer.sampleRate,length=buffer.mono.length,margin=Math.round(AUTOTUNE_SPAN_MARGIN_SECONDS*sr),from=timed&&span4?Math.max(0,Math.floor(span4.from)-margin):0,to=timed&&span4?Math.min(length,Math.ceil(span4.to)+margin):length;if(to<=from)return untuned(buffer);let key=["at",bufferId(buffer),sr,buffer.left&&buffer.right?"st":"mo",placement.rate.toFixed(9),timed?`${placement.start.toFixed(6)}:${placement.offset.toFixed(6)}:${from}-${to}`:"",pitch2.version,autotuneDigest(r),targetPlan.digest,extraKey].join("|"),hit2=cache3.get(key);if(hit2)return cache3.delete(key),cache3.set(key,hit2),counters.hits+=1,hit2;counters.misses+=1;let live2=liveFitActive(),whole=pitch2.curve(buffer,r.voice,live2?{defer:!0}:{});if(!whole)return untuned(buffer);let curve=atRate(sliceCurve(whole,from/sr,to/sr),placement.rate),local={...placement,offset:placement.offset-from/sr},targets=timed?targetPlan.build(local):targetPlan.targets,cut=x=>from===0&&to===length?x:x.subarray(from,to),job=function*(){counters.tuned+=1;let run=x=>autotuneJob(cut(x),sr,curve,targets,r,pitch2.psola,12,pitch2.psolaJob),source=cut(buffer.mono),mono=yield*autotuneJob(source,sr,curve,targets,r,pitch2.psola,12,pitch2.psolaJob);if(mono===source)return untuned(buffer);let left=buffer.left?yield*run(buffer.left):void 0,right=buffer.right?yield*run(buffer.right):void 0;return{mono,...left&&right?{left,right}:{},from}};if(live2&&to-from>LIVE_SYNC_AUTOTUNE_SECONDS*sr)return deferLiveJob(key,job,out=>remember3(key,out)),untuned(buffer);let steps2=job();for(;;){let step2=steps2.next();if(step2.done)return remember3(key,step2.value),step2.value}}function autotuneVoice(score,track2,buffer,startSeconds,regionStart,rate2,span4){return autotuneSpan(score,track2,buffer,{start:startSeconds,offset:regionStart/buffer.sampleRate,rate:rate2},"",span4)}function autotuneClipDigest(offsetSeconds,latencySeconds=0,nudgeSeconds=0){return`o${offsetSeconds.toFixed(6)}l${latencySeconds.toFixed(6)}n${nudgeSeconds.toFixed(6)}`}function autotuneClip(score,track2,buffer,startSeconds,offsetSeconds,clipKey="",latencySeconds=0,nudgeSeconds=0){return autotuneSpan(score,track2,buffer,{start:startSeconds,offset:offsetSeconds,rate:1},`clip:${clipKey}:${autotuneClipDigest(offsetSeconds,latencySeconds,nudgeSeconds)}`)}var BUNDLED_VOCALS=[];var BUNDLED_SAMPLE_BASE="https://dawg.sh/bundled/studio-v1/",phraseSlices=(a,b)=>[a,b,a,b].map((name,i)=>Object.freeze({name,begin:i/4,end:(i+1)/4})),BUNDLED_SAMPLES=Object.freeze([{id:"hold-on",title:"Hold On",description:"Original alto machine-voice phrase; four clean syllables for garage chops.",tags:["vocal","phrase","garage","chop"],root:60,seconds:2,bpm:120,sha256:"2ba6611084af627e05e375ef5d35e3947a004969d04202b4c0bf7814d85184d1",slices:phraseSlices("hold","on")},{id:"stay-up",title:"Stay Up",description:"Original tenor machine-voice phrase; tight consonants for pop and electro.",tags:["vocal","phrase","pop","electro","chop"],root:60,seconds:2,bpm:120,sha256:"86e53719fdc7a28ab1f4062fd6160be51c067a64226f5ad3576f65ea08ec3d80",slices:phraseSlices("stay","up")},{id:"vowel-ah",title:"Ah",description:"Dry C4 alto vowel for playable chords, pads and reverse swells.",tags:["vocal","vowel","pad","chord"],root:60,seconds:1,sha256:"fc2203d1b567348baee1aeafad74e0c980a5bb3a730ad21ced80572399c024eb",slices:[]},{id:"vowel-oh",title:"Oh",description:"Dry C4 tenor vowel; a rounded counterpoint to the bright Ah.",tags:["vocal","vowel","pad","chord"],root:60,seconds:1,sha256:"c98b8f9b8683d8eab3f1420e88ee6e7aef01fa0bdf7564f5d09ddc9c724980e8",slices:[]},{id:"glass-hit",title:"Glass",description:"C6 tuned glass strike with a bright inharmonic ring.",tags:["percussion","glass","bell","bright"],root:84,seconds:.8,sha256:"d9b0785e8172cba4e6fa5e57320a70392e6c1a9db8f3737d087704a86812086b",slices:[]},{id:"metal-hit",title:"Metal",description:"C5 struck metal; short, woody attack and irregular partials.",tags:["percussion","metal","industrial"],root:72,seconds:.8,sha256:"d6a80299a60b764d538e041c4c7ff3c6d11237182336217d28cf27202145a454",slices:[]},{id:"tape-hit",title:"Tape",description:"Saturated low thump and hiss for fills and transition punctuation.",tags:["percussion","texture","lofi","thump"],root:60,seconds:.45,sha256:"7abfa46ffbd43ee40bba87a8bfe59db2eceb15b0e78e57c05600c1452399645f",slices:[]},{id:"riser",title:"Rise",description:"Two-second noise and sine sweep; reverse for a downlifter.",tags:["fx","transition","noise","riser"],root:60,seconds:2,sha256:"5a57894a109dc4fd117cee9acd9ea15c48a61fcfd27a9ba262e852ef9cff2108",slices:[]},...BUNDLED_VOCALS].map(sample=>Object.freeze({...sample,tags:Object.freeze(sample.tags),slices:Object.freeze(sample.slices)})));var CRC8=new Uint8Array(256),CRC16=new Uint16Array(256);for(let i=0;i<256;i+=1){let c8=i,c16=i<<8;for(let bit=0;bit<8;bit+=1)c8=c8&128?(c8<<1^7)&255:c8<<1&255,c16=c16&32768?(c16<<1^32773)&65535:c16<<1&65535;CRC8[i]=c8,CRC16[i]=c16}var PACK_LIMITS=Object.freeze({maxManifestBytes:8*1024*1024,maxSounds:2e4,maxFilesPerSound:1024,maxFileNameLength:512,fetchTimeoutMs:3e4,maxRedirects:4,maxZones:SCORE_LIMITS.maxSamplerVoices}),NO_LICENSE="none stated",GITHUB=/^github:([A-Za-z0-9_.-]{1,100})\/([A-Za-z0-9_.-]{1,100})(?:\/([A-Za-z0-9_./-]{1,200}))?\/?$/,DOUGH="https://raw.githubusercontent.com/felixroos/dough-samples/main",BANK_ALIASES_URL="https://strudel.b-cdn.net/tidal-drum-machines-alias.json",STRUDEL_BANK_ALIASES=Object.freeze({AJKPercusyn:"Percysyn",AkaiLinn:"Linn",AkaiMPC60:"MPC60",AkaiXR10:"XR10",AlesisHR16:"HR16",AlesisSR16:"SR16",BossDR110:"DR110",BossDR220:"DR220",BossDR55:"DR55",BossDR550:"DR550",CasioRZ1:"RZ1",CasioSK1:"SK1",CasioVL1:"VL1",DoepferMS404:"MS404",EmuDrumulator:"Drumulator",EmuSP12:"SP12",KorgDDM110:"DDM110",KorgKPR77:"KPR77",KorgKR55:"KR55",KorgKRZ:"KRZ",KorgM1:"M1",KorgMinipops:"Minipops",KorgPoly800:"Poly800",KorgT3:"T3",Linn9000:"9000",LinnLM1:"LM1",LinnLM2:"LM2",MoogConcertMateMG1:"ConcertMateMG1",OberheimDMX:"DMX",RhodesPolaris:"Polaris",RhythmAce:"Ace",RolandCompurhythm1000:"Compurhythm1000",RolandCompurhythm78:"Compurhythm78",RolandCompurhythm8000:"Compurhythm8000",RolandD110:"D110",RolandD70:"D70",RolandDDR30:"DDR30",RolandJD990:"JD990",RolandMC202:"MC202",RolandMC303:"MC303",RolandMT32:"MT32",RolandR8:"R8",RolandS50:"S50",RolandSH09:"SH09",RolandSystem100:"System100",RolandTR505:"TR505",RolandTR606:"TR606",RolandTR626:"TR626",RolandTR707:"TR707",RolandTR727:"TR727",RolandTR808:"TR808",RolandTR909:"TR909",SakataDPM48:"DPM48",SequentialCircuitsDrumtracks:"CircuitsDrumtracks",SequentialCircuitsTom:"CircuitsTom",SimmonsSDS400:"SDS400",SimmonsSDS5:"SDS5",SoundmastersR88:"R88",UnivoxMicroRhythmer12:"MicroRhythmer12",ViscoSpaceDrum:"SpaceDrum",XdrumLM8953:"LM8953",YamahaRM50:"RM50",YamahaRX21:"RX21",YamahaRX5:"RX5",YamahaRY30:"RY30",YamahaTG33:"TG33"});var PACK_CATALOG=Object.freeze([{name:"studio",title:"Studio \xB7 original offline vocals, hits and transitions",source:`${BUNDLED_SAMPLE_BASE}manifest.json`,license:"CC0-1.0",kind:"strudel"},{name:"tidal-drum-machines",title:"Tidal drum machines (TR-808, TR-909, LinnDrum, \u2026)",source:`${DOUGH}/tidal-drum-machines.json`,license:NO_LICENSE,homepage:"https://github.com/ritchse/tidal-drum-machines",kind:"strudel",aliasesUrl:BANK_ALIASES_URL},{name:"dirt-samples",title:"TidalCycles Dirt-Samples",source:"github:tidalcycles/dirt-samples",license:NO_LICENSE,homepage:"https://github.com/tidalcycles/Dirt-Samples",kind:"strudel"},{name:"uzu-drumkit",title:"uzu drumkit",source:"github:tidalcycles/uzu-drumkit",license:"Unlicense",homepage:"https://github.com/tidalcycles/uzu-drumkit",kind:"strudel"},{name:"uzu-wavetables",title:"uzu wavetables (Strudel's wt_ tables)",source:"github:tidalcycles/uzu-wavetables",license:"Unlicense",homepage:"https://github.com/tidalcycles/uzu-wavetables",kind:"strudel"},{name:"vcsl",title:"Versilian Community Sample Library",source:`${DOUGH}/vcsl.json`,license:"CC0-1.0",homepage:"https://github.com/sgossner/VCSL",kind:"strudel"},{name:"piano",title:"Salamander Grand Piano",source:`${DOUGH}/piano.json`,license:"CC-BY-3.0",attribution:"Salamander Grand Piano V3 by Alexander Holm (CC BY 3.0, https://creativecommons.org/licenses/by/3.0/)",homepage:"https://archive.org/details/SalamanderGrandPianoV3",kind:"strudel"},{name:"mridangam",title:"Mridangam",source:`${DOUGH}/mridangam.json`,license:"CC-BY-SA-4.0",attribution:"Mridangam samples (c) Arthur Carabott 2022, performer Harishankar V Menon (CC BY-SA 4.0, https://creativecommons.org/licenses/by-sa/4.0/)",homepage:"https://github.com/felixroos/dough-samples",kind:"strudel"},{name:"emu-sp12",title:"E-mu SP-12",source:`${DOUGH}/EmuSP12.json`,license:NO_LICENSE,homepage:"https://github.com/felixroos/dough-samples",kind:"strudel"},{name:"gm",title:"General MIDI soundfont (FluidR3_GM)",source:"https://gleitz.github.io/midi-js-soundfonts/FluidR3_GM/names.json",license:"CC-BY-3.0",attribution:"FluidR3_GM soundfont by Frank Wen, via gleitz/midi-js-soundfonts (CC BY 3.0, https://creativecommons.org/licenses/by/3.0/)",homepage:"https://github.com/gleitz/midi-js-soundfonts",kind:"gm"},{name:"gm-musyngkite",title:"General MIDI soundfont (Musyng Kite)",source:"https://gleitz.github.io/midi-js-soundfonts/MusyngKite/names.json",license:"CC-BY-SA-3.0",attribution:"Musyng Kite soundfont, via gleitz/midi-js-soundfonts (CC BY-SA 3.0, https://creativecommons.org/licenses/by-sa/3.0/)",homepage:"https://github.com/gleitz/midi-js-soundfonts",kind:"gm"}].map(entry=>Object.freeze({...entry,manifestUrl:resolveManifestUrl(entry.source),builtin:!0}))),PackError=class extends Error{constructor(message){super(message),this.name="PackError"}};function resolveManifestUrl(source){let trimmed=source.trim(),github=GITHUB.exec(trimmed);if(github){let[,user,repo,branch2]=github;if([user,repo,branch2].some(part=>part&&/(^|\/)\.\.?(\/|$)/.test(part)))throw new PackError(`${trimmed} \xB7 not a valid github: shorthand`);return`https://raw.githubusercontent.com/${user}/${repo}/${(branch2??"main").replace(/\/$/,"")}/strudel.json`}if(trimmed.startsWith("github:"))throw new PackError(`${trimmed.slice(0,80)} \xB7 use github:<user>/<repo>[/<branch>]`);return trimmed.endsWith("/")?`${trimmed}strudel.json`:trimmed}var GM_FILE_NOTES=(()=>{let names=["C","Db","D","Eb","E","F","Gb","G","Ab","A","Bb","B"],out=[];for(let midi2=21;midi2<=108;midi2+=1)out.push({note:midi2,name:`${names[midi2%12]}${Math.floor(midi2/12)-1}`});return out})();var DEFAULT_KITS=Object.freeze({909:{pack:"tidal-drum-machines",bank:"RolandTR909"},808:{pack:"tidal-drum-machines",bank:"RolandTR808"},707:{pack:"tidal-drum-machines",bank:"RolandTR707"},606:{pack:"tidal-drum-machines",bank:"RolandTR606"},linn:{pack:"tidal-drum-machines",bank:"LinnDrum"},lm1:{pack:"tidal-drum-machines",bank:"LinnLM1"},dmx:{pack:"tidal-drum-machines",bank:"OberheimDMX"},cr78:{pack:"tidal-drum-machines",bank:"RolandCompurhythm78"},uzu:{pack:"uzu-drumkit",bank:""},dirt:{pack:"dirt-samples",bank:""}}),GM_INSTRUMENTS=Object.freeze(["gm_acoustic_grand_piano","gm_electric_piano_1","gm_electric_piano_2","gm_vibraphone","gm_marimba","gm_drawbar_organ","gm_acoustic_guitar_nylon","gm_electric_guitar_clean","gm_acoustic_bass","gm_electric_bass_finger","gm_synth_bass_1","gm_string_ensemble_1","gm_choir_aahs","gm_trumpet","gm_flute","gm_lead_1_square","gm_pad_2_warm"]);var KIT_SOUNDS=Object.freeze({kick:["bd"],snare:["sd","sn"],clap:["cp"],rim:["rim","rs","cb"],tom:["mt","lt","ht"],hat:["hh","ch"],openhat:["oh","ho"]});var MAX_HARMONICS=1024,MAX_FRAMES=512;var LEVELS=11,WavetableError=class extends Error{constructor(message){super(message),this.name="WavetableError"}},Wavetable=class{name;frames;id;spectra;source;levels=[];scale;constructor(name,id,frames,source){if(!Number.isInteger(frames)||frames<1||frames>MAX_FRAMES)throw new WavetableError(`${name} \xB7 needs 1..${MAX_FRAMES} frames`);this.name=name,this.id=id,this.frames=frames,this.source=source,this.spectra=new Array(frames);for(let level2=0;level2<LEVELS;level2+=1)this.levels.push(new Array(frames))}spectrum(index){let spectrum=this.spectra[index];return spectrum||(spectrum=this.source(index),this.spectra[index]=spectrum),spectrum}gain(){if(this.scale===void 0){let peak=0;for(let frame=0;frame<this.frames;frame+=1){let table2=this.table(frame,0);for(let i=0;i<table2.length;i+=1)peak=Math.max(peak,Math.abs(table2[i]))}this.scale=peak>1e-9?1/peak:0}return this.scale}table(frame,level2){let row2=this.levels[level2],table2=row2[frame];return table2||(table2=synthesizeLevel(this.spectrum(frame),MAX_HARMONICS>>level2),row2[frame]=table2),table2}};function levelSize(harmonics){return Math.min(4096,Math.max(256,harmonics*8))}function synthesizeLevel(spectrum,harmonics){let size=levelSize(harmonics),re=new Float64Array(size),im=new Float64Array(size),top=Math.min(harmonics,spectrum.re.length-1,size/2-1);for(let h=1;h<=top;h+=1)re[h]=spectrum.re[h]/2,im[h]=-spectrum.im[h]/2,re[size-h]=spectrum.re[h]/2,im[size-h]=spectrum.im[h]/2;return fft(re,im,!0),re}function fft(re,im,inverse2=!1){let n2=re.length;if(n2&n2-1)throw new WavetableError("fft size must be a power of two");for(let i=1,j=0;i<n2;i+=1){let bit=n2>>1;for(;j&bit;bit>>=1)j^=bit;if(j^=bit,i<j){let tr=re[i];re[i]=re[j],re[j]=tr;let ti=im[i];im[i]=im[j],im[j]=ti}}let sign=inverse2?1:-1;for(let length=2;length<=n2;length<<=1){let half=length>>1,step2=sign*2*Math.PI/length;for(let k=0;k<half;k+=1){let wr=Math.cos(step2*k),wi=Math.sin(step2*k);for(let start=k;start<n2;start+=length){let a=start,b=start+half,xr=re[b]*wr-im[b]*wi,xi=re[b]*wi+im[b]*wr;re[b]=re[a]-xr,im[b]=im[a]-xi,re[a]+=xr,im[a]+=xi}}}}var PI=Math.PI;function shapes(h){let odd=h%2===1,sine2=h===1?1:0,triangle2=odd?((h-1)/2%2===0?1:-1)*8/(PI*PI*h*h):0,saw2=(h%2===1?1:-1)*2/(PI*h),square2=odd?4/(PI*h):0;return[sine2,triangle2,saw2,square2]}var VOWELS=[[800,1150,2900],[400,1600,2700],[350,2300,3e3],[450,800,2830],[325,700,2530]],BUILTIN_TABLES=Object.freeze({basic:{title:"sine \u2192 triangle \u2192 saw \u2192 square",frames:64,harmonic:(h,x)=>{let s=shapes(h),at3=x*3,i=Math.min(2,Math.floor(at3)),t=at3-i;return s[i]*(1-t)+s[i+1]*t}},pwm:{title:"pulse width 50% \u2192 5%",frames:64,harmonic:(h,x)=>{let duty=.5-.45*x;return 4/(PI*h)*Math.sin(PI*h*duty)*.5}},formant:{title:"vowels a \u2192 e \u2192 i \u2192 o \u2192 u",frames:64,harmonic:(h,x)=>{let at3=x*(VOWELS.length-1),i=Math.min(VOWELS.length-2,Math.floor(at3)),t=at3-i,hz3=h*110,amplitude=0;return VOWELS[i].forEach((centre,k)=>{let c=centre*(1-t)+VOWELS[i+1][k]*t,width=90+40*k;amplitude+=Math.exp(-(((hz3-c)/width)**2))/(1+k)}),h>64?0:amplitude*(h%2===0?-1:1)}},harmonics:{title:"additive: 1 \u2192 32 harmonics",frames:32,harmonic:(h,x)=>{let count2=1+Math.round(x*31);return h<=count2?1/h:0}}}),BUILTIN_TABLE_NAMES=Object.freeze(Object.keys(BUILTIN_TABLES)),builtinCache=new Map;function builtinWavetable(name){let spec=BUILTIN_TABLES[name];if(!spec)return;let table2=builtinCache.get(name);return table2||(table2=new Wavetable(name,`${BUILTIN_TABLE_PREFIX}${name}`,spec.frames,index=>{let x=spec.frames===1?0:index/(spec.frames-1),re=new Float64Array(MAX_HARMONICS+1),im=new Float64Array(MAX_HARMONICS+1);for(let h=1;h<=MAX_HARMONICS;h+=1)im[h]=spec.harmonic(h,x);return Object.freeze({re,im})}),builtinCache.set(name,table2)),table2}function tableFor2(track2,settings,loaded){let src=settings.table.src;return src.startsWith(BUILTIN_TABLE_PREFIX)?builtinWavetable(src.slice(BUILTIN_TABLE_PREFIX.length)):loaded?.get(track2.id)}function param(settings,name){return settings[name]??WAVETABLE_PARAMS[name][2]}function warpPhase(mode,w){if(w<=0||mode==="none")return{map:p=>p,slope:1};switch(mode){case"asym":{let knee3=.5-.49*w;return{map:p=>p<knee3?.5*p/knee3:.5+.5*(p-knee3)/(1-knee3),slope:.5/knee3}}case"bendp":{let k=1+3*w;return{map:p=>p**k,slope:k}}case"bendm":{let k=1+3*w;return{map:p=>1-(1-p)**k,slope:k}}case"bendmp":{let k=1+3*w;return{map:p=>p<.5?.5*(2*p)**k:1-.5*(2-2*p)**k,slope:k}}case"sync":{let ratio2=1+15*w;return{map:p=>p*ratio2%1,slope:ratio2}}case"quant":{let steps2=2**Math.round(11-10*w);return{map:p=>Math.floor(p*steps2)/steps2,slope:1}}}}function levelFor(frequency,sampleRate){let nyquist=sampleRate/2;for(let level2=0;level2<LEVELS;level2+=1)if((MAX_HARMONICS>>level2)*frequency<=nyquist)return level2;return-1}function hermite(table2,position){let mask=table2.length-1,i=Math.floor(position),t=position-i,y0=table2[i-1&mask],y1=table2[i&mask],y2=table2[i+1&mask],y3=table2[i+2&mask],c1=.5*(y2-y0),c2=y0-2.5*y1+2*y2-.5*y3;return(((.5*(y3-y0)+1.5*(y1-y2))*t+c2)*t+c1)*t+y1}function positionEnvelope(settings,seconds2,gate){let attack=param(settings,"wtattack"),decay=param(settings,"wtdecay"),sustain=param(settings,"wtsustain"),release=param(settings,"wtrelease"),held=t=>{if(t<attack)return attack>0?t/attack:1;let d=t-attack;return d<decay?1-(1-sustain)*(decay>0?d/decay:1):sustain};if(seconds2<=gate)return held(seconds2);let after=seconds2-gate;return release>0?held(gate)*Math.max(0,1-after/release):0}function wavetableOscillator(table2,settings,note2,context){let warp2=warpPhase(settings.warpmode??"none",param(settings,"warp")),gain=table2.gain(),base=param(settings,"wt"),envAmount=param(settings,"wtenv"),lfoRate=param(settings,"wtrate"),lfoDepth=param(settings,"wtdepth"),phaseRand=param(settings,"wtphaserand"),last=table2.frames-1,startSeconds=note2.startTick*context.secondsPerTick,ticksPerSecond=context.sampleRate/context.samplesPerTick;return init=>{let startPhase=phaseRand>0?phaseRand*init.random():0,lastIncrement=Number.NaN,level2=-1;return(phase,increment)=>{if(increment!==lastIncrement&&(lastIncrement=increment,level2=levelFor(Math.abs(increment)*init.sampleRate*warp2.slope,init.sampleRate)),level2<0)return 0;let seconds2=init.time(),position=context.positionAt?context.positionAt(note2.startTick+seconds2*ticksPerSecond):base;envAmount!==0&&(position+=envAmount*positionEnvelope(settings,seconds2,context.gate)),lfoDepth!==0&&lfoRate>0&&(position+=.5*lfoDepth*Math.sin(2*PI*lfoRate*(startSeconds+seconds2))),position=Math.max(0,Math.min(1,position));let at3=position*last,lower=Math.floor(at3),mix3=at3-lower,cycle=startPhase+phase,read=warp2.map(cycle-Math.floor(cycle)),a=table2.table(lower,level2),value=hermite(a,read*a.length);if(mix3>0&&lower<last){let b=table2.table(lower+1,level2);value+=(hermite(b,read*b.length)-value)*mix3}return value*gain}}}registerOscillatorResolver(sound=>sound===WAVETABLE_INSTRUMENT2?init=>{let table2=builtinWavetable("basic"),stored=init.param("wt");return wavetableOscillator(table2,{table:{src:`${BUILTIN_TABLE_PREFIX}basic`},...typeof stored=="number"?{wt:stored}:{}},{id:"",trackId:"",startTick:0,durationTicks:1,pitch:60,velocity:1},{sampleRate:init.sampleRate,samplesPerTick:1,secondsPerTick:1/init.sampleRate,gate:Number.POSITIVE_INFINITY,positionAt:void 0})(init)}:void 0);var KIT_EXTRA_VOICES=Object.freeze({crash:49,ride:51,cowbell:56,floortom:41,midtom:47,hitom:50});var WAV_DEFAULT_MAXIMUM_BYTES=256*1024*1024;var WORKSPACE_LIMITS=Object.freeze({maxPathChars:512,maxPathSegments:32,maxListEntries:500,maxReadBytes:256*1024,maxScanBytes:4*1024*1024,maxWriteBytes:1024*1024,maxReadLines:1e5,maxOutlineLines:30,maxOutlineLineChars:120,maxNotesBytes:1024}),RUNTIME_DIR=".dawn";var DENIED_DIRS=Object.freeze([RUNTIME_DIR,".git","node_modules"]);var TRASH_DIR=`${RUNTIME_DIR}/trash`;var UV_INSTALL="curl -LsSf https://astral.sh/uv/install.sh | sh",UV_HINT=`install uv: ${UV_INSTALL} (or brew install uv)`;import{createHash as createHash2}from"node:crypto";import{createHash}from"node:crypto";var OPS={osc:7,noise:8,svf:9,onepole:10,adsr:11,ar:12,slew:13,follow:14,lfo:15,sh:16,random:17,const:18,add:19,mul:20,min:21,max:22,gt:23,lt:24,abs:25,not:26,pitch2hz:27,db2gain:28,scale:29,clamp:30,clock:31,vca:32,mix:33,xfade:34,pan:35,voicesum:5,pass:5,macro:6,in:0,song:1,voice:2,out:3},STATE={7:1,8:8,9:2,10:1,11:3,12:1,13:2,14:1,15:4,16:2,17:3},SEED_CELL={8:0,15:2,17:1},MODE_PARAM={7:"wave",8:"color",9:"mode",10:"mode",15:"shape",17:"per",29:"curve"},SAMPLED={11:["gate"],12:["gate"],13:["in"],16:["in","trig"],19:"all",20:"all",21:"all",22:"all",23:"all",24:"all",25:"all",26:"all",27:"all",28:"all",29:"all",30:"all"};var INPUT_WIDTH=10;var PATCH_COST_BUDGET=1100,BOUNDARY_VOICE_PORTS=BOUNDARY_SPECS.voice.outputs.map(p=>p.name);function canonical(value){if(Array.isArray(value))return`[${value.map(canonical).join(",")}]`;if(value!==null&&typeof value=="object"){let record2=value;return`{${Object.keys(record2).filter(key=>record2[key]!==void 0).sort().map(key=>`${JSON.stringify(key)}:${canonical(record2[key])}`).join(",")}}`}return JSON.stringify(value)??"null"}function nestedNames(patch,library,out){for(let node2 of patch.nodes)if(node2.type.startsWith("patch.")){let name=node2.type.slice(6),sub=library[name];sub&&!out.has(name)&&(out.add(name),nestedNames(sub,library,out))}return out}function patchDigest(patch,library={}){let names=[...nestedNames(patch,library,new Set)].sort(),text2=canonical({patch,nested:names.map(name=>library[name])});return createHash("sha256").update(text2).digest("hex").slice(0,16)}var audioPort=name=>({name,kind:name==="notes"?"notes":"audio",doc:name});function passSpec(names){return{type:"pass",family:"mix",doc:"a nested patch's boundary",inputs:names.map(audioPort),outputs:names.map(audioPort),params:{},rate:"any",process:"block",cost:0}}function macroSpec(macro2){let spec={kind:"number",min:macro2.min,max:macro2.max,default:macro2.default,step:(macro2.max-macro2.min)/100,doc:macro2.label??macro2.id};return{type:"macro",family:"mix",doc:"a nested patch's knob",inputs:[{name:"in",kind:"control",spec,doc:spec.doc}],outputs:[{name:"out",kind:"control",doc:"the knob value"}],params:{},rate:"any",process:"block",cost:0}}function flatten(patch,library){let flat={nodes:new Map,cables:[],bases:new Map,warnings:[]},top=new Set(["in","out","voice","song"]);for(let id of top)flat.nodes.set(id,{id,type:id,spec:BOUNDARY_SPECS[id],params:{},global:!1});return inline(patch,"",library,flat,0),patch.macros.forEach((macro2,index)=>{for(let target of macro2.to){let port2=rewriteTarget(target.port,"",patch,library);if(flat.bases.has(port2)){flat.warnings.push(`macro ${macro2.id}: ${port2} is already set by another macro`);continue}flat.bases.set(port2,{kind:1,index,macro:macro2,min:target.min,max:target.max})}}),flat}function rewriteEnd(ref,prefix,patch,library,dir){let[id,port2]=splitPort(ref);if(id==="voice"||id==="song")return ref;if(id==="in"||id==="out")return`${prefix}${id}.${port2}`.replace(/^\./,"");let node2=patch.nodes.find(n2=>n2.id===id);if(node2?.type.startsWith("patch.")){let sub=library[node2.type.slice(6)];return dir==="from"?`${prefix}${id}/out.${port2}`:sub?.macros.some(m=>m.id===port2)?`${prefix}${id}/@${port2}.in`:`${prefix}${id}/in.${port2}`}return`${prefix}${id}.${port2}`}function rewriteTarget(ref,prefix,patch,library){return rewriteEnd(ref,prefix,patch,library,"to")}function inline(patch,prefix,library,flat,depth){if(depth>PATCH_LIMITS.maxDepth)throw new Error(`patch ${patch.name} nests deeper than ${PATCH_LIMITS.maxDepth}`);if(prefix){let inner=prefix.slice(0,-1);flat.nodes.set(`${inner}/in`,{id:`${inner}/in`,type:"pass",spec:passSpec(["notes","audio","right","side"]),params:{},global:!1}),flat.nodes.set(`${inner}/out`,{id:`${inner}/out`,type:"pass",spec:passSpec(["audio","right"]),params:{},global:!1})}for(let node2 of patch.nodes){let id=`${prefix}${node2.id}`;if(node2.type.startsWith("patch.")){let sub=library[node2.type.slice(6)];if(!sub)throw new Error(`node ${id}: no project patch "${node2.type.slice(6)}"`);nestedSpec(sub),inline(sub,`${id}/`,library,flat,depth+1);for(let macro2 of sub.macros){let macroId=`${id}/@${macro2.id}`;flat.nodes.set(macroId,{id:macroId,type:"macro",spec:macroSpec(macro2),params:{},global:!1});for(let target of macro2.to){let port2=rewriteTarget(target.port,`${id}/`,sub,library);flat.bases.has(port2)||flat.bases.set(port2,{kind:2,node:macroId,macro:macro2,min:target.min,max:target.max})}}continue}let spec=nodeSpec(node2.type);if(!spec)throw new Error(`node ${id}: unknown type ${node2.type}`);flat.nodes.set(id,{id,type:node2.type,spec,params:node2.params??{},global:node2.rate==="global"})}for(let cable of patch.cables)flat.cables.push({id:`${prefix}${cable.id}`,from:rewriteEnd(cable.from,prefix,patch,library,"from"),to:rewriteEnd(cable.to,prefix,patch,library,"to"),...cable.amount!==void 0?{amount:cable.amount}:{}})}var compareText2=(a,b)=>a<b?-1:a>b?1:0,PROGRAMS=new Map,CACHE_SIZE=64;function compilePatch(patch,library={}){let digest=patchDigest(patch,library),hit2=PROGRAMS.get(digest);if(hit2)return PROGRAMS.delete(digest),PROGRAMS.set(digest,hit2),hit2;let program=buildProgram(patch,library,digest);return PROGRAMS.set(digest,program),PROGRAMS.size>CACHE_SIZE&&PROGRAMS.delete(PROGRAMS.keys().next().value),program}function buildProgram(patch,library,digest){let flat=flatten(patch,library),warnings=flat.warnings,nodes=flat.nodes,cables=flat.cables.filter(cable=>{let[from,fromPort]=splitPort(cable.from),[to,toPort]=splitPort(cable.to),a=nodes.get(from),b=nodes.get(to);return a!==void 0&&b!==void 0&&a.spec.outputs.some(p=>p.name===fromPort)&&b.spec.inputs.some(p=>p.name===toPort)}),feeds=new Map;for(let cable of cables){let to=splitPort(cable.to)[0];feeds.has(to)||feeds.set(to,new Set),feeds.get(to).add(splitPort(cable.from)[0])}for(let[port2,base]of flat.bases)if(base.kind===2){let to=splitPort(port2)[0];feeds.has(to)||feeds.set(to,new Set),feeds.get(to).add(base.node)}let live2=new Set(["out"]),stack=["out"];for(;stack.length;)for(let from of feeds.get(stack.pop())??[])live2.has(from)||(live2.add(from),stack.push(from));for(let id of[...nodes.keys()].sort(compareText2))if(!live2.has(id)){let node2=nodes.get(id);!["in","voice","song"].includes(id)&&node2.type!=="pass"&&node2.type!=="macro"&&warnings.push(`unused node ${id}`),nodes.delete(id)}cables=cables.filter(c=>nodes.has(splitPort(c.from)[0])&&nodes.has(splitPort(c.to)[0]));for(let id of["in","song"])nodes.has(id)||nodes.set(id,{id,type:id,spec:BOUNDARY_SPECS[id],params:{},global:!1});let voice=new Set;for(let node2 of nodes.values())node2.spec.rate==="voice"&&voice.add(node2.id);let canVoice=id=>{let n2=nodes.get(id);return n2.spec.rate==="any"&&!n2.global},extraEdges=[];for(let[port2,base]of flat.bases)base.kind===2&&nodes.has(base.node)&&nodes.has(splitPort(port2)[0])&&extraEdges.push([base.node,splitPort(port2)[0]]);let edges=()=>[...cables.map(c=>[splitPort(c.from)[0],splitPort(c.to)[0]]),...extraEdges];for(let changed=!0;changed;){changed=!1;for(let[from,to]of edges())voice.has(from)&&!voice.has(to)&&canVoice(to)&&(voice.add(to),changed=!0)}let post=new Set,next=new Map;for(let[from,to]of edges())next.has(from)||next.set(from,[]),next.get(from).push(to);let walk=[...voice],seen=new Set(walk);for(;walk.length;)for(let to of next.get(walk.pop())??[])seen.has(to)||(seen.add(to),walk.push(to),voice.has(to)||post.add(to));cables=cables.filter(cable=>{let from=splitPort(cable.from)[0],to=splitPort(cable.to)[0];return post.has(from)&&voice.has(to)?(warnings.push(`cable ${cable.id}: ${from} runs after the voices, so it cannot feed ${to}`),!1):!0});let userNodes=[...nodes.values()].filter(n2=>!["in","out","voice","song"].includes(n2.id)),report=findCycles({kind:"patch",role:patch.role,name:patch.name,nodes:userNodes.map(n2=>({id:n2.id,type:n2.type})),cables,macros:[]}),delayed=new Set;for(let id of report.breaks){let cable=cables.find(c=>c.id===id),head=splitPort(cable.to)[0];(report.cycles.find(c=>c.includes(head))??[head]).some(n2=>nodes.get(n2)?.spec.process==="buffer")?(warnings.push(`cable ${id}: a feedback loop through an engine or effect node is cut`),cables=cables.filter(c=>c.id!==id)):(delayed.add(id),warnings.push(`feedback: cable ${id} is delayed one block (32 samples)`))}let order=ids=>{let indegree=new Map;for(let id of ids)indegree.set(id,0);let outs=new Map,add=(from,to)=>{!ids.has(from)||!ids.has(to)||from===to||(indegree.set(to,indegree.get(to)+1),outs.has(from)||outs.set(from,[]),outs.get(from).push(to))};for(let cable of cables)delayed.has(cable.id)||add(splitPort(cable.from)[0],splitPort(cable.to)[0]);for(let[from,to]of extraEdges)add(from,to);let ready=[...ids].filter(id=>indegree.get(id)===0),out=[],rank=id=>nodes.get(id).spec.process==="buffer"?1:0;for(;ready.length;){ready.sort((a,b)=>rank(a)-rank(b)||compareText2(a,b));let id=ready.shift();out.push(id);for(let to of outs.get(id)??[])indegree.set(to,indegree.get(to)-1),indegree.get(to)===0&&ready.push(to)}if(out.length!==ids.size)throw new Error(`patch ${patch.name}: a nested knob feeds back into itself`);return out},voiceIds=new Set([...nodes.keys()].filter(id=>voice.has(id))),globalIds=new Set([...nodes.keys()].filter(id=>!voice.has(id))),preIds=new Set([...globalIds].filter(id=>!post.has(id))),postIds=new Set([...globalIds].filter(id=>post.has(id))),preOrder=order(preIds),postOrder=order(postIds),voiceOrder=order(voiceIds),lead=(list,first)=>[...first.filter(id=>list.includes(id)),...list.filter(id=>!first.includes(id))],preList=lead(preOrder,["song","in"]);voiceOrder=lead(voiceOrder,["voice"]);let phaseOf2=new Map,phaseLists=[];for(let list of[preList,postOrder]){let current;for(let id of list)nodes.get(id).spec.process==="buffer"?(phaseLists.push({kind:"buffer",ids:[id]}),current=void 0):(current||(current={kind:"block",ids:[]},phaseLists.push(current)),current.ids.push(id)),phaseOf2.set(id,phaseLists.length-1);current=void 0}let preCount=phaseLists.findIndex(p=>p.ids.some(id=>post.has(id)));for(let id of[...delayed]){let cable=cables.find(c=>c.id===id),from=splitPort(cable.from)[0],to=splitPort(cable.to)[0];!voice.has(from)&&phaseOf2.get(from)!==phaseOf2.get(to)&&(warnings.push(`cable ${id}: a feedback loop across an engine or effect node is cut`),delayed.delete(id),cables=cables.filter(c=>c.id!==id))}let consts=[],constant3=value=>(consts.push(value),consts.length-1),one=constant3(1),into=new Map;for(let cable of cables)into.has(cable.to)||into.set(cable.to,[]),into.get(cable.to).push(cable);let needsFull=new Set;for(let cable of cables){let from=splitPort(cable.from)[0],to=splitPort(cable.to)[0];voice.has(from)||(voice.has(to)||nodes.get(from).spec.process==="buffer"||nodes.get(to).spec.process==="buffer"||phaseOf2.get(from)!==phaseOf2.get(to))&&needsFull.add(cable.from)}for(let[port2,base]of flat.bases)if(base.kind===2&&!voice.has(base.node)){let to=splitPort(port2)[0];(voice.has(to)||phaseOf2.get(base.node)!==phaseOf2.get(to))&&needsFull.add(`${base.node}.out`)}needsFull.add("song.beat");let g={full:0,local:1,slotOf:new Map},v={full:0,local:1,slotOf:new Map},local=b=>-1-b.local++,fullSlot=b=>b.full++;for(let id of[...preList,...postOrder]){let node2=nodes.get(id);for(let port2 of node2.spec.outputs){if(port2.kind==="notes")continue;let ref=`${id}.${port2.name}`,whole=needsFull.has(ref)||node2.spec.process==="buffer";g.slotOf.set(ref,whole?fullSlot(g):local(g))}}for(let id of voiceOrder)for(let port2 of nodes.get(id).spec.outputs)port2.kind!=="notes"&&v.slotOf.set(`${id}.${port2.name}`,local(v));let accumulators=new Map,fanIns=new Map;for(let cable of cables){let from=splitPort(cable.from)[0],to=splitPort(cable.to)[0];voice.has(from)&&!voice.has(to)&&!accumulators.has(cable.from)&&accumulators.set(cable.from,fullSlot(g)),!voice.has(from)&&voice.has(to)&&!fanIns.has(cable.from)&&fanIns.set(cable.from,local(v))}for(let[port2,base]of flat.bases)if(base.kind===2){let ref=`${base.node}.out`,to=splitPort(port2)[0];voice.has(base.node)&&!voice.has(to)&&!accumulators.has(ref)&&accumulators.set(ref,fullSlot(g)),!voice.has(base.node)&&voice.has(to)&&!fanIns.has(ref)&&fanIns.set(ref,local(v))}let buffers=[],maxRelease=0,emit=(ids,isVoice,b)=>{let n2=ids.length,op=new Int32Array(n2),mode=new Int32Array(n2),nIn=new Int32Array(n2),slotBase=new Int32Array(n2),ctlBase=new Int32Array(n2),stBase=new Int32Array(n2),inStart=new Int32Array(n2),inCount=new Int32Array(n2),slots=[],inputs2=[],cableList=[],delayList=[],seeds=[],ctl=0,state=0,sourceSlot=(cable,ref)=>{let from=splitPort(ref)[0];if(isVoice){if(!voice.has(from))return fanIns.get(ref)}else if(voice.has(from))return accumulators.get(ref);let slot=b.slotOf.get(ref);if(cable&&delayed.has(cable.id)){let delay=local(b);return delayList.push(slot,delay),delay}return slot},baseSlot=node2=>sourceSlot(void 0,`${node2}.out`);return ids.forEach((id,index)=>{let node2=nodes.get(id),spec=node2.spec,code=spec.process==="buffer"?4:node2.type==="pass"?5:OPS[node2.type];if(code===void 0)throw new Error(`node ${id}: no kernel for ${node2.type}`);op[index]=code,nIn[index]=spec.inputs.length;let modeParam=MODE_PARAM[code];if(modeParam){let values=spec.params[modeParam].values,chosen=node2.params[modeParam]??spec.params[modeParam].default;mode[index]=Math.max(0,values.indexOf(chosen))}code===4&&buffers.push({id,type:node2.type,params:node2.params,spec});let settings=Object.entries(spec.params).filter(([name,p])=>p.kind==="number"&&!spec.inputs.some(i=>i.name===name)).map(([name])=>name).sort(compareText2);ctlBase[index]=ctl,stBase[index]=state;let seedCell=SEED_CELL[code];seedCell!==void 0&&seeds.push([state+seedCell,id]),state+=STATE[code]??0,slotBase[index]=slots.length,inStart[index]=inputs2.length/INPUT_WIDTH;let sampled=SAMPLED[code],ports=[...spec.inputs.map(p=>({port:p.name,spec:p.spec,kind:p.kind,sampled:p.kind==="control"&&(p.audioRate===!0||sampled==="all"||(sampled?.includes(p.name)??!1)),smooth:p.smooth===!0})),...settings.map(name=>({port:name,spec:spec.params[name],kind:"control",sampled:!1,smooth:!1}))];ports.forEach((p,k)=>{let ref=`${id}.${p.port}`,list=(into.get(ref)??[]).filter(c=>nodes.get(splitPort(c.from)[0]).spec.outputs.find(o=>o.name===splitPort(c.from)[1])?.kind!=="notes"),record2=new Array(INPUT_WIDTH).fill(0);record2[2]=ctl+k,record2[5]=-1,record2[6]=-1,record2[8]=cableList.length/2;let slot=-1;if(p.kind==="notes"||code===4){if(record2[0]=0,code===4&&p.kind!=="notes"){record2[0]=p.kind==="audio"?1:2;for(let c of list)cableList.push(sourceSlot(c,c.from),c.amount===void 0?one:constant3(c.amount));record2[9]=list.length;let base=p.kind==="control"?flat.bases.get(ref):void 0;record2[3]=0,base&&(record2[5]=constant3(base.macro.min),constant3(base.macro.max),constant3(base.macro.curve==="exp"?1:0),constant3(base.min??Number.NaN),constant3(base.max??Number.NaN),base.kind===1?(record2[3]=1,record2[4]=base.index):base.kind===2&&nodes.has(base.node)?(record2[3]=2,record2[4]=baseSlot(base.node)):record2[5]=-1),p.spec&&record2[3]!==0&&(record2[6]=constant3(p.spec.min),constant3(p.spec.max))}}else if(p.kind==="audio"){if(list.length===1&&(list[0].amount??1)===1)record2[0]=0,slot=sourceSlot(list[0],list[0].from);else if(list.length>0){record2[0]=1,slot=local(b);for(let c of list)cableList.push(sourceSlot(c,c.from),c.amount===void 0?one:constant3(c.amount));record2[9]=list.length}}else{record2[0]=p.sampled?3:2,p.sampled&&(slot=local(b));for(let c of list)cableList.push(sourceSlot(c,c.from),c.amount===void 0?one:constant3(c.amount));record2[9]=list.length,record2[7]=p.smooth?1:0;let range=p.spec;range&&(record2[6]=constant3(range.min),constant3(range.max));let raw=node2.params[p.port],fallback=typeof raw=="number"?raw:list.length>0?0:range?.default??0,base=flat.bases.get(ref);base&&(record2[5]=constant3(base.macro.min),constant3(base.macro.max),constant3(base.macro.curve==="exp"?1:0),constant3(base.min??Number.NaN),constant3(base.max??Number.NaN)),base?.kind===1?(record2[3]=1,record2[4]=base.index):base?.kind===2&&nodes.has(base.node)?(record2[3]=2,record2[4]=baseSlot(base.node)):(record2[3]=0,record2[4]=constant3(fallback),base&&(record2[5]=-1)),(code===11||code===12)&&p.port==="release"&&(maxRelease=Math.max(maxRelease,list.length===0&&record2[3]===0?fallback:range?.max??10))}record2[1]=slot,inputs2.push(...record2),k<spec.inputs.length&&slots.push(slot)}),inCount[index]=ports.length,ctl+=ports.length;for(let port2 of spec.outputs)slots.push(port2.kind==="notes"?-1:b.slotOf.get(`${id}.${port2.name}`))}),{section:{ids,op,mode,nIn,slotBase,slots:Int32Array.from(slots),ctlBase,stBase,inStart,inCount,...hotInputs(inputs2,inStart,inCount),inputs:Int32Array.from(inputs2),cables:Int32Array.from(cableList),delays:Int32Array.from(delayList),ctlCount:ctl,stateCount:state,fullSlots:b.full,localSlots:b.local,seeds}}},globalIdsOrdered=[...preList,...postOrder],{section:globalSection}=emit(globalIdsOrdered,!1,g),{section:voiceSection}=emit(voiceOrder,!0,v),finalGlobal={...globalSection,fullSlots:g.full,localSlots:g.local},finalVoice={...voiceSection,fullSlots:0,localSlots:v.local},indexOf=new Map(globalIdsOrdered.map((id,i)=>[id,i])),phaseDelays=phaseLists.map(()=>[]),gDelays=finalGlobal.delays,slotOwner=new Map;for(let[ref,slot]of g.slotOf)slotOwner.set(slot,splitPort(ref)[0]);for(let i=0;i<gDelays.length;i+=2){let owner=slotOwner.get(gDelays[i]);phaseDelays[phaseOf2.get(owner)].push(gDelays[i],gDelays[i+1])}let phases2=phaseLists.map((p,i)=>p.kind==="buffer"?{kind:"buffer",node:indexOf.get(p.ids[0])}:{kind:"block",nodes:p.ids.map(id=>indexOf.get(id)),delays:Int32Array.from(phaseDelays[i])}),split=preCount<0?phases2.length:preCount,voiceUsed=0;BOUNDARY_VOICE_PORTS.forEach((name,k)=>{cables.some(c=>c.from===`voice.${name}`)&&(voiceUsed|=1<<k)});let fanOuts=[];for(let[ref,slot]of fanIns)fanOuts.push(g.slotOf.get(ref),slot);let voiceSums=[];for(let[ref,slot]of accumulators)voiceSums.push(v.slotOf.get(ref),slot);let voiceCost=0,globalCost=0;for(let id of nodes.keys()){let cost=nodes.get(id).spec.cost;voice.has(id)?voiceCost+=cost:globalCost+=cost}let requested=patch.voices??PATCH_LIMITS.defaultVoices,voices=voiceCap(requested,voiceCost,globalCost);voices<requested&&warnings.push(`over the cost budget: voices capped at ${voices} (asked for ${requested})`);let stereo=(into.get("out.right")??[]).length>0;return Object.freeze({digest,name:patch.name,role:patch.role,global:finalGlobal,voice:finalVoice,pre:phases2.slice(0,split),post:phases2.slice(split),voiceUsed,fanOuts:Int32Array.from(fanOuts),voiceSums:Int32Array.from(voiceSums),beatSlot:g.slotOf.get("song.beat"),macros:patch.macros,consts:Float64Array.from(consts),buffers,stereo,voices:voiceSums.length>0?voices:0,maxRelease,cost:voiceCost*voices+globalCost,warnings:Object.freeze([...warnings])})}function hotInputs(inputs2,inStart,inCount){let hot=[],hotStart=new Int32Array(inStart.length),hotCount=new Int32Array(inStart.length);for(let n2=0;n2<inStart.length;n2+=1){hotStart[n2]=hot.length;for(let j=0;j<inCount[n2];j+=1){let r=(inStart[n2]+j)*INPUT_WIDTH,kind=inputs2[r+0];if(kind===0)continue;kind===2&&inputs2[r+9]===0&&inputs2[r+3]===0||hot.push(inStart[n2]+j)}hotCount[n2]=hot.length-hotStart[n2]}return{hot:Int32Array.from(hot),hotStart,hotCount}}function voiceCap(requested,voiceCost,globalCost,budget=PATCH_COST_BUDGET){if(voiceCost<=0)return requested;let fit=Math.floor((budget-globalCost)/voiceCost);return Math.max(1,Math.min(requested,fit))}function mapMacro(value,min,max,exp,tmin,tmax){if(tmin!==tmin&&tmax!==tmax)return value;let v=value<min?min:value>max?max:value,p=exp?Math.log(v/min)/Math.log(max/min):(v-min)/(max-min);Number.isFinite(p)||(p=0);let lo=tmin===tmin?tmin:min;return lo+((tmax===tmax?tmax:max)-lo)*p}function at(f,node2,k){let s=f.slots[f.slotBase[node2]+k];return s>=0?s*f.stride+f.blk:f.local-(s+1)*32}function draw(st,cell2){let a=st[cell2]+1831565813|0;st[cell2]=a;let t=Math.imul(a^a>>>15,1|a);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296}function flush(x){return x>1e-30||x<-1e-30?x:0}function put(m,value,o){for(let i=0;i<32;i+=1)m[o+i]=value}function adsr(f,n2){let m=f.m,st=f.st,c=f.ctlBase[n2],s=f.stBase[n2],gate=at(f,n2,0),o=at(f,n2,5),sr=f.sampleRate,attack=f.ctl[c+1],decay=f.ctl[c+2],sustain=f.ctl[c+3],release=f.ctl[c+4],up=attack>0?1/(attack*sr):1,down=decay>0?(1-sustain)/(decay*sr):1,stage=st[s],level2=st[s+1],step2=st[s+2];for(let i=0;i<32;i+=1)m[gate+i]>.5?(stage===0||stage===4)&&(stage=1):stage>=1&&stage<=3&&(stage=4,step2=release>0?level2/(release*sr):level2),stage===1?(level2+=up,level2>=1&&(level2=1,stage=2)):stage===2?(level2-=down,level2<=sustain&&(level2=sustain,stage=3)):stage===3?level2=sustain:stage===4&&(level2-=step2,level2<=0&&(level2=0,stage=0)),m[o+i]=level2;st[s]=stage,st[s+1]=level2,st[s+2]=step2}function ar(f,n2){let m=f.m,c=f.ctlBase[n2],s=f.stBase[n2],gate=at(f,n2,0),o=at(f,n2,3),sr=f.sampleRate,attack=f.ctl[c+1],release=f.ctl[c+2],up=attack>0?1/(attack*sr):1,down=release>0?1/(release*sr):1,level2=f.st[s];for(let i=0;i<32;i+=1)level2=m[gate+i]>.5?Math.min(1,level2+up):Math.max(0,level2-down),m[o+i]=level2;f.st[s]=level2}function slew(f,n2){let m=f.m,c=f.ctlBase[n2],s=f.stBase[n2],x=at(f,n2,0),o=at(f,n2,3),sr=f.sampleRate,rise=f.ctl[c+1],fall=f.ctl[c+2],up=rise>0?1/(rise*sr):1/0,down=fall>0?1/(fall*sr):1/0,y=f.st[s+1]===0?m[x]:f.st[s];for(let i=0;i<32;i+=1){let target=m[x+i];target>y?y=Math.min(target,y+up):target<y&&(y=Math.max(target,y-down)),m[o+i]=y}f.st[s]=y,f.st[s+1]=1}function follow(f,n2){let m=f.m,c=f.ctlBase[n2],s=f.stBase[n2],x=at(f,n2,0),o=at(f,n2,3),sr=f.sampleRate,ca=Math.exp(-1/(f.ctl[c+1]*sr)),cr=Math.exp(-1/(f.ctl[c+2]*sr)),env=f.st[s];for(let i=0;i<32;i+=1){let v=m[x+i],a=v<0?-v:v;env=a>env?a+(env-a)*ca:a+(env-a)*cr,env<1e-30&&(env=0),m[o+i]=env>1?1:env}f.st[s]=env}function warp(cutoff2,sampleRate){let fc=Math.min(Math.max(cutoff2,1),.49*sampleRate);return Math.tan(Math.PI*fc/sampleRate)}function damping(q3){return 2-1.94*q3}function svf(f,n2){let m=f.m,c=f.ctlBase[n2],s=f.stBase[n2],x=at(f,n2,0),o=at(f,n2,3),mode=f.mode[n2],g0=warp(f.prev[c+1],f.sampleRate),g1=warp(f.ctl[c+1],f.sampleRate),k0=damping(f.prev[c+2]),k1=damping(f.ctl[c+2]),dg=(g1-g0)/32,dk=(k1-k0)/32,still=dg===0&&dk===0,ic1=f.st[s],ic2=f.st[s+1],g=g1,k=k1,a1=1/(1+g*(g+k)),a2=g*a1,a3=g*a2;for(let i=0;i<32;i+=1){still||(g=g0+dg*(i+1),k=k0+dk*(i+1),a1=1/(1+g*(g+k)),a2=g*a1,a3=g*a2);let input=m[x+i],v3=input-ic2,v1=a1*ic1+a2*v3,v2=ic2+a2*ic1+a3*v3;ic1=2*v1-ic1,ic2=2*v2-ic2,m[o+i]=mode===0?v2:mode===1?input-k*v1-v2:mode===2?v1:input-k*v1}f.st[s]=flush(ic1),f.st[s+1]=flush(ic2)}function onepole(f,n2){let m=f.m,c=f.ctlBase[n2],s=f.stBase[n2],x=at(f,n2,0),o=at(f,n2,2),hp=f.mode[n2]===1,g0=warp(f.prev[c+1],f.sampleRate),g1=warp(f.ctl[c+1],f.sampleRate),dg=(g1-g0)/32,z=f.st[s];for(let i=0;i<32;i+=1){let g=dg===0?g1:g0+dg*(i+1),input=m[x+i],v=(input-z)*g/(1+g),lp2=v+z;z=lp2+v,m[o+i]=hp?input-lp2:lp2}f.st[s]=flush(z)}function constant2(f,n2){let o=at(f,n2,0);put(f.m,f.ctl[f.ctlBase[n2]],o)}function binary2(f,n2,op){let m=f.m,a=at(f,n2,0),b=at(f,n2,1),o=at(f,n2,2);switch(op){case 0:for(let i=0;i<32;i+=1)m[o+i]=m[a+i]+m[b+i];break;case 1:for(let i=0;i<32;i+=1)m[o+i]=m[a+i]*m[b+i];break;case 2:for(let i=0;i<32;i+=1)m[o+i]=Math.min(m[a+i],m[b+i]);break;case 3:for(let i=0;i<32;i+=1)m[o+i]=Math.max(m[a+i],m[b+i]);break;case 4:for(let i=0;i<32;i+=1)m[o+i]=m[a+i]>m[b+i]?1:0;break;default:for(let i=0;i<32;i+=1)m[o+i]=m[a+i]<m[b+i]?1:0}}function unary2(f,n2,op){let m=f.m,x=at(f,n2,0),o=at(f,n2,1);switch(op){case 0:for(let i=0;i<32;i+=1)m[o+i]=Math.abs(m[x+i]);break;case 1:for(let i=0;i<32;i+=1)m[o+i]=m[x+i]<.5?1:0;break;case 2:for(let i=0;i<32;i+=1)m[o+i]=440*Math.pow(2,(m[x+i]-69)/12);break;default:for(let i=0;i<32;i+=1)m[o+i]=Math.pow(10,m[x+i]/20)}}function scale(f,n2){let m=f.m,x=at(f,n2,0),i0=at(f,n2,1),i1=at(f,n2,2),lo=at(f,n2,3),hi=at(f,n2,4),o=at(f,n2,5),exp=f.mode[n2]===1;for(let i=0;i<32;i+=1){let span4=m[i1+i]-m[i0+i],t=span4===0?0:(m[x+i]-m[i0+i])/span4,a=m[lo+i],b=m[hi+i];m[o+i]=exp&&a>0&&b>0?a*Math.pow(b/a,t):a+(b-a)*t}}function clamp3(f,n2){let m=f.m,x=at(f,n2,0),lo=at(f,n2,1),hi=at(f,n2,2),o=at(f,n2,3);for(let i=0;i<32;i+=1)m[o+i]=Math.min(Math.max(m[x+i],m[lo+i]),m[hi+i])}function vca(f,n2){let m=f.m,x=at(f,n2,0),g=at(f,n2,1),o=at(f,n2,2);for(let i=0;i<32;i+=1)m[o+i]=m[x+i]*m[g+i]}function mix2(f,n2){let m=f.m,c=f.ctlBase[n2],a=at(f,n2,0),b=at(f,n2,1),cc=at(f,n2,2),d=at(f,n2,3),o=at(f,n2,8),pa=f.prev[c+4],pb=f.prev[c+5],pc=f.prev[c+6],pd=f.prev[c+7],da=(f.ctl[c+4]-pa)/32,db2=(f.ctl[c+5]-pb)/32,dc=(f.ctl[c+6]-pc)/32,dd=(f.ctl[c+7]-pd)/32;for(let i=0;i<32;i+=1){let r=i+1;m[o+i]=m[a+i]*(pa+da*r)+m[b+i]*(pb+db2*r)+m[cc+i]*(pc+dc*r)+m[d+i]*(pd+dd*r)}}function xfade(f,n2){let m=f.m,c=f.ctlBase[n2],a=at(f,n2,0),b=at(f,n2,1),o=at(f,n2,3),x0=f.prev[c+2],dx=(f.ctl[c+2]-x0)/32;for(let i=0;i<32;i+=1){let x=x0+dx*(i+1);m[o+i]=m[a+i]*(1-x)+m[b+i]*x}}function pan(f,n2){let m=f.m,c=f.ctlBase[n2],x=at(f,n2,0),l=at(f,n2,2),r=at(f,n2,3),t0=(f.prev[c+1]+1)*Math.PI/4,t1=(f.ctl[c+1]+1)*Math.PI/4,l0=Math.cos(t0),r0=Math.sin(t0),dl=(Math.cos(t1)-l0)/32,dr=(Math.sin(t1)-r0)/32;for(let i=0;i<32;i+=1){let v=m[x+i];m[l+i]=v*(l0+dl*(i+1)),m[r+i]=v*(r0+dr*(i+1))}}function pass(f,n2){let m=f.m,count2=f.nIn[n2];for(let k=0;k<count2;k+=1){let x=at(f,n2,k),o=at(f,n2,count2+k);x!==o&&m.copyWithin(o,x,x+32)}}function macro(f,n2){let o=at(f,n2,1);put(f.m,f.ctl[f.ctlBase[n2]],o)}var TAU=2*Math.PI;function lfo2(f,n2){let m=f.m,st=f.st,c=f.ctlBase[n2],s=f.stBase[n2],o=at(f,n2,3),offset=f.ctl[c+1],depth=f.ctl[c+2],sync2=f.ctl[c+3],inc=(sync2>0?f.bps/sync2:f.ctl[c])/f.sampleRate,shape=f.mode[n2];st[s+3]===0&&(st[s+1]=draw(st,s+2)*2-1,st[s+3]=1);let ph2=st[s];for(let i=0;i<32;i+=1){let cyc=ph2+offset;cyc>=1&&(cyc-=1);let v;switch(shape){case 0:v=Math.sin(TAU*cyc);break;case 1:v=1-4*Math.abs(cyc-.5);break;case 2:v=cyc<.5?1:-1;break;case 3:v=1-2*cyc;break;case 4:v=2*cyc-1;break;default:v=st[s+1]}m[o+i]=v*depth,ph2+=inc,ph2>=1&&(ph2-=Math.floor(ph2),shape===5&&(st[s+1]=draw(st,s+2)*2-1))}st[s]=ph2}function sh(f,n2){let m=f.m,s=f.stBase[n2],x=at(f,n2,0),trig=at(f,n2,1),o=at(f,n2,2),held=f.st[s],last=f.st[s+1];for(let i=0;i<32;i+=1){let t=m[trig+i];t>.5&&last<=.5&&(held=m[x+i]),last=t,m[o+i]=held}f.st[s]=held,f.st[s+1]=last}function random(f,n2){let st=f.st,s=f.stBase[n2],o=at(f,n2,0);(f.mode[n2]===1||st[s+2]===0)&&(st[s]=draw(st,s+1),st[s+2]=1),put(f.m,st[s],o)}function clock2(f,n2){let m=f.m,c=f.ctlBase[n2],o=at(f,n2,1),width=f.ctl[c],beats=f.ctl[c+1],b=f.beatSlot*f.stride+f.blk;for(let i=0;i<32;i+=1){let x=m[b+i]/beats;m[o+i]=x-Math.floor(x)<width?1:0}}var TAU2=2*Math.PI;function blep(t,dt){if(t<dt){let x=t/dt;return x+x-x*x-1}if(t>1-dt){let x=(t-1)/dt;return x*x+x+x+1}return 0}function step(hz3,ratio2){let dt=hz3*ratio2;return dt>.5?.5:dt<-.5?-.5:dt}function wrap(ph2){return ph2>=1?ph2-1:ph2<0?ph2+1:ph2}function osc(f,n2){let m=f.m,c=f.ctlBase[n2],s=f.stBase[n2],pitch2=at(f,n2,0),fm=at(f,n2,3),o=at(f,n2,5),ratio2=Math.pow(2,f.ctl[c+1]/1200)/f.sampleRate,pw0=f.prev[c+2],dpw=(f.ctl[c+2]-pw0)/32,lv0=f.prev[c+4],dlv=(f.ctl[c+4]-lv0)/32,wave2=f.mode[n2],ph2=f.st[s];if(wave2===0)for(let i=0;i<32;i+=1){let dt=step(m[pitch2+i]+m[fm+i],ratio2);m[o+i]=Math.sin(TAU2*ph2)*(lv0+dlv*(i+1)),ph2=wrap(ph2+dt)}else if(wave2===1)for(let i=0;i<32;i+=1){let dt=step(m[pitch2+i]+m[fm+i],ratio2),adt=dt<0?-dt:dt;m[o+i]=(2*ph2-1-blep(ph2,adt))*(lv0+dlv*(i+1)),ph2=wrap(ph2+dt)}else if(wave2===3)for(let i=0;i<32;i+=1){let dt=step(m[pitch2+i]+m[fm+i],ratio2);m[o+i]=(1-4*Math.abs(ph2-.5))*(lv0+dlv*(i+1)),ph2=wrap(ph2+dt)}else{let square2=wave2===2;for(let i=0;i<32;i+=1){let dt=step(m[pitch2+i]+m[fm+i],ratio2),adt=dt<0?-dt:dt,pw=square2?.5:pw0+dpw*(i+1),h=ph2+1-pw>=1?ph2-pw:ph2+1-pw,v=(ph2<pw?1:-1)+blep(ph2,adt)-blep(h,adt);m[o+i]=v*(lv0+dlv*(i+1)),ph2=wrap(ph2+dt)}}f.st[s]=ph2}function noise(f,n2){let m=f.m,st=f.st,c=f.ctlBase[n2],s=f.stBase[n2],o=at(f,n2,1),lv0=f.prev[c],dlv=(f.ctl[c]-lv0)/32,color=f.mode[n2];for(let i=0;i<32;i+=1){let w=draw(st,s)*2-1,v;if(color===1)st[s+1]=.99886*st[s+1]+w*.0555179,st[s+2]=.99332*st[s+2]+w*.0750759,st[s+3]=.969*st[s+3]+w*.153852,st[s+4]=.8665*st[s+4]+w*.3104856,st[s+5]=.55*st[s+5]+w*.5329522,st[s+6]=-.7616*st[s+6]-w*.016898,v=(st[s+1]+st[s+2]+st[s+3]+st[s+4]+st[s+5]+st[s+6]+st[s+7]+w*.5362)*.11,st[s+7]=w*.115926;else if(color===2){let y=(st[s+1]+.02*w)/1.02;st[s+1]=y,v=y*3.5}else v=w;m[o+i]=v*(lv0+dlv*(i+1))}}function voiceAddr(s){return s>=0?s*32:-(s+1)*32}var port=(s,n2,k)=>voiceAddr(s.slots[s.slotBase[n2]+k]),zero=(s,n2,k)=>s.slots[s.slotBase[n2]+k]===-1,HELPERS=`
|
|
7
|
+
const TAU = 2 * Math.PI;
|
|
8
|
+
function blep(t, dt) {
|
|
9
|
+
if (t < dt) { const x = t / dt; return x + x - x * x - 1; }
|
|
10
|
+
if (t > 1 - dt) { const x = (t - 1) / dt; return x * x + x + x + 1; }
|
|
11
|
+
return 0;
|
|
12
|
+
}
|
|
13
|
+
function warp(cutoff, sampleRate) {
|
|
14
|
+
const fc = Math.min(Math.max(cutoff, 1), 0.49 * sampleRate);
|
|
15
|
+
return Math.tan((Math.PI * fc) / sampleRate);
|
|
16
|
+
}
|
|
17
|
+
function flush(x) {
|
|
18
|
+
return x > 1e-30 || x < -1e-30 ? x : 0;
|
|
19
|
+
}
|
|
20
|
+
`,KERNEL_HELPERS=HELPERS;function scoped(code,n2){return code.replace(/\$([A-Za-z]\w*)/g,`n${n2}_$1`)}function standalone(p){return`{
|
|
21
|
+
${p.pre}for (let i = 0; i < ${32}; i += 1) {
|
|
22
|
+
${p.body}}
|
|
23
|
+
${p.post}}
|
|
24
|
+
`}function oscParts(s,n2){let c=s.ctlBase[n2],st=s.stBase[n2],pitch2=port(s,n2,0),o=port(s,n2,5),hz3=zero(s,n2,3)?`m[${pitch2} + i]`:`m[${pitch2} + i] + m[${port(s,n2,3)} + i]`,wave2=s.mode[n2],pre=`const $ratio = Math.pow(2, ctl[${c+1}] / 1200) / f.sampleRate;
|
|
25
|
+
const $lv0 = prev[${c+4}];
|
|
26
|
+
const $dlv = (ctl[${c+4}] - $lv0) / ${32};
|
|
27
|
+
let $ph = st[${st}];
|
|
28
|
+
`,body2=`let dt = (${hz3}) * $ratio;
|
|
29
|
+
dt = dt > 0.5 ? 0.5 : dt < -0.5 ? -0.5 : dt;
|
|
30
|
+
`;if(wave2===0)body2+=`m[${o} + i] = Math.sin(TAU * $ph) * ($lv0 + $dlv * (i + 1));
|
|
31
|
+
`;else if(wave2===1)body2+=`const adt = dt < 0 ? -dt : dt;
|
|
32
|
+
m[${o} + i] = (2 * $ph - 1 - blep($ph, adt)) * ($lv0 + $dlv * (i + 1));
|
|
33
|
+
`;else if(wave2===3)body2+=`m[${o} + i] = (1 - 4 * Math.abs($ph - 0.5)) * ($lv0 + $dlv * (i + 1));
|
|
34
|
+
`;else{let pw=wave2===2?"0.5":"$pw0 + $dpw * (i + 1)";wave2!==2&&(pre+=`const $pw0 = prev[${c+2}];
|
|
35
|
+
const $dpw = (ctl[${c+2}] - $pw0) / ${32};
|
|
36
|
+
`),body2+=`const adt = dt < 0 ? -dt : dt;
|
|
37
|
+
const pw = ${pw};
|
|
38
|
+
const h = $ph + 1 - pw >= 1 ? $ph - pw : $ph + 1 - pw;
|
|
39
|
+
const v = ($ph < pw ? 1 : -1) + blep($ph, adt) - blep(h, adt);
|
|
40
|
+
m[${o} + i] = v * ($lv0 + $dlv * (i + 1));
|
|
41
|
+
`}return body2+=`$ph = $ph + dt;
|
|
42
|
+
$ph = $ph >= 1 ? $ph - 1 : $ph < 0 ? $ph + 1 : $ph;
|
|
43
|
+
`,{pre,body:body2,post:`st[${st}] = $ph;
|
|
44
|
+
`}}function svfParts(s,n2){let c=s.ctlBase[n2],st=s.stBase[n2],x=port(s,n2,0),o=port(s,n2,3),mode=s.mode[n2],out=mode===0?"v2":mode===1?"input - $k * v1 - v2":mode===2?"v1":"input - $k * v1";return{pre:`const $g0 = warp(prev[${c+1}], f.sampleRate);
|
|
45
|
+
const $g1 = warp(ctl[${c+1}], f.sampleRate);
|
|
46
|
+
const $k0 = 2 - 1.94 * prev[${c+2}];
|
|
47
|
+
const $k1 = 2 - 1.94 * ctl[${c+2}];
|
|
48
|
+
const $dg = ($g1 - $g0) / ${32};
|
|
49
|
+
const $dk = ($k1 - $k0) / ${32};
|
|
50
|
+
const $still = $dg === 0 && $dk === 0;
|
|
51
|
+
let $ic1 = st[${st}];
|
|
52
|
+
let $ic2 = st[${st+1}];
|
|
53
|
+
let $g = $g1;
|
|
54
|
+
let $k = $k1;
|
|
55
|
+
let $a1 = 1 / (1 + $g * ($g + $k));
|
|
56
|
+
let $a2 = $g * $a1;
|
|
57
|
+
let $a3 = $g * $a2;
|
|
58
|
+
`,body:`if (!$still) {
|
|
59
|
+
$g = $g0 + $dg * (i + 1);
|
|
60
|
+
$k = $k0 + $dk * (i + 1);
|
|
61
|
+
$a1 = 1 / (1 + $g * ($g + $k));
|
|
62
|
+
$a2 = $g * $a1;
|
|
63
|
+
$a3 = $g * $a2;
|
|
64
|
+
}
|
|
65
|
+
const input = m[${x} + i];
|
|
66
|
+
const v3 = input - $ic2;
|
|
67
|
+
const v1 = $a1 * $ic1 + $a2 * v3;
|
|
68
|
+
const v2 = $ic2 + $a2 * $ic1 + $a3 * v3;
|
|
69
|
+
$ic1 = 2 * v1 - $ic1;
|
|
70
|
+
$ic2 = 2 * v2 - $ic2;
|
|
71
|
+
m[${o} + i] = ${out};
|
|
72
|
+
`,post:`st[${st}] = flush($ic1);
|
|
73
|
+
st[${st+1}] = flush($ic2);
|
|
74
|
+
`}}function adsrParts(s,n2){let c=s.ctlBase[n2],st=s.stBase[n2],gate=port(s,n2,0),o=port(s,n2,5);return{pre:`const $attack = ctl[${c+1}];
|
|
75
|
+
const $decay = ctl[${c+2}];
|
|
76
|
+
const $sustain = ctl[${c+3}];
|
|
77
|
+
const $release = ctl[${c+4}];
|
|
78
|
+
const $up = $attack > 0 ? 1 / ($attack * f.sampleRate) : 1;
|
|
79
|
+
const $down = $decay > 0 ? (1 - $sustain) / ($decay * f.sampleRate) : 1;
|
|
80
|
+
let $stage = st[${st}];
|
|
81
|
+
let $level = st[${st+1}];
|
|
82
|
+
let $step = st[${st+2}];
|
|
83
|
+
`,body:`if (m[${gate} + i] > 0.5) {
|
|
84
|
+
if ($stage === 0 || $stage === 4) $stage = 1;
|
|
85
|
+
} else if ($stage >= 1 && $stage <= 3) {
|
|
86
|
+
$stage = 4;
|
|
87
|
+
$step = $release > 0 ? $level / ($release * f.sampleRate) : $level;
|
|
88
|
+
}
|
|
89
|
+
if ($stage === 1) {
|
|
90
|
+
$level += $up;
|
|
91
|
+
if ($level >= 1) { $level = 1; $stage = 2; }
|
|
92
|
+
} else if ($stage === 2) {
|
|
93
|
+
$level -= $down;
|
|
94
|
+
if ($level <= $sustain) { $level = $sustain; $stage = 3; }
|
|
95
|
+
} else if ($stage === 3) $level = $sustain;
|
|
96
|
+
else if ($stage === 4) {
|
|
97
|
+
$level -= $step;
|
|
98
|
+
if ($level <= 0) { $level = 0; $stage = 0; }
|
|
99
|
+
}
|
|
100
|
+
m[${o} + i] = $level;
|
|
101
|
+
`,post:`st[${st}] = $stage;
|
|
102
|
+
st[${st+1}] = $level;
|
|
103
|
+
st[${st+2}] = $step;
|
|
104
|
+
`}}function vcaParts(s,n2){return{pre:"",body:`m[${port(s,n2,2)} + i] = m[${port(s,n2,0)} + i] * m[${port(s,n2,1)} + i];
|
|
105
|
+
`,post:""}}function mixParts(s,n2){let c=s.ctlBase[n2],[a,b,cc,d,o]=[0,1,2,3,8].map(k=>port(s,n2,k));return{pre:`const $pa = prev[${c+4}];
|
|
106
|
+
const $pb = prev[${c+5}];
|
|
107
|
+
const $pc = prev[${c+6}];
|
|
108
|
+
const $pd = prev[${c+7}];
|
|
109
|
+
const $da = (ctl[${c+4}] - $pa) / ${32};
|
|
110
|
+
const $db = (ctl[${c+5}] - $pb) / ${32};
|
|
111
|
+
const $dc = (ctl[${c+6}] - $pc) / ${32};
|
|
112
|
+
const $dd = (ctl[${c+7}] - $pd) / ${32};
|
|
113
|
+
`,body:`const r = i + 1;
|
|
114
|
+
m[${o} + i] = m[${a} + i] * ($pa + $da * r) + m[${b} + i] * ($pb + $db * r) + m[${cc} + i] * ($pc + $dc * r) + m[${d} + i] * ($pd + $dd * r);
|
|
115
|
+
`,post:""}}function panParts(s,n2){let c=s.ctlBase[n2],[x,l,r]=[0,2,3].map(k=>port(s,n2,k));return{pre:`const $t0 = ((prev[${c+1}] + 1) * Math.PI) / 4;
|
|
116
|
+
const $t1 = ((ctl[${c+1}] + 1) * Math.PI) / 4;
|
|
117
|
+
const $l0 = Math.cos($t0);
|
|
118
|
+
const $r0 = Math.sin($t0);
|
|
119
|
+
const $dl = (Math.cos($t1) - $l0) / ${32};
|
|
120
|
+
const $dr = (Math.sin($t1) - $r0) / ${32};
|
|
121
|
+
`,body:`const v = m[${x} + i];
|
|
122
|
+
m[${l} + i] = v * ($l0 + $dl * (i + 1));
|
|
123
|
+
m[${r} + i] = v * ($r0 + $dr * (i + 1));
|
|
124
|
+
`,post:""}}function voiceParts(s,n2,used){let pre=`const $note = voice.note;
|
|
125
|
+
const $pos = voice.pos;
|
|
126
|
+
`,body2="",post="",value=["$note.pitch","$note.note","","$note.velocity","","voice.random","voice.index",""];for(let k=0;k<8;k+=1){if(!(used&1<<k))continue;let o=port(s,n2,k);k===2?body2+=`m[${o} + i] = $pos + i < $note.end ? 1 : 0;
|
|
127
|
+
`:k===4?(pre+=`const $inc = $note.pitch / sr;
|
|
128
|
+
let $p = voice.phase;
|
|
129
|
+
`,body2+=`m[${o} + i] = $p;
|
|
130
|
+
$p += $inc;
|
|
131
|
+
if ($p >= 1) $p -= Math.floor($p);
|
|
132
|
+
`,post+=`voice.phase = $p;
|
|
133
|
+
`):k===7?body2+=`m[${o} + i] = ($pos - $note.start + i) / sr;
|
|
134
|
+
`:(pre+=`const $v${k} = ${value[k]};
|
|
135
|
+
`,body2+=`m[${o} + i] = $v${k};
|
|
136
|
+
`)}return{pre:scoped(pre,n2),body:scoped(body2,n2),post:scoped(post,n2)}}function kernelParts(s,n2){let p;switch(s.op[n2]){case 7:p=oscParts(s,n2);break;case 9:p=svfParts(s,n2);break;case 11:p=adsrParts(s,n2);break;case 32:p=vcaParts(s,n2);break;case 33:p=mixParts(s,n2);break;case 35:p=panParts(s,n2);break;default:return null}return{pre:scoped(p.pre,n2),body:scoped(p.body,n2),post:scoped(p.post,n2)}}function lit(x){if(Object.is(x,-0))return"(-0)";if(x!==x)return"NaN";if(x===1/0)return"Infinity";if(x===-1/0)return"(-Infinity)";let s=String(x);return x<0?`(${s})`:s}function inputCode(section,consts,record2,first){let rec=section.inputs,cab=section.cables,r=record2*INPUT_WIDTH,kind=rec[r+0],c0=rec[r+8]*2,c1=c0+rec[r+9]*2,cables=[];for(let c=c0;c<c1;c+=2)cables.push({x:voiceAddr(cab[c]),a:lit(consts[cab[c+1]])});let q3=`$r${record2}`;if(kind===1){let o=voiceAddr(rec[r+1]);if(cables.every(c=>c.x!==o)){let terms=cables.map(c=>`m[${c.x} + i] * ${c.a}`);return{pre:"",body:`m[${o} + i] = ${terms.join(" + ")};
|
|
137
|
+
`,post:"",blockReads:[],write:o,fusable:!0}}let code2=`for (let i = 0; i < ${32}; i += 1) m[${o} + i] = m[${cables[0].x} + i] * ${cables[0].a};
|
|
138
|
+
`;for(let c of cables.slice(1))code2+=`for (let i = 0; i < ${32}; i += 1) m[${o} + i] += m[${c.x} + i] * ${c.a};
|
|
139
|
+
`;return{pre:code2,body:"",post:"",blockReads:[],write:-1,fusable:!1}}let slot=rec[r+2],cl=rec[r+6],lo=cl>=0?lit(consts[cl]):"(-Infinity)",hi=cl>=0?lit(consts[cl+1]):"Infinity",bi=rec[r+4],mp=rec[r+5],baseKind=rec[r+3],blockReads=[],base;if(baseKind===0)base=lit(consts[bi]);else{baseKind!==1&&blockReads.push(voiceAddr(bi));let raw=baseKind===1?`ctx.ext[${bi}]`:`m[${voiceAddr(bi)+32-1}]`;base=mp>=0?`mapMacro(${raw}, k[${mp}], k[${mp+1}], k[${mp+2}] === 1, k[${mp+3}], k[${mp+4}])`:raw}let settle=value=>`{
|
|
140
|
+
let v = ${value};
|
|
141
|
+
if (v !== v) { v = 0; ctx.scrubbed += 1; }
|
|
142
|
+
`+(first?`prev[${slot}] = v;
|
|
143
|
+
`:`prev[${slot}] = ctl[${slot}];
|
|
144
|
+
`)+`ctl[${slot}] = v;
|
|
145
|
+
}
|
|
146
|
+
`;if(kind===3){let o=voiceAddr(rec[r+1]);if(cables.every(c=>c.x!==o)){let sum=`${q3}base`;for(let c of cables)sum=`(${sum}) + m[${c.x} + i] * ${c.a}`;let v=cl>=0?`v < ${lo} ? ${lo} : v > ${hi} ? ${hi} : v`:"v";return{pre:`const ${q3}base = ${base};
|
|
147
|
+
let ${q3}last = 0;
|
|
148
|
+
`,body:`{
|
|
149
|
+
const v = ${sum};
|
|
150
|
+
const w = ${v};
|
|
151
|
+
m[${o} + i] = w;
|
|
152
|
+
${q3}last = w;
|
|
153
|
+
}
|
|
154
|
+
`,post:settle(`${q3}last`),blockReads,write:o,fusable:!0}}let code2=`{
|
|
155
|
+
const base = ${base};
|
|
156
|
+
for (let i = 0; i < ${32}; i += 1) m[${o} + i] = base;
|
|
157
|
+
`;for(let c of cables)code2+=`for (let i = 0; i < ${32}; i += 1) m[${o} + i] += m[${c.x} + i] * ${c.a};
|
|
158
|
+
`;return cl>=0&&(code2+=`for (let i = 0; i < ${32}; i += 1) { const v = m[${o} + i]; m[${o} + i] = v < ${lo} ? ${lo} : v > ${hi} ? ${hi} : v; }
|
|
159
|
+
`),code2+=`}
|
|
160
|
+
${settle(`m[${o+32-1}]`)}`,{pre:code2,body:"",post:"",blockReads,write:-1,fusable:!1}}let code=`{
|
|
161
|
+
let value = ${base};
|
|
162
|
+
`;for(let c of cables)blockReads.push(c.x),code+=`value += m[${c.x+32-1}] * ${c.a};
|
|
163
|
+
`;return code+=`if (value < ${lo}) value = ${lo};
|
|
164
|
+
else if (value > ${hi}) value = ${hi};
|
|
165
|
+
`,code+=`${settle("value")}}
|
|
166
|
+
`,{pre:code,body:"",post:"",blockReads,write:-1,fusable:!0}}function stillValues(section,consts){let rec=section.inputs,known=new Map,hot=new Set(section.hot);for(let n2=0;n2<section.op.length;n2+=1)for(let j=0;j<section.inCount[n2];j+=1){let record2=section.inStart[n2]+j,r=record2*INPUT_WIDTH;if(hot.has(record2)||rec[r+0]!==2||rec[r+9]!==0||rec[r+3]!==0)continue;let cl=rec[r+6],lo=cl>=0?consts[cl]:-1/0,hi=cl>=0?consts[cl+1]:1/0,value=consts[rec[r+4]];value<lo?value=lo:value>hi&&(value=hi),value!==value&&(value=0),known.set(rec[r+2],value)}return known}var CALL=/Math\.(sin|cos|tan|pow|exp|log)\(/,LOOP="/*loop*/",END="/*end*/",REF=/(?<![\w$])m\[(\d+)( \+ [^\]]+)?\]/g;function localize(code,keep){let parts=code.split(LOOP),loops=parts.slice(1).map(p=>p.split(END)),outside=[parts[0],...loops.map(l=>l[1])].join(`
|
|
167
|
+
`),owner=new Map,bad=new Set,base=x=>x-x%32;for(let r of outside.matchAll(REF))bad.add(base(Number(r[1])));loops.forEach(([loop],j)=>{for(let r of loop.matchAll(REF)){let x=Number(r[1]);r[2]!==" + i"||x%32!==0?bad.add(base(x)):(owner.get(x)??j)!==j?bad.add(x):owner.set(x,j)}});let out=[parts[0]];return loops.forEach(([loop,rest],j)=>{let decl="",text2=loop;for(let[x,o]of owner){if(o!==j||bad.has(x)||keep.has(x))continue;let at3=text2.indexOf(`m[${x} + i]`);text2.startsWith(`m[${x} + i] = `,at3)&&(decl+=`let s${x} = 0;
|
|
168
|
+
`,text2=text2.split(`m[${x} + i] = `).join(`s${x} = `),text2=text2.split(`m[${x} + i]`).join(`s${x}`))}out.push(decl+text2+rest)}),out.join("")}function fuseVoice(section,consts,first,kernelOf2,deps,io={fanOuts:new Int32Array(0),voiceSums:new Int32Array(0)},sampleRate){let rec=section.inputs,body2="",head="",blockConst=new Map,group=[],written=new Set,close=()=>{group.length===1?body2+=standalone(group[0]):group.length>1&&(body2+=`{
|
|
169
|
+
${group.map(g=>g.pre).join("")}${LOOP}for (let i = 0; i < ${32}; i += 1) {
|
|
170
|
+
${group.map(g=>`{
|
|
171
|
+
${g.body}}
|
|
172
|
+
`).join("")}}${END}
|
|
173
|
+
${group.map(g=>g.post).join("")}}
|
|
174
|
+
`),group=[],written=new Set},portsEnd=n2=>n2+1<section.op.length?section.slotBase[n2+1]:section.slots.length,keep=new Set,sumPairs=[];for(let k=0;k<io.voiceSums.length;k+=2)keep.add(voiceAddr(io.voiceSums[k])),sumPairs.push([voiceAddr(io.voiceSums[k]),io.voiceSums[k+1]]);for(let d=0;d<section.delays.length;d+=2)keep.add(voiceAddr(section.delays[d]));let voiceOp=section.ids.indexOf("voice");for(let n2=0;n2<section.op.length;n2+=1){if(n2===voiceOp){let vp=voiceParts(section,n2,deps.voiceUsed);head+=vp.pre;let vbody=vp.body.split(`
|
|
175
|
+
`).filter(line=>{let c=/^m\[(\d+) \+ i\] = (n\d+_v\d+);$/.exec(line);return c?(blockConst.set(Number(c[1]),c[2]),!1):!0}).join(`
|
|
176
|
+
`);group.push({pre:"",body:vbody,post:vp.post});let end2=n2+1<section.op.length?section.slotBase[n2+1]:section.slots.length;for(let k=section.slotBase[n2];k<end2;k+=1)written.add(voiceAddr(section.slots[k]));continue}let records=[];if(first)for(let j=0;j<section.inCount[n2];j+=1){let record2=section.inStart[n2]+j;rec[record2*INPUT_WIDTH+0]!==0&&records.push(record2)}else for(let j=0;j<section.hotCount[n2];j+=1)records.push(section.hot[section.hotStart[n2]+j]);let inputs2=records.map(record2=>inputCode(section,consts,record2,first)),parts=kernelParts(section,n2);if(!parts||!inputs2.every(x=>x.fusable)){close();for(let x of inputs2)body2+=scoped(x.body?standalone(x):x.pre+x.post,n2);let call=parts?standalone(parts):kernelOf2(section.op[n2],n2);if(!parts)for(let k=section.slotBase[n2];k<portsEnd(n2);k+=1)keep.add(voiceAddr(section.slots[k]));call&&(body2+=call+`
|
|
177
|
+
`);continue}let alone=CALL.test(parts.body);(alone||inputs2.some(x=>x.blockReads.some(o=>written.has(o))))&&close(),group.push({pre:scoped(inputs2.map(x=>x.pre).join(""),n2)+parts.pre,body:scoped(inputs2.map(x=>x.body).join(""),n2)+parts.body,post:scoped(inputs2.map(x=>x.post).join(""),n2)+parts.post});for(let x of inputs2)x.write>=0&&written.add(x.write);if(alone){close();continue}let end=n2+1<section.op.length?section.slotBase[n2+1]:section.slots.length;for(let k=section.slotBase[n2]+section.nIn[n2];k<end;k+=1)written.add(voiceAddr(section.slots[k]))}let sums=sumPairs.length>0&&new Set(sumPairs.map(p=>p[1])).size===sumPairs.length;if(sums){let sumBody="",pre="";sumPairs.forEach(([x,g],j)=>{pre+=`const sd${j} = ${g} * stride + sumAt;
|
|
178
|
+
`,sumBody+=`{
|
|
179
|
+
const x = m[${x} + i];
|
|
180
|
+
if (sumAt < 0) out[${x} + i] = x;
|
|
181
|
+
else if (x - x === 0) gm[sd${j} + i] += x;
|
|
182
|
+
else ctx.scrubbed += 1;
|
|
183
|
+
}
|
|
184
|
+
`}),group.push({pre,body:sumBody,post:""});for(let[x]of sumPairs)keep.delete(x)}close();for(let[x,name]of blockConst)body2=body2.replace(REF,(ref,at3)=>Number(at3)-Number(at3)%32===x?name:ref),keep.has(x)&&(body2=`for (let i = 0; i < ${32}; i += 1) m[${x} + i] = ${name};
|
|
185
|
+
${body2}`);body2=head+body2,body2=localize(body2,keep);let direct=new Set,fans="";for(let k=0;k<io.fanOuts.length;k+=2){let d=voiceAddr(io.fanOuts[k+1]);keep.has(d)||(direct.add(d),fans+=`const F${d} = fanAt >= 0 ? gm : m;
|
|
186
|
+
const o${d} = fanAt >= 0 ? ${io.fanOuts[k]} * stride + fanAt : ${d};
|
|
187
|
+
`)}body2=body2.replace(REF,(ref,at3,rest)=>{let x=Number(at3),d=x-x%32;return direct.has(d)?rest?`F${d}[o${d} + ${x-d}${rest}]`:`F${d}[o${d} + ${x-d}]`:ref});function fold(){let known=stillValues(section,consts);body2=body2.split("f.sampleRate").join(lit(sampleRate)),body2=body2.replace(/(?<![\w$])(ctl|prev)\[(\d+)\](?!\s*=[^=])/g,(ref,_a,c)=>{let value=known.get(Number(c));return value===void 0?ref:lit(value)})}let names=Object.keys(deps);sampleRate!==void 0&&fold();let code=`"use strict";
|
|
188
|
+
${KERNEL_HELPERS}
|
|
189
|
+
return function fused(f, ctx, voice, sr, gm, stride, fanAt, sumAt) {
|
|
190
|
+
const m = f.m;
|
|
191
|
+
const out = m;
|
|
192
|
+
${fans}const st = f.st;
|
|
193
|
+
const ctl = f.ctl;
|
|
194
|
+
const prev = f.prev;
|
|
195
|
+
const k = ctx.consts;
|
|
196
|
+
${body2}};`,fn=new Function("mapMacro",...names,code)(mapMacro,...names.map(name=>deps[name]));return Object.assign(fn,{direct,sums})}var FADE_SECONDS=.002,SILENCE=Math.pow(10,-90/20),SILENCE_SECONDS=.05,TAIL_SECONDS=.1;function frameOf(section,m,ctl,prev,st,stride,local,sampleRate,beatSlot){return{m,ctl,prev,st,stride,blk:0,local,sampleRate,bps:2,slotBase:section.slotBase,slots:section.slots,ctlBase:section.ctlBase,stBase:section.stBase,mode:section.mode,nIn:section.nIn,beatSlot}}function addr(f,s){return s>=0?s*f.stride+f.blk:f.local-(s+1)*32}function prologue(f,section,ctx,n2,first){let rec=section.inputs,cab=section.cables,k=ctx.consts,m=f.m,ctl=f.ctl,prev=f.prev,hot=section.hot,start=first?section.inStart[n2]:section.hotStart[n2],count2=first?section.inCount[n2]:section.hotCount[n2];for(let j=0;j<count2;j+=1){let r=(first?start+j:hot[start+j])*INPUT_WIDTH,kind=rec[r+0];if(kind===0)continue;let cables=rec[r+9],c0=rec[r+8]*2,c1=c0+cables*2;if(kind===1){let o=addr(f,rec[r+1]),x0=addr(f,cab[c0]),a0=k[cab[c0+1]];for(let i=0;i<32;i+=1)m[o+i]=m[x0+i]*a0;for(let c=c0+2;c<c1;c+=2){let x=addr(f,cab[c]),a=k[cab[c+1]];for(let i=0;i<32;i+=1)m[o+i]+=m[x+i]*a}continue}let slot=rec[r+2],baseKind=rec[r+3],bi=rec[r+4],mp=rec[r+5],cl=rec[r+6],lo=cl>=0?k[cl]:-1/0,hi=cl>=0?k[cl+1]:1/0,base;if(baseKind===0)base=k[bi];else{let raw=baseKind===1?ctx.ext[bi]:m[addr(f,bi)+32-1];base=mp>=0?mapMacro(raw,k[mp],k[mp+1],k[mp+2]===1,k[mp+3],k[mp+4]):raw}let value;if(kind===3&&cables===1){let o=addr(f,rec[r+1]),x=addr(f,cab[c0]),a=k[cab[c0+1]];for(let i=0;i<32;i+=1){let v=base+m[x+i]*a;m[o+i]=v<lo?lo:v>hi?hi:v}value=m[o+32-1]}else if(kind===3){let o=addr(f,rec[r+1]);put(m,base,o);for(let c=c0;c<c1;c+=2){let x=addr(f,cab[c]),a=k[cab[c+1]];for(let i=0;i<32;i+=1)m[o+i]+=m[x+i]*a}if(cl>=0)for(let i=0;i<32;i+=1){let v=m[o+i];m[o+i]=v<lo?lo:v>hi?hi:v}value=m[o+32-1]}else{value=base;for(let c=c0;c<c1;c+=2)value+=m[addr(f,cab[c])+32-1]*k[cab[c+1]];value<lo?value=lo:value>hi&&(value=hi)}value!==value&&(value=0,ctx.scrubbed+=1),prev[slot]=first?value:ctl[slot],ctl[slot]=value}}function kernel(f,section,n2){switch(section.op[n2]){case 7:return osc(f,n2);case 8:return noise(f,n2);case 9:return svf(f,n2);case 10:return onepole(f,n2);case 11:return adsr(f,n2);case 12:return ar(f,n2);case 13:return slew(f,n2);case 14:return follow(f,n2);case 15:return lfo2(f,n2);case 16:return sh(f,n2);case 17:return random(f,n2);case 18:return constant2(f,n2);case 19:return binary2(f,n2,0);case 20:return binary2(f,n2,1);case 21:return binary2(f,n2,2);case 22:return binary2(f,n2,3);case 23:return binary2(f,n2,4);case 24:return binary2(f,n2,5);case 25:return unary2(f,n2,0);case 26:return unary2(f,n2,1);case 27:return unary2(f,n2,2);case 28:return unary2(f,n2,3);case 29:return scale(f,n2);case 30:return clamp3(f,n2);case 31:return clock2(f,n2);case 32:return vca(f,n2);case 33:return mix2(f,n2);case 34:return xfade(f,n2);case 35:return pan(f,n2);case 5:return pass(f,n2);case 6:return macro(f,n2);default:return}}function scrubState(st,ctx){for(let i=0;i<st.length;i+=1){let v=st[i];v-v!==0&&(st[i]=0,ctx.scrubbed+=1)}}function copyDelays(f,delays){let m=f.m;for(let d=0;d<delays.length;d+=2){let x=addr(f,delays[d]),o=addr(f,delays[d+1]);for(let i=0;i<32;i+=1){let v=m[x+i];m[o+i]=v-v===0?v:0}}}var valueAt=(source,block,fallback)=>source===void 0?fallback:typeof source=="number"?source:source[Math.min(block,source.length-1)]??fallback;function runPatch(program,options){let{frames,sampleRate}=options,blocks=Math.ceil(frames/32),stride=(blocks+1)*32,g=program.global,ctx={program,consts:program.consts,ext:new Float64Array(program.macros.length),sampleRate,scrubbed:0},macroValues2=options.macros??[],setExt=block=>{for(let i=0;i<program.macros.length;i+=1)ctx.ext[i]=valueAt(macroValues2[i],block,program.macros[i].default)},tempo=options.tempo??120,beatsPerBar=options.beatsPerBar??4,local=g.fullSlots*stride,gm=new Float64Array(local+g.localSlots*32),gctl=new Float64Array(g.ctlCount),gprev=new Float64Array(g.ctlCount),gst=new Float64Array(g.stateCount),globalSeed=options.seed??program.name;for(let[cell2,node2]of g.seeds)gst[cell2]=seedHash(`${globalSeed}:patch:${node2}`)|0;let gf=frameOf(g,gm,gctl,gprev,gst,stride,local,sampleRate,program.beatSlot),left=new Float64Array(frames),right=program.stereo?new Float64Array(frames):void 0,beats=new Float64Array(blocks+1);{let beat2=options.beat0??0;for(let b=0;b<=blocks;b+=1)beats[b]=beat2,beat2+=valueAt(tempo,b,120)/60*(32/sampleRate)}let runGlobal=(phase,b,first)=>{gf.blk=b*32;let bpm=valueAt(tempo,b,120);gf.bps=bpm/60,setExt(b);for(let n2 of phase.nodes){let op=g.op[n2];op===1?song2(gf,n2,beats[b],bpm,sampleRate,beatsPerBar):op===0?inputs(gf,n2,options,b*32,frames):(prologue(gf,g,ctx,n2,first),op===3?output(gf,n2,left,right,b*32,frames):kernel(gf,g,n2))}copyDelays(gf,phase.delays),scrubState(gst,ctx)},runBuffer=phase=>{let n2=phase.node,node2=program.buffers.find(b=>b.id===g.ids[n2]),ins={},start=g.inStart[n2],bases={};node2.spec.inputs.forEach((port2,j)=>{let r=(start+j)*INPUT_WIDTH,count2=g.inputs[r+9],baseKind=g.inputs[r+3],bi=g.inputs[r+4];if(port2.kind==="control"&&(baseKind===1||baseKind===2&&bi>=0)){let mp=g.inputs[r+5],cl=g.inputs[r+6],k=program.consts,lo=cl>=0?k[cl]:-1/0,hi=cl>=0?k[cl+1]:1/0,values=new Float64Array(blocks);for(let b=0;b<blocks;b+=1){let raw;baseKind===1?(setExt(b),raw=ctx.ext[bi]):raw=gm[bi*stride+Math.min(frames-1,b*32)];let v=mp>=0?mapMacro(raw,k[mp],k[mp+1],k[mp+2]===1,k[mp+3],k[mp+4]):raw;values[b]=v<lo?lo:v>hi?hi:v}bases[port2.name]=values}if(port2.kind==="notes"||count2===0)return;let sum=new Float64Array(frames),c0=g.inputs[r+8]*2;for(let c=c0;c<c0+count2*2;c+=2){let x=g.cables[c]*stride,a=program.consts[g.cables[c+1]];for(let i=0;i<frames;i+=1)sum[i]+=gm[x+i]*a}ins[port2.name]=sum});let outs={};if(node2.spec.outputs.forEach((port2,j)=>{if(port2.kind==="notes")return;let slot=g.slots[g.slotBase[n2]+node2.spec.inputs.length+j];outs[port2.name]=gm.subarray(slot*stride,slot*stride+frames)}),!options.buffer)throw new Error(`node ${node2.id}: no handler for ${node2.type}`);options.buffer({node:node2,inputs:ins,bases,outputs:outs,frames,sampleRate});for(let buf of Object.values(outs))for(let i=0;i<frames;i+=1){let v=buf[i];v-v!==0&&(buf[i]=0,ctx.scrubbed+=1)}},runPhases=phases2=>{for(let phase of phases2)if(phase.kind==="buffer")runBuffer(phase);else for(let b=0;b<blocks;b+=1)runGlobal(phase,b,b===0)};runPhases(program.pre);let stolen=program.voices>0?runVoices(program,options,ctx,gm,stride):0;return runPhases(program.post),ctx.scrubbed+=scrub(left)+(right?scrub(right):0),{left,...right?{right}:{},stolen,scrubbed:ctx.scrubbed}}function scrub(buffer){let count2=0;for(let i=0;i<buffer.length;i+=1){let v=buffer[i];v-v!==0&&(buffer[i]=0,count2+=1)}return count2}function song2(f,n2,beat2,bpm,sr,perBar){let m=f.m,ob=at(f,n2,0),op=at(f,n2,1),ot=at(f,n2,2),step2=bpm/60/sr;for(let i=0;i<32;i+=1){let x=beat2+step2*i;m[ob+i]=x;let bar=x/perBar;m[op+i]=bar-Math.floor(bar),m[ot+i]=bpm}}function inputs(f,n2,o,pos,frames){let sources=[void 0,o.audio,o.right??o.audio,o.side];for(let k=1;k<4;k+=1){if(f.slots[f.slotBase[n2]+k]===-1)continue;let dst=at(f,n2,k),src=sources[k];for(let i=0;i<32;i+=1){let x=pos+i;f.m[dst+i]=src!==void 0&&x<frames?src[x]??0:0}}}function output(f,n2,left,right,pos,frames){let a=at(f,n2,0),r=at(f,n2,1),end=Math.min(32,frames-pos);for(let i=0;i<end;i+=1)left[pos+i]=f.m[a+i],right&&(right[pos+i]=f.m[r+i])}var FUSED=new WeakMap,KERNEL_NAMES={7:"osc",8:"noise",9:"svf",10:"onepole",11:"adsr",12:"ar",13:"slew",14:"follow",15:"lfo",16:"sh",17:"random",18:"constant",29:"scale",30:"clamp",31:"clock",32:"vca",33:"mix",34:"xfade",35:"pan",5:"pass",6:"macro"},BINARY_OPS={19:0,20:1,21:2,22:3,23:4,24:5},UNARY_OPS={25:0,26:1,27:2,28:3},kernelOf=(op,n2)=>KERNEL_NAMES[op]!==void 0?`${KERNEL_NAMES[op]}(f, ${n2});`:BINARY_OPS[op]!==void 0?`binary(f, ${n2}, ${BINARY_OPS[op]});`:UNARY_OPS[op]!==void 0?`unary(f, ${n2}, ${UNARY_OPS[op]});`:null;function fusedOf(program,sampleRate){let bySr=FUSED.get(program);bySr||FUSED.set(program,bySr=new Map);let fused=bySr.get(sampleRate);if(fused)return fused;let deps={voiceUsed:program.voiceUsed,osc,noise,svf,onepole,adsr,ar,slew,follow,lfo:lfo2,sh,random,constant:constant2,scale,clamp:clamp3,clock:clock2,vca,mix:mix2,xfade,pan,pass,macro,binary:binary2,unary:unary2},v=program.voice;return fused=[fuseVoice(v,program.consts,!0,kernelOf,deps,program,sampleRate),fuseVoice(v,program.consts,!1,kernelOf,deps,program,sampleRate)],bySr.set(sampleRate,fused),fused}function runVoices(program,options,ctx,gm,stride){let v=program.voice,sr=options.sampleRate,frames=options.frames,tempo=options.tempo??120,macroValues2=options.macros??[],notes=[...options.notes??[]].filter(note2=>note2.start<frames&¬e2.end>note2.start).sort((a,b)=>a.start-b.start||(a.seed<b.seed?-1:a.seed>b.seed?1:0)),fade=Math.max(1,Math.round(FADE_SECONDS*sr)),quietLimit=Math.round(SILENCE_SECONDS*sr),tail=Math.round((program.maxRelease+TAIL_SECONDS)*sr),pool=[],playing=[],fanOuts=program.fanOuts,sums=program.voiceSums,voiceOp=v.ids.indexOf("voice"),[fusedFirst,fusedNext]=fusedOf(program,sr),fuse=options.fuse??!0,macroCount=program.macros.length,stolen=0,order=0,acquire=(note2,index)=>{let voice=pool.pop()??newVoice();voice.m.fill(0),voice.ctl.fill(0),voice.prev.fill(0),voice.st.fill(0);for(let[cell2,node2]of v.seeds)voice.st[cell2]=seedHash(`${note2.seed}:patch:${node2}`)|0;return voice.index=index,voice.note=note2,voice.order=order++,voice.pos=note2.start,voice.first=!0,voice.phase=0,voice.random=seedHash(`${note2.seed}:patch:voice`)/4294967296,voice.quiet=0,voice.fadeAt=1/0,voice.done=!1,voice};function newVoice(){let m=new Float64Array(v.localSlots*32),ctl=new Float64Array(v.ctlCount),prev=new Float64Array(v.ctlCount),st=new Float64Array(v.stateCount);return{m,ctl,prev,st,frame:frameOf(v,m,ctl,prev,st,32,0,sr,0),index:0,note:void 0,order:0,pos:0,first:!0,phase:0,random:0,quiet:0,fadeAt:1/0,done:!1}}let block=voice=>{let f=voice.frame,pos=voice.pos,gb=Math.floor(pos/32),bpm=valueAt(tempo,gb,120);f.bps=bpm/60;let endBlock=Math.floor((pos+32-1)/32);for(let i=0;i<macroCount;i+=1)ctx.ext[i]=valueAt(macroValues2[i],endBlock,program.macros[i].default);let fused=voice.first?fusedFirst:fusedNext,fanAt=pos;for(let k=0;k<fanOuts.length;k+=2)fanOuts[k]*stride+pos+32>gm.length&&(fanAt=-1);for(let k=0;k<fanOuts.length;k+=2){let dst=addr(f,fanOuts[k+1]);if(fuse&&fanAt>=0&&fused.direct.has(dst))continue;let src=fanOuts[k]*stride+pos,vm2=f.m;if(src+32<=gm.length)for(let i=0;i<32;i+=1)vm2[dst+i]=gm[src+i];else for(let i=0;i<32;i+=1)vm2[dst+i]=gm[src+i]??0}let fadeAt=voice.fadeAt,gateOff=voice.note.end,plain=fadeAt>=pos+32&&pos+32<=stride-32,track2=pos+32>gateOff,sumAt=fuse&&fused.sums&&plain&&!track2?pos:-1;if(fuse)fused(f,ctx,voice,sr,gm,stride,fanAt,sumAt);else for(let node2=0;node2<v.op.length;node2+=1){if(node2===voiceOp){voiceSources(f,node2,voice,sr,program.voiceUsed);continue}prologue(f,v,ctx,node2,voice.first),kernel(f,v,node2)}copyDelays(f,v.delays),scrubState(voice.st,ctx),voice.first=!1;let peak=0,vm=f.m;for(let k=0;k<sums.length&&sumAt<0;k+=2){let src=addr(f,sums[k]),dst=sums[k+1]*stride+pos;if(plain&&!track2){for(let i=0;i<32;i+=1){let x=vm[src+i];x-x===0?gm[dst+i]+=x:ctx.scrubbed+=1}continue}for(let i=0;i<32;i+=1){let x=vm[src+i];x-x!==0&&(x=0,ctx.scrubbed+=1);let t=pos+i;t>=fadeAt&&(x*=t-fadeAt>=fade?0:1-(t-fadeAt+1)/fade),t<stride-32&&(gm[dst+i]+=x);let a=x<0?-x:x;a>peak&&(peak=a)}}voice.pos=pos+32,voice.pos>=fadeAt+fade?voice.done=!0:pos>=gateOff&&(voice.quiet=peak<SILENCE?voice.quiet+32:0,(voice.quiet>=quietLimit||voice.pos>=gateOff+tail)&&(voice.done=!0)),voice.pos>=frames&&(voice.done=!0)},advance=until=>{for(let voice of playing)for(;!voice.done&&voice.pos+32<=until;)block(voice);for(let i=playing.length-1;i>=0;i-=1)playing[i].done&&pool.push(...playing.splice(i,1))};for(let note2 of notes){advance(note2.start);let owners=playing.filter(p=>p.fadeAt===1/0),index=-1;if(owners.length<program.voices){let used=new Set(owners.map(p=>p.index));for(index=0;used.has(index);)index+=1}else{let oldest=owners.reduce((a,b)=>b.order<a.order?b:a);oldest.fadeAt=note2.start,index=oldest.index,stolen+=1}playing.push(acquire(note2,index))}return advance(1/0),stolen}function voiceSources(f,n2,voice,sr,used){let m=f.m,note2=voice.note,pos=voice.pos;if(used&1){let o=at(f,n2,0);put(m,note2.pitch,o)}if(used&2){let o=at(f,n2,1);put(m,note2.note,o)}if(used&4){let o=at(f,n2,2);for(let i=0;i<32;i+=1)m[o+i]=pos+i<note2.end?1:0}if(used&8){let o=at(f,n2,3);put(m,note2.velocity,o)}if(used&16){let o=at(f,n2,4),inc=note2.pitch/sr,p=voice.phase;for(let i=0;i<32;i+=1)m[o+i]=p,p+=inc,p>=1&&(p-=Math.floor(p));voice.phase=p}if(used&32){let o=at(f,n2,5);put(m,voice.random,o)}if(used&64){let o=at(f,n2,6);put(m,voice.index,o)}if(used&128){let o=at(f,n2,7);for(let i=0;i<32;i+=1)m[o+i]=(pos-note2.start+i)/sr}}var DEVICE_DIR="devices";var DEVICE_TAIL_SECONDS=2;function deviceHash(bytes2){return`sha256:${createHash2("sha256").update(bytes2).digest("hex")}`}var COMPILED=new Map,CACHE_SIZE2=32,VERIFIED=new WeakMap;function compiledDevice(hash,bytes2){let actual=VERIFIED.get(bytes2);if(actual===void 0&&(actual=deviceHash(bytes2),VERIFIED.set(bytes2,actual)),actual!==hash)throw new Error(`device ${hash.slice(0,19)}\u2026 does not match its bytes`);let hit2=COMPILED.get(hash);if(hit2)return COMPILED.delete(hash),COMPILED.set(hash,hit2),hit2;let compiled=compileDevice(bytes2);for(COMPILED.set(hash,compiled);COMPILED.size>CACHE_SIZE2;)COMPILED.delete(COMPILED.keys().next().value);return compiled}function startDevice(hash,kind,devices,sampleRate,label){if(typeof hash!="string")throw new Error(`${label}: no device hash`);let bytes2=devices?.get(hash);if(!bytes2)throw new Error(`${label}: device ${hash.slice(0,19)}\u2026 is not loaded \xB7 put its .wasm file in the project's ${DEVICE_DIR}/ folder`);let compiled=compiledDevice(hash,bytes2);if(compiled.kind!==kind)throw new Error(`${label}: device ${hash.slice(0,19)}\u2026 is a ${compiled.kind} device, not ${kind}`);return new Device(compiled,sampleRate,label)}function controlAt(io,name,frame){let own=io.node.params[name],knob=io.bases?.[name],cable=io.inputs[name],value=(knob?knob[Math.min(knob.length-1,Math.floor(frame/32))]:typeof own=="number"?own:0)+(cable?cable[frame]:0);return Number.isFinite(value)?Math.min(1,Math.max(0,value)):0}function noteEvents(notes,frames){let events=[];return notes.forEach((note2,voice)=>{if(note2.start>=frames)return;let base={voice,note:Math.max(0,Math.min(127,Math.round(note2.note))),velocity:note2.velocity,hz:note2.pitch};events.push({...base,at:Math.max(0,note2.start),frame:0,on:!0}),note2.end<frames&&events.push({...base,at:Math.max(0,note2.end),frame:0,on:!1})}),events.sort((a,b)=>a.at-b.at||Number(a.on)-Number(b.on)||a.voice-b.voice)}function runDeviceNode(io,devices,notes){let{node:node2,outputs,frames}=io,synth=node2.type==="device.synth",device=startDevice(node2.params.device,synth?"synth":"fx",devices,io.sampleRate,`node ${node2.id}`),left=synth?outputs.out:outputs.left,right=outputs.right,inLeft=synth?void 0:io.inputs.left,inRight=synth?void 0:io.inputs.right??inLeft,events=synth?noteEvents(notes,frames):[],bufL=new Float64Array(128),bufR=new Float64Array(128),outL=new Float64Array(128),outR=new Float64Array(128),next=0;for(let start=0;start<frames;start+=128){let n2=Math.min(128,frames-start);for(let p=0;p<8;p+=1)device.params[p]=controlAt(io,`p${p+1}`,start);bufL.fill(0),bufR.fill(0),inLeft&&bufL.set(inLeft.subarray(start,start+n2)),inRight&&bufR.set(inRight.subarray(start,start+n2));let block=[];for(;next<events.length&&events[next].at<start+128&&block.length<DEVICE_LIMITS.maxEvents;){let e=events[next++];block.push({frame:Math.max(0,e.at-start),on:e.on,voice:e.voice,note:e.note,velocity:e.velocity,hz:e.hz})}device.block(synth?void 0:bufL,synth?void 0:bufR,block,outL,outR),left.set(outL.subarray(0,n2),start),right?.set(outR.subarray(0,n2),start)}}function noteDevice(patch){return patch.nodes.find(node2=>node2.type==="device.notes")}function transformPatchNotes(patch,notes,devices,sampleRate){let node2=noteDevice(patch);if(!node2)return[...notes];let device=startDevice(node2.params?.device,"notes",devices,sampleRate,`node ${node2.id}`);for(let p=0;p<8;p+=1){let value=node2.params?.[`p${p+1}`];device.params[p]=typeof value=="number"?value:0}let order=notes.map((note2,index)=>({note:note2,index})).sort((a,b)=>a.note.start-b.note.start||a.index-b.index),out=[],made=new Map;for(let i=0;i<order.length;i+=DEVICE_LIMITS.maxNotesIn){let chunk=order.slice(i,i+DEVICE_LIMITS.maxNotesIn).map(({note:note2,index})=>({start:note2.start,length:Math.max(1,note2.end-note2.start),pitch:note2.note,velocity:note2.velocity,source:index}));for(let result of device.transform(chunk)){let source=notes[result.source],k=made.get(result.source)??0;made.set(result.source,k+1);let start=Math.round(result.start);out.push({seed:`${source.seed}~${k}`,start,end:start+Math.max(1,Math.round(result.length)),pitch:source.pitch*2**((result.pitch-source.note)/12),note:Math.round(result.pitch),velocity:result.velocity})}}return out}var EMPTY_SAMPLE_BANK=Object.freeze({voices:new Map,problems:Object.freeze([])});function sampleKey(trackId,voice){return`${trackId}\0${voice}`}function hasClips(track2){return track2?.clips?.some(clip=>!clip.mute)??!1}function clipAudio(bank,trackId,clip){if(!bank)return;let exact=bank.voices.get(sampleKey(trackId,`${CLIP_VOICE_PREFIX}${clip.id}`));if(exact)return exact;let pass2=clip.id.lastIndexOf("~");return pass2>0?bank.voices.get(sampleKey(trackId,`${CLIP_VOICE_PREFIX}${clip.id.slice(0,pass2)}`)):void 0}function withClipLengths(score,bank){return!bank||!score.tracks.some(track2=>track2.clips)?score:resolveClipLengths(score,(trackId,clip)=>{let audio=clipAudio(bank,trackId,clip);return audio&&audio.frames>0?audio.frames/audio.sampleRate:void 0})}function sampleAt2(context,tick){return context.warp?context.warp.sample(tick):tick*context.samplesPerTick}function takeOf(track2,clip){if(clip.take!==void 0)return track2.takes?.find(take=>take.name===clip.take)}function readHermite(data,position){let base=Math.floor(position),t=position-base,at3=index=>index>=0&&index<data.length?data[index]:0,y0=at3(base-1),y1=at3(base),y2=at3(base+1),y3=at3(base+2),c1=.5*(y2-y0),c2=y0-2.5*y1+2*y2-.5*y3;return(((.5*(y3-y0)+1.5*(y1-y2))*t+c2)*t+c1)*t+y1}function equalPowerFade(x){return x<=0?0:x>=1?1:Math.sin(x*Math.PI/2)}function renderClips(target,track2,context,bank,gainAt,score){let missing=[];if(!track2.clips)return missing;let{sampleRate,samples}=context,tickAt4=index=>context.warp?context.warp.tick(index):index/context.samplesPerTick;for(let clip of track2.clips){if(clip.mute)continue;let audio=clipAudio(bank,track2.id,clip);if(!audio||audio.frames===0){missing.push(clip.id);continue}let take=takeOf(track2,clip),drift=1+(take?.ppm??0)/1e6,nudge=(take?.nudge??0)/1e3,fileSeconds=audio.frames/audio.sampleRate,offset=Math.min(fileSeconds,clip.offset??0),length=Math.max(0,Math.min(clip.dur??Number.POSITIVE_INFINITY,(fileSeconds-offset)/drift));if(length<=0)continue;let start=sampleAt2(context,clipSongTick(clip,track2.time))+nudge*sampleRate,total=length*sampleRate,first=Math.max(0,Math.ceil(start)),last=Math.min(samples,Math.ceil(start+total));if(first>=last)continue;let step2=audio.sampleRate/sampleRate*drift,begin=offset*audio.sampleRate,span4=length*audio.sampleRate*drift,fadeIn=Math.min(clip.fadeInTime??DEFAULT_CLIP_FADE,length/2),fadeOut=Math.min(clip.fadeTime??DEFAULT_CLIP_FADE,length/2),fadeInFrames=fadeIn*sampleRate,fadeOutFrames=fadeOut*sampleRate,gain=clip.gain??1,tuned=track2.autotune&&score&&!clip.rev?autotuneClip(score,track2,{sha256:audio.sha256,sampleRate:audio.sampleRate,mono:audio.mono},start/sampleRate,offset,clip.id,0,nudge):void 0,data=tuned?tuned.mono:audio.mono,shiftFrom=tuned?tuned.from:0,blockGain=0;for(let index=first;index<last;index+=1){(index-first)%32===0&&(blockGain=gainAt(tickAt4(index)));let elapsed=index-start,position=elapsed*step2;if(position>=span4)break;position=clip.rev?begin+span4-1-position:begin+position;let shape=gain*blockGain;fadeInFrames>0&&elapsed<fadeInFrames&&(shape*=equalPowerFade(elapsed/fadeInFrames));let remaining=total-elapsed;fadeOutFrames>0&&remaining<fadeOutFrames&&(shape*=equalPowerFade(remaining/fadeOutFrames)),target[index]+=readHermite(data,position-shiftFrom)*shape}}return missing}function clipsDigest(track2,bank,guide=!1){if(!(!track2.clips||track2.clips.length===0))return(guide?"guide|":"")+track2.clips.map(clip=>{let take=takeOf(track2,clip);return[clip.id,clipAudio(bank,track2.id,clip)?.sha256??`missing:${clip.sha256}`,clip.startTick,clip.offset??"",clip.dur??"",clip.gain??"",clip.fadeInTime??"",clip.fadeTime??"",clip.rev?"r":"",clip.mute?"m":"",take?`${take.ppm??0}/${take.nudge??0}`:""].join(",")}).join(";")}function sliceSongTime(score,pieces){if(!score.time?.tempo&&!score.time?.fermatas)return{tempoBpm:score.tempoBpm,...score.time?{time:score.time}:{}};let clampBpm=bpm=>Math.min(SCORE_LIMITS.maxTempoBpm,Math.max(SCORE_LIMITS.minTempoBpm,bpm)),map=timeMapFor(score),bpmAtTick3=(_score,tick)=>map?map.tempoAt(tick):score.tempoBpm,sorted=[...pieces].sort((a,b)=>a.offset-b.offset),first=sorted[0],tempoBpm=clampBpm(first&&first.offset===0?bpmAtTick3(score,first.from):score.tempoBpm),tempo=[],fermatas=[],current=tempoBpm;for(let piece of sorted){let shift=piece.offset-piece.from,inner=(score.time.tempo??[]).filter(event=>event.tick>=piece.from&&event.tick<piece.to),startBpm=clampBpm(bpmAtTick3(score,piece.from));piece.offset>0&&Math.abs(startBpm-current)>1e-9&&!inner.some(event=>event.tick===piece.from)&&tempo.push({tick:piece.offset,bpm:startBpm}),current=startBpm;for(let event of inner){let tick=event.tick+shift;if(tick<1){current=event.bpm;continue}tempo.push({...event,tick}),current=event.bpm}let crossing=(score.time.tempo??[]).find(event=>event.tick>=piece.to),lastTick=inner.at(-1)?.tick??piece.from;if(crossing?.ramp&&piece.to-1>lastTick){let bpm=clampBpm(bpmAtTick3(score,piece.to-1)),tick=piece.to-1+shift;tick>=1&&Math.abs(bpm-current)>1e-9&&tempo.push({tick,bpm,ramp:crossing.ramp})}current=clampBpm(bpmAtTick3(score,Math.max(piece.from,piece.to-1)));for(let fermata of score.time.fermatas??[])fermata.tick>=piece.from&&fermata.tick<piece.to&&fermatas.push({...fermata,tick:fermata.tick+shift})}let time=normalizeSongTime({...tempo.length>0?{tempo}:{},...fermatas.length>0?{fermatas}:{},...score.time.meter?{meter:score.time.meter}:{}});return{tempoBpm,...time?{time}:{}}}function bakeTrackTime(score,options={}){if(!hasTrackTime(score)||score.sections.length===0&&!options.always)return score;let seen=new Map,notes=performedNotes(score).map(note2=>{let count2=(seen.get(note2.id)??0)+1;return seen.set(note2.id,count2),{...note2,id:count2===1?note2.id:`${note2.id}~p${count2}`,startTick:Math.round(note2.startTick),durationTicks:Math.max(1,Math.round(note2.durationTicks))}});return withNoteCap(BAKED_NOTE_CAP,()=>new TrackScore({...score.toJSON(),tracks:score.tracks.map(track2=>{let{time:_time,...rest}=bakeClipTime(track2);return rest}),notes}))}var BAKED_NOTE_CAP=SCORE_LIMITS.maxNotes*64,SECTION_KINDS=Object.freeze(["intro","verse","pre","chorus","build","drop","breakdown","bridge","outro"]),MAX_SONG_SECONDS=900;function barTicks(score){return score.time?.meter?barStartTick(score,1):score.beatsPerBar*score.ticksPerBeat}function findSection(score,name){let key=foldName(name);return score.sections.find(section=>foldName(section.name)===key)}function foldName(name){return name.trim().replace(/\s+/gu," ").toLowerCase()}function formSegments(score){let segments=[],bar=0;return score.form.forEach((entry,index)=>{let section=findSection(score,entry.section);if(section)for(let pass2=0;pass2<(entry.repeat??1);pass2+=1)segments.push({section,entry:index,pass:pass2,startBar:bar,bars:section.bars}),bar+=section.bars}),segments}function arrangedBars(score){let segments=formSegments(score);if(segments.length===0)return score.bars;let last=segments[segments.length-1];return last.startBar+last.bars}function sectionAtBar(score,bar){let found;for(let section of score.sections)bar<section.startBar||bar>=section.startBar+section.bars||(!found||section.startBar>found.startBar)&&(found=section);return found}function transposes(track2){return!track2||isDrumInstrument(track2.instrument)?!1:isSamplerInstrument(track2.instrument)?track2.sampler?.mode==="keyed":!0}function varyNote(note2,variation,track2){if(!variation)return note2;let{pitch:pitch2,velocity}=note2;return variation.transpose!==void 0&&transposes(track2)&&(pitch2=Math.max(0,Math.min(127,pitch2+variation.transpose))),variation.gain!==void 0&&(velocity=Math.max(0,Math.min(1,velocity*variation.gain))),pitch2===note2.pitch&&velocity===note2.velocity?note2:{...note2,pitch:pitch2,velocity}}function applySectionChanges(score){if(!score.sections.some(section=>section.mute!==void 0||section.vary!==void 0))return score;let ticks=barTicks(score),tracks=new Map(score.tracks.map(track2=>[track2.id,track2])),changed=!1,notes=[];for(let note2 of score.notes){let section=sectionAtBar(score,Math.floor(note2.startTick/ticks));if(section?.mute?.includes(note2.trackId)){changed=!0;continue}let varied=varyNote(note2,section?.vary?.[note2.trackId],tracks.get(note2.trackId));varied!==note2&&(changed=!0);let startBar=Math.floor(note2.startTick/ticks),endTick=note2.startTick+varied.durationTicks,cut=varied;for(let bar=startBar+1;bar*ticks<endTick;bar+=1)if(sectionAtBar(score,bar)?.mute?.includes(note2.trackId)){cut={...varied,durationTicks:bar*ticks-note2.startTick},changed=!0;break}notes.push(cut)}let total=Math.max(score.bars,...score.sections.map(s=>s.startBar+s.bars)),clipTracks=score.tracks.map(track2=>{if(!track2.clips)return track2;let pieces=[];for(let bar=0;bar<total;bar+=1){let section=sectionAtBar(score,bar);pieces.push({from:bar*ticks,to:(bar+1)*ticks,offset:bar*ticks,...clipPieceState(section,track2.id)})}pieces.length>0&&(pieces[pieces.length-1]={...pieces[pieces.length-1],to:SCORE_LIMITS.maxTick+1});let next=withClips(track2,sliceClips(track2.clips,pieces,score));return JSON.stringify(next.clips)!==JSON.stringify(track2.clips)&&(changed=!0),next});return changed?new TrackScore({...score.toJSON(),tracks:clipTracks,notes,sections:[],form:[]}):score}function clipPieceState(section,trackId){if(!section)return{};if(section.mute?.includes(trackId))return{mute:!0};let gain=section.vary?.[trackId]?.gain;return gain===void 0||gain===1?{}:{gain}}function withClips(track2,clips){let{clips:_clips,...rest}=track2;return clips&&clips.length>0?{...rest,clips}:rest}function sliceTrackClips(track2,pieces,time){return track2.clips?withClips(track2,sliceClips(track2.clips,pieces,time)):track2}function sectionScore(score,section){let ticks=barTicks(score),from=Math.round(section.startBar*ticks),to=from+section.bars*ticks,tracks=new Map(score.tracks.map(track2=>[track2.id,track2])),notes=[];for(let note2 of score.notes){if(note2.startTick<from||note2.startTick>=to||section.mute?.includes(note2.trackId))continue;let varied=varyNote(note2,section.vary?.[note2.trackId],tracks.get(note2.trackId));notes.push({...varied,startTick:note2.startTick-from,durationTicks:Math.max(1,Math.min(note2.durationTicks,to-note2.startTick))})}let timed=sliceSongTime(score,[{from,to,offset:0}]);return new TrackScore({...score.toJSON(),tempoBpm:timed.tempoBpm,time:timed.time??null,bars:section.bars,tracks:score.tracks.map(track2=>sliceTrackClips(slicePedals(mapAutomation(track2,points=>cropPoints(points,from,to)),[{from,to,offset:0}]),[{from,to,offset:0,...clipPieceState(section,track2.id)}],score)),notes,sections:[],form:[]})}var TRACK_LANES=["volumeAutomation","panAutomation","filterAutomation","resonanceAutomation","delayFeedbackAutomation","delayMixAutomation","wtAutomation"];function mapAutomation(track2,edit){let out={...track2},changed=!1;for(let field of TRACK_LANES){let points=track2[field];if(!points||points.length===0)continue;let next=edit(points);next!==points&&(out[field]=next,changed=!0)}if(track2.fxAutomation){let lanes={},lanesChanged=!1;for(let[lane,points]of Object.entries(track2.fxAutomation)){if(!points)continue;let next=points.length===0?points:edit(points);next!==points&&(lanesChanged=!0),lanes[lane]=next}lanesChanged&&(out.fxAutomation=lanes,changed=!0)}return changed?out:track2}function valueAt2(points,tick){let first=points[0];if(!(!first||tick<first.tick)){for(let index=1;index<points.length;index+=1){let right=points[index];if(tick>right.tick)continue;let left=points[index-1],span4=right.tick-left.tick;if(span4<=0)return right.value;let value=left.value+(right.value-left.value)*(tick-left.tick)/span4;return Math.min(Math.max(value,Math.min(left.value,right.value)),Math.max(left.value,right.value))}return points[points.length-1].value}}function sortPoints(points){let byTick=new Map;for(let point of points)byTick.set(point.tick,point);return[...byTick.values()].sort((a,b)=>a.tick-b.tick)}function cropPoints(points,from,to){let out=[],start=valueAt2(points,from);start!==void 0&&out.push({tick:0,value:start});for(let point of points)point.tick>from&&point.tick<to&&out.push({tick:point.tick-from,value:point.value});let last=points[points.length-1];if(last&&last.tick>=to&&points[0].tick<to){let end=valueAt2(points,to);end!==void 0&&out.push({tick:to-from,value:end})}return sortPoints(out)}function arrangedNotes(score,fromBar,toBar){let ticks=barTicks(score),tracks=new Map(score.tracks.map(track2=>[track2.id,track2])),segments=formSegments(score),passes=new Map,taken=new Set,notes=[];return segments.forEach((segment,index)=>{if(segment.startBar>=toBar)return;let section=segment.section,sectionFrom=section.startBar*ticks,sectionTo=sectionFrom+section.bars*ticks,start=Math.max(segment.startBar,fromBar),stop=Math.min(segment.startBar+segment.bars,toBar),from=Math.round((section.startBar+start-segment.startBar)*ticks),to=stop>start?Math.round(from+(stop-start)*ticks):from,origin=(segment.startBar-section.startBar)*ticks;for(let note2 of score.notes){if(note2.startTick<sectionFrom||note2.startTick>=sectionTo||section.mute?.includes(note2.trackId))continue;let pass2=(passes.get(note2.id)??0)+1;if(passes.set(note2.id,pass2),note2.startTick<from||note2.startTick>=to)continue;let varied=varyNote(note2,section.vary?.[note2.trackId],tracks.get(note2.trackId)),hold=holdEnd(segments,index,note2.trackId)*ticks;notes.push({...varied,id:passId(note2.id,pass2,taken),startTick:note2.startTick+origin,durationTicks:Math.max(1,Math.min(note2.durationTicks,hold-note2.startTick))})}}),notes}function holdEnd(segments,index,trackId){let end=segments[index].section.startBar+segments[index].bars;for(let next=index+1;next<segments.length;next+=1){let section=segments[next].section;if(section.startBar!==end||section.mute?.includes(trackId))break;end=section.startBar+section.bars}return end}function passId(id,pass2,taken){let suffix=pass2>1?`~${pass2}`:"",out=`${id.slice(0,SCORE_LIMITS.maxIdLength-suffix.length)}${suffix}`;for(let extra=2;taken.has(out);extra+=1){let tail=`~${pass2}.${extra}`;out=`${id.slice(0,SCORE_LIMITS.maxIdLength-tail.length)}${tail}`}return taken.add(out),out}function arrangedSlice(score,fromBar,bars,noteBars=bars){let ticks=barTicks(score),pieces=[],clipPieces=[],end=fromBar+bars,previous;for(let segment of formSegments(score)){let segEnd=segment.startBar+segment.bars,before=previous;if(previous=segment,segEnd<=fromBar||segment.startBar>=end)continue;let start=Math.max(segment.startBar,fromBar),stop=Math.min(segEnd,end),from=Math.round((segment.section.startBar+start-segment.startBar)*ticks),piece={from,to:Math.round(from+(stop-start)*ticks),offset:Math.round((start-fromBar)*ticks)};pieces.push(piece);let straight=before!==void 0&&before.section.startBar+before.bars===segment.section.startBar;clipPieces.push({...piece,section:segment.section,...stop<segEnd?{to:Math.round(from+(segEnd-start)*ticks)}:{},...clipPieces.length===0&&fromBar>0&&(start>segment.startBar||straight)?{seam:!0}:{}})}let shift=Math.round(fromBar*ticks),timed=sliceSongTime(score,pieces);return new TrackScore({...score.toJSON(),tempoBpm:timed.tempoBpm,time:timed.time??null,bars,tracks:score.tracks.map(track2=>sliceTrackClips(slicePedals(sliceLanes(track2,pieces),pieces),clipPieces.map(({section,...piece})=>({...piece,...clipPieceState(section,track2.id)})),score)),notes:arrangedNotes(score,fromBar,fromBar+noteBars).map(note2=>({...note2,startTick:note2.startTick-shift})),sections:[],form:[]})}function sliceLanes(track2,pieces){let slice=(points,fallback)=>{let out2=[];for(let{from,to,offset}of pieces){let start=valueAt2(points,from)??fallback;start!==void 0&&out2.push({tick:offset,value:start});for(let point of points)point.tick>from&&point.tick<to&&out2.push({tick:point.tick-from+offset,value:point.value});let last=valueAt2(points,to-1)??fallback;last!==void 0&&to-from>1&&out2.push({tick:offset+to-from-1,value:last})}return sortPoints(out2)},out={...track2};for(let field of TRACK_LANES){let points=track2[field];!points||points.length===0||(out[field]=slice(points,laneFallback(track2,field)))}if(track2.fxAutomation){let lanes={};for(let[lane,points]of Object.entries(track2.fxAutomation))points&&(lanes[lane]=points.length===0?points:slice(points,laneFallback(track2,lane)));out.fxAutomation=lanes}return out}function laneFallback(track2,lane){switch(lane){case"volumeAutomation":return 1;case"panAutomation":return track2.pan??0;case"filterAutomation":return track2.filter?.cutoff??SCORE_LIMITS.maxFilterCutoff;case"resonanceAutomation":return track2.filter?.resonance??0;case"delayFeedbackAutomation":return track2.delay?.feedback;case"delayMixAutomation":return track2.delay?.mix;case"wtAutomation":return wavetableOf(track2).wt??0}let spec=FX_LANES.find(candidate=>candidate.lane===lane);if(!spec)return;if(spec.effect==="string"){let value=resolveString(track2.string)[spec.param];return typeof value=="number"?value:spec.spec.default}let stored=(spec.effect==="reverb"?track2.reverb:spec.effect==="synth"?track2.synth:spec.effect==="keys"?track2.keys:spec.effect==="modal"?track2.modal&&modalSettings(track2.modal):spec.effect==="texture"?track2.texture&&textureSettings(track2.texture):spec.effect==="wind"?track2.wind&&windSettings(track2.wind):spec.effect==="sing"?track2.sing&&resolveSing(track2.sing):track2.fx?.[spec.effect])?.[spec.param];return typeof stored=="number"?stored:spec.spec.default}var SNARE=DRUM_VOICES.find(voice=>voice.voice==="snare").pitch,TOM=DRUM_VOICES.find(voice=>voice.voice==="tom").pitch;var KICK=DRUM_VOICES.find(voice=>voice.voice==="kick").pitch,OPEN_HAT=DRUM_VOICES.find(voice=>voice.voice==="openhat").pitch;var GENERATOR_TRACKS=Object.freeze({riser:"riser",uplifter:"uplifter",impact:"impact",roll:"roll",fills:"fills"}),GENERATOR_IDS=new Set(Object.values(GENERATOR_TRACKS));var FILL_STYLES=Object.freeze(["toms","roll","kick"]);import{createHash as createHash3}from"node:crypto";var SAMPLE_LEVEL=.7,ATTACK_SECONDS=.001,END_FADE_SECONDS=.003,RELEASE_SECONDS=.01,REACH_MARGIN_FRAMES=64,CHOKE_SECONDS=.005,LOOP_CROSSFADE_SECONDS=.005;function travelAt(elapsed,step2,ramp){if(ramp===0)return elapsed*step2;let e=ramp<0?Math.min(elapsed,-1/ramp):elapsed;return step2*(e+ramp*e*e/2)}function framesToTravel(distance,step2,ramp){if(ramp===0)return distance/step2;let d=distance/step2,disc=1+2*ramp*d;return disc<0?1/0:(Math.sqrt(disc)-1)/ramp}function noteStartFrame(note2,timing){let{score,sampleRate,warp:warp2}=timing;return warp2?warpedSpan(warp2,note2.startTick,note2.durationTicks).start:Math.max(0,Math.floor(note2.startTick/score.ticksPerBeat*60/score.tempoBpm*sampleRate))}function noteLengthFrames(note2,timing){let{score,sampleRate,warp:warp2}=timing;return warp2?warpedSpan(warp2,note2.startTick,note2.durationTicks).length:Math.max(1,Math.floor(note2.durationTicks/score.ticksPerBeat*60/score.tempoBpm*sampleRate))}function voiceResolver(track2,tuning){let sampler=track2.sampler,pick=layerPicker(track2.id,sampler.voices,sampler.mode==="oneshot");if(sampler.mode==="oneshot"){let byPitch=new Map;for(let[voice,slot]of samplerVoiceSlots(sampler))byPitch.set(slot,voice);return(pitch2,velocity)=>{let slotted=byPitch.get(pitch2);if(slotted===void 0)return;let voice=pick(slotted,velocity);return voice===void 0?void 0:{voice,ratio:1}}}let keyed=Object.entries(sampler.voices).map(([voice,ref])=>({voice,root:ref.root??60,vel:ref.vel})).sort((a,b)=>a.root-b.root||(a.voice<b.voice?-1:1));return(pitch2,velocity)=>{let chosen;for(let candidate of keyed)inLayer(candidate.vel,velocity)&&(chosen===void 0||candidate.root<=pitch2)&&(chosen=candidate);if(!chosen)return;let voice=pick(chosen.voice,velocity)??chosen.voice;if(!tuning)return{voice,ratio:2**((pitch2-chosen.root)/12)};let hz3=tuning.hz[pitch2];if(hz3>0)return{voice,ratio:hz3/(440*2**((chosen.root-69)/12))}}}function midiVelocity(velocity){return Math.max(0,Math.min(127,Math.round(velocity*127)))}function inLayer(vel,velocity){if(!vel)return!0;let v=midiVelocity(velocity);return v>=vel[0]&&v<=vel[1]}function layerPicker(trackId,voices,oneshot){let counters2=new Map,names=Object.keys(voices).sort();return(voice,velocity)=>{let ref=voices[voice];if(ref.rr===void 0)return oneshot||inLayer(ref.vel,velocity)?voice:void 0;let members=names.filter(name=>{let other=voices[name];return other.rr===ref.rr&&(other.root??60)===(ref.root??60)}),group=members.filter(name=>inLayer(voices[name].vel,velocity));if(group.length===0){let v=midiVelocity(velocity),gap=name=>{let vel=voices[name].vel;return v<vel[0]?vel[0]-v:v-vel[1]},nearest2=Math.min(...members.map(gap));group=members.filter(name=>gap(name)===nearest2)}if(group.length===0)return;let key=`${ref.rr}:${ref.root??60}:${group.join(",")}`,turn=counters2.get(key)??seedHash(`${trackId}:${key}`)%group.length;return counters2.set(key,turn+1),group[turn%group.length]}}function planSamplerVoices(track2,notes,bank,timing){let sampler=track2.sampler;if(!sampler)return[];let resolve=voiceResolver(track2,resolveTuning(timing.score.tuning,track2.tuning,timing.score.key)),ordered=[...notes].sort((a,b)=>a.startTick-b.startTick||a.pitch-b.pitch||(a.id<b.id?-1:a.id>b.id?1:0)),{sampleRate}=timing,voices=[],lastInGroup=new Map,maxVoices=SCORE_LIMITS.maxSamplerVoices,stop=(voice,at3,seconds2)=>{if(voice.end<=at3)return;let fade=Math.max(1,Math.round(seconds2*sampleRate)),end=Math.max(voice.start+1,at3+fade);end>=voice.end||(voice.end=end,voice.fade=Math.min(fade,end-voice.start))};for(let note2 of ordered){let resolved=resolve(note2.pitch,note2.velocity);if(!resolved)continue;let target=note2.cents?{...resolved,ratio:resolved.ratio*2**(note2.cents/1200)}:resolved,ref=sampler.voices[target.voice],decoded=bank.voices.get(sampleKey(track2.id,target.voice));if(!ref||!decoded)continue;let held=noteLengthFrames(note2,timing),reach=ref.loop!==!0&&(ref.accelerate??0)===0&&(sampler.mode==="keyed"||ref.clip!==void 0)?Math.ceil(((ref.clip===void 0?held:Math.max(1,Math.floor(held*ref.clip)))+Math.round(RELEASE_SECONDS*sampleRate))*target.ratio)+REACH_MARGIN_FRAMES:1/0,fitted=isFitted(ref)?fitVoice(ref,decoded,note2.startTick,held,timing,reach):void 0;if(fitted===null)continue;let shifted=isShifted(ref)?shiftVoice(ref,fitted?.sample??decoded,fitted?"fit":"raw"):void 0,sample=shifted??fitted?.sample??decoded,repitch=shifted===void 0&&isShifted(ref)?2**((ref.shift??0)/12):1,speed=fitted?repitch:(ref.speed??1)*repitch,regionStart=fitted?0:(ref.begin??0)*sample.frames,regionEnd=fitted?sample.frames:(ref.end??1)*sample.frames,unit4=ref.unit??"r",seconds2=fitted?void 0:ref.fit?held/sampleRate:unit4==="c"?cycleSeconds(timing.score,note2.startTick)/Math.abs(speed):unit4==="s"?Math.abs(speed):void 0,step2=seconds2===void 0?Math.abs(speed)*sample.sampleRate/sampleRate*target.ratio:(regionEnd-regionStart)/(seconds2*sampleRate)*target.ratio,natural=Math.max(1,Math.floor((regionEnd-regionStart)/step2)),release=Math.max(1,Math.round((ref.fadeTime??RELEASE_SECONDS)*sampleRate)),endFade=Math.max(1,Math.round((ref.fadeTime??END_FADE_SECONDS)*sampleRate)),loop=ref.loop===!0,clipped=ref.clip===void 0?held:Math.max(1,Math.floor(held*ref.clip)),length,fade;loop||(sampler.mode==="keyed"||ref.clip!==void 0)&&clipped+release<natural?(length=clipped+release,fade=release):(length=natural,fade=endFade);let accelerate=ref.accelerate??0,ramp=accelerate===0?0:accelerate/length;if(ramp!==0&&!loop){let reach2=Math.min(framesToTravel(regionEnd-regionStart,step2,ramp),ramp<0?-1/ramp:1/0),until=Math.max(1,Math.floor(reach2));until<length&&(length=until,fade=endFade)}let loopFrom=fitted?fitted.loopFrom:ref.loopBegin===void 0?regionStart:ref.loopBegin*sample.frames,loopTo=fitted?fitted.loopTo:ref.loopEnd===void 0?regionEnd:ref.loopEnd*sample.frames,start=noteStartFrame(note2,timing),performance2=note2.performance,reads=loop||ramp!==0||performance2?.cents?{from:Math.min(regionStart,loopFrom),to:Math.max(regionEnd,loopTo)}:{from:regionStart,to:Math.min(regionEnd,regionStart+length*step2+2)},tuned=track2.autotune&&speed>0?autotuneSample(timing,track2,sample,sample===decoded,start,regionStart,step2,reads):{sample,from:0},voice={voice:target.voice,sample:tuned.sample,startTick:note2.startTick,start,end:start+length,fade:Math.min(fade,length),step:step2,reverse:speed<0,loop,regionStart:regionStart-tuned.from,regionEnd:regionEnd-tuned.from,gain:(ref.gain??1)*Math.max(0,Math.min(1,note2.velocity)),choke:ref.choke,loopStart:speed<0?regionEnd-loopTo:loopFrom-regionStart,loopSpan:loopTo-loopFrom,ramp,squiz:ref.squiz??1,...ref.fadeInTime!==void 0?{attack:Math.max(1,ref.fadeInTime*sampleRate)}:{},...ref.from!==void 0&&tuned.sample.left&&tuned.sample.right?{stereo:!0}:{},...performance2?.cents?{cents:performance2.cents}:{},...performance2?.damp?{damp:performance2.damp}:{}};if(voice.choke!==void 0){let previous=lastInGroup.get(voice.choke);previous&&stop(previous,start,CHOKE_SECONDS),lastInGroup.set(voice.choke,voice)}let sounding=voices.filter(other=>other.end>start);if(sounding.length>=maxVoices)for(let other of sounding.slice(0,sounding.length-maxVoices+1))stop(other,start,CHOKE_SECONDS);voices.push(voice)}return voices}function isFitted(ref){return ref.bpm!==void 0||ref.len!==void 0||ref.fit===!0&&(ref.fitmode==="beats"||ref.fitmode==="tones")}function fitVoice(ref,decoded,startTick,held,timing,reach){let{sampleRate,score,warp:warp2}=timing,speed=ref.speed??1,reverse=speed<0,from=(ref.begin??0)*decoded.frames,to=(ref.end??1)*decoded.frames,rate2=decoded.sampleRate/sampleRate,window=windowAt(decoded.mono,from,to,rate2,reverse),frames=window.length,map;if(ref.fit===!0)map=spanFitMap(frames,held);else{let perBeat=ref.bpm!==void 0?sampleRate*60/ref.bpm*Math.abs(speed):frames/ref.len;map=beatFitMap(warp2,{tempoBpm:score.tempoBpm,ticksPerBeat:score.ticksPerBeat,sampleRate},startTick,frames,perBeat)}let algorithm=ref.fitmode??"repitch",windowKey=`${decoded.sha256}:${decoded.sampleRate}:${from}:${to}:${sampleRate}:${reverse?1:0}`,length=Math.min(map.length,reach),key=`${windowKey}:${algorithm}:${mapPrint(map,frames)}:${Math.round(length)}`,buffer=fittedBuffer(key,window,sampleRate,map,algorithm,windowKey,length);if(!buffer)return null;audioIds.set(buffer,key);let sample=Object.freeze({sha256:decoded.sha256,sampleRate,channels:1,frames:buffer.length,mono:buffer}),loopAt=(fraction,fallback)=>{if(fraction===void 0)return fallback;let source=fraction*decoded.frames,inWindow=(reverse?to-source:source-from)/rate2;return Math.max(0,Math.min(buffer.length,map.outAt(inWindow)))},a=loopAt(ref.loopBegin,0),b=loopAt(ref.loopEnd,buffer.length);return Object.freeze({sample,loopFrom:Math.min(a,b),loopTo:Math.max(a,b)})}function autotuneSample(timing,track2,sample,decoded,start,regionStart,step2,reads){let id=decoded?void 0:audioIds.get(sample.mono),tuned=autotuneVoice(timing.score,track2,{...id!==void 0?{id}:decoded?{sha256:sample.sha256}:{},sampleRate:sample.sampleRate,mono:sample.mono,...decoded&&sample.left&&sample.right?{left:sample.left,right:sample.right}:{}},start/timing.sampleRate,regionStart,step2*timing.sampleRate/sample.sampleRate,reads);return tuned.mono===sample.mono?{sample,from:0}:{sample:Object.freeze({...sample,frames:tuned.mono.length,mono:tuned.mono,left:tuned.left,right:tuned.right}),from:tuned.from}}var audioIds=new WeakMap;function isShifted(ref){return ref.shift!==void 0&&ref.shift!==0||ref.formant!==void 0}var shiftKeys=new WeakMap,shiftSerial=0;function shiftVoice(ref,sample,kind){let base=shiftKeys.get(sample.mono);base===void 0&&(base=kind==="raw"?`${sample.sha256}:${sample.sampleRate}:${sample.frames}`:`fit#${shiftSerial+=1}`,shiftKeys.set(sample.mono,base));let key=`shift:${base}:${ref.shift??0}:${ref.formant??"follow"}`,buffer=shiftedBuffer(key,sample.mono,sample.sampleRate,ref.shift??0,ref.formant);if(buffer)return audioIds.set(buffer,key),Object.freeze({...sample,frames:buffer.length,mono:buffer})}function mapPrint(map,frames){let parts=[map.length.toString()];for(let i=1;i<=64;i+=1)parts.push(map.outAt(frames*i/64).toString());return parts.join(",")}function readAt(mono,position){let last=mono.length-1;if(position<=0)return mono[0];if(position>=last)return mono[last];let base=Math.floor(position),a=mono[base];return a+(mono[base+1]-a)*(position-base)}function renderSamplerVoices(target,voices,timing,gainAt,channel){let{sampleRate,score,warp:warp2}=timing,samplesPerTick=sampleRate*60/(score.tempoBpm*score.ticksPerBeat),attack=Math.max(1,ATTACK_SECONDS*sampleRate);for(let voice of voices){let{sample,step:step2,regionStart,regionEnd,reverse,loop}=voice,{loopStart,loopSpan,ramp}=voice,mono=channel&&voice.stereo?sample[channel]??sample.mono:sample.mono,span4=regionEnd-regionStart,crossfade=loop?Math.min(LOOP_CROSSFADE_SECONDS*sample.sampleRate,loopSpan/4):0,period=loopSpan-crossfade,end=Math.min(target.length,voice.end),fadeFrom=voice.end-voice.fade,level2=SAMPLE_LEVEL*voice.gain,at3=offset=>readAt(mono,reverse?regionEnd-1-offset:regionStart+offset),bent=voice.cents,bentAt=0,bentTravel=0,travel=elapsed=>{if(!bent)return ramp===0?elapsed*step2:travelAt(elapsed,step2,ramp);for(elapsed<bentAt&&(bentAt=0,bentTravel=0);bentAt<elapsed;){let rate2=step2*(ramp===0?1:Math.max(0,1+ramp*bentAt))*2**(bent(bentAt/sampleRate)/1200);bentTravel+=rate2,bentAt+=1}return bentTravel},read=elapsed=>{let travelled=travel(elapsed);if(!loop)return travelled>=span4?void 0:at3(travelled);if(travelled<loopStart)return at3(travelled);let into=travelled-loopStart,phase=into<crossfade||period<=0?into%Math.max(loopSpan,1e-9):crossfade+(into-crossfade)%period,value=at3(loopStart+phase);if(crossfade>0&&phase>=period){let mix3=(phase-period)/crossfade;value=value*(1-mix3)+at3(loopStart+phase-period)*mix3}return value},squizzed=voice.squiz>1?squizBuffer(read,end-voice.start,voice.squiz):void 0;for(let index=voice.start;index<end;index+=1){let elapsed=index-voice.start,value=squizzed?squizzed[elapsed]:read(elapsed);if(value===void 0)break;let envelope2=Math.min(1,elapsed/(voice.attack??attack));index>=fadeFrom&&(envelope2*=(voice.end-index)/voice.fade);let damp=voice.damp;damp&&elapsed/sampleRate>damp.from&&(envelope2*=Math.exp(-(elapsed/sampleRate-damp.from)/damp.tau)),target[index]+=value*envelope2*level2*gainAt(warp2?warp2.tick(index):voice.startTick+elapsed/samplesPerTick)}}}var SQUIZ_MAX_CYCLE=4096;function squizBuffer(read,length,ratio2){let raw=new Float64Array(Math.max(0,length)),filled=raw.length;for(let i=0;i<raw.length;i+=1){let value=read(i);if(value===void 0){filled=i;break}raw[i]=value}let out=new Float64Array(raw.length),start=0;for(;start<filled;){let stop=start+1;for(;stop<filled&&stop-start<SQUIZ_MAX_CYCLE&&!(raw[stop-1]<0&&raw[stop]>=0);)stop+=1;let size=stop-start;for(let i=0;i<size;i+=1){let position=i*ratio2%size,base=Math.floor(position),next=base+1<size?base+1:0,frac2=position-base;out[start+i]=raw[start+base]+(raw[start+next]-raw[start+base])*frac2}start=stop}return out}function samplerNoteSeconds(score,track2,note2,bank,sampleRate){if(!track2.sampler||bank.voices.size===0)return 0;let warp2=sampleWarpFor(score,sampleRate),timing={score,sampleRate,...warp2?{warp:warp2}:{}},frames=0;for(let voice of planSamplerVoices(track2,[note2],bank,timing))frames=Math.max(frames,voice.end-voice.start);return frames/sampleRate}function samplerTailSeconds(score,bank,sampleRate){if(bank.voices.size===0)return 0;let loopEnd=loopSecondsOf(score)*sampleRate,warp2=sampleWarpFor(score,sampleRate),timing={score,sampleRate,...warp2?{warp:warp2}:{}},latest=0,performance2=performanceTimingFor(score);for(let track2 of soundingTracks(score)){if(!track2.sampler)continue;let notes=performNotes(track2,performedNotes(score).filter(note2=>note2.trackId===track2.id),tunedTiming(performance2,score,track2));for(let voice of planSamplerVoices(track2,notes,bank,timing))latest=Math.max(latest,voice.end-loopEnd)}return latest/sampleRate}function cycleSeconds(score,tick){if(!score.time)return score.beatsPerBar*60/score.tempoBpm;let bar=barAt(score,tick);return secondsAtTick(score,bar.tick+bar.barTicks)-secondsAtTick(score,bar.tick)}function clamp4(x,lo,hi){return x<lo?lo:x>hi?hi:x}var OnePole2=class{p=0;y=0;constructor(hz3,sampleRate){this.set(hz3,sampleRate)}set(hz3,sampleRate){this.p=Math.exp(-2*Math.PI*clamp4(hz3,1,sampleRate*.49)/sampleRate)}process(x){return this.y=x+this.p*(this.y-x),this.y}reset(){this.y=0}},DcBlock=class{r;x1=0;y1=0;constructor(sampleRate,hz3=15){this.r=Math.exp(-2*Math.PI*hz3/sampleRate)}process(x){let y=x-this.x1+this.r*this.y1;return this.x1=x,this.y1=y,y}reset(){this.x1=0,this.y1=0}};var J={"01":2.4048,11:3.8317,21:5.1356,"02":5.5201,31:6.3802,12:7.0156,41:7.5883,22:8.4172,"03":8.6537,51:8.7715},MODE_TABLES={marimba:{shape:"bar",ratios:[1,3.99,9.95,17.8],gains:[1,.32,.12,.03],decays:[1,1,1,1.4],beam:[0,1,2,3],level:2.9},vibraphone:{shape:"bar",ratios:[1,3.98,9.92,17.6],gains:[1,.28,.1,.03],beam:[0,1,2,3],level:2.6},xylophone:{shape:"bar",ratios:[1,3,6.1,10.2],gains:[1,.45,.25,.08],beam:[0,1,2,3],level:3.5},glockenspiel:{shape:"bar",ratios:[1,2.756,5.404,8.933,13.345,18.638],gains:[1,.55,.35,.2,.1,.05],beam:[0,1,2,3,4,5],level:3.6},celesta:{shape:"bar",ratios:[1,2.756,5.404,8.933],gains:[1,.25,.1,.04],beam:[0,1,2,3],level:2.5},chimes:{shape:"bar",ratios:[.2238,.617,1.2096,2,2.987,4.172,5.555],gains:[.05,.15,.35,1,.8,.6,.3],beam:[0,1,2,3,4,5,6],level:3.1},mbira:{shape:"tine",ratios:[1,5.9,16.7],gains:[1,.3,.06],beam:[0,1,2],level:.76},kalimba:{shape:"tine",ratios:[1,6.1,17.2],gains:[1,.22,.05],beam:[0,1,2],level:2},musicbox:{shape:"tine",ratios:[1,6.267,17.55,34.39],gains:[1,.4,.15,.05],beam:[0,1,2,3]},toypiano:{shape:"tine",ratios:[1,6.27,17.55,3.1],gains:[1,.5,.2,.12],beam:[0,1,2,0]},saron:{shape:"shell",ratios:[1,2.34,2.76,4.75,5.08,5.91],gains:[1,.3,.45,.18,.15,.1]},bonang:{shape:"shell",ratios:[1,1.52,3.46,3.92],gains:[1,.45,.3,.25],split:.002},gender:{shape:"shell",ratios:[1,2.77,5.18,5.33],gains:[1,.3,.12,.1]},kempul:{shape:"shell",ratios:[1,2,2.86,3.67,4.6],gains:[1,.25,.15,.1,.06],split:.012},gong:{shape:"shell",ratios:[1,2,2.9,3.8,4.95,6.2],gains:[1,.35,.2,.12,.08,.05],decays:[1,.8,.6,.5,.4,.3],split:.03,level:1.25},bell:{shape:"shell",ratios:[.5,1,1.183,1.506,2,2.514,2.662,3.011,4.166],gains:[.45,.5,.55,.25,.9,.35,.3,.25,.2],split:.0015},crotale:{shape:"shell",ratios:[1,1.73,2.328,3.91,4.11,6.3],gains:[1,.3,.6,.25,.35,.15]},steelpan:{shape:"shell",ratios:[1,2.004,3,4.02,5.1],gains:[1,.55,.3,.1,.05],level:1.4},bowl:{shape:"shell",ratios:[1,2.7,4.8,7.5,10.7,14.2],gains:[1,.5,.3,.15,.08,.04],split:.004,level:1.85},timpani:{shape:"membrane",ratios:[.85,1,1.5,1.98,2.44,2.9],gains:[.6,1,.7,.5,.3,.2],decays:[.12,1,.9,.8,.7,.6],membrane:[[0,J["01"]],[1,J[11]],[2,J[21]],[3,J[31]],[4,J[41]],[5,J[51]]],level:2.45},tabla:{shape:"membrane",ratios:[1,2,3,3.01,4,4.02,5],gains:[1,.8,.5,.4,.3,.25,.15],decays:[.6,1,1,.9,.9,.8,.8],membrane:[[0,J["01"]],[1,J[11]],[2,J[21]],[0,J["02"]],[3,J[31]],[1,J[12]],[4,J[41]]]},frame:{shape:"membrane",ratios:[1,1.593,2.136,2.296,2.653,2.918,3.156,3.501,3.6],gains:[1,.8,.6,.5,.45,.35,.3,.25,.2],membrane:[[0,J["01"]],[1,J[11]],[2,J[21]],[0,J["02"]],[3,J[31]],[1,J[12]],[4,J[41]],[2,J[22]],[0,J["03"]]]}},LN1000=Math.log(1e3);function clamp5(value,min,max){return value<min?min:value>max?max:value}function radiusForT60(t60,sampleRate){return Math.exp(-LN1000/(Math.max(1e-4,t60)*sampleRate))}function besselJ(m,x){let sum=0;for(let i=0;i<64;i+=1){let t=(i+.5)/64*Math.PI;sum+=Math.cos(m*t-x*Math.sin(t))}return sum/64}function beamShape(kind,mode,x){let table2=kind==="free"?[4.7300408,7.8532046,10.9956078,14.1371655,17.2787597]:[1.8751041,4.6940911,7.8547574,10.9955407,14.1371684],beta=mode<table2.length?table2[mode]:(2*mode+(kind==="free"?3:1))*Math.PI/2,bx=beta*x;if(kind==="free"){let sigma2=(Math.cosh(beta)-Math.cos(beta))/(Math.sinh(beta)-Math.sin(beta));return beta>15?Math.cos(bx)-Math.sin(bx)+Math.exp(-bx)+(mode%2?-1:1)*Math.exp(bx-beta):(Math.cosh(bx)+Math.cos(bx)-sigma2*(Math.sinh(bx)+Math.sin(bx)))/2}let sigma=(Math.cosh(beta)+Math.cos(beta))/(Math.sinh(beta)+Math.sin(beta));return beta>15?Math.cos(bx)-Math.sin(bx)-Math.exp(-bx):(Math.cosh(bx)-Math.cos(bx)-sigma*(Math.sinh(bx)-Math.sin(bx)))/2}var POSITION_FLOOR=.02;function positionWeight(table2,index,p){let u=clamp5(p,0,1),weight;if(table2.shape==="bar")weight=Math.abs(beamShape("free",table2.beam?.[index]??index,u));else if(table2.shape==="tine")weight=Math.abs(beamShape("clamped",table2.beam?.[index]??index,.08+.92*u));else if(table2.shape==="membrane"){let[m,j]=table2.membrane[index];weight=Math.abs(besselJ(m,j*(.05+.85*u)))}else return table2.ratios[index]**(2*(u-.5));return Math.max(POSITION_FLOOR,Math.min(1,weight))}var MalletPulse=class{samples;constructor(hardness,velocity,fundamentalHz,sampleRate){let tau=Math.exp(Math.log(.004)+(Math.log(2e-4)-Math.log(.004))*hardness);tau*=Math.max(.05,velocity)**-.2*.9,tau=Math.min(tau,.5*(1.6-velocity)/Math.max(20,fundamentalHz));let length=Math.max(1,Math.round(tau*sampleRate)),samples=new Float64Array(length),area=0;for(let i=0;i<length;i+=1){let value=Math.sin(Math.PI*(i+.5)/length);samples[i]=value,area+=value}for(let i=0;i<length;i+=1)samples[i]/=area;this.samples=samples}},MODAL_BLOCK=32,RING_REF_HZ=261.63,SILENT=1e-5,VELOCITY_HARDNESS=.5,VELOCITY_TILT=1.5,NYQUIST_GUARD=.45,ModalBank=class{constructor(settings,note2,sampleRate,maxTail){this.settings=settings;this.note=note2;this.sampleRate=sampleRate;let table2=MODE_TABLES[settings.body]??MODE_TABLES.marimba,f0=note2.hz,v=clamp5(note2.velocity,0,1);this.random=seededRandom(`${note2.seed}:modal`);let keep=2*(NYQUIST_GUARD*sampleRate),twins=settings.ombak>0?2:1,splits=table2.split?2:1,capacity=table2.ratios.length*twins*splits;this.hz=new Float64Array(capacity),this.t60=new Float64Array(capacity),this.zr=new Float64Array(capacity),this.zi=new Float64Array(capacity),this.cr=new Float64Array(capacity),this.ci=new Float64Array(capacity),this.g=new Float64Array(capacity),this.fade=new Float64Array(capacity),this.fadeStep=new Float64Array(capacity),this.live=new Uint8Array(capacity),this.motorMode=new Uint8Array(capacity);let weightSum=0,k=0;for(let i=0;i<table2.ratios.length;i+=1){let ratio2=table2.ratios[i],weight=table2.gains[i]*positionWeight(table2,i,settings.position)*ratio2**(VELOCITY_TILT*(v-.6));if(weightSum+=Math.abs(table2.gains[i]),!(weight>1e-4))continue;let decay=table2.decays?.[i]??1;for(let s=0;s<splits;s+=1)for(let t=0;t<twins;t+=1){let hz3=f0*ratio2*(splits>1?1+(s?.5:-.5)*table2.split:1)+(twins>1?(t?.5:-.5)*settings.ombak:0);hz3>=keep||hz3<=0||(this.hz[k]=hz3,this.t60[k]=Math.max(.01,settings.ring*decay*(RING_REF_HZ/hz3)**settings.tilt),this.g[k]=weight/(splits*twins),this.motorMode[k]=i===0?1:0,this.live[k]=1,k+=1)}}this.count=k;let norm=settings.gain*v*(table2.level??1)/Math.max(1e-9,weightSum);for(let i=0;i<k;i+=1)this.g[i]*=norm;let hard=clamp5(settings.hardness+VELOCITY_HARDNESS*(v-.6)+(note2.accent??0),0,1);this.pulse=new MalletPulse(hard,v,f0*Math.min(1,table2.ratios[0]),sampleRate).samples;let clickLength=settings.click>0?Math.round(.004*sampleRate):0;this.clickBurst=new Float64Array(clickLength);let last=0;for(let i=0;i<clickLength;i+=1){let noise2=this.random()*2-1;this.clickBurst[i]=(noise2-last)*Math.exp(-i/(8e-4*sampleRate))*settings.click*v*settings.gain*.25,last=noise2}this.buzzFilter.set("bpf",Math.min(3200,.4*sampleRate),.8,sampleRate),this.buzzVel=v/.6,this.offAt=Math.round(note2.duration*sampleRate);let longest=0;for(let i=0;i<k;i+=1)longest=Math.max(longest,this.t60[i]);let tail=settings.damp>.999?note2.duration+settings.release:Math.max(note2.duration,longest);this.endAt=Math.max(1,Math.round(Math.min(tail,note2.duration+maxTail)*sampleRate)),this.updatePoles(0);for(let i=0;i<k;i+=1)this.fade[i]=this.fade[i]+this.fadeStep[i]*MODAL_BLOCK,this.fadeStep[i]=0;this.fading=!1}settings;note;sampleRate;count;hz;t60;zr;zi;cr;ci;g;fade;fadeStep;live;motorMode;pulse;clickBurst;random;buzzFilter=new Biquad;buzzVel;offAt;endAt;n=0;motorGain=1;released=!1;fading=!1;updatePoles(n2){let t=n2/this.sampleRate,{settings,note:note2}=this,semis=0;settings.strikebend!==0&&(semis=settings.strikebend*clamp5(note2.velocity,0,1)*Math.exp(-t/Math.max(.001,settings.strikedecay)));let cents=note2.cents?note2.cents(t):0,scale3=2**(semis/12+cents/1200),damping2=this.released?settings.damp/Math.max(.001,settings.release):0,guard=NYQUIST_GUARD*this.sampleRate,fading=!1;for(let k=0;k<this.count;k+=1){if(!this.live[k])continue;let hz3=this.hz[k]*scale3,w=2*Math.PI*hz3/this.sampleRate,rate2=1/this.t60[k]+damping2,r=radiusForT60(1/rate2,this.sampleRate);this.cr[k]=r*Math.cos(w),this.ci[k]=r*Math.sin(w);let step2=((hz3<guard?1:0)-this.fade[k])/MODAL_BLOCK;this.fadeStep[k]=step2,step2!==0&&(fading=!0)}this.fading=fading;let depth=note2.motordepth?note2.motordepth(t):settings.motordepth;if(settings.motor>0&&depth>0){let phase=(note2.start+t)*settings.motor;this.motorGain=1-clamp5(depth,0,1)*(.5-.5*Math.cos(2*Math.PI*phase))}else this.motorGain=1}get position(){return this.n}process(out,offset,count2){let{zr,zi,cr,ci,g,live:live2,motorMode,pulse:pulse2,clickBurst,settings}=this,modes=this.count,buzz=settings.buzz,motor=settings.motor>0&&(settings.motordepth>0||this.note.motordepth!==void 0),dynamic=settings.strikebend!==0||this.note.cents!==void 0||motor,fade=this.fade,fadeStep=this.fadeStep;for(let i=0;i<count2;i+=1){let n2=this.n;if(n2>=this.endAt)return!1;if(n2%MODAL_BLOCK===0){if(this.fading){for(let k=0;k<modes;k+=1)fade[k]=clamp5(fade[k],0,1),fadeStep[k]=0;this.fading=!1}let changed=!1;if(!this.released&&n2>=this.offAt&&settings.damp>0&&(this.released=!0,changed=!0),n2>pulse2.length&&n2%(MODAL_BLOCK*16)===0){let alive=0;for(let k=0;k<modes;k+=1)live2[k]&&(Math.abs(g[k])*Math.hypot(zr[k],zi[k])<SILENT?live2[k]=0:alive+=1);if(alive===0)return this.n=this.endAt,!1}n2>0&&(dynamic||changed||this.released)&&this.updatePoles(n2)}let x=n2<pulse2.length?pulse2[n2]:0,y=0,ym=0;if(this.fading)for(let k=0;k<modes;k+=1){let a=zr[k],b=zi[k],nr=a*cr[k]-b*ci[k]+x,ni=a*ci[k]+b*cr[k];zr[k]=nr,zi[k]=ni;let level2=g[k]*fade[k];fade[k]=fade[k]+fadeStep[k],motor&&motorMode[k]?ym+=level2*ni:y+=level2*ni}else for(let k=0;k<modes;k+=1){let a=zr[k],b=zi[k],nr=a*cr[k]-b*ci[k]+x,ni=a*ci[k]+b*cr[k];zr[k]=nr,zi[k]=ni;let level2=g[k]*fade[k];motor&&motorMode[k]?ym+=level2*ni:y+=level2*ni}if(y+=ym*this.motorGain,n2<clickBurst.length&&(y+=clickBurst[n2]),buzz>0){let excess=Math.abs(y)-.04;excess>0?y+=this.buzzFilter.process((this.random()*2-1)*excess*buzz*6*this.buzzVel):this.buzzFilter.process(0)}out[offset+i]+=y,this.n+=1}return!0}};function logCosh(x){let a=Math.abs(x);return a+Math.log1p(Math.exp(-2*a))-Math.LN2}var Adaa1=class{constructor(f,F2){this.f=f;this.F=F2;this.F1=F2(0)}f;F;x1=0;F1;process(x){let Fx=this.F(x),dx=x-this.x1,y=Math.abs(dx)<1e-5?this.f(.5*(x+this.x1)):(Fx-this.F1)/dx;return this.x1=x,this.F1=Fx,y}reset(){this.x1=0,this.F1=this.F(0)}};var STEAL_FADE=.08,ACCENT_HARDNESS=.2,MODAL_KNEE=1,KNEE=MODAL_KNEE,CEILING=1.38,SPAN=CEILING-KNEE;function knee(x){let a=Math.abs(x);return a<=KNEE?x:Math.sign(x)*(KNEE+SPAN*Math.tanh((a-KNEE)/SPAN))}function kneeF(x){let a=Math.abs(x);return a<=KNEE?.5*x*x:.5*KNEE*KNEE+KNEE*(a-KNEE)+SPAN*SPAN*logCosh((a-KNEE)/SPAN)}function applyModalKnee(dry,samples){let x1=0,F1=0;for(let index=0;index<samples;index+=1){let x=dry[index],Fx=kneeF(x);if(Math.abs(x)>KNEE||Math.abs(x1)>KNEE){let dx=x-x1;dry[index]=Math.abs(dx)<1e-5?knee(.5*(x+x1)):(Fx-F1)/dx}x1=x,F1=Fx}}function span(note2,context){if(context.warp)return warpedSpan(context.warp,note2.startTick,note2.durationTicks);let perTick=60*context.sampleRate/(context.tempoBpm*context.ticksPerBeat);return{start:Math.max(0,Math.floor(note2.startTick*perTick)),length:Math.max(1,Math.floor(note2.durationTicks*perTick))}}function laneOf(track2,param2){let points=track2.fxAutomation?.[`modal-${param2}`];return points&&points.length>0?points:void 0}function renderResonatorTrack(dry,notes,track2,context){let{sampleRate,samples}=context,samplesPerTick=context.samplesPerTick,tickAt4=index=>context.warp?context.warp.tick(index):index/samplesPerTick,planned=notes.map(note2=>({note:note2,...span(note2,context)})).filter(entry=>entry.start<samples).sort((a,b)=>a.start-b.start||a.note.pitch-b.note.pitch||(a.note.id<b.note.id?-1:a.note.id>b.note.id?1:0)),lanes=new Map;for(let{param:param2}of MODAL_LANE_PARAMS){let points=laneOf(track2,param2);points&&lanes.set(param2,points)}let motorLane=lanes.get("motordepth"),volumeLane=track2.volumeAutomation??[],volume=Math.max(0,Math.min(1,track2.volume??1)),gainAt=index=>volume*(volumeLane.length>0?interpolateAutomation(volumeLane,tickAt4(index),1):1),seedTick=context.seedTick??0,base=modalSettings(track2.modal),paired=track2.modal?.pair!==void 0,banks=[],ends=[],steals=[],sounding=[];for(let i=0;i<planned.length;i+=1){let{note:note2,start,length}=planned[i],onsetTick=note2.startTick,settings=lanes.size===0?base:clampLanes(modalSettings(track2.modal,param2=>{let points=lanes.get(param2);return points?interpolateAutomation(points,onsetTick,base[param2]):void 0})),performance2=note2.performance,accent=performance2?.accent||note2.articulation==="marcato"?ACCENT_HARDNESS:0,hz3=noteHz(note2.pitch,note2.cents,context.tuning),bank=new ModalBank(paired?{...settings,ombak:0}:settings,{hz:paired?hz3+settings.ombak:hz3,velocity:note2.velocity,start:start/sampleRate,duration:length/sampleRate,seed:`${note2.id}:${note2.startTick+seedTick}:modal`,...accent?{accent}:{},...performance2?.cents?{cents:performance2.cents}:{},...motorLane?{motordepth:t=>interpolateAutomation(motorLane,tickAt4(start+t*sampleRate),settings.motordepth)}:{}},sampleRate,MAX_RESONATOR_TAIL);banks.push(bank),ends.push(start+bank.endAt),steals.push(1/0);for(let k=sounding.length-1;k>=0;k-=1)ends[sounding[k]]<=start&&sounding.splice(k,1);for(;sounding.length>=MAX_RESONATOR_VOICES;){let oldest=sounding.shift();steals[oldest]=start,ends[oldest]=Math.min(ends[oldest],start+Math.round(STEAL_FADE*sampleRate))}sounding.push(i)}let scratch=new Float64Array(MODAL_BLOCK),fade=Math.max(1,Math.round(STEAL_FADE*sampleRate));for(let i=0;i<planned.length;i+=1){let{note:note2,start}=planned[i],bank=banks[i],stop=Math.min(samples,ends[i]),steal=steals[i],damp=note2.performance?.damp,dampFrom=damp?start+Math.round(damp.from*sampleRate):0,at3=start;for(;at3<stop;){let count2=Math.min(MODAL_BLOCK,stop-at3);scratch.fill(0,0,count2);let alive=bank.process(scratch,0,count2),gain=gainAt(at3);for(let j=0;j<count2;j+=1){let index=at3+j,level2=gain;index>=steal&&(level2*=index-steal>=fade?0:.5+.5*Math.cos(Math.PI*(index-steal)/fade)),damp&&index>dampFrom&&(level2*=Math.exp(-(index-dampFrom)/(damp.tau*sampleRate))),dry[index]+=scratch[j]*level2}if(!alive)break;at3+=count2}}applyModalKnee(dry,samples)}function clampLanes(settings){let out={...settings};for(let{param:param2,spec}of MODAL_LANE_PARAMS){let value=out[param2];typeof value=="number"&&(out[param2]=Math.max(spec.min,Math.min(spec.max,value)))}return Object.freeze(out)}var MODAL_ENGINE=Object.freeze({id:"modal",field:"modal",render(dry,_dryR,notes,track2,context){renderResonatorTrack(dry,notes,track2,context)},tailSeconds:(track2,lowestPitch)=>modalTailSeconds(track2.modal,lowestPitch),ringOut:track2=>modalSettings(track2.modal).damp===0,stereo:()=>!1,assetDigests:()=>[`resonators:${RESONATOR_TABLE_VERSION}`]});var WIND_TRIM_TABLE={22050:{flute:{lo:58,cents:[509,457,405,354,306,266,222,179,137,91,62,23,-17,-31,-94,-115,-144,-228,-261,-202,-329,-316,-285,-454,-407,-561,-447,-496,-459,-479,-513,-575,-771,-704,-1141,-823,-884,-1129,-1039,-1387,-1358],level:.7651,gains:[32,29,27,26,24,22,21,19,18,16,15,13,12,10,9,7,6,5,4,1,0,-3,-5,-6,-9,-11,-16,-20,-25,-30,-36,-42,-48,-54,-58,-65,-71,-75,-76,-75,-81]},recorder:{lo:63,cents:[318,270,227,177,127,102,59,21,7,-74,-95,-80,-222,-257,-175,-203,-274,-264,-398,-414,-586,-428,-501,-434,-451,-490,-561,-804,-690,-1207,-843,-903,-1172],level:1.0736,gains:[24,23,21,20,19,17,15,14,12,11,9,8,8,6,3,2,0,-2,-3,-6,-8,-13,-17,-21,-26,-32,-38,-44,-50,-53,-61,-67,-71]},whistle:{lo:72,cents:[-42,-63,-32,-181,-172,-135,-157,-227,-229,-280,-392,-572,-382,-479,-409,-415,-451,-545,-789,-672,-1079,-835,-893,-1151,-1052,-1297,-1358,-1357,-1465],level:.7381,gains:[32,30,28,27,26,24,22,21,19,17,15,13,8,4,0,-5,-10,-16,-22,-29,-31,-39,-44,-48,-47,-45,-51,-47,-50]},ney:{lo:53,cents:[612,550,490,433,377,326,277,229,182,140,98,56,17,-18,-58,-96,-135,-167,-194,-226,-250,-287,-333,-340,-402,-415,-470,-426,-525,-502,-624,-672,-592,-633,-780,-850],level:1.3239,gains:[28,26,23,21,19,17,16,14,12,11,9,8,7,5,4,3,1,0,-2,-3,-5,-6,-8,-10,-11,-13,-14,-17,-19,-22,-24,-28,-34,-39,-43,-49]},shakuhachi:{lo:60,cents:[282,234,193,149,106,67,34,-7,-49,-76,-120,-149,-177,-200,-243,-294,-295,-348,-376,-434,-373,-489,-460,-589,-646,-549,-538,-758,-716],level:.9254,gains:[21,19,18,16,15,13,12,10,9,7,6,5,3,1,0,-1,-3,-5,-6,-8,-11,-13,-16,-18,-22,-28,-32,-36,-44]},panpipe:{lo:58,cents:[1144,1015,894,784,671,569,465,348,279,183,101,14,-92,-179,-242,-265,-438,-507,-607,-505,-622,-885,-679,-1055,-849,-1183,-1447,-1350,-1319,-1362,-1486,-1717,-2098,-1621,-2137,-1798,-2728,-2266,-2236,-2410,-2242],level:.6231,gains:[25,24,23,21,20,19,18,17,15,14,13,12,11,9,8,6,6,5,3,1,0,-1,-3,-5,-8,-11,-13,-17,-22,-27,-32,-38,-43,-50,-57,-60,-65,-71,-69,-70,-69]},suling:{lo:65,cents:[141,101,56,24,-13,-73,-72,-127,-149,-208,-258,-289,-242,-355,-422,-321,-478,-436,-585,-542,-525,-497,-504,-536,-596,-793,-756,-1162,-837,-899,-1151],level:1.0788,gains:[24,22,21,19,18,17,15,14,12,11,10,8,6,5,4,0,-1,-5,-6,-12,-16,-20,-26,-31,-38,-44,-50,-54,-61,-67,-71]},bansuri:{lo:53,cents:[725,661,599,541,484,428,376,326,277,235,188,151,102,72,29,-4,-40,-91,-122,-147,-169,-219,-270,-300,-265,-359,-421,-341,-477,-441,-580,-646,-530,-512],level:.9295,gains:[29,27,24,21,19,17,16,14,12,10,9,7,6,4,3,1,0,-1,-3,-4,-6,-7,-8,-11,-13,-14,-15,-18,-20,-23,-25,-28,-34,-39]},clarinet:{lo:48,cents:[5,-4,-6,5,5,-13,-8,7,-9,-12,9,-19,-19,10,-5,6,6,-11,13,-25,-8,-11,-37,17,-16,16,21,-78,-85,24,19,-20,28,-9,30,-75,-13,16,28,32,33,29,17,-13,-71,38],level:.5033,gains:[9,39,-4,-8,0,-15,-13,-17,-17,-18,-18,-17,-17,-16,-15,-14,-13,-12,-11,-10,-9,-7,-5,-4,-2,0,2,5,8,10,12,15,18,20,23,25,26,28,28,29,29,29,30,31,34,38]},bassclarinet:{lo:35,cents:[11,2,3,-47,22,16,-104,48,23,-11,-35,14,-4,1,6,-40,9,-9,0,-10,5,-6,-9,6,-14,-14,7,-4,4,4,-8,10,-18,-6,-8,-27,12,-12,11,15],level:.5566,gains:[637,681,1500,598,395,344,420,382,226,201,365,147,120,180,74,85,45,29,16,0,-16,-22,-41,-47,-57,-68,-75,-81,-85,-88,-89,-89,-89,-88,-87,-85,-83,-82,-80,-78]},oboe:{lo:56,cents:[20,22,25,4,10,23,-16,-4,40,29,25,19,39,43,24,43,-16,20,-3,81,25,86,38,72,24,30,23,65,146,188,148,152,131,181,164,278,244,328],level:.3383,gains:[-5,3,-10,-16,-16,-15,-14,-16,-20,-21,-20,-19,-20,-19,-15,-16,1,-7,3,-11,0,-7,3,0,13,15,23,10,3,2,5,5,10,6,9,6,8,13]},bassoon:{lo:32,cents:[328,533,372,670,223,274,299,315,154,658,70,191,108,201,37,71,38,107,30,13,13,1,64,12,0,-2,3,-19,-16,-3,-46,-33,10,0,-5,-13,6,10,-11,8,-61,-20,-50],level:.3736,gains:[359,364,313,389,293,201,206,178,129,246,87,101,74,117,49,50,19,96,15,0,28,-3,22,-16,-12,-24,-22,-28,-31,-31,-31,-33,-35,-36,-36,-37,-38,-38,-38,-40,-34,-39,-37]},sax:{lo:42,cents:[-97,-103,-59,-70,-76,-40,-31,-31,100,-38,-44,-40,-5,-26,-41,-43,-39,-60,-56,-45,-91,-76,-34,-44,-50,-56,-39,-36,-62,-40,-130,-79,-66,4,-88,2,-82,-36,-123,-124],level:.2819,gains:[122,99,96,98,172,63,47,42,109,31,23,18,44,9,7,6,2,4,0,-1,1,-1,-5,-5,-5,-6,-7,-8,-7,-9,-2,-8,-5,-13,-10,-16,-13,-18,-15,-17]},altosax:{lo:47,cents:[-40,-31,-31,100,-38,-44,-40,-5,-26,-41,-43,-39,-60,-56,-45,-91,-76,-34,-44,-50,-56,-39,-36,-62,-40,-130,-79,-66,4,-88,2,-82,-36,-123,-124,-155,-79],level:.2775,gains:[67,51,46,98,35,28,21,42,12,10,9,5,8,3,2,5,3,-1,-2,-2,-3,-4,-5,-4,-5,2,-3,0,-8,-5,-10,-7,-11,-7,-9,-7,-18]},barisax:{lo:34,cents:[221,768,-240,-161,-272,-158,-116,66,-124,-109,-58,61,-67,-13,-23,67,-15,-24,-47,-30,-47,-19,-34,-36,-33,-52,-51,-39,-86,-71,-29,-39,-45,-53,-33,-31,-55,-34],level:.2644,gains:[391,528,303,214,171,169,166,284,109,81,69,160,54,37,23,97,3,-2,0,-17,0,-27,-25,-34,-34,-37,-37,-40,-37,-39,-43,-44,-44,-44,-46,-47,-45,-48]},trumpet:{lo:50,cents:[-2763,-2754,-2751,-2751,-2758,-2767,-2781,-2804,-2819,-2847,-2887,-2941,-2981,-3029,-3079,-3133,-3196,-3258,-3325,-3397,-3471,-3557,-3635,-3722,-3812,-3903,-4e3,-4100,-4220,-4317,-4441,-4564,-4694,-4829,-5008],level:.543,gains:[159,149,144,142,131,123,121,111,100,93,80,73,59,50,37,26,12,0,-15,-27,-41,-55,-69,-80,-94,-105,-117,-130,-145,-151,-159,-169,-178,-197,-217]},harmon:{lo:50,cents:[-2763,-2754,-2751,-2751,-2758,-2767,-2781,-2804,-2819,-2847,-2887,-2942,-2981,-3029,-3079,-3133,-3196,-3258,-3325,-3397,-3471,-3557,-3635,-3722,-3812,-3903,-4e3,-4100,-4220,-4317,-4441,-4564,-4694,-4829,-5008],level:.3514,gains:[992,925,822,744,680,571,381,355,292,209,194,62,88,29,-240,-231,-18,0,-39,15,25,-100,-361,-584,-481,-206,-64,-22,-43,-146,-354,-445,-213,-62,7]},plunger:{lo:50,cents:[-2753,-2747,-2742,-2743,-2750,-2760,-2777,-2795,-2816,-2841,-2877,-2924,-2970,-3022,-3072,-3129,-3185,-3253,-3321,-3396,-3472,-3554,-3636,-3717,-3813,-3907,-4004,-4107,-4222,-4325,-4445,-4570,-4679,-4840,-5016],level:.5198,gains:[-106,-114,-117,-117,-120,-122,-117,-122,-123,-118,-115,-100,-86,-62,-44,-26,-14,0,11,24,37,47,50,48,45,39,35,34,46,71,111,169,243,324,413]},trombone:{lo:38,cents:[-3155,-3110,-3060,-3021,-2976,-2937,-2900,-2868,-2840,-2814,-2791,-2775,-2762,-2754,-2750,-2751,-2758,-2768,-2784,-2802,-2820,-2847,-2886,-2941,-2978,-3026,-3077,-3131,-3195,-3258,-3325,-3396,-3472,-3556,-3635,-3720,-3812],level:.6702,gains:[89,74,81,77,67,63,57,61,52,53,45,42,38,31,23,22,16,7,0,-2,-13,-24,-27,-39,-44,-57,-66,-80,-89,-102,-114,-126,-139,-153,-167,-178,-192]},tuba:{lo:26,cents:[-3391,-2966,-2945,-2966,-3036,-3078,-3136,-3230,-3252,-3248,-3246,-3201,-3157,-3114,-3065,-3021,-2977,-2937,-2900,-2868,-2838,-2814,-2792,-2775,-2762,-2755,-2750,-2752,-2758,-2767,-2781,-2802,-2819,-2847,-2883],level:.7494,gains:[166,77,49,39,33,32,51,23,4,8,2,1,-3,10,4,9,-6,2,-7,-8,0,4,-4,-11,-13,-12,-16,-25,-31,-31,-39,-49,-54,-59,-69]},horn:{lo:39,cents:[-3139,-3094,-3048,-3005,-2965,-2927,-2893,-2862,-2835,-2815,-2797,-2782,-2775,-2770,-2770,-2776,-2786,-2798,-2815,-2836,-2870,-2908,-2947,-2991,-3038,-3089,-3143,-3203,-3267,-3333,-3403,-3478,-3562,-3640,-3720,-3817,-3900,-3993,-4101,-4207,-4318],level:1.0517,gains:[60,55,54,46,56,45,47,52,58,55,48,43,43,39,31,23,24,20,11,1,0,-9,-13,-23,-29,-40,-50,-60,-69,-81,-93,-103,-119,-132,-145,-158,-171,-185,-199,-214,-226]}},44100:{flute:{lo:58,cents:[556,505,457,412,367,325,287,248,212,176,142,112,81,50,20,-6,-32,-62,-82,-116,-130,-160,-179,-202,-246,-255,-278,-288,-334,-335,-367,-343,-447,-506,-398,-549,-499,-645,-592,-573,-545],level:.763,gains:[36,34,32,30,28,27,25,23,22,20,19,17,15,14,12,10,8,7,4,3,0,-2,-5,-8,-11,-15,-20,-25,-30,-37,-44,-51,-57,-64,-73,-78,-85,-89,-95,-99,-102]},recorder:{lo:63,cents:[379,337,297,258,221,186,151,118,87,57,24,-2,-25,-52,-80,-105,-139,-154,-180,-210,-208,-267,-277,-261,-332,-370,-321,-345,-407,-383,-573,-510,-674],level:1.0702,gains:[29,27,25,24,22,20,19,17,15,14,12,10,8,6,4,2,0,-3,-6,-9,-14,-17,-22,-28,-34,-40,-48,-55,-62,-69,-74,-81,-85]},whistle:{lo:72,cents:[102,76,39,20,-9,-36,-66,-102,-112,-140,-166,-161,-235,-243,-214,-330,-345,-280,-302,-367,-348,-448,-486,-659,-491,-558,-490,-502,-522],level:.7292,gains:[42,40,39,36,35,33,30,28,25,22,19,15,11,6,0,-5,-12,-19,-26,-33,-40,-47,-52,-56,-62,-66,-69,-71,-72]},ney:{lo:53,cents:[647,587,530,475,424,374,327,283,240,200,162,125,90,56,23,-8,-37,-65,-94,-121,-146,-171,-194,-218,-242,-265,-293,-310,-335,-357,-373,-398,-412,-435,-450,-472],level:1.3252,gains:[29,27,24,22,20,18,17,15,13,12,10,9,8,6,5,3,2,0,-2,-3,-5,-7,-8,-10,-12,-15,-17,-20,-23,-26,-30,-35,-40,-46,-52,-59]},shakuhachi:{lo:60,cents:[336,294,252,214,177,140,107,73,43,13,-16,-46,-71,-95,-124,-146,-170,-195,-221,-241,-265,-292,-312,-328,-351,-364,-392,-403,-427],level:.9261,gains:[22,20,19,17,16,14,13,11,10,8,7,5,3,2,0,-2,-4,-6,-8,-10,-13,-16,-20,-24,-28,-34,-39,-46,-53]},panpipe:{lo:58,cents:[1247,1128,1018,909,806,710,615,528,443,358,282,205,137,65,-2,-65,-128,-186,-245,-315,-354,-454,-501,-571,-601,-633,-694,-789,-805,-849,-924,-1008,-933,-1160,-964,-1293,-1085,-1349,-1630,-1525,-1485],level:.6211,gains:[30,28,27,25,24,23,22,20,19,18,16,15,14,12,11,9,7,6,4,2,0,-2,-4,-7,-11,-14,-19,-23,-29,-35,-41,-48,-56,-62,-70,-76,-82,-88,-91,-95,-98]},suling:{lo:65,cents:[211,175,139,106,73,45,13,-16,-42,-69,-96,-125,-150,-167,-196,-229,-240,-278,-296,-312,-324,-364,-368,-399,-383,-474,-532,-439,-575,-529,-671],level:1.0762,gains:[27,26,24,23,21,20,18,16,14,13,11,9,7,5,2,0,-3,-6,-11,-15,-21,-26,-32,-39,-46,-53,-59,-68,-73,-80,-84]},bansuri:{lo:53,cents:[759,697,638,581,528,477,427,381,337,295,255,217,180,145,111,79,47,19,-11,-39,-64,-90,-116,-142,-167,-186,-213,-241,-263,-289,-306,-326,-338,-371],level:.931,gains:[30,27,24,22,20,18,16,14,12,11,9,8,6,5,3,2,0,-2,-3,-5,-7,-8,-10,-12,-14,-17,-19,-21,-24,-28,-32,-37,-42,-47]},clarinet:{lo:48,cents:[-2,-4,-7,3,3,3,-10,0,-11,-16,-6,5,5,-3,-6,5,5,-13,-8,7,-9,-12,9,-19,-19,10,-5,6,6,-11,13,-25,-8,-11,-37,17,-16,16,21,-78,-85,24,19,-20,28,-9],level:.4838,gains:[37,67,24,18,27,11,12,7,6,4,3,3,2,2,2,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,-1,-1,-2,-3,-4,-7,-9,-13,-16,-21,-26,-31,-36,-41,-44]},bassclarinet:{lo:35,cents:[11,2,5,-50,21,19,-101,52,23,-6,-34,15,-1,-8,6,-51,4,-8,9,-11,1,-7,-10,-4,3,3,-2,-4,4,3,-9,-6,5,-7,-9,6,-14,-14,7,-4],level:.5518,gains:[644,683,1500,616,404,351,418,398,235,207,370,154,125,187,79,87,49,30,19,0,-15,-22,-42,-48,-60,-72,-80,-86,-92,-96,-99,-100,-101,-102,-103,-103,-103,-103,-104,-104]},oboe:{lo:56,cents:[1,1,7,74,16,-9,13,10,-4,5,6,19,11,14,19,2,7,20,-16,-4,39,29,25,19,39,43,24,43,-16,20,-3,81,25,86,38,72,24,30],level:.3156,gains:[34,40,27,-6,18,19,13,13,12,9,8,6,5,4,3,4,3,0,8,2,-5,-6,-6,-8,-12,-15,-14,-20,-7,-21,-17,-37,-33,-45,-43,-52,-47,-50]},bassoon:{lo:32,cents:[326,531,373,686,223,273,297,313,156,707,72,191,111,208,34,68,34,110,23,2,35,10,47,-9,-10,-12,-4,3,2,-5,-2,-6,-21,-11,-11,-1,-8,-7,-3,-21,-17,-5,-46],level:.3724,gains:[363,368,316,391,296,203,209,180,131,241,89,103,76,121,51,51,20,104,16,0,32,-4,20,-17,-13,-26,-24,-31,-34,-35,-37,-38,-39,-41,-42,-44,-45,-48,-50,-51,-53,-57,-56]},sax:{lo:42,cents:[-98,-83,-64,-51,-65,-36,-27,-24,60,-34,-11,-16,38,-29,-16,-40,-27,-26,-22,-30,-28,-33,-48,-41,-42,-34,-41,-42,-40,-58,-56,-45,-91,-76,-34,-44,-50,-58,-39,-36],level:.2789,gains:[129,105,103,104,164,69,53,47,80,36,28,21,36,13,9,9,5,5,0,0,-2,-3,-5,-6,-8,-10,-12,-14,-16,-17,-19,-23,-21,-26,-34,-37,-40,-44,-50,-56]},altosax:{lo:47,cents:[-36,-27,-24,60,-34,-11,-16,38,-29,-16,-40,-27,-26,-22,-30,-28,-33,-48,-41,-42,-34,-41,-42,-40,-58,-56,-45,-91,-76,-34,-44,-50,-58,-39,-36,-61,-40],level:.2731,gains:[78,61,55,60,44,35,28,28,20,16,16,11,3,7,6,4,3,1,0,-2,-4,-6,-8,-10,-11,-13,-17,-14,-19,-27,-30,-33,-36,-42,-47,-50,-58]},barisax:{lo:34,cents:[219,761,-241,-165,-275,-158,-116,80,-128,-95,-63,30,-56,-12,-19,50,-13,-21,-20,-8,11,-28,-27,-30,-23,-17,-19,-26,-24,-29,-44,-37,-38,-28,-37,-37,-35,-53],level:.263,gains:[396,532,308,219,175,174,170,283,112,84,73,158,55,40,24,77,5,0,1,-16,-3,-26,-25,-34,-35,-39,-41,-42,-44,-45,-45,-48,-50,-52,-53,-55,-58,-59]},trumpet:{lo:50,cents:[-2593,-2574,-2559,-2548,-2540,-2537,-2538,-2546,-2539,-2550,-2574,-2609,-2629,-2657,-2688,-2720,-2757,-2794,-2836,-2880,-2926,-2973,-3022,-3077,-3129,-3183,-3241,-3301,-3364,-3427,-3496,-3565,-3639,-3718,-3791],level:.547,gains:[155,146,140,138,127,119,118,108,97,90,77,70,57,48,35,25,11,0,-15,-27,-40,-52,-66,-79,-91,-103,-114,-125,-135,-148,-157,-166,-177,-185,-195]},harmon:{lo:50,cents:[-2593,-2574,-2559,-2548,-2540,-2537,-2538,-2546,-2539,-2550,-2574,-2609,-2629,-2657,-2688,-2720,-2757,-2794,-2836,-2880,-2926,-2973,-3022,-3077,-3129,-3183,-3241,-3301,-3364,-3427,-3496,-3565,-3639,-3718,-3791],level:.3449,gains:[999,931,826,748,685,571,384,359,294,215,195,67,93,25,-237,-216,-11,0,-38,20,26,-106,-375,-583,-456,-193,-54,-10,-33,-147,-343,-386,-173,-33,35]},plunger:{lo:50,cents:[-2586,-2566,-2551,-2539,-2532,-2528,-2529,-2532,-2535,-2541,-2561,-2593,-2618,-2651,-2681,-2713,-2750,-2788,-2830,-2873,-2918,-2967,-3016,-3071,-3124,-3179,-3235,-3297,-3360,-3423,-3488,-3563,-3634,-3715,-3789],level:.5254,gains:[-114,-122,-125,-124,-127,-129,-124,-129,-129,-124,-121,-105,-91,-66,-47,-28,-15,0,11,26,39,48,52,51,49,41,39,41,53,77,116,175,246,328,412]},trombone:{lo:38,cents:[-3079,-3037,-2975,-2931,-2879,-2832,-2790,-2748,-2711,-2676,-2643,-2616,-2594,-2575,-2560,-2548,-2540,-2537,-2538,-2546,-2545,-2550,-2574,-2603,-2629,-2657,-2687,-2720,-2756,-2795,-2836,-2879,-2924,-2973,-3022,-3075,-3127],level:.6734,gains:[91,74,83,77,68,62,57,61,51,52,45,42,37,30,22,21,15,6,0,-2,-12,-24,-26,-39,-43,-56,-65,-79,-88,-99,-111,-123,-136,-148,-161,-174,-187]},tuba:{lo:26,cents:[-3336,-2943,-2922,-2946,-3019,-3060,-3106,-3205,-3211,-3200,-3185,-3143,-3090,-3039,-2978,-2932,-2879,-2833,-2789,-2748,-2709,-2675,-2644,-2617,-2594,-2575,-2559,-2547,-2540,-2537,-2537,-2546,-2539,-2550,-2575],level:.7528,gains:[165,76,49,40,34,33,54,25,6,9,3,1,-3,11,5,10,-6,2,-7,-8,0,4,-5,-12,-13,-12,-16,-25,-31,-31,-39,-48,-53,-58,-69]},horn:{lo:39,cents:[-3065,-3014,-2959,-2908,-2861,-2816,-2773,-2734,-2700,-2670,-2640,-2616,-2597,-2580,-2569,-2561,-2558,-2556,-2555,-2560,-2578,-2597,-2623,-2647,-2674,-2704,-2737,-2773,-2811,-2852,-2894,-2940,-2987,-3036,-3089,-3142,-3195,-3250,-3311,-3374,-3439],level:1.0573,gains:[60,54,56,46,56,45,45,52,58,53,46,42,43,38,30,23,24,19,11,1,0,-9,-13,-23,-28,-39,-48,-58,-67,-79,-90,-100,-114,-128,-140,-152,-165,-178,-191,-204,-216]}},48e3:{flute:{lo:58,cents:[560,510,462,416,373,331,292,253,217,183,149,119,89,59,30,4,-21,-48,-73,-96,-119,-145,-171,-185,-204,-234,-255,-306,-305,-339,-369,-389,-389,-369,-401,-485,-519,-569,-528,-558,-568],level:.7631,gains:[36,34,32,30,28,27,25,23,22,20,19,17,15,14,12,10,8,6,4,2,0,-2,-5,-8,-12,-16,-20,-24,-31,-37,-43,-51,-59,-66,-73,-79,-85,-91,-96,-100,-104]},recorder:{lo:63,cents:[385,342,303,265,227,192,157,126,96,67,35,11,-21,-48,-71,-91,-121,-137,-163,-183,-222,-243,-264,-301,-268,-366,-386,-393,-357,-388,-488,-540,-585],level:1.0699,gains:[29,27,26,24,23,21,19,17,16,14,12,10,9,7,5,2,0,-3,-6,-9,-13,-17,-22,-28,-35,-40,-47,-55,-63,-69,-75,-81,-86]},whistle:{lo:72,cents:[112,84,54,28,4,-31,-47,-80,-93,-124,-143,-147,-210,-222,-211,-221,-337,-356,-369,-320,-350,-460,-357,-565,-511,-556,-564,-770,-710],level:.7289,gains:[43,41,39,37,35,33,31,29,25,23,19,15,11,6,0,-6,-11,-18,-26,-34,-41,-46,-53,-57,-63,-66,-70,-71,-74]},ney:{lo:53,cents:[650,590,533,479,427,378,331,287,245,205,167,130,95,62,30,0,-29,-57,-84,-111,-136,-160,-185,-209,-231,-251,-276,-294,-318,-339,-355,-377,-408,-418,-439,-451],level:1.3254,gains:[29,27,24,22,20,18,17,15,13,12,10,9,8,6,5,3,2,0,-2,-3,-5,-7,-8,-10,-12,-15,-17,-20,-23,-26,-31,-35,-40,-46,-53,-59]},shakuhachi:{lo:60,cents:[341,298,258,219,182,146,114,81,50,20,-8,-35,-61,-88,-112,-139,-158,-185,-204,-231,-248,-275,-296,-308,-330,-364,-372,-396,-402],level:.9261,gains:[22,21,19,17,16,14,13,12,10,8,7,5,3,2,0,-2,-4,-6,-8,-10,-13,-16,-20,-24,-29,-33,-40,-46,-52]},panpipe:{lo:58,cents:[1255,1139,1027,920,819,722,630,541,455,375,296,225,154,82,20,-43,-108,-167,-221,-276,-332,-407,-437,-481,-529,-585,-673,-728,-808,-810,-840,-892,-984,-897,-1027,-1325,-1069,-1451,-1348,-1191,-1162],level:.6211,gains:[30,28,27,26,24,23,22,20,19,18,17,15,14,12,11,9,7,6,4,2,0,-2,-5,-8,-11,-15,-19,-24,-29,-35,-42,-49,-56,-64,-71,-76,-83,-87,-93,-97,-100]},suling:{lo:65,cents:[217,181,147,114,82,52,21,-6,-32,-62,-85,-109,-132,-161,-181,-208,-222,-242,-268,-290,-337,-338,-369,-402,-423,-421,-408,-443,-519,-546,-598],level:1.0759,gains:[28,26,25,23,22,20,18,17,15,13,11,9,7,5,3,0,-3,-7,-11,-15,-20,-26,-32,-38,-46,-54,-61,-68,-74,-81,-86]},bansuri:{lo:53,cents:[762,700,641,585,531,480,432,386,342,300,260,222,186,151,117,86,56,25,-3,-29,-55,-82,-106,-129,-152,-177,-206,-222,-239,-260,-282,-304,-344,-349],level:.9311,gains:[30,27,25,22,20,18,16,14,13,11,9,8,6,5,3,2,0,-2,-3,-5,-7,-8,-10,-12,-14,-16,-19,-22,-25,-29,-32,-37,-41,-48]},clarinet:{lo:48,cents:[1,-6,1,3,-4,1,-12,1,-3,-4,1,-12,-18,-5,-19,-10,6,-22,6,-25,7,-4,1,-10,8,9,9,-9,8,10,7,-20,11,15,-35,16,9,-39,11,20,-69,-62,-83,25,12,-52],level:.4825,gains:[39,69,26,20,29,12,14,8,7,5,5,4,3,3,3,2,2,2,1,1,1,0,0,0,-1,-1,-1,-1,-1,-2,-2,-2,-3,-4,-5,-7,-10,-12,-16,-21,-25,-30,-35,-41,-46,-50]},bassclarinet:{lo:35,cents:[11,2,5,-50,21,19,-101,53,23,-6,-34,15,-1,-9,6,-51,8,-11,9,-12,2,-2,-3,1,-9,-13,-4,-14,-8,4,-16,4,-19,5,-3,1,-8,6,7,6],level:.5514,gains:[645,683,1500,617,405,352,418,399,235,208,370,155,125,187,80,87,50,30,19,0,-15,-22,-42,-48,-60,-73,-80,-87,-92,-97,-99,-101,-102,-103,-104,-104,-105,-105,-106,-106]},oboe:{lo:56,cents:[11,6,-1,69,-2,11,-2,5,14,-4,2,20,18,10,22,16,14,-16,17,24,4,21,6,14,12,37,48,46,13,31,10,65,22,29,90,3,47,78],level:.3138,gains:[37,43,30,-6,22,21,17,16,12,13,11,7,6,12,4,3,3,9,0,-2,0,-5,-4,-7,-9,-15,-20,-22,-20,-27,-27,-39,-37,-42,-55,-43,-58,-65]},bassoon:{lo:32,cents:[325,531,373,686,223,273,297,313,155,712,75,193,112,209,38,67,34,119,29,15,46,1,55,-5,2,-5,-12,-12,-15,-2,-16,-10,-1,-21,-14,3,0,-9,2,-5,-8,-42,-8],level:.3725,gains:[362,367,316,391,295,203,209,180,131,239,89,103,76,121,50,51,19,102,15,0,32,-4,19,-18,-14,-27,-24,-31,-34,-36,-38,-38,-40,-41,-43,-45,-47,-49,-51,-53,-55,-55,-61]},sax:{lo:42,cents:[-99,-81,-59,-56,-72,-36,-25,-23,59,-21,-14,-24,23,-24,-21,-32,-34,-36,-38,-25,-41,-35,-28,-50,-43,-29,-32,-42,-33,-41,-45,-84,-47,-42,-66,-49,-68,-61,-65,-39],level:.2786,gains:[130,106,104,105,164,70,53,48,76,36,29,22,34,13,10,9,6,3,2,0,-1,-3,-5,-5,-7,-11,-12,-14,-17,-19,-21,-19,-26,-30,-31,-37,-40,-45,-50,-58]},altosax:{lo:47,cents:[-36,-25,-23,59,-21,-14,-24,23,-24,-21,-32,-34,-36,-38,-25,-41,-35,-28,-50,-43,-29,-32,-42,-33,-41,-45,-84,-47,-42,-66,-49,-68,-61,-65,-39,-30,-33],level:.2724,gains:[80,63,56,57,45,37,30,25,22,18,17,14,0,10,8,7,5,2,3,0,-3,-5,-7,-10,-11,-13,-11,-19,-22,-23,-29,-31,-36,-41,-48,-55,-60]},barisax:{lo:34,cents:[219,760,-241,-166,-276,-158,-118,82,-130,-94,-59,29,-64,-13,-17,51,-4,-7,-24,-16,5,-20,-15,-21,-30,-30,-36,-21,-38,-32,-24,-46,-39,-24,-28,-37,-28,-36],level:.2628,gains:[397,533,308,220,175,175,171,284,113,85,73,156,56,40,25,76,5,0,1,-16,-2,-26,-25,-34,-34,-38,-39,-42,-43,-44,-47,-47,-49,-52,-54,-56,-58,-60]},trumpet:{lo:50,cents:[-2580,-2560,-2544,-2531,-2523,-2518,-2518,-2525,-2516,-2526,-2549,-2582,-2601,-2627,-2655,-2687,-2721,-2757,-2796,-2838,-2881,-2927,-2972,-3021,-3072,-3124,-3179,-3237,-3294,-3355,-3420,-3483,-3553,-3627,-3694],level:.5472,gains:[155,146,140,137,127,119,118,107,97,90,77,70,57,48,35,25,11,0,-15,-27,-40,-52,-66,-78,-90,-103,-114,-125,-135,-147,-157,-165,-177,-184,-193]},harmon:{lo:50,cents:[-2580,-2559,-2544,-2531,-2523,-2518,-2518,-2525,-2516,-2526,-2549,-2582,-2601,-2627,-2655,-2687,-2721,-2757,-2796,-2838,-2881,-2927,-2972,-3021,-3072,-3124,-3179,-3237,-3294,-3355,-3420,-3483,-3553,-3627,-3694],level:.3445,gains:[1e3,931,827,748,685,572,384,359,294,216,195,67,94,25,-237,-215,-11,0,-38,21,27,-106,-375,-584,-454,-191,-52,-9,-32,-147,-342,-381,-168,-30,36]},plunger:{lo:50,cents:[-2572,-2551,-2535,-2523,-2514,-2510,-2509,-2511,-2512,-2517,-2536,-2566,-2590,-2620,-2649,-2680,-2714,-2750,-2788,-2832,-2874,-2920,-2967,-3015,-3066,-3119,-3177,-3231,-3288,-3351,-3416,-3479,-3549,-3624,-3692],level:.526,gains:[-114,-123,-126,-125,-128,-130,-125,-130,-130,-125,-121,-106,-91,-66,-47,-29,-15,0,11,26,39,48,52,51,49,42,39,41,53,77,116,176,246,328,412]},trombone:{lo:38,cents:[-3073,-3031,-2968,-2924,-2871,-2823,-2781,-2738,-2700,-2665,-2632,-2603,-2581,-2560,-2544,-2531,-2523,-2518,-2518,-2525,-2524,-2526,-2548,-2575,-2601,-2627,-2656,-2687,-2721,-2757,-2796,-2837,-2880,-2925,-2972,-3021,-3071],level:.6736,gains:[92,74,83,77,68,62,57,62,51,52,45,42,37,30,22,21,15,6,0,-2,-12,-23,-26,-39,-43,-56,-65,-78,-87,-99,-111,-123,-136,-148,-161,-173,-186]},tuba:{lo:26,cents:[-3331,-2942,-2920,-2945,-3018,-3058,-3103,-3203,-3208,-3196,-3180,-3138,-3084,-3033,-2971,-2925,-2871,-2824,-2780,-2738,-2699,-2664,-2632,-2604,-2580,-2560,-2544,-2531,-2523,-2518,-2517,-2525,-2516,-2526,-2549],level:.7531,gains:[164,76,49,40,34,33,54,25,6,9,3,1,-3,11,5,10,-6,2,-7,-8,0,4,-5,-12,-13,-12,-16,-25,-31,-31,-39,-48,-53,-58,-69]},horn:{lo:39,cents:[-3059,-3008,-2951,-2900,-2852,-2807,-2763,-2723,-2689,-2658,-2627,-2603,-2582,-2565,-2552,-2543,-2539,-2536,-2534,-2538,-2555,-2572,-2597,-2619,-2644,-2673,-2704,-2738,-2773,-2811,-2853,-2896,-2941,-2988,-3035,-3086,-3137,-3191,-3248,-3304,-3366],level:1.0577,gains:[60,54,56,46,56,45,45,52,58,53,46,42,43,38,30,23,24,19,11,1,0,-9,-13,-23,-28,-39,-48,-58,-66,-79,-90,-100,-114,-127,-139,-152,-165,-177,-191,-203,-215]}}};var WIND_TRIM_TABLE_1={22050:{trumpet:{lo:50,cents:[-4225,-4228,-4232,-4238,-4246,-4256,-4267,-4281,-4296,-4313,-4333,-4354,-4379,-4404,-4433,-4464,-4499,-4535,-4572,-4616,-4665,-4713,-4767,-4823,-4878,-4948,-5019,-5091,-5177,-5257,-5352,-5450,-5551,-5652,-5784],level:.9712,gains:[138,131,124,118,111,104,97,90,83,75,67,59,50,41,32,21,11,0,-14,-25,-35,-48,-61,-74,-92,-101,-112,-126,-133,-147,-153,-161,-169,-181,-176]},harmon:{lo:50,cents:[-4225,-4228,-4232,-4238,-4246,-4256,-4267,-4281,-4296,-4313,-4333,-4354,-4379,-4404,-4433,-4464,-4499,-4535,-4572,-4616,-4665,-4713,-4767,-4823,-4878,-4948,-5019,-5091,-5177,-5257,-5352,-5450,-5551,-5652,-5784],level:.6641,gains:[1292,1201,1089,1028,939,862,750,650,454,487,509,434,300,40,-245,-50,106,79,-24,39,0,-165,-484,-728,-450,-232,-166,-207,-357,-677,-924,-616,-345,-204,-117]},plunger:{lo:50,cents:[-4235,-4238,-4243,-4249,-4256,-4267,-4278,-4292,-4307,-4324,-4344,-4366,-4390,-4416,-4445,-4476,-4511,-4548,-4585,-4629,-4678,-4726,-4781,-4837,-4892,-4963,-5034,-5107,-5194,-5274,-5370,-5468,-5571,-5672,-5805],level:.798,gains:[15,0,-14,-27,-41,-56,-70,-84,-97,-108,-114,-116,-114,-110,-106,-99,-86,-65,-33,11,62,111,157,192,216,232,240,247,260,284,324,382,456,543,637]},trombone:{lo:38,cents:[-4316,-4300,-4284,-4272,-4261,-4251,-4243,-4236,-4231,-4227,-4225,-4224,-4225,-4228,-4232,-4238,-4246,-4256,-4267,-4281,-4296,-4313,-4333,-4354,-4379,-4404,-4433,-4464,-4499,-4535,-4572,-4616,-4665,-4713,-4767,-4823,-4878],level:1.1414,gains:[118,110,103,99,92,84,77,72,66,59,51,44,37,31,25,19,12,7,0,-6,-13,-20,-26,-34,-42,-50,-58,-68,-77,-88,-101,-112,-122,-135,-148,-162,-180]},tuba:{lo:26,cents:[-4028,-3992,-4101,-4190,-4224,-4209,-4268,-4354,-4368,-4358,-4338,-4329,-4316,-4300,-4286,-4272,-4261,-4251,-4243,-4236,-4231,-4227,-4225,-4224,-4225,-4228,-4232,-4238,-4246,-4256,-4267,-4281,-4296,-4313,-4333],level:1.2795,gains:[144,115,104,96,84,70,62,72,67,56,46,36,27,20,11,9,4,0,-3,-3,-6,-8,-14,-21,-28,-34,-40,-45,-51,-56,-62,-68,-74,-80,-86]},horn:{lo:39,cents:[-4278,-4265,-4251,-4240,-4230,-4222,-4215,-4210,-4207,-4204,-4203,-4204,-4207,-4211,-4217,-4224,-4234,-4245,-4258,-4273,-4290,-4310,-4331,-4355,-4380,-4409,-4439,-4473,-4509,-4545,-4588,-4636,-4684,-4737,-4793,-4847,-4916,-4986,-5057,-5142,-5220],level:1.7422,gains:[93,84,82,78,74,72,73,71,71,65,58,51,45,39,34,29,23,17,12,6,0,-6,-12,-19,-26,-33,-42,-50,-60,-72,-82,-92,-105,-118,-133,-150,-162,-176,-192,-203,-219]}},44100:{trumpet:{lo:50,cents:[-4106,-4101,-4097,-4094,-4092,-4091,-4092,-4094,-4097,-4101,-4107,-4114,-4122,-4131,-4142,-4154,-4167,-4182,-4199,-4217,-4238,-4259,-4282,-4308,-4335,-4365,-4397,-4432,-4469,-4508,-4548,-4594,-4640,-4695,-4751],level:.9423,gains:[160,153,145,138,131,123,115,107,98,89,80,70,60,49,38,26,13,0,-14,-28,-42,-57,-73,-88,-104,-119,-134,-149,-163,-176,-190,-202,-214,-221,-228]},harmon:{lo:50,cents:[-4106,-4101,-4097,-4094,-4092,-4091,-4092,-4094,-4097,-4101,-4107,-4114,-4122,-4131,-4142,-4154,-4167,-4182,-4199,-4217,-4238,-4259,-4282,-4308,-4335,-4365,-4397,-4432,-4469,-4508,-4548,-4594,-4640,-4695,-4751],level:.617,gains:[1335,1242,1130,1064,972,893,778,669,469,500,527,453,311,43,-240,-54,99,64,-44,29,0,-157,-469,-703,-437,-232,-173,-218,-379,-699,-947,-655,-387,-236,-154]},plunger:{lo:50,cents:[-4116,-4110,-4106,-4103,-4102,-4101,-4102,-4104,-4107,-4111,-4117,-4124,-4132,-4141,-4152,-4164,-4178,-4193,-4210,-4228,-4249,-4271,-4294,-4320,-4346,-4377,-4410,-4444,-4481,-4521,-4561,-4607,-4654,-4709,-4765],level:.792,gains:[16,0,-14,-29,-43,-58,-72,-87,-101,-112,-118,-121,-121,-118,-115,-109,-97,-76,-43,1,53,107,157,200,232,255,272,287,307,337,381,443,521,609,705]},trombone:{lo:38,cents:[-4263,-4243,-4223,-4206,-4191,-4176,-4163,-4151,-4139,-4129,-4120,-4113,-4106,-4101,-4097,-4094,-4092,-4091,-4092,-4094,-4097,-4101,-4107,-4114,-4122,-4131,-4142,-4154,-4167,-4182,-4199,-4217,-4238,-4259,-4282,-4308,-4335],level:1.1326,gains:[126,117,111,105,98,90,83,78,71,64,56,49,41,34,27,21,14,7,0,-8,-15,-23,-31,-39,-49,-58,-68,-79,-91,-103,-116,-130,-144,-158,-174,-189,-206]},tuba:{lo:26,cents:[-4009,-3969,-4075,-4161,-4193,-4176,-4232,-4316,-4327,-4314,-4291,-4280,-4263,-4243,-4225,-4207,-4191,-4176,-4163,-4151,-4139,-4129,-4120,-4113,-4106,-4101,-4097,-4094,-4092,-4091,-4092,-4094,-4097,-4101,-4107],level:1.2794,gains:[146,117,106,98,86,71,64,74,69,58,47,37,28,21,12,9,4,0,-3,-4,-7,-9,-15,-22,-30,-36,-43,-49,-55,-61,-68,-74,-81,-88,-95]},horn:{lo:39,cents:[-4222,-4205,-4187,-4171,-4156,-4143,-4131,-4120,-4110,-4101,-4093,-4087,-4081,-4077,-4074,-4072,-4071,-4072,-4073,-4076,-4080,-4086,-4092,-4100,-4110,-4120,-4132,-4145,-4160,-4176,-4195,-4214,-4236,-4259,-4284,-4310,-4341,-4372,-4406,-4442,-4481],level:1.7269,gains:[102,92,90,86,82,80,80,78,78,72,64,57,50,44,38,32,26,20,13,7,0,-7,-14,-22,-30,-39,-48,-59,-70,-82,-95,-108,-122,-138,-153,-170,-186,-203,-220,-236,-252]}},48e3:{trumpet:{lo:50,cents:[-4097,-4091,-4086,-4082,-4080,-4078,-4078,-4079,-4081,-4084,-4089,-4094,-4101,-4109,-4119,-4129,-4141,-4155,-4170,-4186,-4204,-4223,-4245,-4267,-4292,-4319,-4348,-4378,-4411,-4448,-4487,-4527,-4572,-4618,-4665],level:.9403,gains:[162,155,147,140,132,124,116,108,99,90,81,71,61,50,38,26,13,0,-14,-28,-43,-58,-74,-89,-105,-121,-136,-152,-167,-180,-193,-206,-216,-225,-236]},harmon:{lo:50,cents:[-4097,-4091,-4086,-4082,-4080,-4078,-4078,-4079,-4081,-4084,-4089,-4094,-4101,-4109,-4119,-4129,-4141,-4155,-4170,-4186,-4204,-4223,-4245,-4267,-4292,-4319,-4348,-4378,-4411,-4448,-4487,-4527,-4572,-4618,-4665],level:.6137,gains:[1339,1245,1133,1066,974,895,780,671,469,501,528,454,312,43,-240,-55,99,63,-46,28,0,-156,-467,-701,-436,-232,-173,-220,-381,-701,-948,-657,-388,-239,-159]},plunger:{lo:50,cents:[-4106,-4100,-4095,-4092,-4089,-4088,-4088,-4089,-4091,-4094,-4099,-4104,-4111,-4119,-4129,-4140,-4152,-4165,-4180,-4196,-4215,-4234,-4256,-4279,-4304,-4331,-4360,-4390,-4423,-4461,-4499,-4539,-4585,-4632,-4679],level:.7915,gains:[16,0,-14,-29,-43,-58,-72,-87,-101,-112,-119,-122,-121,-119,-116,-110,-98,-77,-44,0,53,106,157,200,233,257,275,290,310,341,386,448,526,615,711]},trombone:{lo:38,cents:[-4258,-4238,-4219,-4201,-4185,-4170,-4156,-4144,-4132,-4122,-4112,-4104,-4097,-4091,-4086,-4082,-4080,-4078,-4078,-4079,-4081,-4084,-4089,-4094,-4101,-4109,-4119,-4129,-4141,-4155,-4170,-4186,-4204,-4223,-4245,-4267,-4292],level:1.1319,gains:[126,118,111,106,99,91,84,78,71,64,56,49,41,34,28,21,14,7,0,-8,-15,-23,-31,-40,-49,-59,-69,-80,-92,-104,-117,-131,-146,-160,-176,-192,-208]},tuba:{lo:26,cents:[-4007,-3967,-4073,-4159,-4190,-4173,-4229,-4313,-4324,-4311,-4287,-4276,-4258,-4238,-4220,-4202,-4185,-4170,-4156,-4144,-4132,-4122,-4112,-4104,-4097,-4091,-4086,-4082,-4080,-4078,-4078,-4079,-4081,-4084,-4089],level:1.2794,gains:[146,117,106,98,86,72,65,74,69,58,48,38,28,21,12,9,4,0,-3,-4,-7,-9,-15,-22,-30,-36,-43,-49,-55,-61,-68,-75,-81,-89,-96]},horn:{lo:39,cents:[-4218,-4200,-4182,-4165,-4151,-4137,-4124,-4113,-4102,-4093,-4084,-4077,-4071,-4066,-4062,-4060,-4058,-4058,-4059,-4061,-4064,-4068,-4073,-4080,-4088,-4097,-4108,-4119,-4133,-4147,-4163,-4181,-4200,-4221,-4244,-4268,-4295,-4324,-4353,-4386,-4422],level:1.7256,gains:[102,93,91,86,82,80,80,79,78,72,65,57,51,44,38,33,26,20,13,7,0,-7,-14,-22,-31,-39,-49,-59,-71,-83,-96,-109,-124,-139,-155,-172,-188,-205,-223,-240,-255]}}};var WIND_TRIM_RATES=Object.freeze([22050,44100,48e3]);function nearestRate(sampleRate){let best=WIND_TRIM_RATES[0];for(let rate2 of WIND_TRIM_RATES)Math.abs(rate2-sampleRate)<Math.abs(best-sampleRate)&&(best=rate2);return best}function windTrimRow(preset5,sampleRate,calibration=0){let rate2=nearestRate(sampleRate);if(calibration>=1){let row2=WIND_TRIM_TABLE_1[rate2]?.[preset5];if(row2)return row2}return WIND_TRIM_TABLE[rate2]?.[preset5]}function windCalibrated(preset5){return WIND_TRIM_TABLE_1[WIND_TRIM_RATES[0]]?.[preset5]!==void 0}function interpolate(lo,grid2,hz3){let midi2=69+12*Math.log2(hz3/440)-lo,last=grid2.length-1;if(last<0)return 0;if(midi2<=0)return grid2[0]/100;if(midi2>=last)return grid2[last]/100;let i=Math.floor(midi2),u=midi2-i;return((1-u)*grid2[i]+u*grid2[i+1])/100}function rowCents(row2,hz3){return interpolate(row2.lo,row2.cents,hz3)}function rowGain(row2,hz3){return row2.gains?10**(interpolate(row2.lo,row2.gains,hz3)/20):1}function windTrim(preset5,sampleRate,calibration=0){let lips=calibration>=1&&windCalibrated(preset5),row2=windTrimRow(preset5,sampleRate,calibration);return row2?{cents:hz3=>rowCents(row2,hz3),level:row2.level,gain:hz3=>rowGain(row2,hz3),...lips?{lips:1}:{}}:{cents:()=>0,level:1,...lips?{lips:1}:{}}}var WindBiquad=class{b0=1;b1=0;b2=0;a1=0;a2=0;z1=0;z2=0;set(type,hz3,q3,gainDb,sampleRate){let f=Math.min(Math.max(hz3,10),.45*sampleRate),w=2*Math.PI*f/sampleRate,cos=Math.cos(w),alpha=Math.sin(w)/(2*Math.max(.05,q3)),A=10**(gainDb/40),b0=1,b1=0,b2=0,a0=1,a1=0,a2=0;switch(type){case"lpf":b0=(1-cos)/2,b1=1-cos,b2=b0,a0=1+alpha,a1=-2*cos,a2=1-alpha;break;case"hpf":b0=(1+cos)/2,b1=-(1+cos),b2=b0,a0=1+alpha,a1=-2*cos,a2=1-alpha;break;case"bpf":b0=alpha,b2=-alpha,a0=1+alpha,a1=-2*cos,a2=1-alpha;break;case"peak":b0=1+alpha*A,b1=-2*cos,b2=1-alpha*A,a0=1+alpha/A,a1=-2*cos,a2=1-alpha/A;break;case"highshelf":{let sq=2*Math.sqrt(A)*alpha;b0=A*(A+1+(A-1)*cos+sq),b1=-2*A*(A-1+(A+1)*cos),b2=A*(A+1+(A-1)*cos-sq),a0=A+1-(A-1)*cos+sq,a1=2*(A-1-(A+1)*cos),a2=A+1-(A-1)*cos-sq;break}}return this.b0=b0/a0,this.b1=b1/a0,this.b2=b2/a0,this.a1=a1/a0,this.a2=a2/a0,this}process(x){let y=this.b0*x+this.z1;return this.z1=this.b1*x-this.a1*y+this.z2,this.z2=this.b2*x-this.a2*y,y}},LoopDelay=class{buffer;mask;write=0;whole=1;a=0;u1=0;y1=0;constructor(maxDelay){let size=8;for(;size<Math.ceil(maxDelay)+8;)size*=2;this.buffer=new Float64Array(size),this.mask=size-1}set(delay,w=0){let total=Math.min(Math.max(delay,1.5),this.mask-3),whole=Math.floor(total-.5);this.whole=whole,this.a=thiranFor(total-whole,w)}read(){let u=this.buffer[this.write-this.whole&this.mask],y=this.a*u+this.u1-this.a*this.y1;return this.u1=u,this.y1=y,y}push(value){this.buffer[this.write]=value,this.write=this.write+1&this.mask}};function onePoleDelay(p,w){return w<1e-9?p/(1-p):Math.atan2(p*Math.sin(w),1-p*Math.cos(w))/w}function dcBlockDelay(r,w){let num9=Math.atan2(Math.sin(w),1-Math.cos(w)),den=Math.atan2(r*Math.sin(w),1-r*Math.cos(w));return-(num9-den)/w}var WIND_BLOCK=32,NO_TRIM={cents:()=>0,level:1},SLUR_SECONDS=.03,ADAA_DELAY=.5,clamp6=(x,lo,hi)=>x<lo?lo:x>hi?hi:x;function reedG(p,s){return p*clamp6(.7-s*p,-1,1)}function reedF(p,s){let p1=-.3/s,p2=1.7/s,mid=x=>.35*x*x-s*x*x*x/3;return p<p1?.5*p*p+mid(p1)-.5*p1*p1:p>p2?-.5*p*p+mid(p2)+.5*p2*p2:mid(p)}var JET_EDGE=1.3247179572447458;function jetG(x){return clamp6(x*x*x-x,-1,1)}function jetF(x){let a=Math.abs(x),poly=v=>.25*v**4-.5*v*v;return a<=JET_EDGE?poly(x):poly(JET_EDGE)+(a-JET_EDGE)}var LipResonator=class{a1=0;a2=0;y1=0;y2=0;g=1;set(hz3,q3,gain,sampleRate){let radius=Math.exp(-Math.PI*hz3/(q3*sampleRate));this.a1=-2*radius*Math.cos(2*Math.PI*hz3/sampleRate),this.a2=radius*radius,this.g=gain*(1+this.a1+this.a2)}process(x){let y=this.g*x-this.a1*this.y1-this.a2*this.y2;return this.y2=this.y1,this.y1=y,y}},Adaa=class{constructor(f,F2){this.f=f;this.F=F2;this.F1=F2(0)}f;F;x1=0;F1;process(x){let Fx=this.F(x),dx=x-this.x1,y=Math.abs(dx)<1e-6?this.f(.5*(x+this.x1)):(Fx-this.F1)/dx;return this.x1=x,this.F1=Fx,y}},WindVoice=class{constructor(base,note2,sampleRate,trim=NO_TRIM){this.note=note2;this.sampleRate=sampleRate;this.trim=trim;this.settings=base;let p=base;this.os=p.model!=="lips",this.rate=this.os?2*sampleRate:sampleRate,this.random=seededRandom(`${note2.seed}:wind`);let lowest=1/0;for(let s2 of note2.segments)lowest=Math.min(lowest,s2.hz);lowest=Math.max(15,lowest)*.5;let maxDelay=this.rate/lowest*2.2+16;this.d0=new LoopDelay(maxDelay),this.d1=new LoopDelay(maxDelay),this.loopLp=new OnePole2(4e3,this.rate),this.dc=new DcBlock(this.rate,20),this.outDc=new DcBlock(sampleRate,20),this.noiseLp=new OnePole2(2500,this.rate),this.decimate=this.os?new Decimate2:void 0,this.reedSlope=.3*(.6+.8*p.reed);let s=this.reedSlope;p.model==="reed"?this.shaper=new Adaa(x=>reedG(x,s),x=>reedF(x,s)):p.model==="jet"&&(this.shaper=new Adaa(jetG,jetF)),this.hz=note2.segments[0].hz,this.growlHz=70+50*this.random();let k={jet:8,reed:10,sax:14,lips:22}[p.model],v=clamp6(note2.velocity+(note2.push??0),0,1);this.shelf.set("highshelf",1500,.7,(v-.6)*k,sampleRate),this.setupMute(sampleRate),this.endAt=note2.length+Math.round((p.release*3+.05)*sampleRate),this.control(0)}note;sampleRate;trim;endAt;rate;os;random;d0;d1;loopLp;dc;outDc;noiseLp;lip=new LipResonator;shelf=new WindBiquad;tone=new WindBiquad;mutes=[];wahFilter=new WindBiquad;decimate;shaper;reedSlope;settings;n=0;envelope=0;oz1=0;hz;slurFrom=0;slurAt=-1;segment=0;pressure=0;breathGain=1;wah=1;gainTarget=1;gainNow=-1;growlHz;setupMute(sr){let add=(type,hz3,q3,db2)=>this.mutes.push(new WindBiquad().set(type,hz3,q3,db2,sr));switch(this.settings.mute){case"straight":add("hpf",450,.7,0),add("peak",1800,2,9),add("lpf",7e3,.7,0);break;case"cup":add("hpf",220,.7,0),add("peak",850,1.5,5),add("lpf",2200,.8,0);break;case"harmon":add("hpf",700,.8,0),add("peak",1650,4,14),add("lpf",4200,1,0);break;default:break}}control(n2){let{note:note2,sampleRate:sr,rate:rate2}=this,t=n2/sr,p=this.settings;if(note2.lane){let next={...p},changed=!1;for(let key of["breath","noise","wah","growl","flutter"]){let value=note2.lane(key,t);value!==void 0&&(next[key]=clamp6(value,0,1),changed=!0)}changed&&(p=this.settings=next)}for(;this.segment+1<note2.segments.length&¬e2.segments[this.segment+1].at<=n2;)this.segment+=1,this.slurFrom=this.hz,this.slurAt=note2.segments[this.segment].at;let target=note2.segments[this.segment].hz,hz3=target;if(this.slurAt>=0){let u=(n2-this.slurAt)/(SLUR_SECONDS*sr);u>=1?this.slurAt=-1:hz3=this.slurFrom*(target/this.slurFrom)**u}this.hz=hz3,this.gainTarget=this.trim.gain?this.trim.gain(hz3):1,this.gainNow<0&&(this.gainNow=this.gainTarget);let cents=note2.cents?note2.cents(t):0,vib=p.vibmod>0?p.vibmod*Math.sin(2*Math.PI*p.vib*t)*Math.min(1,t/.3):0,f0=hz3*2**(cents/1200+vib/12),f=f0*2**(this.trim.cents(f0)/1200),w=2*Math.PI*f/rate2,period=rate2/f;switch(p.model){case"reed":this.d0.set(period/2-.5-ADAA_DELAY,w);break;case"sax":{let total=period-.5;this.d0.set((1-.35)*total,w),this.d1.set(.35*total,w);break}case"jet":{let corner=clamp6(f*(3+9*p.bright),800,.4*rate2);this.loopLp.set(corner,rate2);let filters=onePoleDelay(this.loopLp.p,w)+dcBlockDelay(this.dc.r,w)+ADAA_DELAY;p.stopped?(this.d0.set(.5*period-filters,w),this.d1.set(.5*period*(.9+.2*p.reed),w)):(this.d0.set(1.5*period-filters,w),this.d1.set(.5*period*(.9+.2*p.reed),w));break}case"lips":this.d0.set(2*period-dcBlockDelay(this.dc.r,w),w),this.trim.lips?this.lip.set(f*(1+.04*(p.reed-.5)),40,3,rate2):this.lip.set(f*(.95+.04*(p.reed-.5)),12,3,rate2);break}p.model!=="jet"&&this.tone.set("highshelf",clamp6(4*hz3,500,.4*sr),.7,(p.bright-.5)*18,sr);let v=clamp6(note2.velocity+(note2.push??0),0,1),drive=clamp6(p.breath*(.55+.45*v),0,1),floor=.45;switch(p.model){case"reed":this.pressure=floor+.45*drive;break;case"sax":this.pressure=floor+.45*drive;break;case"jet":this.pressure=.9+.35*drive;break;case"lips":this.pressure=.6+.5*drive;break}if(this.breathGain=10**(30*(p.breath-.6)/20),p.mute==="plunger"){let open=Math.min(1,t/.15);this.wah=p.wah+p.wahenv*(1-p.wah)*open,this.wahFilter.set("lpf",400+4600*this.wah*this.wah,1.4,0,sr)}}tick(breath){let p=this.settings;switch(p.model){case"reed":{let bore=this.d0.read(),oz=.5*(bore+this.oz1);this.oz1=bore;let pdiff=-.95*oz-breath;return this.d0.push(breath+this.shaper.process(pdiff)),bore}case"sax":{let a=this.d0.read(),b=this.d1.read(),oz=.5*(a+this.oz1);this.oz1=a;let temp=-.95*oz,frame=temp-b,pdiff=breath-frame;return this.d1.push(temp),this.d0.push(breath-pdiff*clamp6(.7+this.reedSlope*pdiff,-1,1)-temp),frame}case"jet":{let boreOut=this.d0.read(),temp=this.dc.process(-this.loopLp.process(boreOut)),jet=this.d1.read();this.d1.push(breath-.5*temp);let offset=p.stopped?0:.12,jt=this.shaper.process(jet+offset)-jetG(offset);return this.d0.push(jt+.5*temp),.3*boreOut+(p.stopped?0:.12*jt)}case"lips":{let bore=.85*this.d0.read(),mouth=.3*breath,delta=this.lip.process(mouth-bore);delta*=delta,this.trim.lips?delta=delta/(1+delta):delta>1&&(delta=1);let frame=delta*mouth+(1-delta)*bore;return this.d0.push(this.dc.process(frame)),bore*2}}}process(out,offset,count2){let{sampleRate:sr,note:note2}=this,p=this.settings,attack=Math.max(1,p.attack*sr),release=Math.max(1,p.release*sr),level2=this.trim.level*p.gain;for(let i=0;i<count2;i+=1){let n2=this.n;if(n2>=this.endAt)return!1;n2%WIND_BLOCK===0&&n2>0&&(this.control(n2),p=this.settings),n2<note2.length?this.envelope=Math.min(1,this.envelope+1/attack):this.envelope=Math.max(0,this.envelope-1/release);let t=n2/sr,amp=this.pressure*this.envelope;p.vibmod>0&&(amp*=1+.04*Math.sin(2*Math.PI*p.vib*t)),p.flutter>0&&(amp*=1-p.flutter*.5*(.5+.5*Math.sin(2*Math.PI*26*t))),p.growl>0&&(amp*=1+p.growl*.25*Math.sin(2*Math.PI*this.growlHz*t));let y;if(this.os){let a=this.tick(this.breath(amp,p)),b=this.tick(this.breath(amp,p));y=this.decimate.process(a,b)}else y=this.tick(this.breath(amp,p));p.growl>0&&(y=Math.tanh(y*(1+2*p.growl))/(1+p.growl)),p.model!=="jet"&&(y=this.tone.process(y));for(let filter of this.mutes)y=filter.process(y);p.mute==="plunger"&&(y=this.wahFilter.process(y)),y=this.shelf.process(y),this.gainNow+=(this.gainTarget-this.gainNow)*.002,out[offset+i]+=this.outDc.process(y)*level2*this.gainNow*this.breathGain,this.n+=1}return!0}breath(amp,p){let noise2=this.noiseLp.process(this.random()*2-1);return amp*(1+p.noise*1.6*noise2)}};var SLUR_GAP_SECONDS=.01,WIND_STEAL_FADE=.08,SECTION_CENTS=9,SECTION_LATE=.018,PUSH=Object.freeze({accent:.15,marcato:.25,ghost:-.4});function span2(note2,context){if(context.warp)return warpedSpan(context.warp,note2.startTick,note2.durationTicks);let perTick=60*context.sampleRate/(context.tempoBpm*context.ticksPerBeat);return{start:Math.max(0,Math.floor(note2.startTick*perTick)),length:Math.max(1,Math.floor(note2.durationTicks*perTick))}}function laneOf2(track2,param2){let points=track2.fxAutomation?.[`wind-${param2}`];return points&&points.length>0?points:void 0}function windLines(notes,context,legato){let planned=notes.map(note2=>({note:note2,...span2(note2,context)})).filter(entry=>entry.start<context.samples).sort((a,b)=>a.start-b.start||b.note.pitch-a.note.pitch||(a.note.id<b.note.id?-1:a.note.id>b.note.id?1:0)),lines=[],slurGap=Math.round(SLUR_GAP_SECONDS*context.sampleRate),index=0,previous=[];for(;index<planned.length;){let at3=planned[index].start,group=[];for(;index<planned.length&&planned[index].start===at3;)group.push(planned[index++]);let held=previous.filter(line=>line.start+line.length+slurGap>at3),only=group[0];if(legato&&group.length===1&&held.length===1&&previous.length===1&&!only.note.performance?.cents&&only.note.articulation!=="staccato"){let line=held[0];line.notes.push(only.note),line.segments.push({at:at3-line.start,hz:noteHz(only.note.pitch,only.note.cents,context.tuning)}),line.length=only.start+only.length-line.start;continue}previous=group.map(({note:note2,start,length})=>({start,length,notes:[note2],segments:[{at:0,hz:noteHz(note2.pitch,note2.cents,context.tuning)}]})),lines.push(...previous)}return lines}function renderWindTrack(dry,notes,track2,context){let{sampleRate,samples}=context,tickAt4=index=>context.warp?context.warp.tick(index):index/context.samplesPerTick,lanes=new Map;for(let{param:param2}of WIND_LANE_PARAMS){let points=laneOf2(track2,param2);points&&lanes.set(param2,points)}let base=windSettings(track2.wind),trim=windTrim(windPresetOf(track2.wind),sampleRate,context.score.calibration??0),players=Math.max(1,Math.round(base.players)),seedTick=context.seedTick??0,volumeLane=track2.volumeAutomation??[],volume=Math.max(0,Math.min(1,track2.volume??1)),gainAt=index=>volume*(volumeLane.length>0?interpolateAutomation(volumeLane,tickAt4(index),1):1),lines=windLines(notes,context,track2.glide===void 0),planned=[],i=0;for(;i<lines.length;){let j=i;for(;j<lines.length&&lines[j].start===lines[i].start;)j+=1;let tones=lines.slice(i,j),counts2=tones.map(()=>1);for(let k=tones.length;k<players;k+=1)counts2[k%tones.length]+=1;tones.forEach((line,t)=>{let head=line.notes[0],seed=`${head.id}:${head.startTick+seedTick}`,push=PUSH[head.articulation??""]??0,count2=counts2[t],random2=seededRandom(`${seed}:section`);for(let player=0;player<count2;player+=1){let cents=player===0?0:SECTION_CENTS*(2*random2()-1)||.5,late=player===0?0:Math.round(SECTION_LATE*random2()*sampleRate),soft=player===0?1:.8+.15*random2(),start=line.start+late;if(start>=samples)continue;let ratio2=2**(cents/1200),bend=head.performance?.cents,voice=new WindVoice(base,{segments:line.segments.map(s=>({at:s.at,hz:s.hz*ratio2})),length:Math.max(1,line.length-late),velocity:head.velocity,seed:player===0?seed:`${seed}:${player}`,...push?{push}:{},...bend?{cents:bend}:{},...lanes.size>0?{lane:(param2,t2)=>{let points=lanes.get(param2);return points?interpolateAutomation(points,tickAt4(start+t2*sampleRate),base[param2]):void 0}}:{}},sampleRate,trim);planned.push({voice,start,end:start+voice.endAt,steal:1/0,level:soft/Math.sqrt(count2)})}}),i=j}planned.sort((a,b)=>a.start-b.start);let fade=Math.max(1,Math.round(WIND_STEAL_FADE*sampleRate)),sounding=[];for(let entry of planned){for(let k=sounding.length-1;k>=0;k-=1)sounding[k].end<=entry.start&&sounding.splice(k,1);for(;sounding.length>=MAX_WIND_VOICES;){let oldest=sounding.shift();oldest.steal=entry.start,oldest.end=Math.min(oldest.end,entry.start+fade)}sounding.push(entry)}let scratch=new Float64Array(WIND_BLOCK);for(let{voice,start,end,steal,level:level2}of planned){let stop=Math.min(samples,end),at3=start;for(;at3<stop;){let count2=Math.min(WIND_BLOCK,stop-at3);scratch.fill(0,0,count2);let alive=voice.process(scratch,0,count2),gain=gainAt(at3)*level2;for(let k=0;k<count2;k+=1){let index=at3+k,g=gain;index>=steal&&(g*=index-steal>=fade?0:.5+.5*Math.cos(Math.PI*(index-steal)/fade)),dry[index]+=scratch[k]*g}if(!alive)break;at3+=count2}}applyModalKnee(dry,samples)}var WIND_ENGINE=Object.freeze({id:"wind",field:"wind",render(dry,_dryR,notes,track2,context){renderWindTrack(dry,notes,track2,context)},tailSeconds:track2=>windTailSeconds(track2.wind),stereo:()=>!1,assetDigests:track2=>[`winds:1:${windPresetOf(track2.wind)}`]});var VOWEL_FORMANTS=Object.freeze({a:[[650,0,80],[1080,-6,90],[2650,-7,120],[2900,-8,130],[3250,-22,140]],e:[[400,0,70],[1700,-14,80],[2600,-12,100],[3200,-14,120],[3580,-20,120]],i:[[290,0,40],[1870,-15,90],[2800,-18,100],[3250,-20,120],[3540,-30,120]],o:[[400,0,40],[800,-10,80],[2600,-12,100],[2800,-12,120],[3e3,-26,120]],u:[[350,0,40],[600,-20,60],[2700,-17,100],[2900,-14,120],[3300,-26,120]],ae:extended(660,1720,2410),aa:extended(710,1100,2540),oe:extended(390,1680,2400),ue:extended(300,1600,2200),y:extended(250,1750,2160),uh:extended(600,1170,2390),un:extended(500,1400,2500),en:extended(550,1650,2500),an:extended(650,1050,2550),on:extended(450,850,2550)});function extended(f1,f2,f3){return[[f1,0,70],[f2,-8,90],[f3,-14,110],[3300,-16,130],[3750,-24,140]]}function morphFormants(from,to,morph){let m=Math.min(1,Math.max(0,morph));return from.map(([hz3,level2,bw],index)=>{if(m===0)return[hz3,level2,bw];let[toHz,toLevel,toBw]=to[index]??[hz3,level2,bw];return m===1?[toHz,toLevel,toBw]:[hz3*(toHz/hz3)**m,level2+(toLevel-level2)*m,bw*(toBw/bw)**m]})}var row=(f,db2,bw)=>f.map((hz3,i)=>[hz3,db2[i],bw[i]]),SINGER_FORMANTS={soprano:{a:row([800,1150,2900,3900,4950],[0,-6,-32,-20,-50],[80,90,120,130,140]),e:row([350,2e3,2800,3600,4950],[0,-20,-15,-40,-56],[60,100,120,150,200]),i:row([270,2140,2950,3900,4950],[0,-12,-26,-26,-44],[60,90,100,120,120]),o:row([450,800,2830,3800,4950],[0,-11,-22,-22,-50],[70,80,100,130,135]),u:row([325,700,2700,3800,4950],[0,-16,-35,-40,-60],[50,60,170,180,200])},alto:{a:row([800,1150,2800,3500,4950],[0,-4,-20,-36,-60],[80,90,120,130,140]),e:row([400,1600,2700,3300,4950],[0,-24,-30,-35,-60],[60,80,120,150,200]),i:row([350,1700,2700,3700,4950],[0,-20,-30,-36,-60],[50,100,120,150,200]),o:row([450,800,2830,3500,4950],[0,-9,-16,-28,-55],[70,80,100,130,135]),u:row([325,700,2530,3500,4950],[0,-12,-30,-40,-64],[50,60,170,180,200])},tenor:{a:row([650,1080,2650,2900,3250],[0,-6,-7,-8,-22],[80,90,120,130,140]),e:row([400,1700,2600,3200,3580],[0,-14,-12,-14,-20],[70,80,100,120,120]),i:row([290,1870,2800,3250,3540],[0,-15,-18,-20,-30],[40,90,100,120,120]),o:row([400,800,2600,2800,3e3],[0,-10,-12,-12,-26],[40,80,100,120,120]),u:row([350,600,2700,2900,3300],[0,-20,-17,-14,-26],[40,60,100,120,120])},bass:{a:row([600,1040,2250,2450,2750],[0,-7,-9,-9,-20],[60,70,110,120,130]),e:row([400,1620,2400,2800,3100],[0,-12,-9,-12,-18],[40,80,100,120,120]),i:row([250,1750,2600,3050,3340],[0,-30,-16,-22,-28],[60,90,100,120,120]),o:row([400,750,2400,2600,2900],[0,-11,-21,-20,-40],[40,80,100,120,120]),u:row([350,600,2400,2675,2950],[0,-20,-32,-28,-36],[40,80,100,120,120])}};function morphVowel(a,b,t){return a.map(([fa,da,ba],i)=>{let[fb,db2,bb]=b[i];return[fa*(fb/fa)**t,da+(db2-da)*t,ba*(bb/ba)**t]})}function vowelAt(voice,spec,t){let table2=SINGER_FORMANTS[voice],names=spec.split(">").map(s=>table2[s]?s:"a");if(names.length===1)return[...table2[names[0]]];if(t>=1)return[...table2[names[names.length-1]]];let x=Math.min(.999999,Math.max(0,t))*(names.length-1),i=Math.floor(x);return morphVowel(table2[names[i]],table2[names[i+1]],x-i)}var Resonator=class{a=1;b=0;c=0;y1=0;y2=0;set(hz3,bw,sampleRate){let t=1/sampleRate,f=Math.min(hz3,sampleRate*.45);this.c=-Math.exp(-2*Math.PI*bw*t),this.b=2*Math.exp(-Math.PI*bw*t)*Math.cos(2*Math.PI*f*t),this.a=1-this.b-this.c}coeffsInto(out,at3){return out[at3]=this.a,out[at3+1]=this.b,out[at3+2]=this.c,at3+3}response(cw,sw,c2w,s2w){let out=new Float64Array(2);return this.responseInto(cw,sw,c2w,s2w,out),[out[0],out[1]]}responseInto(cw,sw,c2w,s2w,out){let re=1-this.b*cw-this.c*c2w,im=this.b*sw+this.c*s2w,d=re*re+im*im;out[0]=this.a*re/d,out[1]=-this.a*im/d}process(x){let y=this.a*x+this.b*this.y1+this.c*this.y2;return this.y2=this.y1,this.y1=y,y}},Bandpass=class{b0=0;b2=0;a1=0;a2=0;x1=0;x2=0;y1=0;y2=0;set(hz3,bw,sampleRate){let w=2*Math.PI*Math.min(hz3,sampleRate*.45)/sampleRate,q3=Math.max(.3,hz3/Math.max(1,bw)),alpha=Math.sin(w)/(2*q3),a0=1+alpha;this.b0=alpha/a0,this.b2=-alpha/a0,this.a1=-2*Math.cos(w)/a0,this.a2=(1-alpha)/a0}coeffsInto(out,at3){return out[at3]=this.b0,out[at3+1]=this.b2,out[at3+2]=this.a1,out[at3+3]=this.a2,at3+4}response(cw,sw,c2w,s2w){let out=new Float64Array(2);return this.responseInto(cw,sw,c2w,s2w,out),[out[0],out[1]]}responseInto(cw,sw,c2w,s2w,out){let nr=this.b0+this.b2*c2w,ni=-this.b2*s2w,dr=1+this.a1*cw+this.a2*c2w,di=-this.a1*sw-this.a2*s2w,d=dr*dr+di*di;out[0]=(nr*dr+ni*di)/d,out[1]=(ni*dr-nr*di)/d}process(x){let y=this.b0*x+this.b2*this.x2-this.a1*this.y1-this.a2*this.y2;return this.x2=this.x1,this.x1=x,this.y2=this.y1,this.y1=y,y}},Cascade=class{res=[new Resonator,new Resonator,new Resonator,new Resonator,new Resonator];set(formants,scale3,sampleRate){for(let i=0;i<5;i+=1){let[hz3,,bw]=formants[i];this.res[i].set(hz3*scale3,bw*Math.sqrt(scale3),sampleRate)}}process(x){let y=x;for(let r of this.res)y=r.process(y);return y}};function tuneToPitch(formants,f0,scale3){let need1=1.05*f0/scale3;if(formants[0][0]>=need1&&formants[1][0]>=Math.max(2.05*f0/scale3,formants[0][0]*1.25))return formants;let out=formants.map(f=>[...f]),f1=out[0],want1=1.05*f0/scale3;f1[0]<want1&&(f1[2]*=want1/f1[0],f1[0]=want1);let f2=out[1],want2=Math.max(2.05*f0/scale3,f1[0]*1.25);return f2[0]<want2&&(f2[2]*=want2/f2[0],f2[0]=want2),out}var GLOTTAL_TABLE=2048,RD_MIN=.3,RD_MAX=2.7,RD_STEP=.1,RD_COUNT=Math.round((RD_MAX-RD_MIN)/RD_STEP)+1;function lfTable(rd,n2){let ra=(-1+4.8*rd)/100,rk=(22.4+11.8*rd)/100,tp=1/(2*(rk/(4*(.11*rd/(.5+1.2*rk)-ra)))),te=tp*(1+rk);te>.98&&(te=.98);let ta=Math.max(ra,1e-4),tc=1,eps=1/ta;for(let i=0;i<60;i+=1)eps=(1-Math.exp(-eps*(tc-te)))/ta;let wg=Math.PI/tp,shape=(alpha,out2)=>{let e0=-1/(Math.exp(alpha*te)*Math.sin(wg*te)),sum=0;for(let i=0;i<n2;i+=1){let t=i/n2,v;t<=te?v=e0*Math.exp(alpha*t)*Math.sin(wg*t):v=-(1/(eps*ta))*(Math.exp(-eps*(t-te))-Math.exp(-eps*(tc-te))),out2[i]=v,sum+=v}return sum/n2},out=new Float64Array(n2),lo=-50,hi=200;for(let i=0;i<80;i+=1){let mid=(lo+hi)/2;shape(mid,out)>0?hi=mid:lo=mid}shape((lo+hi)/2,out);let mean=0;for(let v of out)mean+=v;mean/=n2;for(let i=0;i<n2;i+=1)out[i]=out[i]-mean;return out}var tables;function lfTables(){if(!tables){tables=[];for(let i=0;i<RD_COUNT;i+=1)tables.push(lfTable(RD_MIN+i*RD_STEP,GLOTTAL_TABLE))}return tables}var MIP_HARMONICS=[2,3,4,6,8,11,16,23,32,45,64,91,128,181,256,362,512,724,1023],mips;function truncate(src,harmonics){let n2=src.length,re=Float64Array.from(src),im=new Float64Array(n2);fftInPlace(re,im);for(let k=0;k<n2;k+=1)(k<=n2/2?k:n2-k)>harmonics&&(re[k]=0,im[k]=0);fftInPlace(re,im,!0);for(let i=0;i<n2;i+=1)re[i]=re[i]/n2;return re}function mipTables(){if(!mips){let base=lfTables();mips=MIP_HARMONICS.map(h=>base.map(t=>truncate(t,h)))}return mips}function readLevel(level2,ri,rf,i0,i1,pf){let a=level2[ri],b=level2[ri+1],va=a[i0]+(a[i1]-a[i0])*pf,vb=b[i0]+(b[i1]-b[i0])*pf;return va+(vb-va)*rf}var lastInc=Number.NaN,lastLevel=0,lastBlend=0;function chooseLevel(inc){lastInc=inc;let nmax=.5/Math.max(inc,1e-9),j=0;for(;j+1<MIP_HARMONICS.length&&MIP_HARMONICS[j+1]<=nmax;)j+=1;if(j===0||MIP_HARMONICS[j]>nmax){lastLevel=0,lastBlend=-1;return}let top=j+1<MIP_HARMONICS.length?MIP_HARMONICS[j+1]:MIP_HARMONICS[j]*Math.SQRT2;lastLevel=j,lastBlend=Math.min(1,Math.log(nmax/MIP_HARMONICS[j])/Math.log(top/MIP_HARMONICS[j]))}function glottal(phase,rd,inc){let r=(Math.min(RD_MAX,Math.max(RD_MIN,rd))-RD_MIN)/RD_STEP,ri=Math.min(RD_COUNT-2,Math.floor(r)),rf=r-ri,p=phase*GLOTTAL_TABLE,pi=Math.floor(p),pf=p-pi,i0=pi%GLOTTAL_TABLE,i1=(pi+1)%GLOTTAL_TABLE;if(inc===void 0)return readLevel(lfTables(),ri,rf,i0,i1,pf);let m=mipTables();inc!==lastInc&&chooseLevel(inc);let j=lastLevel;if(lastBlend<0)return readLevel(m[0],ri,rf,i0,i1,pf);let lo=readLevel(m[j-1],ri,rf,i0,i1,pf),hi=readLevel(m[j],ri,rf,i0,i1,pf);return lo+(hi-lo)*lastBlend}var owRd=Number.NaN,owTe=0;function openWeight(phase,rd){if(rd!==owRd){let rk=(22.4+11.8*rd)/100,ra=(-1+4.8*rd)/100,rg=rk/(4*(.11*rd/(.5+1.2*rk)-ra));owRd=rd,owTe=Math.min(.98,1/(2*rg)*(1+rk))}let te=owTe;return phase<te?.5-.5*Math.cos(2*Math.PI*phase/te):.15}var spectra=new Map;function glottalSpectrum(rd,count2){let index=Math.round((Math.min(RD_MAX,Math.max(RD_MIN,rd))-RD_MIN)/RD_STEP),key=index*1024+count2,hit2=spectra.get(key);if(hit2)return hit2;let at3=RD_MIN+index*RD_STEP,n2=1024,x=new Float64Array(n2);for(let i=0;i<n2;i+=1)x[i]=glottal(i/n2,at3);let out=new Float64Array(count2+1);for(let h=1;h<=count2;h+=1){let re=0,im=0;for(let i=0;i<n2;i+=1){let a=2*Math.PI*h*i/n2;re+=x[i]*Math.cos(a),im-=x[i]*Math.sin(a)}out[h]=(re*re+im*im)/(n2*n2)}return spectra.set(key,out),out}var ph=p=>Object.freeze(p),V=(f,sung,to)=>ph({kind:"vowel",voiced:!0,f,...to?{to}:{},bw:[70,90,140],dur:.09,av:1,...sung?{sung}:{}}),S_BANDS=[[5600,1800,0],[8e3,2400,-4],[3800,1200,-18]],SH_BANDS=[[2600,800,0],[3600,1200,-3],[5200,2e3,-10]],F_BANDS=[[1600,2400,-6],[5e3,3500,0],[8e3,3e3,-4]],TH_BANDS=[[3200,2400,-6],[6200,3500,0],[8500,3e3,-3]],P_BURST=[[900,1200,0],[2200,1800,-10],[5e3,3e3,-18]],T_BURST=[[4200,2200,0],[6500,3e3,-2],[2600,1200,-12]],K_BURST=[[1900,700,0],[3100,1400,-6],[5500,2500,-16]],VOX_PHONE_TABLE=Object.freeze({iy:V([300,2200,2960],"i"),ih:V([400,1850,2560]),eh:V([530,1680,2500],"e"),ae:V([650,1700,2430]),aa:V([700,1150,2600],"a"),ah:V([620,1200,2550],"a"),ao:V([570,900,2550],"o"),uh:V([450,1100,2350]),uw:V([330,900,2300],"u"),er:V([470,1300,1600]),ax:V([500,1450,2450]),ey:V([480,1750,2520],"e>i",[330,2150,2700]),ay:V([680,1200,2550],"a>i",[380,1950,2600]),aw:V([680,1150,2550],"a>u",[400,900,2350]),oy:V([560,900,2400],"o>i",[360,1850,2500]),ow:V([520,950,2400],"o",[420,850,2350]),w:ph({kind:"approximant",voiced:!0,f:[290,620,2150],bw:[50,80,160],dur:.06,av:.75}),y:ph({kind:"approximant",voiced:!0,f:[260,2100,3e3],bw:[50,100,200],dur:.055,av:.8}),r:ph({kind:"approximant",voiced:!0,f:[310,1100,1450],bw:[70,100,140],dur:.065,av:.8}),l:ph({kind:"approximant",voiced:!0,f:[320,1050,2800],bw:[50,120,200],dur:.06,av:.75}),m:ph({kind:"nasal",voiced:!0,f:[260,1100,2150],bw:[60,300,400],dur:.075,zero:900,av:.6}),n:ph({kind:"nasal",voiced:!0,f:[260,1500,2550],bw:[60,300,400],dur:.07,zero:1500,av:.6}),ng:ph({kind:"nasal",voiced:!0,f:[260,2e3,2800],bw:[60,300,400],dur:.075,zero:2700,av:.6}),s:ph({kind:"fricative",voiced:!1,f:[320,1400,2550],bw:[200,200,300],dur:.1,noise:S_BANDS,noiseLevel:.5,av:0}),z:ph({kind:"fricative",voiced:!0,f:[250,1500,2500],bw:[70,200,300],dur:.08,noise:S_BANDS,noiseLevel:.3,av:.4}),sh:ph({kind:"fricative",voiced:!1,f:[300,1850,2750],bw:[200,200,300],dur:.1,noise:SH_BANDS,noiseLevel:.5,av:0}),zh:ph({kind:"fricative",voiced:!0,f:[300,1850,2750],bw:[70,200,300],dur:.08,noise:SH_BANDS,noiseLevel:.3,av:.4}),f:ph({kind:"fricative",voiced:!1,f:[340,1100,2100],bw:[200,200,300],dur:.09,noise:F_BANDS,noiseLevel:.25,av:0}),v:ph({kind:"fricative",voiced:!0,f:[250,1100,2100],bw:[70,200,300],dur:.07,noise:F_BANDS,noiseLevel:.15,av:.5}),th:ph({kind:"fricative",voiced:!1,f:[320,1300,2550],bw:[200,200,300],dur:.09,noise:TH_BANDS,noiseLevel:.22,av:0}),dh:ph({kind:"fricative",voiced:!0,f:[270,1300,2550],bw:[70,200,300],dur:.06,noise:TH_BANDS,noiseLevel:.12,av:.55}),hh:ph({kind:"aspirate",voiced:!1,f:[500,1500,2500],bw:[300,300,300],dur:.06,noiseLevel:.5,av:0}),p:ph({kind:"stop",voiced:!1,f:[400,1100,2150],bw:[200,200,300],dur:.015,closure:.06,aspiration:.04,noise:P_BURST,noiseLevel:.6,av:0}),b:ph({kind:"stop",voiced:!0,f:[200,1100,2150],bw:[70,120,200],dur:.01,closure:.05,noise:P_BURST,noiseLevel:.35,av:0}),t:ph({kind:"stop",voiced:!1,f:[400,1650,2600],bw:[200,200,300],dur:.015,closure:.055,aspiration:.045,noise:T_BURST,noiseLevel:.7,av:0}),d:ph({kind:"stop",voiced:!0,f:[200,1650,2600],bw:[70,120,200],dur:.01,closure:.045,noise:T_BURST,noiseLevel:.4,av:0}),k:ph({kind:"stop",voiced:!1,f:[300,1950,2850],bw:[200,200,300],dur:.018,closure:.06,aspiration:.05,noise:K_BURST,noiseLevel:.6,av:0}),g:ph({kind:"stop",voiced:!0,f:[200,1950,2850],bw:[70,120,200],dur:.012,closure:.05,noise:K_BURST,noiseLevel:.35,av:0}),ch:ph({kind:"affricate",voiced:!1,f:[350,1800,2800],bw:[200,200,300],dur:.07,closure:.05,noise:SH_BANDS,noiseLevel:.5,av:0}),jh:ph({kind:"affricate",voiced:!0,f:[260,1800,2800],bw:[70,200,300],dur:.06,closure:.045,noise:SH_BANDS,noiseLevel:.3,av:.35}),q:ph({kind:"stop",voiced:!1,f:[500,1500,2500],bw:[200,200,300],dur:.005,closure:.04,av:0}),dx:ph({kind:"stop",voiced:!0,f:[250,1650,2600],bw:[70,120,200],dur:.008,closure:.018,noise:T_BURST,noiseLevel:.12,av:0})});function isVoxPhone(name){return Object.prototype.hasOwnProperty.call(VOX_PHONE_TABLE,name)}function isVoxVowel(name){return isVoxPhone(name)&&VOX_PHONE_TABLE[name].kind==="vowel"}function normalizePhone(text2){let name=text2.trim().toLowerCase().replace(/[0-2]$/,"");return isVoxPhone(name)?name:void 0}var G2P_VERSION=1,RULE_TEXT=Object.freeze({a:`
|
|
197
|
+
[a] =ax
|
|
198
|
+
[are] =aa r
|
|
199
|
+
[ar]o=ax r
|
|
200
|
+
[ar]#=eh r
|
|
201
|
+
^[as]#=ey s
|
|
202
|
+
[a]wa=ax
|
|
203
|
+
[aw]=ao
|
|
204
|
+
:[any]=eh n iy
|
|
205
|
+
[a]^+#=ey
|
|
206
|
+
#:[ally]=ax l iy
|
|
207
|
+
[al]#=ax l
|
|
208
|
+
[again]=ax g eh n
|
|
209
|
+
#:[ag]e=ih jh
|
|
210
|
+
[a]^+:#=ae
|
|
211
|
+
:[a]^+ =ey
|
|
212
|
+
[a]^%=ey
|
|
213
|
+
[arr]=ax r
|
|
214
|
+
[arr]=ae r
|
|
215
|
+
:[ar] =aa r
|
|
216
|
+
[ar] =er
|
|
217
|
+
[ar]=aa r
|
|
218
|
+
[air]=eh r
|
|
219
|
+
[ai]=ey
|
|
220
|
+
[ay]=ey
|
|
221
|
+
[au]=ao
|
|
222
|
+
#:[al] =ax l
|
|
223
|
+
#:[als] =ax l z
|
|
224
|
+
[alk]=ao k
|
|
225
|
+
[al]^=ao l
|
|
226
|
+
:[able]=ey b ax l
|
|
227
|
+
[able]=ax b ax l
|
|
228
|
+
[ang]+=ey n jh
|
|
229
|
+
[a]=ae`,b:`
|
|
230
|
+
[be]^#=b ih
|
|
231
|
+
[being]=b iy ih ng
|
|
232
|
+
[both] =b ow th
|
|
233
|
+
[bus]#=b ih z
|
|
234
|
+
[buil]=b ih l
|
|
235
|
+
[bb]=b
|
|
236
|
+
[b]=b`,c:`
|
|
237
|
+
[ch]^=k
|
|
238
|
+
^e[ch]=k
|
|
239
|
+
[ch]=ch
|
|
240
|
+
s[ci]#=s ay
|
|
241
|
+
[ci]a=sh
|
|
242
|
+
[ci]o=sh
|
|
243
|
+
[ci]en=sh
|
|
244
|
+
[c]+=s
|
|
245
|
+
[ck]=k
|
|
246
|
+
[com]%=k ah m
|
|
247
|
+
[cc]+=k s
|
|
248
|
+
[c]=k`,d:`
|
|
249
|
+
#:[ded] =d ih d
|
|
250
|
+
.e[d] =d
|
|
251
|
+
#^:e[d] =t
|
|
252
|
+
[de]^#=d ih
|
|
253
|
+
[do] =d uw
|
|
254
|
+
[does]=d ah z
|
|
255
|
+
[doing]=d uw ih ng
|
|
256
|
+
[dow]=d aw
|
|
257
|
+
[du]a=jh uw
|
|
258
|
+
[dd]=d
|
|
259
|
+
[d]=d`,e:`
|
|
260
|
+
#:[e] =
|
|
261
|
+
:^[e] =
|
|
262
|
+
:[e] =iy
|
|
263
|
+
#[ed] =d
|
|
264
|
+
#:[e]d =
|
|
265
|
+
[ev]er=eh v
|
|
266
|
+
[e]^%=iy
|
|
267
|
+
[eri]#=iy r iy
|
|
268
|
+
[eri]=eh r ih
|
|
269
|
+
#:[er]#=er
|
|
270
|
+
[er]#=eh r
|
|
271
|
+
[er]=er
|
|
272
|
+
[even]=iy v eh n
|
|
273
|
+
#:[e]w=
|
|
274
|
+
@[ew]=uw
|
|
275
|
+
[ew]=y uw
|
|
276
|
+
[e]o=iy
|
|
277
|
+
#:&[es] =ih z
|
|
278
|
+
#:[e]s =
|
|
279
|
+
#:[ely] =l iy
|
|
280
|
+
#:[ement]=m eh n t
|
|
281
|
+
[eful]=f uh l
|
|
282
|
+
[ee]=iy
|
|
283
|
+
[earn]=er n
|
|
284
|
+
[ear]^=er
|
|
285
|
+
[ead]=eh d
|
|
286
|
+
#:[ea] =iy ax
|
|
287
|
+
[ea]su=eh
|
|
288
|
+
[ea]=iy
|
|
289
|
+
[eigh]=ey
|
|
290
|
+
[ei]=iy
|
|
291
|
+
[eye]=ay
|
|
292
|
+
[ey]=iy
|
|
293
|
+
[eu]=y uw
|
|
294
|
+
[e]=eh`,f:`
|
|
295
|
+
[ful]=f uh l
|
|
296
|
+
[ff]=f
|
|
297
|
+
[f]=f`,g:`
|
|
298
|
+
[giv]=g ih v
|
|
299
|
+
[g]i^=g
|
|
300
|
+
[ge]t=g eh
|
|
301
|
+
su[gges]=g jh eh s
|
|
302
|
+
[gg]=g
|
|
303
|
+
b#[g]=g
|
|
304
|
+
[g]+=jh
|
|
305
|
+
[great]=g r ey t
|
|
306
|
+
#[gh]=
|
|
307
|
+
[g]=g`,h:`
|
|
308
|
+
[hav]=hh ae v
|
|
309
|
+
[here]=hh iy r
|
|
310
|
+
[hour]=aw er
|
|
311
|
+
[how]=hh aw
|
|
312
|
+
[h]#=hh
|
|
313
|
+
[h]=`,i:`
|
|
314
|
+
[in]=ih n
|
|
315
|
+
[i] =ay
|
|
316
|
+
[in]d=ay n
|
|
317
|
+
[ier]=iy er
|
|
318
|
+
#:r[ied] =iy d
|
|
319
|
+
[ied] =ay d
|
|
320
|
+
[ien]=iy eh n
|
|
321
|
+
[ie]t=ay eh
|
|
322
|
+
:[i]%=ay
|
|
323
|
+
[i]%=iy
|
|
324
|
+
[ie]=iy
|
|
325
|
+
[i]^+:#=ih
|
|
326
|
+
[ir]#=ay r
|
|
327
|
+
[iz]%=ay z
|
|
328
|
+
[is]%=ay z
|
|
329
|
+
[i]d%=ay
|
|
330
|
+
+^[i]^+=ih
|
|
331
|
+
[i]t%=ay
|
|
332
|
+
#^:[i]^+=ih
|
|
333
|
+
[i]^+=ay
|
|
334
|
+
[ir]=er
|
|
335
|
+
[igh]=ay
|
|
336
|
+
[ild]=ay l d
|
|
337
|
+
[ign] =ay n
|
|
338
|
+
[ign]^=ay n
|
|
339
|
+
[ign]%=ay n
|
|
340
|
+
[ique]=iy k
|
|
341
|
+
[i]=ih`,j:`
|
|
342
|
+
[j]=jh`,k:`
|
|
343
|
+
[k]n=
|
|
344
|
+
[k]=k`,l:`
|
|
345
|
+
[lo]c#=l ow
|
|
346
|
+
l[l]=
|
|
347
|
+
#^:[l]%=ax l
|
|
348
|
+
[lead]=l iy d
|
|
349
|
+
[l]=l`,m:`
|
|
350
|
+
[mov]=m uw v
|
|
351
|
+
[mm]=m
|
|
352
|
+
[mb] =m
|
|
353
|
+
[m]=m`,n:`
|
|
354
|
+
e[ng]+=n jh
|
|
355
|
+
[ng]%=ng
|
|
356
|
+
[ng]r=ng g
|
|
357
|
+
[ng]#=ng g
|
|
358
|
+
[ngl]%=ng g ax l
|
|
359
|
+
[ng]=ng
|
|
360
|
+
[nk]=ng k
|
|
361
|
+
[now] =n aw
|
|
362
|
+
[nn]=n
|
|
363
|
+
[n]=n`,o:`
|
|
364
|
+
[of] =ax v
|
|
365
|
+
[orough]=er ow
|
|
366
|
+
#:[or] =er
|
|
367
|
+
#:[ors] =er z
|
|
368
|
+
[or]=ao r
|
|
369
|
+
[one]=w ah n
|
|
370
|
+
[ow]=ow
|
|
371
|
+
[over]=ow v er
|
|
372
|
+
[ov]=ah v
|
|
373
|
+
[o]^%=ow
|
|
374
|
+
[o]^en=ow
|
|
375
|
+
[o]^i#=ow
|
|
376
|
+
[ol]d=ow l
|
|
377
|
+
[ought]=ao t
|
|
378
|
+
[ough]=ah f
|
|
379
|
+
[ou]=aw
|
|
380
|
+
h[ou]s#=aw
|
|
381
|
+
[ous]=ax s
|
|
382
|
+
[our]=aw r
|
|
383
|
+
[ould]=uh d
|
|
384
|
+
^[ou]^l=ah
|
|
385
|
+
[oup]=uw p
|
|
386
|
+
[ou]=aw
|
|
387
|
+
[oy]=oy
|
|
388
|
+
[oing]=ow ih ng
|
|
389
|
+
[oi]=oy
|
|
390
|
+
[oor]=ao r
|
|
391
|
+
[ook]=uh k
|
|
392
|
+
[ood]=uh d
|
|
393
|
+
[oo]=uw
|
|
394
|
+
[o]e=ow
|
|
395
|
+
[o] =ow
|
|
396
|
+
[oa]=ow
|
|
397
|
+
[only]=ow n l iy
|
|
398
|
+
[once]=w ah n s
|
|
399
|
+
[on't]=ow n t
|
|
400
|
+
c[o]n=aa
|
|
401
|
+
[o]ng=ao
|
|
402
|
+
:^[o]n=ah
|
|
403
|
+
i[on]=ax n
|
|
404
|
+
#:[on] =ax n
|
|
405
|
+
#^[on]=ax n
|
|
406
|
+
[o]st =ow
|
|
407
|
+
[of]^=ao f
|
|
408
|
+
[other]=ah dh er
|
|
409
|
+
[oss] =ao s
|
|
410
|
+
#^:[om]=ah m
|
|
411
|
+
[o]=aa`,p:`
|
|
412
|
+
[ph]=f
|
|
413
|
+
[peop]=p iy p
|
|
414
|
+
[pow]=p aw
|
|
415
|
+
[put] =p uh t
|
|
416
|
+
[pp]=p
|
|
417
|
+
[p]=p`,q:`
|
|
418
|
+
[quar]=k w ao r
|
|
419
|
+
[qu]=k w
|
|
420
|
+
[q]=k`,r:`
|
|
421
|
+
[re]^#=r iy
|
|
422
|
+
[rr]=r
|
|
423
|
+
[r]=r`,s:`
|
|
424
|
+
[sh]=sh
|
|
425
|
+
#[sion]=zh ax n
|
|
426
|
+
[some]=s ah m
|
|
427
|
+
#[sur]#=zh er
|
|
428
|
+
[sur]#=sh er
|
|
429
|
+
#[su]#=zh uw
|
|
430
|
+
#[ssu]#=sh uw
|
|
431
|
+
#[sed] =z d
|
|
432
|
+
#[s]#=z
|
|
433
|
+
[said]=s eh d
|
|
434
|
+
^[sion]=sh ax n
|
|
435
|
+
[s]s=
|
|
436
|
+
.[s] =z
|
|
437
|
+
#:.e[s] =z
|
|
438
|
+
#^:##[s] =z
|
|
439
|
+
#^:#[s] =s
|
|
440
|
+
u[s] =s
|
|
441
|
+
:#[s] =z
|
|
442
|
+
[sch]=s k
|
|
443
|
+
[s]c+=
|
|
444
|
+
#[sm]=z m
|
|
445
|
+
[s]=s`,t:`
|
|
446
|
+
[the] =dh ax
|
|
447
|
+
[to] =t uw
|
|
448
|
+
[that] =dh ae t
|
|
449
|
+
[this] =dh ih s
|
|
450
|
+
[they]=dh ey
|
|
451
|
+
[there]=dh eh r
|
|
452
|
+
[ther]=dh er
|
|
453
|
+
[their]=dh eh r
|
|
454
|
+
[than] =dh ae n
|
|
455
|
+
[them] =dh eh m
|
|
456
|
+
[these] =dh iy z
|
|
457
|
+
[then]=dh eh n
|
|
458
|
+
[through]=th r uw
|
|
459
|
+
[those]=dh ow z
|
|
460
|
+
[though] =dh ow
|
|
461
|
+
[thus]=dh ah s
|
|
462
|
+
[th]=th
|
|
463
|
+
#:[ted] =t ih d
|
|
464
|
+
s[ti]#n=ch
|
|
465
|
+
[ti]o=sh
|
|
466
|
+
[ti]a=sh
|
|
467
|
+
[tien]=sh ax n
|
|
468
|
+
[tur]#=ch er
|
|
469
|
+
[tu]a=ch uw
|
|
470
|
+
[two]=t uw
|
|
471
|
+
[tt]=t
|
|
472
|
+
[t]=t`,u:`
|
|
473
|
+
[un]i=y uw n
|
|
474
|
+
[un]=ah n
|
|
475
|
+
[upon]=ax p ao n
|
|
476
|
+
@[ur]#=uh r
|
|
477
|
+
[ur]#=y uh r
|
|
478
|
+
[ur]=er
|
|
479
|
+
[u]^ =ah
|
|
480
|
+
[u]^^=ah
|
|
481
|
+
[uy]=ay
|
|
482
|
+
g[u]#=
|
|
483
|
+
g[u]%=
|
|
484
|
+
g[u]#=w
|
|
485
|
+
#n[u]=y uw
|
|
486
|
+
@[u]=uw
|
|
487
|
+
[u]=y uw`,v:`
|
|
488
|
+
[view]=v y uw
|
|
489
|
+
[v]=v`,w:`
|
|
490
|
+
[were]=w er
|
|
491
|
+
[wa]s=w aa
|
|
492
|
+
[wa]t=w aa
|
|
493
|
+
[where]=w eh r
|
|
494
|
+
[what]=w ah t
|
|
495
|
+
[whol]=hh ow l
|
|
496
|
+
[who]=hh uw
|
|
497
|
+
[wh]=w
|
|
498
|
+
[war]=w ao r
|
|
499
|
+
[wor]^=w er
|
|
500
|
+
[wr]=r
|
|
501
|
+
[w]=w`,x:`
|
|
502
|
+
[x]=k s`,y:`
|
|
503
|
+
[young]=y ah ng
|
|
504
|
+
[you]=y uw
|
|
505
|
+
[yes]=y eh s
|
|
506
|
+
[y]=y
|
|
507
|
+
#^:[y] =iy
|
|
508
|
+
#^:[y]i=iy
|
|
509
|
+
:[y] =ay
|
|
510
|
+
:[y]#=ay
|
|
511
|
+
:[y]^+:#=ih
|
|
512
|
+
:[y]^#=ay
|
|
513
|
+
[y]=ih`,z:`
|
|
514
|
+
[zz]=z
|
|
515
|
+
[z]=z`});function parseRules(){let out={};for(let[letter,text2]of Object.entries(RULE_TEXT)){let rules=[];for(let line of text2.split(`
|
|
516
|
+
`)){if(line.trim()==="")continue;let m=/^(.*)\[(.+)\](.*)=(.*)$/.exec(line);if(!m)throw new Error(`g2p: bad rule "${line}"`);let phones=m[4].trim().split(/\s+/).filter(Boolean);for(let p of phones)if(!isVoxPhone(p))throw new Error(`g2p: unknown phone "${p}"`);rules.push({left:m[1],match:m[2],right:m[3],phones})}out[letter]=rules}return out}var RULES=parseRules(),VOWELS2=new Set("aeiou"),isVowel=c=>c!==void 0&&VOWELS2.has(c),isConsonant=c=>c!==void 0&&/[a-z]/.test(c)&&!VOWELS2.has(c),VOICED=new Set("bdvgjlmnrwz"),FRONT=new Set("eiy"),SIBILANT=new Set("scgzxj"),U_LONG=new Set("tsrdlzjn"),SUFFIXES3=["ing","ely","er","es","ed","e"];function matchRight(pattern,word2,at3){if(pattern==="")return!0;let c=pattern[0],rest=pattern.slice(1),ch=word2[at3];switch(c){case" ":return ch===" "&&matchRight(rest,word2,at3+1);case"#":{if(!isVowel(ch))return!1;let i=at3;for(;isVowel(word2[i]);)i+=1;for(let j=i;j>at3;j-=1)if(matchRight(rest,word2,j))return!0;return!1}case":":{let i=at3;for(;isConsonant(word2[i]);)i+=1;for(let j=i;j>=at3;j-=1)if(matchRight(rest,word2,j))return!0;return!1}case"^":return isConsonant(ch)&&matchRight(rest,word2,at3+1);case".":return ch!==void 0&&VOICED.has(ch)&&matchRight(rest,word2,at3+1);case"+":return ch!==void 0&&FRONT.has(ch)&&matchRight(rest,word2,at3+1);case"&":return word2.startsWith("ch",at3)||word2.startsWith("sh",at3)?matchRight(rest,word2,at3+2):ch!==void 0&&SIBILANT.has(ch)&&matchRight(rest,word2,at3+1);case"%":return SUFFIXES3.some(s=>word2.startsWith(s,at3)&&matchRight(rest,word2,at3+s.length));default:return ch===c&&matchRight(rest,word2,at3+1)}}function matchLeft(pattern,word2,at3){if(pattern==="")return!0;let c=pattern[pattern.length-1],rest=pattern.slice(0,-1),i=at3-1,ch=word2[i];switch(c){case" ":return ch===" "&&matchLeft(rest,word2,i);case"#":{if(!isVowel(ch))return!1;let k=i;for(;isVowel(word2[k]);)k-=1;for(let j=k+1;j<=i;j+=1)if(matchLeft(rest,word2,j))return!0;return!1}case":":{let k=i;for(;isConsonant(word2[k]);)k-=1;for(let j=k+1;j<=at3;j+=1)if(matchLeft(rest,word2,j))return!0;return!1}case"^":return isConsonant(ch)&&matchLeft(rest,word2,i);case".":return ch!==void 0&&VOICED.has(ch)&&matchLeft(rest,word2,i);case"+":return ch!==void 0&&FRONT.has(ch)&&matchLeft(rest,word2,i);case"&":return ch!==void 0&&SIBILANT.has(ch)&&matchLeft(rest,word2,i);case"@":return word2.slice(i-1,i+1)==="th"||word2.slice(i-1,i+1)==="ch"?matchLeft(rest,word2,i-1):ch!==void 0&&U_LONG.has(ch)&&matchLeft(rest,word2,i);default:return ch===c&&matchLeft(rest,word2,i)}}function rulePhones(word2){let text2=` ${word2} `,out=[],at3=1;for(;at3<text2.length-1;){let ch=text2[at3],rules=RULES[ch];if(!rules){at3+=1;continue}let matched=!1;for(let rule of rules)if(text2.startsWith(rule.match,at3)&&matchLeft(rule.left,text2,at3)&&matchRight(rule.right,text2,at3+rule.match.length)){out.push(...rule.phones),at3+=rule.match.length,matched=!0;break}matched||(at3+=1)}return out}var W=phones=>Object.freeze(phones.split(" ")),DICT_TEXT=`
|
|
517
|
+
a:ax|i:ay|the:dh ax|you:y uw|me:m iy|my:m ay|love:l ah v|heart:hh aa r t
|
|
518
|
+
baby:b ey b iy|oh:ow|yeah:y eh|night:n ay t|light:l ay t|know:n ow|go:g ow
|
|
519
|
+
one:w ah n|two:t uw|three:th r iy|four:f ao r|five:f ay v|six:s ih k s
|
|
520
|
+
seven:s eh v ax n|eight:ey t|nine:n ay n|ten:t eh n|zero:z ih r ow
|
|
521
|
+
are:aa r|your:y ao r|we:w iy|be:b iy|she:sh iy|he:hh iy|was:w ah z
|
|
522
|
+
what:w ah t|do:d uw|to:t uw|who:hh uw|come:k ah m|some:s ah m|done:d ah n
|
|
523
|
+
of:ah v|from:f r ah m|have:hh ae v|give:g ih v|live:l ih v|said:s eh d
|
|
524
|
+
says:s eh z|there:dh eh r|where:w eh r|were:w er|been:b ih n
|
|
525
|
+
again:ax g eh n|only:ow n l iy|world:w er l d|word:w er d|work:w er k
|
|
526
|
+
eye:ay|eyes:ay z|friend:f r eh n d|people:p iy p ax l|through:th r uw
|
|
527
|
+
though:dh ow|thought:th ao t|dance:d ae n s|sing:s ih ng|song:s ao ng
|
|
528
|
+
day:d ey|way:w ey|say:s ey|stay:s t ey|away:ax w ey|sky:s k ay|fly:f l ay
|
|
529
|
+
cry:k r ay|why:w ay|by:b ay|tonight:t ax n ay t|forever:f er eh v er
|
|
530
|
+
ever:eh v er|never:n eh v er|every:eh v r iy|hello:hh ax l ow
|
|
531
|
+
goodbye:g uh d b ay|good:g uh d|could:k uh d|would:w uh d|should:sh uh d
|
|
532
|
+
want:w aa n t|water:w ao t er|mother:m ah dh er|brother:b r ah dh er
|
|
533
|
+
other:ah dh er|nothing:n ah th ih ng|something:s ah m th ih ng
|
|
534
|
+
machine:m ax sh iy n|robot:r ow b aa t|computer:k ax m p y uw t er
|
|
535
|
+
voice:v oy s|music:m y uw z ih k|dream:d r iy m|feel:f iy l|time:t ay m
|
|
536
|
+
fire:f ay er|heaven:hh eh v ax n|alone:ax l ow n|home:hh ow m
|
|
537
|
+
woman:w uh m ax n|women:w ih m ax n|together:t ax g eh dh er|any:eh n iy
|
|
538
|
+
many:m eh n iy|does:d ah z|gone:g ao n|move:m uw v|touch:t ah ch
|
|
539
|
+
young:y ah ng|door:d ao r|floor:f l ao r|more:m ao r|sure:sh uh r
|
|
540
|
+
heard:hh er d|learn:l er n|break:b r ey k|great:g r ey t|listen:l ih s ax n
|
|
541
|
+
often:ao f ax n|ocean:ow sh ax n|tomorrow:t ax m aa r ow|hey:hh ey
|
|
542
|
+
la:l aa|da:d aa|na:n aa|ooh:uw|ah:aa|mmm:m|hmm:hh m|human:hh y uw m ax n
|
|
543
|
+
after:ae f t er|because:b ih k ah z|into:ih n t uw|down:d aw n|out:aw t
|
|
544
|
+
now:n aw|how:hh aw|our:aw er|hour:aw er|power:p aw er|flower:f l aw er
|
|
545
|
+
star:s t aa r|apart:ax p aa r t|sun:s ah n|run:r ah n|up:ah p|us:ah s
|
|
546
|
+
just:jh ah s t|much:m ah ch|such:s ah ch|is:ih z|it:ih t|in:ih n|on:aa n
|
|
547
|
+
and:ae n d|for:f ao r|with:w ih dh|this:dh ih s|that:dh ae t|all:ao l
|
|
548
|
+
can:k ae n|will:w ih l|not:n aa t|no:n ow|so:s ow|like:l ay k|get:g eh t
|
|
549
|
+
make:m ey k|take:t ey k|see:s iy|look:l uh k|back:b ae k|still:s t ih l
|
|
550
|
+
here:hh iy r|hear:hh iy r|tell:t eh l|well:w eh l|over:ow v er|close:k l ow z
|
|
551
|
+
open:ow p ax n|kiss:k ih s|hold:hh ow l d|wait:w ey t|believe:b ih l iy v
|
|
552
|
+
beautiful:b y uw t ih f ax l|girl:g er l|boy:b oy|man:m ae n|life:l ay f
|
|
553
|
+
die:d ay|lie:l ay|tears:t ih r z|rain:r ey n|summer:s ah m er|winter:w ih n t er
|
|
554
|
+
shine:sh ay n|speak:s p iy k|spell:s p eh l|talk:t ao k|walk:w ao k
|
|
555
|
+
data:d ey t ax|signal:s ih g n ax l|electric:ih l eh k t r ih k
|
|
556
|
+
system:s ih s t ax m|digital:d ih jh ih t ax l|future:f y uw ch er
|
|
557
|
+
`,VOX_DICT=Object.freeze(Object.fromEntries(DICT_TEXT.trim().split(/[|\n]/).map(entry=>entry.trim()).filter(Boolean).map(entry=>{let[word2,phones]=entry.split(":");return[word2,W(phones.trim())]}))),VOX_DICT_SIZE=Object.keys(VOX_DICT).length;function wordPhones(word2){let clean=word2.toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g,"").replace(/[^a-z']/g,"").replace(/^'+|'+$/g,"");if(clean==="")return[];let known=VOX_DICT[clean]??VOX_DICT[clean.replace(/'/g,"")];if(known)return[...known];let s=/^(.+)'(s|re|ll|ve|d|m|t)$/.exec(clean);if(s&&VOX_DICT[s[1]]){let tail={s:["z"],re:["r"],ll:["l"],ve:["v"],d:["d"],m:["m"],t:["t"]};return[...VOX_DICT[s[1]],...tail[s[2]]]}return rulePhones(clean.replace(/'/g,""))}var EMPTY=Object.freeze({onset:Object.freeze([]),coda:Object.freeze([]),hold:!1}),ONSETS=new Set("p r|p l|b r|b l|t r|t w|d r|d w|k r|k l|k w|g r|g l|g w|f r|f l|th r|sh r|s p|s t|s k|s m|s n|s l|s w|s f|p y|b y|k y|m y|f y|v y|h y".split("|"));function onsetCount(cluster){let n2=cluster.length;return n2===0?0:n2===1?cluster[0]==="ng"?0:1:n2>=3&&cluster[n2-3]==="s"&&ONSETS.has(cluster.slice(n2-2).join(" "))?3:ONSETS.has(cluster.slice(n2-2).join(" "))?2:1}function splitSyllables(phones,count2){let vowels=[];phones.forEach((p,i)=>{isVoxVowel(p)&&vowels.push(i)});let out=[];if(vowels.length===0){for(out.push(Object.freeze({onset:Object.freeze([...phones]),coda:Object.freeze([]),hold:!1}));out.length<count2;)out.push(Object.freeze({...EMPTY,hold:!0}));return out}let used=Math.min(count2,vowels.length),starts=[0];for(let k=1;k<used;k+=1){let prev=vowels[k-1],next=vowels[k],cluster=phones.slice(prev+1,next);starts.push(next-onsetCount(cluster))}starts.push(phones.length);for(let k=0;k<used;k+=1){let part=phones.slice(starts[k],starts[k+1]),v=vowels[k]-starts[k];out.push(Object.freeze({onset:Object.freeze(part.slice(0,v)),nucleus:part[v],coda:Object.freeze(part.slice(v+1)),hold:!1}))}for(;out.length<count2;)out.push(Object.freeze({...EMPTY,hold:!0}));return out}function cleanPhones(ph2){let out=[];for(let p of ph2){let name=normalizePhone(p);name&&out.push(name)}return out}var SUNG=/^(a|e|i|o|u|ah|eh|ee|oh|oo)(>(a|e|i|o|u|ah|eh|ee|oh|oo))?$/;function phrasePhones(notes){let out=new Array(notes.length),word2=[],text2="",flush2=()=>{if(word2.length===0)return;let sylls=splitSyllables(wordPhones(text2),word2.length);word2.forEach((index,k)=>{out[index]=sylls[k]}),word2=[],text2=""};return notes.forEach((note2,index)=>{let lyric=note2.lyric?.trim()??"";if(note2.ph&¬e2.ph.length>0){flush2();let phones=cleanPhones(note2.ph);out[index]=phones.length>0?splitSyllables(phones,1)[0]:EMPTY;return}if(lyric==="_"){out[index]=Object.freeze({...EMPTY,hold:!0});return}if(lyric===""||lyric==="~"){flush2(),out[index]=EMPTY;return}let continues=lyric.endsWith("-"),body2=continues?lyric.slice(0,-1):lyric;if(word2.length===0&&!continues&&body2!=="I"&&SUNG.test(body2.toLowerCase())){out[index]=EMPTY;return}word2.push(index),text2+=body2,continues||flush2()}),flush2(),out}var VOICE_SCALE=Object.freeze({bass:.93,tenor:1,alto:1.12,soprano:1.2}),TRANSITION_SECONDS=.035,RELEASE_TRANSITION_SECONDS=.02,CONSONANT_SHARE=.6,VOX_AV_SECONDS=.0025,NOISE_SMOOTH_SECONDS=.0015,ASPIRATION_LEVEL=.3,NOISE_TRIM=.55;function phoneTable(voice,f,bw){let k=VOICE_SCALE[voice],a=SINGER_FORMANTS[voice].a;return[[f[0]*k,0,bw[0]],[f[1]*k,-6,bw[1]],[f[2]*k,-12,bw[2]],[Math.max(a[3][0],f[2]*k*1.15),a[3][1],a[3][2]],[Math.max(a[4][0],f[2]*k*1.3),a[4][1],a[4][2]]]}function vowelTables(voice,phone,spec){let p=phone?VOX_PHONE_TABLE[phone]:void 0,sung=p?p.sung:spec;if(sung!==void 0){let morph=sung.includes(">");return{from:vowelAt(voice,sung,0),...morph?{to:vowelAt(voice,sung,1)}:{},late:p!==void 0}}let q3=p;return{from:phoneTable(voice,q3.f,q3.bw),...q3.to?{to:phoneTable(voice,q3.to,q3.bw)}:{},late:!0}}var Articulation=class{spans=[];cursor=0;constructor(segments,voice,sampleRate,strength){let sec=s=>Math.round(s*sampleRate),heldPhone,heldSpec=segments[0]?.vowel??"a",lastConsonant;segments.forEach((seg,k)=>{let{syllable}=seg,len=Math.max(1,seg.end-seg.at),onset=syllable.hold?[]:syllable.onset,coda=syllable.coda,onSec=onset.reduce((t,p,i)=>t+this.phoneLength(p,k===0&&i===0),0),coSec=coda.reduce((t,p)=>t+this.phoneLength(p,!1),0),want=sec(onSec+coSec),squeeze=want>len*CONSONANT_SHARE?len*CONSONANT_SHARE/want:1,at3=Math.max(seg.at,this.spans[this.spans.length-1]?.end??0);onset.forEach((p,i)=>{at3=this.pushPhone(p,at3,squeeze,sampleRate,voice,k===0&&i===0)});let codaLen=Math.round(sec(coSec)*squeeze),vowelEnd=Math.max(at3+1,seg.end-codaLen);if(syllable.hold||(syllable.nucleus!==void 0?(heldPhone=syllable.nucleus,heldSpec=seg.vowel):(syllable.onset.length>0||coda.length>0,heldPhone=void 0,heldSpec=seg.vowel)),!syllable.hold&&syllable.nucleus===void 0&&onset.length>0){let last2=this.spans[this.spans.length-1];last2&&last2.part==="main"&&(last2.end=vowelEnd),at3=vowelEnd}else{let tables3=vowelTables(voice,heldPhone,heldSpec);this.spans.push({at:at3,end:vowelEnd,...heldPhone?{phone:heldPhone}:{},part:"main",from:tables3.from,...tables3.to?{to:tables3.to}:{},late:tables3.late,av:1,noise:0,aspirate:!1,trans:sec(TRANSITION_SECONDS)}),at3=vowelEnd}coda.forEach(p=>{at3=this.pushPhone(p,at3,squeeze,sampleRate,voice,!1)});let tailSpan=this.spans[this.spans.length-1];tailSpan&&(tailSpan.end=Math.max(tailSpan.end,seg.end)),lastConsonant=coda.length>0?coda[coda.length-1]:void 0});let last=this.spans[this.spans.length-1];if(last){let p=lastConsonant?VOX_PHONE_TABLE[lastConsonant]:void 0,endTable=last.to??last.from,silent=p!==void 0&&(p.kind==="stop"||p.kind==="affricate"||!p.voiced);this.spans.push({at:last.end,end:Number.MAX_SAFE_INTEGER,...last.phone?{phone:last.phone}:{},part:"tail",from:endTable,late:!1,av:p===void 0?1:silent?0:p.av,noise:0,aspirate:!1,...p?.zero!==void 0&&!silent?{zero:p.zero}:{},trans:1})}for(let i=0;i<this.spans.length;i+=1){let span4=this.spans[i];if(!span4.aspirate)continue;let next=this.spans.slice(i+1).find(s=>s.av>.9&&s.part==="main");next&&(span4.from=next.from)}for(let span4 of this.spans)span4.av=1-strength*(1-span4.av),span4.noise*=strength}phoneLength(name,lineStart){let p=VOX_PHONE_TABLE[name];return p?p.kind==="vowel"?p.dur:(lineStart?0:p.closure??0)+p.dur+(p.aspiration??0):0}pushPhone(name,at3,squeeze,sampleRate,voice,lineStart){let p=VOX_PHONE_TABLE[name];if(!p)return at3;let len=s=>Math.max(1,Math.round(s*squeeze*sampleRate)),trans=Math.round(TRANSITION_SECONDS*sampleRate),table2=phoneTable(voice,p.f,p.bw),push=(span4,seconds2)=>{let end=at3+len(seconds2);this.spans.push({at:at3,end,...span4}),at3=end};if(p.kind==="vowel"){let t=vowelTables(voice,name,"a");return push({phone:name,part:"main",from:t.from,...t.to?{to:t.to}:{},late:!0,av:1,noise:0,aspirate:!1,trans},p.dur),at3}return p.kind==="stop"||p.kind==="affricate"?(lineStart||push({phone:name,part:"closure",from:table2,late:!1,av:p.voiced?.15:0,noise:0,aspirate:!1,trans:Math.round(.015*sampleRate)},p.closure??.05),push({phone:name,part:p.kind==="stop"?"burst":"main",from:table2,late:!1,av:p.av,noise:p.noiseLevel??0,...p.noise?{bands:p.noise}:{},aspirate:!1,trans:1},p.dur),p.aspiration&&push({phone:name,part:"aspiration",from:table2,late:!1,av:0,noise:ASPIRATION_LEVEL,aspirate:!0,trans:Math.round(RELEASE_TRANSITION_SECONDS*sampleRate)},p.aspiration),at3):(push({phone:name,part:"main",from:table2,late:!1,av:p.av,noise:p.noiseLevel??0,...p.noise?{bands:p.noise}:{},aspirate:p.kind==="aspirate",...p.zero!==void 0?{zero:p.zero}:{},trans},p.dur),at3)}spanAt(offset){let spans=this.spans,i=this.cursor;for((i>=spans.length||spans[i].at>offset)&&(i=0);i+1<spans.length&&spans[i+1].at<=offset;)i+=1;return this.cursor=i,i}formantsAt(offset,morph){let i=this.spanAt(offset),span4=this.spans[i],table2=span4.from;if(span4.to){let len=Math.max(1,span4.end-span4.at),u=Math.min(1,Math.max(0,(offset-span4.at)/len)),t=span4.late?Math.min(1,Math.max(0,(u-.55)/.45)):u*morph;t>0&&(table2=morphVowel(span4.from,span4.to,t))}if(i>0&&span4.trans>1){let into=(offset-span4.at)/span4.trans;if(into<1){let prev=this.spans[i-1],s=Math.max(0,into);table2=morphVowel(prev.to??prev.from,table2,s*s*(3-2*s))}}return table2}avAt(offset){return this.spans[this.spanAt(offset)].av}zeroAt(offset){return this.spans[this.spanAt(offset)].zero}get noisy(){return this.spans.some(s=>s.noise>0)}renderNoise(seed,start,frames,sampleRate,scale3,control,amp,formants,left,right){if(!this.noisy)return;let rand2=seededRandom(`${seed}:vox`),bands=[new Bandpass,new Bandpass,new Bandpass],gains=[0,0,0],smooth=1-Math.exp(-1/(NOISE_SMOOTH_SECONDS*sampleRate)),level2=0,target=0,SQRT122=Math.sqrt(12);for(let j=0;j<frames;j+=1){if(j%control===0){let span4=this.spans[this.spanAt(j)];if(target=span4.noise,span4.noise>0){if(span4.aspirate){let f=formants(j);for(let b=0;b<3;b+=1)bands[b].set(f[b][0]*scale3,Math.max(150,f[b][2]*2),sampleRate),gains[b]=[1,.6,.35][b]}else if(span4.bands)for(let b=0;b<3;b+=1){let band=span4.bands[b];bands[b].set(band[0]*Math.sqrt(scale3),band[1],sampleRate),gains[b]=10**(band[2]/20)}}}if(level2+=(target-level2)*smooth,level2<1e-6&&target===0)continue;let n2=(rand2()-.5)*SQRT122,y=(bands[0].process(n2)*gains[0]+bands[1].process(n2)*gains[1]+bands[2].process(n2)*gains[2])*level2*NOISE_TRIM*amp(start+j),index=start+j;left[index]=left[index]+y,right&&(right[index]=right[index]+y)}}},Antiresonator=class{a=1;b=0;c=0;x1=0;x2=0;hz=0;set(hz3,bw,sampleRate){if(hz3===this.hz)return;if(this.hz=hz3,hz3<=0){this.a=1,this.b=0,this.c=0;return}let t=1/sampleRate,f=Math.min(hz3,sampleRate*.45),c=-Math.exp(-2*Math.PI*bw*t),b=2*Math.exp(-Math.PI*bw*t)*Math.cos(2*Math.PI*f*t),a=1-b-c;this.a=1/a,this.b=-b/a,this.c=-c/a}process(x){let y=this.a*x+this.b*this.x1+this.c*this.x2;return this.x2=this.x1,this.x1=x,y}};var SING_CONTROL=32,MAX_SING_LINES=16,SLUR_SECONDS2=.03,VOWEL_GLIDE_SECONDS=.04,THROAT_GAP_SECONDS=.25,OVERTONE_GAIN=10,SUB_DEPTH=.95,BAND_SLACK_OCTAVES=1/24,OVERTONE_GLIDE_SECONDS=.04,STEAL_FADE_SECONDS=.08,PUSH2=Object.freeze({accent:.3,marcato:.5,ghost:-.6});function gauss(rand2){let u=Math.max(1e-12,rand2());return Math.sqrt(-2*Math.log(u))*Math.cos(2*Math.PI*rand2())}var SQRT12=Math.sqrt(12),NORM_HARMONICS=40,RESPONSE=new Float64Array(2),LEVEL_FALL_SECONDS=.003,LEVEL_RISE_SECONDS=.12,SMEAR_AT=[-2,-1.5,-1,-.5,0,.5,1,1.5,2],SMEAR=(w=>w.map(x=>x/w.reduce((a,b)=>a+b,0)))(SMEAR_AT.map(x=>Math.exp(-x*x/2))),NORM_EVERY=4,reference=0;function referencePower(){if(reference===0){let ref=glottalSpectrum(1.3,NORM_HARMONICS);for(let h=1;h<=NORM_HARMONICS;h+=1)reference+=ref[h]}return reference}var Drift=class{constructor(rand2,cutoffHz,controlRate){this.rand=rand2;this.a=Math.exp(-2*Math.PI*cutoffHz/controlRate),this.g=Math.sqrt(1-this.a*this.a)}rand;y=0;a;g;next(){return this.y=this.a*this.y+this.g*gauss(this.rand),this.y}},VoiceCore=class{constructor(rand2,sampleRate){this.rand=rand2;this.sampleRate=sampleRate;this.phase=rand2(),this.riseRate=1-Math.exp(-1/(LEVEL_RISE_SECONDS*sampleRate)),this.fallRate=1-Math.exp(-1/(LEVEL_FALL_SECONDS*sampleRate))}rand;sampleRate;phase;amp=1;periodScale=1;odd=!1;hp=0;level=-1;levelTarget=1;riseRate;fallRate;tract=new Cascade;zero=null;ringBand=new Bandpass;ot1=new Bandpass;ot2=new Bandpass;aimKey=new Float64Array(33);aimLast=new Float64Array(33);setTract(formants,scale3,ringHz){this.tract.set(formants,scale3,this.sampleRate),this.ringBand.set(ringHz*scale3,400,this.sampleRate)}setOvertone(hz3,bw){this.ot1.set(hz3,bw,this.sampleRate),this.ot2.set(hz3,bw,this.sampleRate)}source(f0,rd,s){let src=0;if(f0>0){let inc=f0*this.periodScale/this.sampleRate;this.phase+=inc,this.phase>=1&&(this.phase-=Math.floor(this.phase),this.periodScale=1+s.jitter*.01*gauss(this.rand),this.amp=1+s.shimmer*.12*gauss(this.rand),this.odd=!this.odd);let alt=s.sub>0&&this.odd?1-SUB_DEPTH*s.sub:1;src=glottal(this.phase,rd,inc)*this.amp*alt}let n2=(this.rand()-.5)*SQRT12,white=n2-this.hp;return this.hp=n2,src+white*s.breath*.35*(f0>0?openWeight(this.phase,rd):1)}aimLevel(f0,rd,s){let a=s.sub>0?1-SUB_DEPTH*s.sub:1,step2=a<1?.5:1,top=Math.min(NORM_HARMONICS,Math.floor(.45*this.sampleRate/f0));if(!(f0>0)||top<1)return;let spread=Math.max(.006,s.jitter*.01),key=this.aimKey,at3=0;key[at3++]=f0,key[at3++]=rd,key[at3++]=a,key[at3++]=spread,key[at3++]=s.ring,key[at3++]=s.overtone;for(let r of this.tract.res)at3=r.coeffsInto(key,at3);at3=this.ringBand.coeffsInto(key,at3),at3=this.ot1.coeffsInto(key,at3),at3=this.ot2.coeffsInto(key,at3);let last=this.aimLast,same=this.levelTarget>0;for(let i=0;i<at3&&same;i+=1)same=key[i]===last[i];if(same)return;last.set(key);let source=glottalSpectrum(rd,NORM_HARMONICS),power=0;for(let h=step2;h<=top;h+=step2){let g=Number.isInteger(h)?source[h]*((1+a)/2)**2:(h<1?source[1]:(source[h-.5]+source[h+.5])/2)*((1-a)/2)**2,w=2*Math.PI*h*f0/this.sampleRate,r=0;for(let k=0;k<SMEAR.length;k+=1)r+=SMEAR[k]*this.responsePower(w*(1+SMEAR_AT[k]*spread),s);power+=g*r}this.levelTarget=Math.min(8,Math.max(.001,Math.sqrt(referencePower()/power))),this.level<0&&(this.level=this.levelTarget)}responsePower(w,s){let cw=Math.cos(w),sw=Math.sin(w),c2w=2*cw*cw-1,s2w=2*sw*cw,h=RESPONSE,re=1,im=0,res=this.tract.res;for(let k=0;k<res.length;k+=1){res[k].responseInto(cw,sw,c2w,s2w,h);let hr=h[0],hi=h[1],nr=re*hr-im*hi;im=re*hi+im*hr,re=nr}let addRe=1,addIm=0;if(s.ring>0&&(this.ringBand.responseInto(cw,sw,c2w,s2w,h),addRe+=h[0]*s.ring*3,addIm+=h[1]*s.ring*3),s.overtone>0){this.ot1.responseInto(cw,sw,c2w,s2w,h);let ar2=h[0],ai=h[1];this.ot2.responseInto(cw,sw,c2w,s2w,h);let br=h[0],bi=h[1];addRe+=(ar2*br-ai*bi)*s.overtone*OVERTONE_GAIN,addIm+=(ar2*bi+ai*br)*s.overtone*OVERTONE_GAIN}let yr=re*addRe-im*addIm,yi=re*addIm+im*addRe;return yr*yr+yi*yi}shape(x,s){let y=this.tract.process(x);return this.zero!==null&&(y=this.zero.process(y)),s.ring>0&&(y+=this.ringBand.process(y)*s.ring*3),s.overtone>0&&(y+=this.ot2.process(this.ot1.process(y))*s.overtone*OVERTONE_GAIN),this.level<0?y:(this.level+=(this.levelTarget-this.level)*(this.levelTarget>this.level?this.riseRate:this.fallRate),y*this.level)}step(f0,rd,s){return this.shape(this.source(f0,rd,s),s)}};function envelope(t,len,attack,release){if(t<0)return 0;let a=t<attack?.5-.5*Math.cos(Math.PI*t/attack):1,r=t>len?Math.max(0,1-(t-len)/release):1;return a*(r*r*(3-2*r))}function overtoneFor(noteHz2,droneHz,lo,hi){let bandLo=Math.log2(lo*droneHz),bandHi=Math.log2(hi*droneHz),x=Math.log2(noteHz2),best=x,bestDist=1/0,bestShift=1/0;for(let o=-10;o<=10;o+=1){let y=x+o,dist=y<bandLo-BAND_SLACK_OCTAVES?bandLo-y:y>bandHi+BAND_SLACK_OCTAVES?y-bandHi:0;(dist<bestDist-1e-9||Math.abs(dist-bestDist)<1e-9&&Math.abs(o)<bestShift)&&(best=y,bestDist=dist,bestShift=Math.abs(o))}return Math.min(hi,Math.max(lo,Math.round(2**best/droneHz)))}function noteVowel(note2,fallback){let spec=note2.vowel??vowelOf(note2.lyric)??fallback;try{let[a,b]=parseVowel(spec);return b?`${a}>${b}`:a}catch{return fallback}}function heldVowels(notes,fallback){let held=new Map;if(!notes.some(note2=>note2.lyric==="_"))return held;let ordered=[...notes].sort((a,b)=>a.startTick-b.startTick||b.pitch-a.pitch),last=fallback;for(let note2 of ordered)note2.lyric==="_"&¬e2.vowel===void 0?held.set(note2,last):last=noteVowel(note2,fallback);return held}function ringHzOf(voice){return voice==="soprano"||voice==="alto"?3100:2800}function lanesOf(track2){let lanes=new Map,all=track2.fxAutomation;if(!all)return lanes;for(let{param:param2}of SING_LANE_PARAMS){let points=all[`sing-${param2}`];points&&points.length>0&&lanes.set(param2,points)}return lanes}function applyLanes(live2,setup,index){if(setup.lanes.size===0)return;let tick=setup.tickAt(index);for(let[param2,points]of setup.lanes)live2[param2]=interpolateAutomation(points,tick,setup.s[param2])}function singMembers(voices){let v=Math.max(1,Math.round(voices));return Math.max(1,Math.min(v,SCORE_LIMITS.singVoicesPerTrack))}function lineCap(members){return Math.max(1,Math.min(MAX_SING_LINES,Math.floor(SCORE_LIMITS.singVoicesPerTrack/members)))}function renderLine(line,setup,left,right){let{s,sampleRate,samples}=setup,head=line.head,seed=`${head.id}:${head.startTick+setup.seedTick}`,voice=s.voice==="auto"?setup.partVoice??autoVoice(head.pitch):s.voice,ringHz=ringHzOf(voice),lengthSec=line.length/sampleRate,members=singMembers(s.voices),ens=members>1,buckets=ens?2:0,level2=s.gain/Math.sqrt(members),baseRd=2.5-2*s.bright,push=PUSH2[head.articulation??""]??0,bend=head.performance?.cents,ownVibrato=head.performance?.replaceVibrato===!0,damp=head.performance?.damp,releaseFrames=Math.ceil((s.release+.03)*sampleRate),lineEnd=Math.min(samples,line.start+line.length+releaseFrames+Math.ceil(.03*sampleRate),line.steal+Math.round(STEAL_FADE_SECONDS*sampleRate));if(lineEnd<=line.start)return;let frames=lineEnd-line.start,stealFade=Math.max(1,Math.round(STEAL_FADE_SECONDS*sampleRate)),slur=Math.exp(-SING_CONTROL/(SLUR_SECONDS2*sampleRate)),segmentIndex=offset=>{let k=0;for(;k+1<line.segments.length&&line.segments[k+1].at<=offset;)k+=1;return k},segmentAt=offset=>line.segments[segmentIndex(offset)],glideFrames=Math.max(1,VOWEL_GLIDE_SECONDS*sampleRate),vowelTable=(offset,live3,scale3,hz3)=>{let k=segmentIndex(offset),seg=line.segments[k],len=Math.max(1,seg.end-seg.at),t=(Math.min(offset,seg.end)-seg.at)/len,table2=vowelAt(voice,seg.vowel,t*live3.morph),into=(offset-seg.at)/glideFrames,previous=k>0?line.segments[k-1]:void 0;return previous&&into<1&&previous.vowel!==seg.vowel&&(table2=morphVowel(vowelAt(voice,previous.vowel,live3.morph),table2,into)),tuneToPitch(table2,hz3,scale3)},artic=setup.syllables?new Articulation(line.segments.map(seg=>({at:seg.at,end:seg.end,vowel:seg.vowel,syllable:setup.syllables.get(seg.note)??{onset:[],coda:[],hold:!1}})),voice,sampleRate,s.articulate):void 0,tableAt=artic?(offset,live3,scale3,hz3)=>tuneToPitch(artic.formantsAt(offset,live3.morph),hz3,scale3):vowelTable,avRate=1-Math.exp(-1/(VOX_AV_SECONDS*sampleRate)),shared=[],panRandom=seededRandom(`${seed}:pan`),width=.35*(members-1)/7;for(let b=0;b<buckets;b+=1){let st=-.3+.6*b/(buckets-1);shared.push({core:new VoiceCore(seededRandom(`${seed}:bucket:${b}`),sampleRate),st,buf:new Float64Array(frames),pan:(b===0?-1:1)*width*(.6+.4*panRandom())})}let live2={...s};for(let m=0;m<members;m+=1){let rand2=seededRandom(m===0?seed:`${seed}:${m}`),core=new VoiceCore(rand2,sampleRate),detune=ens?gauss(rand2)*s.spread*.5:0,late=ens?Math.round(rand2()*.03*sampleRate):0,vibRate=s.vib*(ens?1+.08*gauss(rand2):1),vibPhase=ens?rand2()*2*Math.PI:0,memberSt=ens?gauss(rand2)*.4:0,drift=new Drift(rand2,.8,sampleRate/SING_CONTROL),driftCents=ens?6:3*Math.min(1,s.jitter/.3),bucket=buckets>0?shared[m%buckets]:void 0;artic&&!bucket&&(core.zero=new Antiresonator);let av=1,avTarget=1,ratio2=1,hz3=line.segments[0].hz,rd=baseRd;for(let j=late;j<frames;j+=1){let offset=j-late,index=line.start+j;if(offset%SING_CONTROL===0){applyLanes(live2,setup,index);let t=offset/sampleRate,seg=segmentAt(offset);hz3=offset===0?seg.hz:seg.hz+(hz3-seg.hz)*slur;let scale3=2**((live2.formant+memberSt)/12);bucket||core.setTract(tableAt(offset,live2,scale3,hz3),scale3,ringHz),artic&&(avTarget=artic.avAt(offset),offset===0&&(av=avTarget),core.zero?.set((artic.zeroAt(offset)??0)*scale3,120,sampleRate));let vibDepth=ownVibrato?0:live2.vibmod*100*Math.min(1,Math.max(0,(t-s.vibdelay)/.3));ratio2=2**((detune+vibDepth*Math.sin(2*Math.PI*vibRate*t+vibPhase)+drift.next()*driftCents+(bend?bend(t):0))/1200),rd=Math.min(2.7,Math.max(.3,2.5-2*live2.bright-1.2*(head.velocity-.6)-push)),!bucket&&offset%(SING_CONTROL*NORM_EVERY)===0&&core.aimLevel(hz3,rd,live2)}let g=level2*head.velocity*envelope(offset/sampleRate,lengthSec,s.attack,s.release);if(damp&&offset/sampleRate>damp.from&&(g*=Math.exp(-(offset/sampleRate-damp.from)/damp.tau)),artic&&(av+=(avTarget-av)*avRate,g*=av),index>=line.steal&&(g*=index-line.steal>=stealFade?0:.5+.5*Math.cos(Math.PI*(index-line.steal)/stealFade)),bucket)bucket.buf[j]=bucket.buf[j]+core.source(hz3*ratio2,rd,live2)*g;else{let y=core.step(hz3*ratio2,rd,live2)*g*setup.gainAt(index);left[index]=left[index]+y,right&&(right[index]=right[index]+y)}}}for(let b of shared)shapeBucket(b,line,setup,live2,frames,slur,push,ringHz,segmentAt,tableAt,left,right,artic);artic&&artic.renderNoise(seed,line.start,frames,sampleRate,2**(s.formant/12),SING_CONTROL,index=>{let g=s.gain*head.velocity*setup.gainAt(index);if(index>=line.steal){let k=(index-line.steal)/stealFade;g*=k>=1?0:.5+.5*Math.cos(Math.PI*k)}return g},offset=>artic.formantsAt(offset,s.morph),left,right)}function shapeBucket(b,line,setup,live2,frames,slur,push,ringHz,segmentAt,vowelTable,left,right,artic){let head=line.head;artic&&(b.core.zero=new Antiresonator);let pl=Math.cos((b.pan+1)*Math.PI/4)*Math.SQRT2,pr=Math.sin((b.pan+1)*Math.PI/4)*Math.SQRT2,hz3=line.segments[0].hz;for(let j=0;j<frames;j+=1){let index=line.start+j;if(j%SING_CONTROL===0){applyLanes(live2,setup,index);let seg=segmentAt(j);hz3=j===0?seg.hz:seg.hz+(hz3-seg.hz)*slur;let scale3=2**((live2.formant+b.st)/12);if(b.core.setTract(vowelTable(j,live2,scale3,hz3),scale3,ringHz),artic&&b.core.zero?.set((artic.zeroAt(j)??0)*scale3,120,setup.sampleRate),j%(SING_CONTROL*NORM_EVERY)===0){let rd=Math.min(2.7,Math.max(.3,2.5-2*live2.bright-1.2*(head.velocity-.6)-push));b.core.aimLevel(hz3,rd,live2)}}let y=b.core.shape(b.buf[j],live2)*setup.gainAt(index);right?(left[index]=left[index]+y*pl,right[index]=right[index]+y*pr):left[index]=left[index]+y}}function renderThroat(lines,setup,context,left){let{s,sampleRate,samples}=setup;if(lines.length===0||s.drone===void 0)return;let droneHz=noteHz(s.drone,void 0,context.tuning),voice=s.voice==="auto"?autoVoice(s.drone):s.voice,ringHz=ringHzOf(voice),[lo,hi]=s.harmonics,gap=Math.round(THROAT_GAP_SECONDS*sampleRate),sorted=[...lines].sort((a,b)=>a.start-b.start),phrases=[],phraseEnd=-1/0;for(let line of sorted)line.start>phraseEnd+gap&&phrases.push([]),phrases[phrases.length-1].push(line),phraseEnd=Math.max(phraseEnd,line.start+line.length);let glide=Math.exp(-SING_CONTROL/(OVERTONE_GLIDE_SECONDS*sampleRate));for(let phrase of phrases){let head=phrase[0].head,seed=`${head.id}:${head.startTick+setup.seedTick}:throat`,rand2=seededRandom(seed),core=new VoiceCore(rand2,sampleRate),drift=new Drift(rand2,.5,sampleRate/SING_CONTROL),start=phrase[0].start,last=Math.max(...phrase.map(l=>l.start+l.length)),lengthSec=(last-start)/sampleRate,end=Math.min(samples,last+Math.ceil((s.release+.03)*sampleRate)),live2={...s},velocity=Math.max(...phrase.map(l=>l.head.velocity)),target=droneHz*lo,current=target,ratio2=1,rd=2.5-2*s.bright,vowel=s.vowel,k=0;for(let i=start;i<end;i+=1){if((i-start)%SING_CONTROL===0){for(applyLanes(live2,setup,i);k+1<phrase.length&&phrase[k+1].start<=i;)k+=1;let line=phrase[k];if(i<line.start+line.length){let seg=[...line.segments].reverse().find(sg=>sg.at<=i-line.start)??line.segments[0];target=overtoneFor(seg.hz,droneHz,lo,hi)*droneHz,vowel=seg.vowel}current=target+(current-target)*glide;let scale3=2**(live2.formant/12);core.setTract(vowelAt(voice,vowel,0),scale3,ringHz),core.tract.res[1].set(current,60,sampleRate),core.setOvertone(current,8+30*(1-live2.overtone)),ratio2=2**(drift.next()*2/1200),rd=Math.min(2.7,Math.max(.3,2.5-2*live2.bright-1.2*(velocity-.6))),(i-start)%(SING_CONTROL*NORM_EVERY)===0&&core.aimLevel(droneHz,rd,live2)}let t=(i-start)/sampleRate,y=core.step(droneHz*ratio2,rd,live2);left[i]=left[i]+y*live2.gain*velocity*envelope(t,lengthSec,s.attack,s.release)*setup.gainAt(i)}}}var horizon=1/0;var SING_OUTPUT_TRIM=1.25;function renderSingTrack(dry,dryR,notes,track2,context){let{sampleRate,samples}=context,keyRoot=parseKey2(context.score.key??void 0)?.tonic,s=resolveSing(track2.sing,keyRoot),tickAt4=index=>context.warp?context.warp.tick(index):index/context.samplesPerTick,volumeLane=track2.volumeAutomation??[],volume=Math.max(0,Math.min(1,track2.volume??1)),gainAt=index=>SING_OUTPUT_TRIM*volume*(volumeLane.length>0?interpolateAutomation(volumeLane,tickAt4(index),1):1),setup={s,lanes:lanesOf(track2),sampleRate,samples:Math.min(samples,horizon),tickAt:tickAt4,gainAt,seedTick:context.seedTick??0};if(s.voice==="auto"){let part=autoPartVoice((context.score?.notes??[]).filter(note2=>note2.trackId===track2.id).map(note2=>note2.pitch));part&&(setup.partVoice=part)}let throat=s.drone!==void 0;s.articulate>0&&!throat&&(setup.syllables=voxSyllables(notes));let melisma=heldVowels(notes,s.vowel),planned=windLines(notes,context,track2.glide===void 0).map(line=>({start:line.start,length:line.length,head:line.notes[0],steal:1/0,segments:line.segments.map((seg,k)=>({at:seg.at,end:k+1<line.segments.length?line.segments[k+1].at:line.length,hz:seg.hz,vowel:(note2=>melisma.get(note2)??noteVowel(note2,s.vowel))(line.notes[k]??line.notes[0]),note:line.notes[k]??line.notes[0]}))}));if(throat)renderThroat(planned,setup,context,dry);else{let cap=lineCap(singMembers(s.voices)),sounding=[],tail=Math.ceil((s.release+.03)*sampleRate);for(let entry of[...planned].sort((a,b)=>a.start-b.start)){for(let k=sounding.length-1;k>=0;k-=1){let other=sounding[k];Math.min(other.steal,other.start+other.length+tail)<=entry.start&&sounding.splice(k,1)}for(;sounding.length>=cap;)sounding.shift().steal=entry.start;sounding.push(entry)}for(let line of planned)renderLine(line,setup,dry,dryR)}applyModalKnee(dry,samples),dryR&&applyModalKnee(dryR,samples)}function voxSyllables(notes){let ordered=[...notes].sort((a,b)=>a.startTick-b.startTick||b.pitch-a.pitch),sylls=phrasePhones(ordered.map(note2=>({...note2.lyric!==void 0?{lyric:note2.lyric}:{},...note2.vox?.ph?{ph:note2.vox.ph}:{}})));return new Map(ordered.map((note2,k)=>[note2,sylls[k]]))}function singStereo(track2){let s=resolveSing(track2.sing);return s.drone===void 0&&singMembers(s.voices)>1}var SING_ENGINE=Object.freeze({id:"sing",field:"sing",render(dry,dryR,notes,track2,context){renderSingTrack(dry,dryR,notes,track2,context)},tailSeconds:track2=>singTailSeconds(track2.sing),releaseSeconds:track2=>resolveSing(track2.sing).release,stereo:singStereo,assetDigests:track2=>[`sing:${SING_VERSION}:${singPresetOf(track2.sing)}`,...resolveSing(track2.sing).articulate>0?[`vox:${G2P_VERSION}`]:[]]});var clamp7=(x,lo,hi)=>x<lo?lo:x>hi?hi:x;function onePoleDelay2(p,w){return w<1e-9?p/(1-p):Math.atan2(p*Math.sin(w),1-p*Math.cos(w))/w}function designLoss(f0,t0,fh,th,sr){let w0=2*Math.PI*f0/sr,wh=2*Math.PI*Math.min(fh,.45*sr)/sr,g0=.001**(1/(t0*f0)),want=.001**(1/(th*f0))/g0,ratio2=p2=>Math.sqrt((1-2*p2*Math.cos(w0)+p2*p2)/(1-2*p2*Math.cos(wh)+p2*p2)),lo=0,hi=.95;(wh<=w0||want>=1)&&(hi=0);for(let i=0;i<50&&hi>0;i+=1){let mid=(lo+hi)/2;ratio2(mid)>want?lo=mid:hi=mid}let gFor=q3=>g0*Math.sqrt(1-2*q3*Math.cos(w0)+q3*q3)/(1-q3),p=(lo+hi)/2;if(gFor(p)>.99995){let a=0,b=p;for(let i=0;i<50;i+=1){let mid=(a+b)/2;gFor(mid)>.99995?b=mid:a=mid}p=a}return{g:Math.min(.99995,gFor(p)),p}}function stiffnessB(stiff){return stiff>0?1e-6*400**stiff:0}function designDispersion(f1,B,sections,sr,maxDelay){if(!(B>0)||sections===0)return 0;let w1=2*Math.PI*f1/sr,ks=[];for(let k=2;k<=16&&!(k*f1*Math.sqrt((1+B*k*k)/(1+B))>.42*sr);k+=1)ks.push(k);if(ks.length===0)return 0;let cost=a=>{if(sections*allpassDelay(a,w1)>maxDelay)return 1e9;let e=0;for(let k of ks){let fk=k*f1*Math.sqrt((1+B*k*k)/(1+B)),wk=2*Math.PI*fk/sr,target=2*Math.PI*k/wk-2*Math.PI/w1,got=sections*(allpassDelay(a,wk)-allpassDelay(a,w1));e+=(got-target)**2}return e},lo=-.95,hi=0,gr=(Math.sqrt(5)-1)/2,c=hi-gr*(hi-lo),d=lo+gr*(hi-lo);for(let i=0;i<60;i+=1)cost(c)<cost(d)?hi=d:lo=c,c=hi-gr*(hi-lo),d=lo+gr*(hi-lo);return(lo+hi)/2}var C4=261.6255653005986,CONTROL=32,JAW_BASE=1.5,JAW_SHORTEST=.5,JAW_LOCK=1.3;function dcBlockDelay2(R,w){if(w<1e-9)return 0;let zero2=Math.atan2(Math.sin(w),1-Math.cos(w)),pole=Math.atan2(R*Math.sin(w),1-R*Math.cos(w));return-(zero2-pole)/w}function minHz(note2,seconds2){let lo=note2.hz;if(note2.cents)for(let t=0;t<=seconds2;t+=.01)lo=Math.min(lo,note2.hz*2**(note2.cents(t)/1200));return lo}var PluckString=class{constructor(spec,note2,sr,maxSeconds=12){this.spec=spec;this.note=note2;this.sr=sr;this.maxSeconds=maxSeconds;let f0=note2.hz,t0=spec.decay*(f0/C4)**-spec.track,th=t0/(1+99*spec.damp*spec.damp),loss=designLoss(f0,t0,Math.max(3e3,3*f0),th,sr);this.lg=loss.g,this.lp=loss.p;let P=sr/f0;this.jaw=spec.jawari,this.base=spec.jawari>0?JAW_BASE:0,this.dcR=spec.jawari>0?Math.exp(-2*Math.PI*10/sr):0;let B=stiffnessB(spec.stiff),sections=B>0?4:0,w0=2*Math.PI*f0/sr;this.dn=sections,this.da=designDispersion(f0,B,sections,sr,Math.max(0,P-2.5-onePoleDelay2(this.lp,w0)-this.base)),this.dx=new Float64Array(sections),this.dy=new Float64Array(sections);let lowest=minHz(note2,note2.hold+spec.release),size=16;for(;size<sr/lowest+16;)size<<=1;this.buf=new Float64Array(size),this.mask=size-1,this.hz=f0,this.retune(f0,!0),this.exc=excitation(spec,note2,sr,P),this.offAt=Math.round(note2.hold*sr),this.rel=.001**(1/(Math.max(.005,spec.release)*sr)),this.pickupTap=spec.pickup>0?Math.max(1,Math.round(spec.pickup*P)):0}spec;note;sr;maxSeconds;buf;mask;w=0;N=1;a=0;tx1=0;ty1=0;lg;lp;ly=0;da;dn;dx;dy;jaw;jv=0;jsum=0;jcount=0;jmean=0;hz;dcR;dcx=0;dcy=0;exc;n=0;offAt;rel;pickupTap;base;quiet=0;done=!1;retune(hz3,first=!1){let sr=this.sr;this.hz=hz3;let w0=2*Math.PI*hz3/sr,rest=sr/hz3-onePoleDelay2(this.lp,w0);if(this.jaw>0){let frac2=this.base-JAW_LOCK*this.jmean;rest-=allpassDelay((1-frac2)/(1+frac2),w0),rest-=dcBlockDelay2(this.dcR,w0)}this.dn>0&&(rest-=this.dn*allpassDelay(this.da,w0));let N=Math.max(1,Math.floor(rest-.5)),D=clamp7(rest-N,.5,1.5),a=thiranFor(D,w0);if(!first&&N!==this.N){let m=this.mask;this.tx1=this.buf[this.w-1-N&m];let pos=this.w-1-N-D,i0=Math.floor(pos),fr=pos-i0;this.ty1=this.buf[i0&m]*(1-fr)+this.buf[i0+1&m]*fr}this.N=N,this.a=a}releaseAt(at3){at3<this.offAt&&(this.offAt=Math.max(this.n,at3))}process(out,offset,count2,gain=1,right,gainR=0){if(this.done)return!1;let{buf,mask,lp:lp2,exc,dx,dy,da,dn,jaw}=this,lgain=this.lg*(1-lp2),cents=this.note.cents,sr=this.sr,peak=0;for(let i=0;i<count2;i+=1){let n2=this.n;n2%CONTROL===0&&(cents||jaw>0)&&(jaw>0&&this.jcount>0&&(this.jmean+=.25*(this.jsum/this.jcount-this.jmean),this.jsum=0,this.jcount=0),this.retune(cents?this.note.hz*2**(cents(n2/sr)/1200):this.hz));let d=buf[this.w-this.N&mask],t=this.a*d+this.tx1-this.a*this.ty1;this.tx1=d,this.ty1=t,this.ly=lgain*t+lp2*this.ly;let s=this.ly;for(let k=0;k<dn;k+=1){let y2=da*s+dx[k]-da*dy[k];dx[k]=s,dy[k]=y2,s=y2}if(jaw>0){let short=Math.min(JAW_BASE-JAW_SHORTEST,jaw*40*Math.max(0,s));this.jsum+=short,this.jcount+=1;let frac2=JAW_BASE-short,k=(1-frac2)/(1+frac2),y2=k*s+this.jv;this.jv=s-k*y2;let blocked=y2-this.dcx+this.dcR*this.dcy;this.dcx=y2,this.dcy=blocked,s=blocked}if(n2>=this.offAt){let ramp=Math.min(1,(n2-this.offAt)/(.005*sr));s*=1-(1-this.rel)*ramp}let y=(n2<exc.length?exc[n2]:0)+s;buf[this.w&mask]=y;let o=this.pickupTap?y-buf[this.w-this.pickupTap&mask]:y;this.w+=1,this.n+=1,out[offset+i]=out[offset+i]+gain*o,right&&(right[offset+i]=right[offset+i]+gainR*o);let ay=Math.abs(y);ay>peak&&(peak=ay)}return this.n>this.offAt&&peak<1e-5?(this.quiet+=count2,this.quiet>=2048&&(this.done=!0)):this.quiet=0,this.n>=this.maxSeconds*sr&&(this.done=!0),!this.done}};function excitation(spec,note2,sr,P){let vel=clamp7(note2.velocity,0,1),b=clamp7(spec.bright*(.3+.7*vel),0,1),lerp2=(x,y2)=>x+(y2-x)*b,width=spec.exciter==="pick"?lerp2(.0012,1e-4):spec.exciter==="finger"?lerp2(.005,9e-4):spec.exciter==="hammer"?lerp2(.004,3e-4):P/sr,L=Math.max(2,Math.min(Math.round(width*sr),Math.round(spec.exciter==="noise"?P:.6*P))),M=Math.max(1,Math.round(spec.pos*P)),len=L+M+1,raw=new Float64Array(len),noisy=spec.exciter==="noise";for(let i=0;i<L;i+=1){let env=.5-.5*Math.cos(2*Math.PI*(i+.5)/L),pulse2=noisy?0:env,r=2*unit3(note2.seed,i,0)-1;raw[i]=pulse2*(1-spec.noise)+(noisy?1:spec.noise)*env*r}let e=new Float64Array(len);for(let i=0;i<len;i+=1)e[i]=raw[i]-(i>=M?raw[i-M]:0);let fc=Math.min(.45*sr,300*2**(5.5*b)),al=1-Math.exp(-2*Math.PI*fc/sr),y=0,energy=0;for(let i=0;i<len;i+=1)y+=al*(e[i]-y),e[i]=y,energy+=y*y;let gain=.25*(.15+.85*vel)/Math.sqrt(energy/P+1e-30);for(let i=0;i<len;i+=1)e[i]=e[i]*gain;return e}var BODIES=Object.freeze({none:{direct:1,modes:[]},guitar:{direct:.55,modes:[[98,10,1.2],[204,14,.9],[390,18,.5],[560,20,.35],[960,12,.3],[2300,5,.35]]},steel:{direct:.6,modes:[[110,10,1],[220,14,.9],[420,16,.6],[700,14,.4],[1600,6,.4],[3200,4,.3]]},small:{direct:.6,modes:[[140,10,1],[270,14,.8],[520,16,.5],[900,12,.4],[2200,5,.35],[3600,4,.3]]},bowl:{direct:.55,modes:[[120,10,1],[250,12,.8],[480,14,.5],[900,10,.35],[1800,6,.3]]},gourd:{direct:.5,modes:[[180,8,.9],[360,10,.5],[720,8,.4],[1500,5,.35],[3e3,4,.3]]},skin:{direct:.45,modes:[[300,6,1.2],[650,6,.8],[1300,5,.6],[2600,4,.5]]},board:{direct:.6,modes:[[95,6,.8],[180,8,.7],[350,8,.6],[700,8,.45],[1400,6,.35],[2800,5,.25]]},violin:{direct:.3,modes:[[275,14,1],[460,18,.9],[540,18,1.1],[700,12,.5],[1100,8,.4],[2500,3,.9],[3400,4,.4]]}});function bodyFor(name,size){let base=name==="bass"?BODIES.violin:BODIES[name]??BODIES.none,k=(name==="bass"?.3:1)/Math.max(.05,size);return k===1?base:{direct:base.direct,modes:base.modes.map(([f,q3,g])=>[f*k,q3,g])}}function applyBody(x,body2,sr){if(body2.modes.length===0&&body2.direct===1)return;let live2=body2.modes.filter(([f])=>f<.45*sr),m=live2.length,B0=new Float64Array(m),A1=new Float64Array(m),A2=new Float64Array(m),G=new Float64Array(m),Z1=new Float64Array(m),Z2=new Float64Array(m);for(let k=0;k<m;k+=1){let[f,q3,g]=live2[k],w=2*Math.PI*f/sr,alpha=Math.sin(w)/(2*q3),a0=1+alpha;B0[k]=alpha/a0,A1[k]=-2*Math.cos(w)/a0,A2[k]=(1-alpha)/a0,G[k]=g}let direct=body2.direct;for(let i=0;i<x.length;i+=1){let xi=x[i],acc=direct*xi;for(let k=0;k<m;k+=1){let b0=B0[k],y=b0*xi+Z1[k];Z1[k]=-A1[k]*y+Z2[k],Z2[k]=-b0*xi-A2[k]*y,acc=acc+G[k]*y}x[i]=acc}let R=Math.exp(-2*Math.PI*10/sr),x1=0,y1=0;for(let i=0;i<x.length;i+=1){let xi=x[i],y=xi-x1+R*y1;x1=xi,y1=y,x[i]=y}}function symKeys(mode,root,steps2){let at3=step2=>{let whole=Math.round(step2);return{key:root+whole,cents:Math.round((step2-whole)*1e3)/10}};if(mode==="open")return[40,45,50,55,59,64].map(key=>({key,cents:0}));if(mode==="drone"){let has=n2=>steps2.some(s=>Math.abs(s-n2)<.01),second=has(7)?at3(-5):has(5)?at3(-7):has(6)?at3(-6):has(11)?at3(-1):at3(-5);return[at3(-12),second,at3(0)]}let sorted=[...steps2].map(s=>(s%12+12)%12).sort((a,b)=>a-b),keys=[];for(let octave2=0;octave2<=12&&keys.length<13;octave2+=12)for(let step2 of sorted)step2+octave2<=19&&keys.length<13&&keys.push(at3(step2+octave2));return keys}function sympathetic(x,hzs,couple,decay,damp,sr){let out=new Float64Array(x.length);for(let hz3 of hzs){if(!(hz3>20)||hz3>.4*sr)continue;let t0=decay*(hz3/C4)**-.3,{g,p}=designLoss(hz3,t0,Math.max(3e3,3*hz3),t0/(1+99*damp*damp),sr),w0=2*Math.PI*hz3/sr,rest=sr/hz3-onePoleDelay2(p,w0),N=Math.max(1,Math.floor(rest-.5)),a=thiranFor(rest-N,w0),size=16;for(;size<N+4;)size<<=1;let buf=new Float64Array(size),m=size-1,tx=0,ty=0,ly=0,lgain=g*(1-p);for(let i=0;i<x.length;i+=1){let d=buf[i-N&m],t=a*d+tx-a*ty;tx=d,ty=t,ly=lgain*t+p*ly,buf[i&m]=couple*x[i]+ly,out[i]=out[i]+ly}}return out}var KEYS_TRIM_KEYS=Object.freeze([24,36,48,60,72,84,96,108]),KEYS_TRIM_MAX_DB=40,KEYS_TRIM_DB_1=Object.freeze({harpsichord:[4.1,7,9.9,13.1,16.2,18.6,18.2,17.5],grand:[-1.4,-1.5,-.6,.8,3.8,4.8,5.5,8.3],ballad:[-4.1,-4.7,-3.4,-2.9,-.5,3.1,5.4,8.2],upright:[1.4,.4,.5,2.2,4,4.2,4.8,8.7],felt:[3.9,4.1,4.5,5.2,6.6,8.9,10.6,15.4],lofi:[4.1,4.1,4.3,5.7,7.8,8.2,9.2,15],honkytonk:[1.2,2.9,3.2,4.1,4,3.5,3.6,6.2],prepared:[2.3,-1.5,1.2,5.7,2,6.2,4.5,7.6],epiano:[6,5.2,4.8,5.3,7.3,7.6,6.5,8.5],suitcase:[7.6,6.3,5.6,5.9,7.7,7.9,6.6,8.5],dyno:[3,4.1,4.5,5.1,6.6,7.5,6.2,7.7],wurli:[9.6,6.1,5.3,6,7.8,6.1,7.6,11.1],clav:[8.1,8.8,8.9,10.4,11.2,10.8,8.5,2.7],funkclav:[7.1,7.9,9,9.1,9,5.1,7.8,5.9]});function keysTrim(preset5,key){let row2=KEYS_TRIM_DB_1[preset5];if(!row2||row2.length!==KEYS_TRIM_KEYS.length)return 1;let keys=KEYS_TRIM_KEYS,db2;if(key<=keys[0])db2=row2[0];else if(key>=keys[keys.length-1])db2=row2[row2.length-1];else{let i=Math.min(keys.length-2,Math.floor((key-keys[0])/12)),t=(key-keys[i])/12;db2=row2[i]+(row2[i+1]-row2[i])*t}return 10**(Math.min(KEYS_TRIM_MAX_DB,db2)/20)}var CONTROL2=32,BETA_MIN=.08,BETA_MAX=.4,BRIDGE_FLOOR=4,OVERSAMPLE_BELOW=24,SLUR_SECONDS3=.007,SLUR_RANGE=24,LOCK_GAIN=.25,LOCK_RANGE=.03,STROKE_STEADY=.7,STROKE_LOCK_GAIN=.2,TURN_FORCE_FLOOR=.05,SPEED_RATIO=8,GAIN_LAW_DB=10,WINDOW_LP0=4.5,WINDOW_LO=["CLLDC??<;:988GG7","CCCJJ??>>;988887","CCDJJEE>>;998888","EELLEEE>>:999988","EEMMEAA>>::99999","FCMMEAA?>;:::999","FFFFBBB@=;:::::9","HFGGBBBAA;;;::::","HFGGECCCB<<<;;;;","HHHHFCDDB==<<<<;","JHHHGCDDCB===<<<","JIIIGDDDDC====<<","JKKKHEEEDD>=====","KKKKHGEEED>>====","KLLJIGEEEE>>>===","MMMLJHFFFF>>>===","MMMLJIFGGF>>>>==","KKKKJIGGGF?>>>==","JJJJJIHOOH?>>>>=","HHHHHHHOOI?>>>>=","MMMMMMMMMJD>>>>=","MMMMMMMMMKK>>>>=","KKKKKKKKKKK>>>>=",">>>>>>>>>>>>>>>="],WINDOW_HI=["KKKKIHEEEICCCFGA","IIIIIIEEEFCCCGGA","IIIIKKHHHFFFFHHA","XLIIHHIIJLJJHHHB","NLLNHHHHLLLLIIMB","NNPMMSHHKXLHHIRC","TXXMMKJJKXLHHKXC","TVWRRKJJXXXXLLXD","TVWXXJJKXXXXXXXD","TVWXXJJKXXXXXXFD","TVWXXJJLXXXXXKFD","TVVWXJJLXXXXXJFE","SUVWWLLMXXXXXJFE","SUVVWXXXXXXXXJFE","STUUVWWXXXXXXJFE","TTTTUVWXXXXXXJFE","TTTTTUVWXXXXXIFE","TTTTTTUVXXXXXIFE","TTTTTTTTXXXXXIFE","RRRRRRRRTXXXXIFF","OOOOOOOOOSXXXJFF","OOOOOOOOOSXXXKFF","XXXXXXXXXXXXXLGF","XXXXXXXXXXXXXXGG"],WINDOW_SPAN=10,WINDOW_MARGIN=3;function cell(table2,lp2,beta){let y=clamp7(Math.floor((lp2-WINDOW_LP0)/.25),0,table2.length-1),row2=table2[y],x=clamp7(Math.floor((beta-BETA_MIN+1e-9)/.02),0,row2.length-1);return row2.charCodeAt(x)-48}var BETA_LP0=5,BETA_T60S=[.4,.6,1,1.5,2.2,3.2,4.5],BETA_SAFE=["2t4v2sjj1dvz1dvz1dvz118v","2sqn2sqn1ekf1ekf1ehr1e3j","2sql2sql1ejh1ejj1ea71dvz","2t4t2sjg1dy40ov20olq0olq","2t4v2sji0ony0ota0olq0olq","2t4v2sqn0ov30osv0olr0olr","2t4v2sqm1e660omn0oj30oj3","2t4u2sqm1e260oj30oi70oi7","2t4u2t4u0orz0oi70olr0olr","2t4s2t4u0onj0olr0olr0omn","2t4o2t4u0oi70oi70olr0olr","2t4g2t4s0nq70npr0nta0npq","1k2o2t0w1dem0npr0npq0npq","00ow2t0g2rks0npq0npr0npq","00lc2szk2rmg1czy0npq0npq","06bk0k5c2se82rk01czq1czy","06bk00e82shs2rk02rk61czq","06bk0cn42shs2sg02rnm1d3a","06bk06bk21hc2sg02rnk2rnq","0cn40cn40cn42scg2scg2scg","0cn40cn40cn42rk02rk02rk0","0cn40cn42pz42rk02rk02rk0","0cn40cn42pz42rk02rk02rk0"];function safeBetas(lp2,t60){let y=clamp7(Math.floor((lp2-BETA_LP0)/.25),0,BETA_SAFE.length-1),x=0;for(;x<BETA_T60S.length-2&&t60>=BETA_T60S[x+1];)x+=1;return parseInt(BETA_SAFE[y].slice(4*x,4*x+4),36)}function playableBeta(pos,period,t60=1){let floor=Math.min(BETA_MAX,BRIDGE_FLOOR/Math.max(1,period)),want=clamp7(pos,Math.max(BETA_MIN,floor),BETA_MAX),raw=safeBetas(Math.log2(Math.max(1,period)),t60),mask=raw&raw<<1&raw>>1||raw,best=want,gap=1/0;for(let k=0;k<17;k+=1){if(!(mask&1<<k))continue;let beta=BETA_MIN+.02*k;if(beta<floor-1e-9)continue;let d=Math.abs(beta-want);d<gap-1e-9&&(gap=d,best=beta)}return best}function bowOversample(hz3,sr){return sr/hz3<OVERSAMPLE_BELOW?2:1}function schellengSlope(pressure,beta,v,period){let lp2=Math.log2(Math.max(1,period)),lo=cell(WINDOW_LO,lp2,beta),hi=Math.min(cell(WINDOW_HI,lp2,beta),lo+WINDOW_SPAN),a=lo+WINDOW_MARGIN,b=hi-WINDOW_MARGIN;return .25/(.01*2**((b>a?a+(b-a)*clamp7(pressure,0,1):(lo+hi)/2)/4)*Math.max(1e-6,v))}var BowedString=class{constructor(spec,note2,sr,maxSeconds=12){this.spec=spec;this.note=note2;this.sr=sr;this.maxSeconds=maxSeconds;let f0=note2.hz;this.f0=f0,this.os=bowOversample(f0,sr),this.rate=sr*this.os;let loss=this.loss(f0);this.sg=loss.g,this.sp=loss.p;let size=16;for(;size<this.rate/f0*4.5+16;)size<<=1;this.nb=new Float64Array(size),this.bb=new Float64Array(size),this.mask=size-1,this.os===2&&(this.decim=new Decimate2),this.hz=f0,this.fromHz=f0,this.beta=playableBeta(spec.pos,this.rate/f0,this.t60(f0)),note2.cents&&(this.cents=note2.cents),note2.vibrato&&(this.vibrato=note2.vibrato),this.tremRate=spec.tremhz*(1+.08*(unit3(note2.seed,0,7)-.5)),this.tremPhase=unit3(note2.seed,0,8),this.off=Math.round(note2.hold*this.rate),this.dcR=1-2*Math.PI*10/sr,this.control(0),this.retune(f0,!0)}spec;note;sr;maxSeconds;os;rate;nb;bb;mask;nw=0;bw=0;Nn=1;Nb=1;a=0;tx1=0;ty1=0;sg;sp;sy=0;beta;fromBeta=0;toBeta=0;slurLoss;f0;hz;fromHz;slurAt=-1;slurLen=1;cents;centsAt=0;vibrato;decim;tremRate;tremPhase;steady=!0;strokeErr=0;strokeCount=0;strokeSkip=0;n=0;off;quiet=0;slope=3;vtarget=.1;gain=1;toneA=1;toneY=0;lock=0;target=1;bpB=0;bpA1=0;bpA2=0;bpX1=0;bpX2=0;bpY1=0;bpY2=0;lastCross=-1;dcR=1;dcX=0;dcY=0;done=!1;t60(hz3){return this.spec.decay*(hz3/C4)**-this.spec.track}loss(hz3){let spec=this.spec,t0=this.t60(hz3),damp=clamp7(spec.damp+(1-spec.damp)*.5*spec.sord,0,1);return designLoss(hz3,t0,Math.max(3e3,2*hz3),t0/(1+99*damp*damp),this.rate)}canSlurTo(hz3){return Math.abs(12*Math.log2(hz3/this.f0))<=SLUR_RANGE&&bowOversample(hz3,this.sr)===this.os}get offAt(){return Math.round(this.off/this.os)}releaseAt(at3){let n2=at3*this.os;n2<this.off&&(this.off=Math.max(this.n,n2))}slurTo(hz3,at3,hold,cents){let n2=Math.max(this.n,at3*this.os);this.fromHz=this.currentHz(),this.hz=hz3,this.slurAt=n2,this.slurLen=Math.max(1,Math.round(SLUR_SECONDS3*this.rate)),this.off=n2+Math.round(hold*this.rate),this.cents=cents,this.centsAt=n2,this.fromBeta=this.beta,this.toBeta=playableBeta(this.spec.pos,this.rate/hz3,this.t60(hz3)),this.slurLoss=this.loss(hz3)}currentHz(){if(this.slurAt<0||this.n>=this.slurAt+this.slurLen)return this.hz;if(this.n<this.slurAt)return this.fromHz;let k=(this.n-this.slurAt)/this.slurLen;return this.fromHz*(this.hz/this.fromHz)**k}retune(hz3,first=!1){let rate2=this.rate,w0=2*Math.PI*hz3/rate2,total=rate2/hz3*(1+this.lock)-onePoleDelay2(this.sp,w0);this.target=rate2/hz3;let alpha=Math.sin(w0)/6,a0=1+alpha;if(this.bpB=alpha/a0,this.bpA1=-2*Math.cos(w0)/a0,this.bpA2=(1-alpha)/a0,first)this.beta=playableBeta(this.spec.pos,total,this.t60(hz3)),this.Nb=Math.max(1,Math.round(this.beta*total));else if(this.slurAt>=0&&this.n>=this.slurAt){this.slurLoss&&(this.sg=this.slurLoss.g,this.sp=this.slurLoss.p,this.slurLoss=void 0,this.lock=0);let k=Math.min(1,(this.n-this.slurAt)/this.slurLen);this.beta=this.fromBeta+(this.toBeta-this.fromBeta)*k,this.Nb=Math.max(1,Math.round(this.beta*total))}let rest=total-this.Nb,Nn=Math.max(1,Math.floor(rest-.5)),D=clamp7(rest-Nn,.5,1.5),a=thiranFor(D,w0);if(!first&&Nn!==this.Nn){let m=this.mask;this.tx1=this.nb[this.nw-1-Nn&m];let pos=this.nw-1-Nn-D,i0=Math.floor(pos),fr=pos-i0;this.ty1=this.nb[i0&m]*(1-fr)+this.nb[i0+1&m]*fr}this.Nn=Nn,this.a=a}control(t){let spec=this.spec,c=this.note.control?.(t),pressure=c?c.pressure:spec.pressure,speed=c?c.speed:spec.speed,sord=clamp7(c?c.sord:spec.sord,0,1),d=clamp7(this.note.velocity*(c?c.dyn:1),0,1),v=(.05+.25*clamp7(speed,0,1))*SPEED_RATIO**(d-1)*.9+.005;this.vtarget=v,this.slope=this.note.capacity!==void 0?.25/(this.note.capacity*v):schellengSlope(pressure,this.beta,v,this.rate/this.hz),this.gain=1.6*(this.beta/.12)*10**(-GAIN_LAW_DB*(1-d)/20)*Math.min(1,d/.05)*(1-.45*sord);let fc=Math.min(.45*this.sr,1400*2**(3*d)*(.6+.8*clamp7(pressure,0,1))*Math.sqrt(.12/this.beta)*(1-.7*sord));this.toneA=1-Math.exp(-2*Math.PI*fc/this.sr)}tick(attack,lift){let{nb,bb,mask}=this,n2=this.n,off=this.off,on=n2<off,env=on?Math.min(1,(n2+1)/attack):Math.max(0,1-(n2-off)/lift),dir=1;if(this.tremRate>0){let s=Math.sin(Math.PI*(this.tremRate*(n2/this.rate)+this.tremPhase));dir=Math.tanh(4*s);let steady2=Math.abs(s)>STROKE_STEADY;steady2!==this.steady&&(this.steady&&this.strokeCount>0&&(this.lock=clamp7(this.lock-STROKE_LOCK_GAIN*this.strokeErr/this.strokeCount,-LOCK_RANGE,LOCK_RANGE)),this.steady=steady2,this.strokeErr=0,this.strokeCount=0,this.strokeSkip=0)}let bowVel=this.vtarget*(on?env:1)*dir,contact=on||env>0?1:0,slope=on?this.slope:this.slope/Math.max(.001,env*env);this.tremRate>0&&(slope/=Math.max(TURN_FORCE_FLOOR,Math.abs(dir))**2);let bOut=bb[this.bw-this.Nb&mask],raw=nb[this.nw-this.Nn&mask],nOut=this.a*raw+this.tx1-this.a*this.ty1;this.tx1=raw,this.ty1=nOut,this.sy=this.sg*(1-this.sp)*bOut+this.sp*this.sy;let bridgeRefl=-this.sy,nutRefl=-nOut,dv=bowVel-(bridgeRefl+nutRefl),r=1/(Math.abs(dv*slope)+.75),r2=r*r,f=r2*r2;f>1&&(f=1);let nv=contact*dv*f;return nb[this.nw&mask]=bridgeRefl+nv,bb[this.bw&mask]=nutRefl+nv,this.nw+=1,this.bw+=1,on&&this.track(bOut,n2),this.n+=1,bOut}track(x,n2){let y=this.bpB*(x-this.bpX2)-this.bpA1*this.bpY1-this.bpA2*this.bpY2;this.bpX2=this.bpX1,this.bpX1=x;let prev=this.bpY1;if(this.bpY2=prev,this.bpY1=y,!(prev<0&&y>=0))return;let cross=n2-1+prev/(prev-y),last=this.steady?this.lastCross:-1;if(this.lastCross=this.steady?cross:-1,last<0||n2<.05*this.rate||this.slurAt>=0&&n2<this.slurAt+this.slurLen+.02*this.rate)return;let err=(cross-last)/this.target-1;if(!(Math.abs(err)>.1)){if(this.tremRate>0){(this.strokeSkip+=1)>1&&(this.strokeErr+=err,this.strokeCount+=1);return}this.lock=clamp7(this.lock-LOCK_GAIN*err,-LOCK_RANGE,LOCK_RANGE)}}process(out,offset,count2,gain=1,right,gainR=0){if(this.done)return!1;let os=this.os,attack=Math.max(1,this.spec.attack*this.rate),lift=Math.max(1,this.spec.release*this.rate),decim=this.decim,peak=0;for(let i=0;i<count2;i+=1){let base=this.n/os;if(base%CONTROL2===0){let t=base/this.sr;this.control(t);let cents=this.vibrato?this.vibrato(this.n/this.rate):0;this.cents&&(cents+=this.cents((this.n-this.centsAt)/this.rate)),this.retune(this.currentHz()*2**(cents/1200))}let y;if(decim){let a=this.tick(attack,lift);y=decim.process(a,this.tick(attack,lift))}else y=this.tick(attack,lift);y*=this.gain,this.toneY+=this.toneA*(y-this.toneY);let s=this.toneY-this.dcX+this.dcR*this.dcY;this.dcX=this.toneY,this.dcY=s,out[offset+i]=out[offset+i]+s*gain,right&&(right[offset+i]=right[offset+i]+s*gainR);let m=Math.abs(s);m>peak&&(peak=m)}return this.n>this.off+this.spec.release*this.rate&&peak<1e-5?(this.quiet+=count2,this.quiet>=2048&&(this.done=!0)):this.quiet=0,this.n>=this.maxSeconds*this.rate&&(this.done=!0),!this.done}};var BLOCK2=128,MAX_RING=12,SYM_DECAY=4;function valueAt3(track2,values,name,tick){let base=values[name],points=track2.fxAutomation?.[`string-${name}`];return points&&points.length>0?interpolateAutomation(points,tick,base):base}function noteSpec(values,note2,track2){let at3=name=>valueAt3(track2,values,name,note2.startTick),mute=clamp7(at3("mute"),0,1),bright=clamp7(values.bright,0,1),velocity=clamp7(note2.velocity,0,1),articulation=note2.articulation;articulation==="staccato"&&(mute=Math.max(mute,.7)),articulation==="ghost"&&(mute=1,bright*=.5),(articulation==="accent"||articulation==="marcato")&&(velocity=Math.min(1,velocity+.15)),velocity=1-clamp7(values.vel,0,1)*(1-velocity);let damp=clamp7(values.damp,0,1);return{spec:{decay:Math.max(.02,at3("ring")*(1-.92*mute)),track:values.track,damp:damp+(1-damp)*.6*mute,stiff:values.stiff,pos:clamp7(values.pos,.01,.5),exciter:values.exciter,bright,noise:values.noise,release:values.release,jawari:clamp7(at3("buzz"),0,1),pickup:values.pickup},velocity}}function isBowed(values){return values.exciter==="bow"}var BOW_LANES=["pressure","speed","sord","dyn"];function bowSpec(values,note2,track2,context){let at3=name=>valueAt3(track2,values,name,note2.startTick),velocity=clamp7(note2.velocity,0,1),articulation=note2.articulation;velocity=1-clamp7(values.vel,0,1)*(1-velocity);let attack=values.attack,release=values.release;(articulation==="staccato"||articulation==="ghost")&&(attack=Math.min(attack,.01),release=Math.min(release,.03));let press=p=>clamp7(p+.3*(velocity-.5),0,1),bite=articulation==="accent"||articulation==="marcato",spec={decay:Math.max(.02,at3("ring")),track:values.track,damp:clamp7(values.damp,0,1),pos:clamp7(at3("pos"),.01,.5),pressure:press(at3("pressure")),speed:clamp7(at3("speed"),0,1),attack,release,tremhz:values.tremhz,sord:clamp7(at3("sord"),0,1)},lanes=BOW_LANES.filter(name=>(track2.fxAutomation?.[`string-${name}`]?.length??0)>0),dyn=clamp7(values.dyn,0,1);if(lanes.length===0&&dyn===1&&!bite)return{spec,velocity};let fixed={pressure:spec.pressure,speed:spec.speed,sord:spec.sord,dyn},bitten={...fixed,pressure:clamp7(spec.pressure+.2,0,1)};if(lanes.length===0)return{spec,velocity,control:bite?t=>t<.08?bitten:fixed:()=>fixed};let ticksPerSecond=context.sampleRate/context.samplesPerTick;return{spec,velocity,control:t=>{let tick=note2.startTick+t*ticksPerSecond,lane=name=>clamp7(valueAt3(track2,values,name,tick),0,1);return{pressure:clamp7(press(lane("pressure"))+(bite&&t<.08?.2:0),0,1),speed:lane("speed"),sord:lane("sord"),dyn:lane("dyn")}}}}function vibratoCurve(note2,values,track2,player=SOLO){if(note2.performance?.replaceVibrato)return;let rate2=valueAt3(track2,values,"vib",note2.startTick)*player.rate,depth=valueAt3(track2,values,"vibmod",note2.startTick)*100*player.depth,delay=values.vibdelay;if(!(rate2>0&&depth>0))return;let phase=player.phase;return t=>{if(t<=delay)return 0;let fade=Math.min(1,(t-delay)/.15);return depth*fade*Math.sin(2*Math.PI*(rate2*(t-delay)+phase))}}var SOLO={rate:1,depth:1,phase:0},SECTION_SPREAD=.025;function sectionPlayer(seed,index,hold){let h=seedHash(`${seed}:${index}:player`);return{rate:.92+.16*unit3(h,0,1),depth:.8+.4*unit3(h,1,1),phase:unit3(h,2,1),onset:index===0?0:SECTION_SPREAD*unit3(h,3,1)*Math.min(1,hold/.25)}}function slurs(pending3,index,start){return pending3[index-1]?.start!==start&&pending3[index+1]?.start!==start}function slurWindow(context){return(context.score.ticksPerBeat??480)/16*context.samplesPerTick}function stringTailSeconds(track2){let values=resolveString(track2.string),release=values.release,sym=values.sym>0?SYM_DECAY:0;return Math.min(MAX_RING,Math.max(release,sym)+.05)}function startSample(note2,context){return context.warp?Math.max(0,Math.floor(context.warp.sample(note2.startTick))):Math.max(0,Math.floor(note2.startTick*context.samplesPerTick))}function holdSamples(note2,start,context){return context.warp?Math.max(1,Math.floor(context.warp.sample(note2.startTick+note2.durationTicks)-start)):Math.max(1,Math.floor(note2.durationTicks*context.samplesPerTick))}function centsCurve(note2,values,track2){let own=note2.performance?.cents,rate2=valueAt3(track2,values,"vib",note2.startTick),depth=valueAt3(track2,values,"vibmod",note2.startTick)*100,delay=values.vibdelay,vibrato=rate2>0&&depth>0&&!note2.performance?.replaceVibrato?t=>{if(t<=delay)return 0;let fade=Math.min(1,(t-delay)/.15);return depth*fade*Math.sin(2*Math.PI*rate2*(t-delay))}:void 0;return own&&vibrato?t=>own(t)+vibrato(t):own??vibrato}function renderStrings(dry,dryR,notes,track2,context){let sr=context.sampleRate,total=Math.min(dry.length,context.samples),values=resolveString(track2.string),unison=Math.max(1,Math.round(values.unison)),detune=values.detune,spread=dryR?clamp7(values.spread,0,1):0,oct=values.oct,octbelow=values.octbelow,cap=Math.max(1,Math.round(values.voices)),tuning=context.tuning,bowed2=isBowed(values),trimPreset=(context.score.calibration??0)>=1?track2.string?.preset:void 0,L=new Float64Array(total),R=dryR?new Float64Array(total):void 0,voices=[],pending3=notes.map(note2=>({note:note2,start:startSample(note2,context)})).filter(item=>item.start<total).sort((a,b)=>a.start-b.start||a.note.pitch-b.note.pitch||(a.note.id<b.note.id?-1:a.note.id>b.note.id?1:0)),next=0;for(let at3=0;at3<total;at3+=BLOCK2){let count2=Math.min(BLOCK2,total-at3);for(;next<pending3.length&&pending3[next].start<at3+count2;){let{note:note2,start}=pending3[next];next+=1;let baseHz=noteHz(note2.pitch,note2.cents,tuning);if(!(baseHz>0)||baseHz>=.45*sr)continue;if(bowed2&&slurs(pending3,next-1,start)){let held2=voices.filter(v=>!v.string.done&&v.string.offAt>start-v.start),groups2=new Set(held2.map(v=>v.group)),pitches=new Set(held2.map(v=>v.pitch)),window=Math.max(.15*sr,slurWindow(context)),letsGo=note2.articulation==="legato"||held2.every(v=>v.start+v.string.offAt<=start+window),range=held2.every(v=>v.string.canSlurTo(baseHz*v.ratio));if(letsGo&&range&&groups2.size===1&&pitches.size===1&&held2[0].start<start){let hold2=holdSamples(note2,start,context)/sr;for(let v of held2)v.string.slurTo(baseHz*v.ratio,start-v.start,Math.max(.01,hold2),note2.performance?.cents),v.pitch=note2.pitch;continue}}for(let v of voices)v.pitch===note2.pitch&&v.string.releaseAt(start-v.start);let held=voices.filter(v=>!v.string.done&&v.string.offAt>start-v.start),groups=new Set(held.map(v=>v.group));if(groups.size>=cap){let oldest=Math.min(...groups);for(let v of held)v.group===oldest&&v.string.releaseAt(start-v.start)}let seed=seedHash(`${note2.id}:${note2.startTick+(context.seedTick??0)}:string`),strings=[],trim=trimPreset?keysTrim(trimPreset,note2.pitch):1,course=seedHash(`${track2.id}:${note2.pitch}:course`),jitters=Array.from({length:unison},(_,i)=>unison>1?(unit3(course,i,1)-.5)*2:0),meanJitter=jitters.reduce((a,b)=>a+b,0)/unison;for(let i=0;i<unison;i+=1){let d=unison>1?(i/(unison-1)-.5)*detune:0,jitter=jitters[i]-meanJitter,ratio2=2**((d*100+jitter)/1200);strings.push({hz:baseHz*ratio2,gain:trim/Math.sqrt(unison),ratio:ratio2})}if(oct>0&¬e2.pitch<octbelow){let up=noteHz(Math.min(127,note2.pitch+12),note2.cents,tuning),hz3=up>0?up:baseHz*2;if(hz3<.45*sr){let tuned=hz3*2**((unit3(course,unison,1)-.5)*4/1200);strings.push({hz:tuned,gain:trim*oct/Math.sqrt(unison),ratio:tuned/baseHz})}}let hold=holdSamples(note2,start,context)/sr,pluck=bowed2?void 0:noteSpec(values,note2,track2),bow=bowed2?bowSpec(values,note2,track2,context):void 0,cents=bowed2?note2.performance?.cents:centsCurve(note2,values,track2),section=bowed2&&unison>1;strings.forEach((s,i)=>{let player=section&&i<unison?sectionPlayer(seed,i,hold):void 0,onset=player?Math.round(player.onset*sr):0,vibrato=bowed2?vibratoCurve(note2,values,track2,player):void 0,pan2=strings.length>1?(i/(strings.length-1)-.5)*spread:0,common={hz:s.hz,hold:Math.max(.01,hold-onset/sr),seed:seedHash(`${seed}:${i}`),...cents?{cents}:{}},string=bow?new BowedString(bow.spec,{...common,velocity:bow.velocity,...vibrato?{vibrato}:{},...bow.control?{control:bow.control}:{}},sr,Math.max(MAX_RING,hold+bow.spec.release+1)):new PluckString(pluck.spec,{...common,velocity:pluck.velocity},sr,MAX_RING),gl=R?s.gain*Math.sqrt(.5-pan2/2)*Math.SQRT2:s.gain,gr=s.gain*Math.sqrt(.5+pan2/2)*Math.SQRT2;voices.push({string,ratio:s.ratio,start:start+onset,pitch:note2.pitch,group:start,gainL:gl,gainR:gr,...note2.performance?.damp?{damp:note2.performance.damp}:{}})})}for(let v of voices){if(v.string.done)continue;let from=Math.max(at3,v.start),n2=at3+count2-from;if(n2<=0)continue;let scale3=1;if(v.damp){let t=(from-v.start)/sr;t>v.damp.from&&(scale3=Math.exp(-(t-v.damp.from)/v.damp.tau))}v.string.process(L,from,n2,v.gainL*scale3,R,v.gainR*scale3)}for(let i=voices.length-1;i>=0;i-=1)voices[i].string.done&&voices.splice(i,1)}finishTrack(L,R,values,track2,context);for(let i=0;i<total;i+=1)dry[i]=dry[i]+L[i],dryR&&R&&(dryR[i]=dryR[i]+R[i])}function finishTrack(L,R,values,track2,context){let sr=context.sampleRate,sym=values.sym,wet;if(sym>0){let mono=R?new Float64Array(L.length):L;if(R)for(let i=0;i<L.length;i+=1)mono[i]=.5*(L[i]+R[i]);let key=parseKey2(context.score.key),root=48+(key?.tonic??0),steps2=key?scaleSteps(key):[0,2,4,5,7,9,11],hzs=symKeys(values.symtune,root,steps2).map(k=>noteHz(k.key,k.cents||void 0,context.tuning));wet=sympathetic(mono,hzs,.02*sym,SYM_DECAY,.3,sr)}let body2=bodyFor(values.body,values.size);if(applyBody(L,body2,sr),R&&applyBody(R,body2,sr),wet)for(let i=0;i<L.length;i+=1)L[i]=L[i]+wet[i],R&&(R[i]=R[i]+wet[i]);let volume=Math.max(0,Math.min(1,track2.volume??1)),volumeLane=track2.volumeAutomation??[],gainLane=track2.fxAutomation?.["string-gain"],warp2=context.warp;for(let at3=0;at3<L.length;at3+=32){let tick=warp2?warp2.tick(at3):at3/context.samplesPerTick,trim=gainLane&&gainLane.length>0?interpolateAutomation(gainLane,tick,values.gain):values.gain,g=Math.max(0,trim)*volume*(volumeLane.length>0?interpolateAutomation(volumeLane,tick,1):1),end=Math.min(L.length,at3+32);for(let i=at3;i<end;i+=1)L[i]=L[i]*g,R&&(R[i]=R[i]*g)}}function stringStereo(track2){let values=resolveString(track2.string),strings=Math.max(1,Math.round(values.unison))+(values.oct>0?1:0);return values.spread>0&&strings>1}var STRING_PRESET_DIGEST=`strings:${fnv1a(stringPresetTableText())}`;function fnv1a(text2){let h=2166136261;for(let i=0;i<text2.length;i+=1)h^=text2.charCodeAt(i),h=Math.imul(h,16777619)>>>0;return h.toString(16).padStart(8,"0")}var STRING_ENGINE=Object.freeze({id:"string",field:"string",render:(dry,dryR,notes,track2,context)=>renderStrings(dry,dryR,notes,track2,context),tailSeconds:stringTailSeconds,stereo:stringStereo,assetDigests:()=>[STRING_PRESET_DIGEST]});var TAU3=2*Math.PI,LN10002=6.907755278982137,CONTROL3=32,MODE_CEILING=.45,FLUSH=1e-30,clamp8=(x,lo,hi)=>Math.min(hi,Math.max(lo,x)),lerp=(a,b,t)=>a+(b-a)*t,radiusFor=(t60,sampleRate)=>Math.exp(-LN10002/(Math.max(1e-4,t60)*sampleRate)),ModeBank=class{n=0;re;im;cr;ci;w;r;u;g;g0;ratio=1;constructor(capacity){this.re=new Float64Array(capacity),this.im=new Float64Array(capacity),this.cr=new Float64Array(capacity),this.ci=new Float64Array(capacity),this.w=new Float64Array(capacity),this.r=new Float64Array(capacity),this.u=new Float64Array(capacity),this.g=new Float64Array(capacity),this.g0=new Float64Array(capacity)}add(hz3,t60,input,output2,sampleRate){if(!(hz3>0)||hz3>=sampleRate*MODE_CEILING||this.n>=this.re.length)return;let k=this.n++;this.w[k]=TAU3*hz3/sampleRate,this.r[k]=radiusFor(t60,sampleRate),this.u[k]=input,this.g[k]=output2,this.g0[k]=output2,this.cr[k]=this.r[k]*Math.cos(this.w[k]),this.ci[k]=this.r[k]*Math.sin(this.w[k])}damp(t60For,sampleRate){for(let k=0;k<this.n;k+=1){let hz3=this.w[k]*sampleRate/TAU3,r=radiusFor(t60For(hz3),sampleRate);r<this.r[k]&&(this.r[k]=r,this.setAngle(k))}}retune(ratio2){if(ratio2!==this.ratio){this.ratio=ratio2;for(let k=0;k<this.n;k+=1)this.setAngle(k)}}setAngle(k){let angle=this.w[k]*this.ratio,muted=angle>=TAU3*MODE_CEILING;this.g[k]=muted?0:this.g0[k];let a=muted?this.w[k]:angle;this.cr[k]=this.r[k]*Math.cos(a),this.ci[k]=this.r[k]*Math.sin(a)}cull(floor){let k=0;for(;k<this.n;)if(Math.hypot(this.re[k],this.im[k])*Math.abs(this.g0[k])<floor){let last=--this.n;this.re[k]=this.re[last],this.im[k]=this.im[last],this.cr[k]=this.cr[last],this.ci[k]=this.ci[last],this.w[k]=this.w[last],this.r[k]=this.r[last],this.u[k]=this.u[last],this.g[k]=this.g[last],this.g0[k]=this.g0[last]}else k+=1}run(out,offset,count2,x,xOffset){let{re,im,cr,ci,u,g}=this,n2=this.n;for(let s=0;s<count2;s+=1){let input=x?x[xOffset+s]??0:0,acc=0;if(input!==0)for(let k=0;k<n2;k+=1){let a=re[k],b=im[k],nr=cr[k]*a-ci[k]*b+u[k]*input,ni=ci[k]*a+cr[k]*b;re[k]=nr,im[k]=ni,acc+=g[k]*ni}else for(let k=0;k<n2;k+=1){let a=re[k],b=im[k],ni=ci[k]*a+cr[k]*b;re[k]=cr[k]*a-ci[k]*b,im[k]=ni,acc+=g[k]*ni}out[offset+s]+=acc}}},Biquad2=class{b0=1;b1=0;b2=0;a1=0;a2=0;z1=0;z2=0;set(type,hz3,q3,gainDb,sampleRate){let w=TAU3*clamp8(hz3,10,sampleRate*.45)/sampleRate,cw=Math.cos(w),alpha=Math.sin(w)/(2*q3),A=10**(gainDb/40),b0=1,b1=0,b2=0,a0=1,a1=0,a2=0;if(type==="lpf")b0=(1-cw)/2,b1=1-cw,b2=b0,a0=1+alpha,a1=-2*cw,a2=1-alpha;else if(type==="hpf")b0=(1+cw)/2,b1=-(1+cw),b2=b0,a0=1+alpha,a1=-2*cw,a2=1-alpha;else if(type==="bpf")b0=alpha,b2=-alpha,a0=1+alpha,a1=-2*cw,a2=1-alpha;else if(type==="peak")b0=1+alpha*A,b1=-2*cw,b2=1-alpha*A,a0=1+alpha/A,a1=-2*cw,a2=1-alpha/A;else{let s=2*Math.sqrt(A)*alpha;type==="lowshelf"?(b0=A*(A+1-(A-1)*cw+s),b1=2*A*(A-1-(A+1)*cw),b2=A*(A+1-(A-1)*cw-s),a0=A+1+(A-1)*cw+s,a1=-2*(A-1+(A+1)*cw),a2=A+1+(A-1)*cw-s):(b0=A*(A+1+(A-1)*cw+s),b1=-2*A*(A-1+(A+1)*cw),b2=A*(A+1+(A-1)*cw-s),a0=A+1-(A-1)*cw+s,a1=2*(A-1-(A+1)*cw),a2=A+1-(A-1)*cw-s)}return this.b0=b0/a0,this.b1=b1/a0,this.b2=b2/a0,this.a1=a1/a0,this.a2=a2/a0,this}process(x){let y=this.b0*x+this.z1,z1=this.b1*x-this.a1*y+this.z2,z2=this.b2*x-this.a2*y;return this.z1=z1<FLUSH&&z1>-FLUSH?0:z1,this.z2=z2<FLUSH&&z2>-FLUSH?0:z2,y}},Burst=class{constructor(seed,hz3,q3,tau,gain,sampleRate,attack=5e-4){this.gain=gain;this.random=seededRandom(seed),this.filter.set("bpf",hz3,q3,0,sampleRate),this.attack=Math.max(1,Math.round(attack*sampleRate)),this.k=Math.exp(-1/(tau*sampleRate)),this.length=this.attack+Math.ceil(tau*7*sampleRate)}gain;filter=new Biquad2;random;n=0;length;attack;k;env=1;next(){let i=this.n++;if(i>=this.length)return 0;let e=i<this.attack?i/this.attack:this.env*=this.k;return this.filter.process(this.random()*2-1)*e*this.gain}get done(){return this.n>=this.length}};function panGains(pan2){let a=(clamp8(pan2,-1,1)+1)*Math.PI/4;return[Math.cos(a),Math.sin(a)]}function hammerPulse(length,sharp){let pulse2=new Float64Array(length),sum=0;for(let m=0;m<length;m+=1)pulse2[m]=Math.sin(Math.PI*(m+.5)/length)**sharp,sum+=pulse2[m];for(let m=0;m<length;m+=1)pulse2[m]/=sum;return pulse2}function pulseMag(pulse2,w){let re=0,im=0;for(let m=0;m<pulse2.length;m+=1)re+=pulse2[m]*Math.cos(w*m),im-=pulse2[m]*Math.sin(w*m);return Math.hypot(re,im)}var ORGAN_VOICES=64,STEAL_SECONDS2=.005,DRAWBAR_SEMITONES=Object.freeze([-12,7,0,12,19,24,28,31,36]),WHEEL_LOW=24,WHEEL_HIGH=114;function wheelPitch(pitch2){let wheel=pitch2;for(;wheel<WHEEL_LOW;)wheel+=12;for(;wheel>WHEEL_HIGH;)wheel-=12;return wheel}var WHEEL_GAIN=.11,PIPE_GAIN=.1;function drawbarGain(digit){return digit<=0?0:10**(-(8-digit)*3/20)}function digitsOf(text2,count2,fallback){return(typeof text2=="string"?text2:fallback).padEnd(count2,"0").slice(0,count2).split("").map(digit=>clamp8(Number(digit)||0,0,8))}function wheelPhase(trackSeed,wheel,hz3,seconds2){let phase0=seedHash(`${trackSeed}:wheel:${wheel}`)/4294967296;return TAU3*((phase0+hz3*seconds2)%1)}function footageKeys(table2){if(!table2||!table2.linear||table2.size===12)return;let step2=table2.period/table2.size;return(pitch2,semis)=>{let base=table2.hz[pitch2]??0;if(!(base>0))return pitch2+semis;let guess=pitch2+Math.round(semis*100/step2),best=guess,error=1/0;for(let key=guess-3;key<=guess+3;key+=1){let hz3=table2.hz[key];if(!hz3||!(hz3>0))continue;let miss=Math.abs(1200*Math.log2(hz3/base)-semis*100);miss<error&&(error=miss,best=key)}return best}}var WHEEL_LOW_HZ=440*2**(-45/12),WHEEL_HIGH_HZ=440*2**(45/12);function foldedWheel(note2,key){if(!note2.keyAt)return wheelPitch(key);let wheel=key;for(let guard=0;guard<12;guard+=1){let hz3=note2.hzOf(wheel);if(!(hz3>0))break;if(hz3<WHEEL_LOW_HZ*.999)wheel=note2.keyAt(wheel,12);else if(hz3>WHEEL_HIGH_HZ*1.001)wheel=note2.keyAt(wheel,-12);else break}return wheel}function footage(note2,semis){return note2.keyAt?note2.keyAt(note2.pitch,semis):note2.pitch+semis}var num7=(values,name,fallback=0)=>{let value=values[name];return typeof value=="number"?value:fallback},str=(values,name,fallback)=>{let value=values[name];return typeof value=="string"?value:fallback},TonewheelVoice=class{constructor(note2,values,sr){this.note=note2;this.sr=sr;let ratio2=note2.hz/(note2.hzOf(note2.pitch)||note2.hz),levels=digitsOf(values.drawbars,9,"888000000"),perc=str(values,"perc","off"),percOn=perc!=="off",percSoft=str(values,"percvol","normal")==="soft",percDrop=percOn&&!percSoft?.7:1;percOn&&(levels[8]=0),this.click=clamp8(num7(values,"click",.5),0,1);let rng=seededRandom(`${note2.noteSeed}:contacts`),wheels=[],wheelHz=[];for(let d=0;d<9;d+=1){let wheel=foldedWheel(note2,footage(note2,DRAWBAR_SEMITONES[d])),hz3=note2.hzOf(wheel)*ratio2;wheels.push(wheel),wheelHz.push(hz3);let w=TAU3*hz3/sr,ph2=wheelPhase(note2.trackSeed,wheel,hz3,note2.startSec);this.c[d]=Math.cos(ph2),this.s[d]=Math.sin(ph2),this.baseW[d]=w,this.rc[d]=Math.cos(w),this.rs[d]=Math.sin(w),this.amp[d]=hz3>0&&hz3<.45*sr?WHEEL_GAIN*percDrop*drawbarGain(levels[d]):0;let draw2=rng();this.on[d]=this.click>0?Math.floor(draw2*.003*sr):0}this.wheels=Object.freeze(wheels),this.wheelHz=Object.freeze(wheelHz),this.click===0?(this.fade=0,this.fadeStep=1/(.004*sr)):this.bursts.push(new Burst(`${note2.noteSeed}:click`,3200,.7,.0012,this.click*.06,sr));let percFast=resolvedPercFast(values);if(this.percK=Math.exp(-6.907755/((percFast?.6:1.8)*sr)),percOn&¬e2.perc>1e-4){let wheel=foldedWheel(note2,footage(note2,perc==="2nd"?12:19)),hz3=note2.hzOf(wheel)*ratio2;if(hz3>0&&hz3<.45*sr){let w=TAU3*hz3/sr,ph2=wheelPhase(note2.trackSeed,wheel,hz3,note2.startSec);this.percC=Math.cos(ph2),this.percS=Math.sin(ph2),this.percW=w,this.percRc=Math.cos(w),this.percRs=Math.sin(w),this.perc=WHEEL_GAIN*(percSoft?.5:1)*note2.perc}}}note;sr;c=new Float64Array(9);s=new Float64Array(9);rc=new Float64Array(9);rs=new Float64Array(9);baseW=new Float64Array(9);amp=new Float64Array(9);on=new Int32Array(9);off;n=0;bursts=[];perc=0;percK;percC=0;percS=0;percRc=1;percRs=0;percW=0;fade=1;fadeStep=0;gateOpen=!0;click;wheels;wheelHz;get released(){return!this.gateOpen}noteOff(){if(!this.gateOpen)return;if(this.gateOpen=!1,this.click===0){this.fadeStep=-1/(.006*this.sr);return}let rng=seededRandom(`${this.note.noteSeed}:open`);this.off=new Int32Array(9);for(let d=0;d<9;d+=1){let draw2=rng();this.off[d]=this.n+Math.floor(draw2*.0015*this.sr)}this.bursts.push(new Burst(`${this.note.noteSeed}:clickoff`,3200,.7,.001,this.click*.03,this.sr))}setCents(cents){let r=2**(cents/1200);for(let d=0;d<9;d+=1)this.rc[d]=Math.cos(this.baseW[d]*r),this.rs[d]=Math.sin(this.baseW[d]*r);this.percW>0&&(this.percRc=Math.cos(this.percW*r),this.percRs=Math.sin(this.percW*r))}process(out,offset,count2){let{c,s,rc,rs,amp,on}=this,off=this.off;for(let i=0;i<count2;i+=1){let t=this.n++,y=0;for(let d=0;d<9;d+=1){if(amp[d]===0)continue;let cc=c[d],ss=s[d];c[d]=cc*rc[d]-ss*rs[d],s[d]=ss*rc[d]+cc*rs[d],!(t<on[d]||off&&t>=off[d])&&(y+=amp[d]*ss)}if(this.perc>1e-6){let cc=this.percC,ss=this.percS;this.percC=cc*this.percRc-ss*this.percRs,this.percS=ss*this.percRc+cc*this.percRs,y+=this.perc*ss,this.perc*=this.percK}this.fadeStep!==0&&(this.fade=clamp8(this.fade+this.fadeStep,0,1),y*=this.fade);for(let burst of this.bursts)burst.done||(y+=burst.next());out[offset+i]+=y}if((this.n&511)<count2)for(let d=0;d<9;d+=1){let m=Math.hypot(c[d],s[d])||1;c[d]/=m,s[d]/=m}if(this.gateOpen||this.bursts.some(burst=>!burst.done))return!0;if(this.fadeStep<0)return this.fade>0;let last=0;for(let d=0;d<9;d+=1)last=Math.max(last,off[d]);return this.n<=last}},COMBO_RATIOS=Object.freeze([.5,1,2,3,4]),COMBO_GAIN=.046,ComboVoice=class{constructor(note2,values,sr){this.note=note2;this.sr=sr;this.lv=digitsOf(values.registers,5,"08800").map(digit=>digit===0?0:COMBO_GAIN*drawbarGain(digit)),this.tone=str(values,"voice","reed"),this.vib=num7(values,"vib",0),this.vibmod=num7(values,"vibmod",0);for(let r=0;r<5;r+=1)this.ph[r]=note2.hz*COMBO_RATIOS[r]*note2.startSec%1;let f=note2.hz;this.tone==="flute"?this.f.set("lpf",clamp8(3*f,300,7e3),.7,0,sr):this.tone==="reed"?this.f.set("peak",1400,1.1,6,sr):this.f.set("hpf",300,.7,0,sr),this.f2.set("lpf",this.tone==="bright"?9e3:5e3,.7,0,sr)}note;sr;ph=new Float64Array(5);dts=new Float64Array(5);lv;f=new Biquad2;f2=new Biquad2;tone;vib;vibmod;env=0;gate=!0;n=0;cents=0;ratio=1;get released(){return!this.gate}noteOff(){this.gate=!1}setCents(cents){this.cents=cents}process(out,offset,count2){let sr=this.sr,attack=.02*(48e3/sr),release=.004*(48e3/sr),hz3=this.note.hz,bright=this.tone==="bright",width=this.tone==="reed"?.3:.5,{ph:ph2,lv,dts}=this,setDts=()=>{for(let r=0;r<5;r+=1)dts[r]=hz3*COMBO_RATIOS[r]*this.ratio/sr};setDts();for(let i=0;i<count2;i+=1){if((this.n&CONTROL3-1)===0){let t=this.note.startSec+this.n/sr,vib=this.vib>0?this.vibmod*100*Math.sin(TAU3*this.vib*t):0;this.ratio=2**((this.cents+vib)/1200),setDts()}this.n+=1;let y=0;for(let r=0;r<5;r+=1){let dt=dts[r];if(!(dt>0)||dt>=.45)continue;let t=ph2[r]+dt;t>=1&&(t-=1),ph2[r]=t;let level2=lv[r];level2!==0&&(y+=level2*(bright?2*t-1-polyBlep(t,dt):blepPulse(t,dt,width)))}this.env+=((this.gate?1:0)-this.env)*(this.gate?attack:release),y=this.f2.process(this.f.process(y))*this.env,out[offset+i]+=y}return this.gate||this.env>1e-5}};function blepPulse(t,dt,width){let y=t<width?1:-1;y+=polyBlep(t,dt);let t2=t-width;return t2<0&&(t2+=1),y-=polyBlep(t2,dt),y-(2*width-1)}var SPECTRA={principal:n2=>n2===2?.55:1/n2**1.15,flute:n2=>[1,.3,.1,.04][n2-1]??.01/n2,stopped:n2=>n2%2?1/n2**1.6:.03/n2,string:n2=>.8/n2**.7,trumpet:n2=>n2<=5?.5+.12*n2:1.1/(n2/5)**1.1,oboe:n2=>Math.exp(-(((n2-4)/3)**2))+.25/n2,krummhorn:n2=>n2%2?.9/n2**.6:.08/n2},SPECTRUM_MAX={principal:24,flute:8,stopped:12,string:40,trumpet:40,oboe:24,krummhorn:30},flue=(spectrum,semis,gain)=>({spectrum,semis,gain,flue:!0}),STOPS=Object.freeze({subbass16:[flue("stopped",-12,1)],bourdon16:[flue("stopped",-12,.8)],principal8:[flue("principal",0,1)],flute8:[flue("flute",0,.9)],gedackt8:[flue("stopped",0,.9)],gamba8:[flue("string",0,.5)],celeste8:[{...flue("string",0,.5),celeste:7}],octave4:[flue("principal",12,.8)],flute4:[flue("flute",12,.7)],nazard:[flue("flute",19,.45)],fifteenth2:[flue("principal",24,.6)],piccolo2:[flue("flute",24,.5)],tierce:[flue("flute",28,.4)],larigot:[flue("flute",31,.35)],mixture:[19,24,31,36].map(semis=>flue("principal",semis,.35)),trumpet8:[{spectrum:"trumpet",semis:0,gain:.7,flue:!1}],oboe8:[{spectrum:"oboe",semis:0,gain:.6,flue:!1}],krummhorn8:[{spectrum:"krummhorn",semis:0,gain:.6,flue:!1}],trombone16:[{spectrum:"trumpet",semis:-12,gain:.8,flue:!1}]}),PIPE_TOP=103,PIPE_TOP_HZ=440*2**((PIPE_TOP-69)/12);function rankRatio(semis){let octave2=Math.floor(semis/12),within=semis-octave2*12,pure=within===7?1.5:within===4?1.25:2**(within/12);return 2**octave2*pure}var TABLE=2048,tables2=new Map;function table(spectrum,harmonics){let key=`${spectrum}:${harmonics}`,cached=tables2.get(key);if(cached)return cached;let out=new Float64Array(TABLE+1),peak=0;for(let i=0;i<TABLE;i+=1){let y=0;for(let n2=1;n2<=harmonics;n2+=1)y+=SPECTRA[spectrum](n2)*Math.sin(TAU3*n2*i/TABLE);out[i]=y,peak=Math.max(peak,Math.abs(y))}let power=0;for(let i=0;i<TABLE;i+=1)out[i]/=peak||1,power+=out[i]**2;let loud=Math.min(2,Math.max(1,.6/Math.sqrt(power/TABLE)));for(let i=0;i<TABLE;i+=1)out[i]*=loud;return out[TABLE]=out[0],tables2.set(key,out),out}var PipeVoice=class{constructor(note2,values,sr){this.note=note2;this.sr=sr;let ratio2=note2.hz/(note2.hzOf(note2.pitch)||note2.hz),keyPos=clamp8((note2.pitch-24)/84,0,1);this.trem=clamp8(num7(values,"trem"),0,1),this.wind=clamp8(num7(values,"wind",.3),0,1);let chiff=clamp8(num7(values,"chiff",.4),0,1),flueGain=0,power=0,shared=(seededRandom(`${note2.trackSeed}:pipe:${note2.pitch}`)()-.5)*2,f1=note2.hzOf(note2.pitch);for(let id of pipeStops(str(values,"stops","principal8")))for(let stop of STOPS[id]??[]){let semis=stop.semis;for(;f1*rankRatio(semis)>PIPE_TOP_HZ&&semis>0;)semis-=12;let pipe=seededRandom(`${note2.trackSeed}:pipe:${id}:${semis}:${note2.pitch}`),detune=shared+(stop.celeste??0),hz3=f1*rankRatio(semis)*ratio2*2**(detune/1200),ph2=(pipe()+hz3*note2.startSec%1)%1,wob=pipe()*TAU3,wobHz=.2+.3*pipe();if(!(hz3>0)||hz3>=.45*sr)continue;let h=Math.max(1,Math.min(SPECTRUM_MAX[stop.spectrum],Math.floor(.45*sr/hz3))),ta=(stop.flue?.02+.06*(1-keyPos):.012)*(semis<0?1.5:1);this.ranks.push({t:table(stop.spectrum,h),ph:ph2,hz:hz3,gain:stop.gain,ta,wob,wobHz,inc:hz3/sr,level:1}),stop.flue&&(flueGain+=stop.gain),power+=stop.gain*stop.gain}let norm=PIPE_GAIN/Math.max(.25,power)**.35;for(let rank of this.ranks)rank.gain*=norm;chiff>0&&flueGain>0&&this.bursts.push(new Burst(`${note2.noteSeed}:chiff`,Math.min(.4*sr,note2.hz*4),3,.025,chiff*.05*Math.min(2,flueGain),sr,.002)),this.relK=Math.exp(-1/(.035*sr))}note;sr;ranks=[];n=0;gate=!0;relEnv=1;relK;bursts=[];cents=0;amp=1;trem;wind;get released(){return!this.gate}noteOff(){this.gate=!1}setCents(cents){this.cents=cents}process(out,offset,count2){let sr=this.sr;for(let i=0;i<count2;i+=1){let t=this.n/sr;if((this.n&CONTROL3-1)===0||i===0){let abs=this.note.startSec+t,trem=this.trem>0?Math.sin(TAU3*5.6*abs):0;for(let rank of this.ranks){let wind2=this.wind*.6*Math.sin(rank.wob+TAU3*rank.wobHz*abs);rank.inc=rank.hz*2**((this.cents+wind2+this.trem*4*trem)/1200)/sr}this.amp=1+this.trem*.12*trem;for(let rank of this.ranks)rank.level=1+this.wind*.03*Math.sin(rank.wob+TAU3*rank.wobHz*abs)}let y=0;for(let rank of this.ranks){rank.ph+=rank.inc,rank.ph>=1&&(rank.ph-=Math.floor(rank.ph));let x=rank.ph*TABLE,j=Math.floor(x),s=rank.t[j]+(rank.t[j+1]-rank.t[j])*(x-j),speak=t>40*rank.ta?1:1-Math.exp(-t/rank.ta);y+=s*rank.gain*rank.level*speak}this.gate||(this.relEnv*=this.relK),y*=this.amp*this.relEnv;for(let burst of this.bursts)burst.done||(y+=burst.next());out[offset+i]+=y,this.n+=1}return this.gate||this.relEnv>1e-5}},HORN_HZ=Object.freeze([0,.8,6.8]),DRUM_HZ=Object.freeze([0,.66,5.9]),SCANNER_DEPTH={off:0,v1:.25,v2:.5,v3:.9,c1:.25,c2:.5,c3:.9};function readHermite2(buffer,write,delay){let size=buffer.length,pos=write-delay,i=Math.floor(pos),f=pos-i,at3=j=>buffer[(j%size+size)%size],xm1=at3(i-1),x0=at3(i),x1=at3(i+1),x2=at3(i+2),c1=.5*(x1-xm1),c2=xm1-2.5*x0+2*x1-.5*x2;return(((.5*(x2-xm1)+1.5*(x0-x1))*f+c2)*f+c1)*f+x0}var makeups=new Map;function driveMakeup(k){let key=Math.round(k*1e3),cached=makeups.get(key);if(cached!==void 0)return cached;let a=10**(-18/20)*Math.SQRT2,dry=0,wet=0;for(let i=0;i<256;i+=1){let x=a*Math.sin(TAU3*(i+.5)/256),y=Math.tanh(k*x)/k;dry+=x*x,wet+=y*y}let makeup=Math.sqrt(dry/wet);return makeups.set(key,makeup),makeup}var OrganPost=class{constructor(settings,sr,startSec=0,seed){this.settings=settings;this.sr=sr;this.startSec=startSec;this.line=new Float64Array(Math.ceil(.004*sr)+8),this.hornLine=new Float64Array(Math.ceil(.004*sr)+8),this.lo1=new OnePole2(800,sr),this.lo2=new OnePole2(800,sr);let speed=clamp8(Math.round(settings.rotary),0,2);this.hornHz=this.hornTarget=HORN_HZ[speed],this.drumHz=this.drumTarget=DRUM_HZ[speed],this.horn=TAU3*(this.hornHz*startSec%1)%TAU3,this.drum=TAU3*(this.drumHz*startSec%1)%TAU3,seed&&(this.horn=seed.horn,this.drum=seed.drum,this.hornHz=this.hornTarget=seed.hornHz,this.drumHz=this.drumTarget=seed.drumHz)}settings;sr;startSec;line;w=0;hornLine;hw=0;horn=0;drum=0;n=0;hornTarget;drumTarget;hornHz;drumHz;lo1;lo2;prev=0;rotor(){return{horn:this.horn,drum:this.drum,hornHz:this.hornHz,drumHz:this.drumHz}}spin(count2,speedAt){let sr=this.sr,glide=(hz3,target,up,down,n2)=>{if(hz3===target)return[hz3,n2*hz3/sr];let r=1-1/((target>hz3?up:down)*sr),rn=r**n2,sum=n2*target+(hz3-target)*r*(1-rn)/(1-r);return[target+(hz3-target)*rn,sum/sr]};for(let i=0;i<count2;i+=CONTROL3){let n2=Math.min(CONTROL3,count2-i),speed=clamp8(Math.round(speedAt(i)),0,2),[hornHz,hornTurns]=glide(this.hornHz,HORN_HZ[speed],.7,1.1,n2),[drumHz,drumTurns]=glide(this.drumHz,DRUM_HZ[speed],3.5,4.5,n2);this.hornHz=hornHz,this.drumHz=drumHz,this.horn=(this.horn+TAU3*hornTurns)%TAU3,this.drum=(this.drum+TAU3*drumTurns)%TAU3}}process(left,right,count2=left.length,speedAt,driveAt){let sr=this.sr,scanner=this.settings.scanner,depth=(SCANNER_DEPTH[scanner]??0)*.001*sr,chorus=scanner.startsWith("c"),drive=this.settings.drive,k=1+6*drive,tk=driveMakeup(k)/k,base=.0012*sr,dop=45e-5*sr;for(let i=0;i<count2;i+=1){if(i%CONTROL3===0&&(driveAt&&(drive=clamp8(driveAt(i),0,1),k=1+6*drive,tk=driveMakeup(k)/k),speedAt)){let speed=clamp8(Math.round(speedAt(i)),0,2);this.hornTarget=HORN_HZ[speed],this.drumTarget=DRUM_HZ[speed]}let x=left[i];if(depth>0){let t=this.startSec+this.n/sr,d=3e-4*sr+depth*.5*(1+Math.sin(TAU3*6.9*t));this.line[this.w]=x;let vib=readHermite2(this.line,this.w,d);this.w=(this.w+1)%this.line.length,x=chorus?.5*(x+vib):vib}if(this.n+=1,drive>0){let mid=.5*(x+this.prev);this.prev=x,x=.5*(Math.tanh(k*mid)+Math.tanh(k*x))*tk}else this.prev=x;if(!this.settings.rotor){left[i]=x,right[i]=x;continue}let hornTau=this.hornTarget>this.hornHz?.7:1.1,drumTau=this.drumTarget>this.drumHz?3.5:4.5;this.hornHz+=(this.hornTarget-this.hornHz)/(hornTau*sr),this.drumHz+=(this.drumTarget-this.drumHz)/(drumTau*sr),this.horn=(this.horn+TAU3*this.hornHz/sr)%TAU3,this.drum=(this.drum+TAU3*this.drumHz/sr)%TAU3;let lo=this.lo2.process(this.lo1.process(x)),hi=x-lo;this.hornLine[this.hw]=hi;let cl=Math.cos(this.horn+Math.PI/2),cr=Math.cos(this.horn-Math.PI/2),hl=readHermite2(this.hornLine,this.hw,base+dop*.5*(1-cl))*(.6+.4*cl),hr=readHermite2(this.hornLine,this.hw,base+dop*.5*(1-cr))*(.6+.4*cr);this.hw=(this.hw+1)%this.hornLine.length;let dl=lo*(.75+.25*Math.cos(this.drum+Math.PI/2)),dr=lo*(.75+.25*Math.cos(this.drum-Math.PI/2));left[i]=hl+dl,right[i]=hr+dr}}};function organPostSettings(family,values,laned=!1){let rotary=family==="pipe"?0:rotarySpeed(values.rotary);return{scanner:family==="tonewheel"?str(values,"scanner","c3"):"off",drive:family==="pipe"?0:clamp8(num7(values,"drive"),0,1),rotary,rotor:family!=="pipe"&&(rotary>0||laned)}}function spanOf2(note2,context,origin=0){let{warp:warp2,samplesPerTick}=context,base=Math.round(origin),at3=tick=>Math.floor((warp2?warp2.sample(tick):tick*samplesPerTick)+origin)-base;if(warp2){let start2=Math.max(0,at3(note2.startTick)),end=at3(note2.startTick+note2.durationTicks);return{start:start2,off:Math.max(start2+1,end)}}let start=Math.max(0,at3(note2.startTick)),length=Math.max(1,Math.floor(note2.durationTicks*samplesPerTick));return{start,off:start+length}}function tickAt(context,sample){return context.warp?context.warp.tick(sample):sample/context.samplesPerTick}function organVoice(family,note2,values,sr){return family==="tonewheel"?new TonewheelVoice(note2,values,sr):family==="combo"?new ComboVoice(note2,values,sr):new PipeVoice(note2,values,sr)}function renderOrganTrack(left,right,notes,track2,context){let family=track2.instrument;if(!isOrganFamily(family))return;let sr=context.sampleRate,total=left.length,values=resolvedKeys(family,track2.keys),trackSeed=`organ:${track2.id}`,seedTick=context.seedTick??0,originSec=context.seedSeconds??seedTick*context.samplesPerTick/sr,hzOf=pitch2=>noteHz(pitch2,void 0,context.tuning),keyAt=footageKeys(context.tuning),percTau=(resolvedPercFast(values)?.6:1.8)/6.907755,percAt=-1/0,onsets2=notes.map(note2=>{let hz3=noteHz(note2.pitch,note2.cents,context.tuning);return{note:note2,hz:hz3,...spanOf2(note2,context,originSec*sr)}}).filter(x=>x.hz>0&&Number.isFinite(x.hz)&&x.start<total).sort((a,b)=>a.start-b.start||a.note.startTick-b.note.startTick||(a.note.id<b.note.id?-1:a.note.id>b.note.id?1:0)),mono=new Float64Array(total),live2=[],next=0,order=0;for(let i=0;i<total;i+=CONTROL3){let count2=Math.min(CONTROL3,total-i);for(;next<onsets2.length&&onsets2[next].start<i+count2;){let onset=onsets2[next];next+=1;let playing=live2.filter(x=>!x.stolen);if(playing.length>=ORGAN_VOICES){let released=playing.filter(x=>x.voice.released),pool=released.length>0?released:playing,victim=pool[0];for(let x of pool)x.order<victim.order&&(victim=x);victim.fadeLength=Math.max(1,Math.round(STEAL_SECONDS2*sr)),victim.fade=victim.fadeLength,victim.stolen=!0}live2.some(x=>!x.voice.released&&x.off>onset.start)||(percAt=onset.start);let perc=Math.exp(-(onset.start-percAt)/sr/percTau),{note:note2}=onset,voice=organVoice(family,{pitch:note2.pitch,hz:onset.hz,hzOf,startSec:originSec+onset.start/sr,trackSeed,noteSeed:`${track2.id}:${note2.id}:${note2.startTick+seedTick}`,perc,...keyAt?{keyAt}:{}},values,sr),bend=note2.performance?.cents;live2.push({voice,start:onset.start,off:onset.off,order:order++,...bend?{cents:bend}:{},stolen:!1,fade:0,fadeLength:0})}for(let k=live2.length-1;k>=0;k-=1){let x=live2[k],from=Math.max(i,x.start),n2=i+count2-from;if(n2<=0)continue;x.cents&&x.voice.setCents(x.cents((from-x.start)/sr)),!x.voice.released&&x.off<from+n2&&x.voice.noteOff();let alive;if(x.stolen){let block=new Float64Array(n2);alive=x.voice.process(block,0,n2);for(let s=0;s<n2;s+=1)mono[from+s]+=block[s]*Math.max(0,x.fade)/x.fadeLength,x.fade-=1;x.fade<=0&&(alive=!1)}else alive=x.voice.process(mono,from,n2);alive||live2.splice(k,1)}}let lane=name=>{let points=track2.fxAutomation?.[`keys-${name}`];return points&&points.length>0?points:void 0},rotaryLane=family==="pipe"?void 0:lane("rotary"),driveLane=family==="pipe"?void 0:lane("drive"),settings=organPostSettings(family,values,rotaryLane!==void 0),seed=rotaryLane?context.seedState?.[track2.id]:void 0,post=new OrganPost(settings,sr,originSec,seed?JSON.parse(seed):void 0),monoR=new Float64Array(total);post.process(mono,monoR,total,rotaryLane?s=>interpolateAutomation(rotaryLane,tickAt(context,s),settings.rotary):void 0,driveLane?s=>interpolateAutomation(driveLane,tickAt(context,s),settings.drive):void 0),applyVolume(mono,monoR,track2,context);for(let s=0;s<total;s+=1)left[s]+=mono[s],right[s]+=monoR[s]}function applyVolume(left,right,track2,context){let volume=clamp8(track2.volume??1,0,1),points=track2.volumeAutomation??[];if(!(points.length===0&&volume===1))for(let i=0;i<left.length;i+=CONTROL3){let gain=points.length===0?volume:volume*interpolateAutomation(points,tickAt(context,i),1),end=Math.min(left.length,i+CONTROL3);for(let s=i;s<end;s+=1)left[s]*=gain,right[s]*=gain}}function organTailSeconds(family){return family==="pipe"?.6:family==="combo"?.15:.1}function organReleaseSeconds(family){return family==="pipe"?.15:family==="combo"?.03:.012}function resolvedPercFast(values){return str(values,"percdecay","fast")==="fast"}function organRotorSeed(history,track2,frames,sampleRate){let family=track2.instrument;if(!isOrganFamily(family)||family==="pipe")return;let lane=track2.fxAutomation?.["keys-rotary"];if(!lane||lane.length===0)return;let values=resolvedKeys(family,track2.keys),settings=organPostSettings(family,values,!0),post=new OrganPost(settings,sampleRate),warp2=sampleWarpFor(history,sampleRate),perTick=sampleRate*60/(history.tempoBpm*history.ticksPerBeat);return post.spin(frames,s=>interpolateAutomation(lane,warp2?warp2.tick(s):s/perTick,settings.rotary)),JSON.stringify(post.rotor())}function organEngine(id){return{id,field:"keys",render(dry,dryR,notes,track2,context){if(dryR){renderOrganTrack(dry,dryR,notes,track2,context);return}let left=new Float64Array(dry.length),right=new Float64Array(dry.length);renderOrganTrack(left,right,notes,track2,context);for(let i=0;i<dry.length;i+=1)dry[i]+=.5*(left[i]+right[i])},windowSeed:organRotorSeed,tailSeconds:()=>organTailSeconds(id),releaseSeconds:()=>organReleaseSeconds(id),stereo:()=>!0}}var ORGAN_ENGINES=Object.freeze(["tonewheel","combo","pipe"].map(organEngine));var PIANO_LOW=21,PIANO_HIGH=108,NO_DAMPER_FROM=89;function pianoB(pitch2,mult){let p=clamp8(pitch2,PIANO_LOW,PIANO_HIGH),lg=p>=33?-4+(p-33)/75*2.3:-4+(33-p)/12*.45;return mult*10**lg}function physicalKey(hz3){let key=69+12*Math.log2(hz3/440),near=Math.round(key);return clamp8(Math.abs(key-near)<1e-6?near:key,PIANO_LOW,PIANO_HIGH)}var undamped=key=>Math.round(key)>=NO_DAMPER_FROM;function damperT60(key,f1,release){return release*(.12+.55*clamp8((64-key)/43,0,1))/(1+f1/2e3)}var stringsFor=pitch2=>pitch2<31?1:pitch2<42?2:3,pianoT60=pitch2=>28*2**(-(clamp8(pitch2,PIANO_LOW,PIANO_HIGH)-21)/22);function octaveWidening(low,inharm){let bl=pianoB(low,inharm),bu=pianoB(low+12,inharm),c21=600*Math.log2((1+4*bl)/(1+bl)),c42=600*Math.log2((1+16*bl)*(1+bu)/((1+bl)*(1+4*bu))),w42=.5*clamp8((72-(low+12))/12,0,1);return(1-w42)*c21+w42*c42}var stretchTables=new Map;function stretchCents(pitch2,inharm){let table2=stretchTables.get(inharm);if(!table2){table2=new Float64Array(128);for(let p=75;p<128;p+=1)table2[p]=table2[p-12]+octaveWidening(p-12,inharm);for(let p=62;p>=0;p-=1)table2[p]=table2[p+12]-octaveWidening(p,inharm);stretchTables.size>32&&stretchTables.clear(),stretchTables.set(inharm,table2)}return table2[clamp8(Math.round(pitch2),0,127)]}function pianoF1(hz3,p){if(!(p.stretch>0))return hz3;let key=clamp8(69+12*Math.log2(hz3/440),0,127),low=Math.floor(key),high=Math.min(127,low+1),cents=lerp(stretchCents(low,p.inharm),stretchCents(high,p.inharm),key-low);return hz3*2**(p.stretch*cents/1200)}var PianoVoice=class{constructor(note2,p,sr){this.note=note2;this.p=p;this.sr=sr;let v=clamp8(lerp(.8,note2.velocity,p.touch),.01,1),key=physicalKey(note2.hz);this.key=key;let prepKey=clamp8(note2.pitch,PIANO_LOW,PIANO_HIGH),keyPos=(key-21)/87,random2=seededRandom(`${note2.noteSeed}:piano`),slot=0,prep=()=>unit3(note2.trackSeed,prepKey,slot++),prepKind=p.prep>0&&prep()<p.prep?Math.floor(prep()*3):-1,B=pianoB(key,p.inharm),f1=pianoF1(note2.hz,p),f0=f1/Math.sqrt(1+B),T1=pianoT60(key)*p.decay*(1-.15*p.felt)*(prepKind===1?.12:prepKind>=0?.5:1),soft=clamp8(note2.soft??0,0,1),after=clamp8(p.after,0,.95),thMs=lerp(3.5,.8,keyPos)*lerp(1.6,.7,v)*(1+1.5*p.felt)*(1.3-.6*p.hardness),softFc=35*2**(5*v*(.4+.6*p.hardness)+1.5*keyPos)*.75**soft,softFloor=1-.75*soft,softW=hz3=>soft>0?Math.max(softFloor,((1+(f1/softFc)**2)/(1+(hz3/softFc)**2))**soft):1;soft>0&&(after=clamp8(after+(1-after)*.4*soft,0,.95));let calibrated=(note2.calibration??0)>=1,contactMs=calibrated?Math.min(thMs,600/f1):thMs;this.pulse=hammerPulse(Math.max(2,Math.round(contactMs*.001*sr)),1+2*v*p.hardness);let strings=stringsFor(key),spread=strings===1?.08:soft>0?p.unison*(1-soft*1/strings):p.unison,maxHz=MODE_CEILING*sr,partials=0;for(;partials<160;){let n2=partials+1;if(n2*f0*Math.sqrt(1+B*n2*n2)>=maxHz)break;partials=n2}let extra=prepKind===0||prepKind===2?4:0,bank=new ModeBank(Math.min(12,partials)*3+Math.max(0,partials-12)+extra),xb=.1+.3*prep(),shift=prepKind===0||prepKind===2?.04+.1*prep():0,candidates=[],energy=0,sum0=0,sumW=0;for(let n2=1;n2<=partials;n2+=1){let fn=n2*f0*Math.sqrt(1+B*n2*n2);shift&&n2>1&&(fn*=1-shift*Math.sin(n2*Math.PI*xb)**2);let shape=Math.sin(n2*Math.PI*p.strike);if(Math.abs(shape)<.001)continue;let tn=1/(1/T1+(fn/3e3)**2/(1.2*p.decay)),damped=prepKind===1&&n2>3?.3:1,u0=shape*damped;energy+=u0*u0;let u=u0*softW(fn);if(sum0+=Math.abs(u0),sumW+=Math.abs(u),n2<=12){let d=spread/2*(1+.3*(random2()-.5));candidates.push({hz:fn,t60:tn*.3,u:u*(1-after)}),candidates.push({hz:fn*2**(-d/1200),t60:tn,u:u*after/2}),candidates.push({hz:fn*2**(d/1200),t60:tn,u:u*after/2})}else candidates.push({hz:fn,t60:tn*.6,u})}if(extra)for(let r of[2.76,5.4,8.93,13.34])candidates.push({hz:f1*r*(1+.05*(prep()-.5)),t60:.6+1.2*prep(),u:.35});let loud=v**1.4*(1-.4*p.felt);soft>0&&(loud*=(1-.3*soft)*Math.sqrt(sum0/Math.max(sumW,1e-9)));let mags=candidates.map(c=>pulseMag(this.pulse,TAU3*c.hz/sr)*Math.abs(c.u)),heard=calibrated?mags.reduce((sum,m)=>sum+m*m,0)/Math.max(1e-12,candidates.reduce((sum,c)=>sum+c.u*c.u,0)):1,G=.35*loud/Math.sqrt(Math.max(energy*heard,1e-9)),peak=Math.max(0,...mags);candidates.forEach((c,i)=>{mags[i]>=peak*1e-4&&bank.add(c.hz,c.t60,c.u*G,1,sr)}),this.bank=bank;let pan2=p.width*clamp8((key-64)/44,-1,1)*.8;[this.gl,this.gr]=panGains(pan2);let s=note2.noteSeed;p.knock>0&&this.bursts.push(new Burst(`${s}:knock`,lerp(90,250,keyPos),1,.02+.03*(1-keyPos),p.knock*.05*v**1.5*(prepKind===1?2:1),sr),new Burst(`${s}:click`,2800,1.5,.002,.02*v*v*p.hardness*(1-p.felt)*(1-.3*soft),sr)),p.felt>0&&p.noise>0&&this.bursts.push(new Burst(`${s}:thud`,300,.9,.03,.04*p.felt*p.noise*v,sr)),this.rattle=prepKind===2?{hz:f1,gain:.05*v,k:Math.exp(-1/(.35*sr)),phase:0,random:seededRandom(`${s}:rattle`)}:void 0}note;p;sr;bank;pulse;pos=0;bursts=[];gl;gr;tmp=new Float64Array(0);key;rattle;age=0;releasedFlag=!1;get released(){return this.releasedFlag}noteOff(){if(this.releasedFlag||(this.releasedFlag=!0,undamped(this.key)))return;let base=this.p.release*(.12+.55*clamp8((64-this.key)/43,0,1));this.bank.damp(hz3=>base/(1+hz3/2e3),this.sr),this.p.noise>0&&this.bursts.push(new Burst(`${this.note.noteSeed}:keyoff`,500,1.2,.015,.012*this.p.noise,this.sr))}setCents(cents){this.bank.retune(2**(cents/1200))}damp(tau){this.bank.damp(()=>LN10002*tau,this.sr)}process(out,offset,count2){this.tmp.length<count2&&(this.tmp=new Float64Array(count2));let tmp=this.tmp;tmp.fill(0,0,count2);let done=0;this.pos<this.pulse.length&&(done=Math.min(count2,this.pulse.length-this.pos),this.bank.run(tmp,0,done,this.pulse,this.pos),this.pos+=done),done<count2&&this.bank.run(tmp,done,count2-done,null,0);for(let b of this.bursts)if(!b.done)for(let i=0;i<count2;i+=1)tmp[i]+=b.next();let r=this.rattle;if(r)for(let i=0;i<count2;i+=1){r.phase+=r.hz/this.sr;let gate=Math.abs(Math.sin(Math.PI*r.phase))**16;tmp[i]+=(r.random()*2-1)*gate*r.gain,r.gain*=r.k}for(let i=0;i<count2;i+=1)out[offset+i]+=tmp[i];return this.age+=count2,this.age%256<count2&&this.bank.cull(2e-6),this.bank.n>0||this.bursts.some(b=>!b.done)||r!==void 0&&r.gain>1e-6}};function pianoBody(kind,sr){let q3=(t,hz3,qq,db2)=>new Biquad2().set(t,hz3,qq,db2,sr);switch(kind){case"upright":return[q3("lowshelf",120,.7,-4),q3("peak",380,1.2,3),q3("peak",1500,1,2),q3("highshelf",5e3,.7,-3)];case"honkytonk":return[q3("lowshelf",120,.7,-4),q3("peak",1200,1,4),q3("highshelf",5e3,.7,1)];case"felt":return[q3("lowshelf",150,.7,2),q3("peak",400,.9,1.5),q3("highshelf",2500,.7,-7)];case"prepared":return[q3("lowshelf",120,.7,1),q3("peak",250,.8,2)];default:return[q3("lowshelf",120,.7,1.5),q3("peak",250,.8,2),q3("peak",2500,1,-2),q3("highshelf",6e3,.7,-2)]}}var trackSeedOf=trackId=>seedHash(`keys:${trackId}`);var BEAM=[1,6.267,17.547],X0=.4;function tineReleaseT60(pitch2,release){return release*(.09+.25*clamp8((60-pitch2)/32,0,1))}function clavReleaseT60(release){return release*.06}var TineVoice=class{constructor(note2,p,sr){this.note=note2;this.p=p;this.sr=sr;let v=clamp8(lerp(.8,note2.velocity,p.touch),.01,1),key=note2.pitch,f=note2.hz,rhodes=p.kind==="epiano";this.rhodes=rhodes;let T=rhodes?p.decay*9*2**(-(key-36)/26):p.decay*4.5*2**(-(key-40)/26),bell=p.bell*(rhodes?.04+.22*v*v:.02+.08*v*v)*2**(-(key-60)/30),drive=lerp(.35,rhodes?1.6:1.5,p.bark),A=(.15+.85*v)*drive,legacy=lerp(2.2,.9,v)*(1.4-.8*p.hardness),contact=(note2.calibration??0)>=1?Math.min(legacy,600/f):legacy;this.pulse=hammerPulse(Math.max(2,Math.round(contact*.001*sr)),1.5),this.bank=new ModeBank(4),this.bank.add(f,T,A*.85,1,sr),rhodes&&this.bank.add(f*2**(.4/1200),T*1.3,A*.15,1,sr),this.bank.add(f*BEAM[1],.35*2**(-(key-60)/24),A*bell,1,sr),rhodes&&this.bank.add(f*BEAM[2],.06,A*bell*.3*v,1,sr);let w=TAU3*f/(2*sr);this.norm=(rhodes?.36:.32)/((rhodes?2*X0/(1+X0*X0)**2:.5)*w),this.prevPhi=this.pickup(0),this.dc=new DcBlock(sr,8),this.lp=p.tone>0?new OnePole2(p.tone,sr):void 0,this.peak=rhodes?void 0:new Biquad2().set("peak",1100,.9,4,sr),[this.gl,this.gr]=panGains(p.width*clamp8((key-60)/30,-1,1)),this.bursts.push(new Burst(`${note2.noteSeed}:tine`,rhodes?1800:1200,1.2,.002,.01*v*v,sr)),this.shape=x=>{this.prevX=x;let phi=this.pickup(x),dy=rhodes?-(phi-this.prevPhi):phi-this.prevPhi;this.prevPhi=phi;let y=dy*this.norm;return rhodes?y:Math.tanh(1.3*y)/1.3}}note;p;sr;bank;pulse;pos=0;over=new Oversample2x;dc;lp;peak;norm;gl;gr;tmp=new Float64Array(0);bursts=[];rhodes;prevX=0;prevPhi=0;releasedFlag=!1;age=0;shape;pickup(x){if(this.rhodes){let d=x-X0;return 1/(1+d*d)}return 1/(1-.5*Math.min(x,1.6))}get released(){return this.releasedFlag}noteOff(){if(this.releasedFlag)return;this.releasedFlag=!0;let t=tineReleaseT60(this.note.pitch,this.p.release);this.bank.damp(()=>t,this.sr),this.bursts.push(new Burst(`${this.note.noteSeed}:damper`,180,1,.02,.006*this.note.velocity,this.sr))}setCents(cents){this.bank.retune(2**(cents/1200))}damp(tau){this.bank.damp(()=>LN10002*tau,this.sr)}process(out,offset,count2){this.tmp.length<count2&&(this.tmp=new Float64Array(count2));let tmp=this.tmp;tmp.fill(0,0,count2);let done=0;this.pos<this.pulse.length&&(done=Math.min(count2,this.pulse.length-this.pos),this.bank.run(tmp,0,done,this.pulse,this.pos),this.pos+=done),done<count2&&this.bank.run(tmp,done,count2-done,null,0);for(let i=0;i<count2;i+=1){let y=this.over.process(tmp[i],this.shape);y=this.dc.process(y),this.peak&&(y=this.peak.process(y)),this.lp&&(y=this.lp.process(y));for(let b of this.bursts)b.done||(y+=b.next());out[offset+i]+=y}return this.age+=count2,this.age%256<count2&&this.bank.cull(1e-6),this.bank.n>0||this.bursts.some(b=>!b.done)||Math.abs(this.prevX)>1e-9}};function clavPositions(trackSeed){let spread=slot=>1+.12*(unit3(trackSeed,0,slot)-.5);return{neck:.19*spread(0),bridge:.065*spread(1),tangent:.04*spread(2)}}var ClavVoice=class{constructor(note2,p,sr){this.p=p;this.sr=sr;let v=clamp8(lerp(.8,note2.velocity,p.touch),.01,1),key=note2.pitch,B=15e-5*2**((key-48)/16),f0=note2.hz/Math.sqrt(1+B),T=p.decay*5*2**(-(key-40)/24),{neck,bridge,tangent}=clavPositions(note2.trackSeed),contact=lerp(.6,.25,v)*(1.4-.8*p.hardness);this.pulse=hammerPulse(Math.max(2,Math.round(contact*.001*sr)),1.2);let bank=new ModeBank(80),modes=[],energy=0;for(let n2=1;n2<=80;n2+=1){let fn=n2*f0*Math.sqrt(1+B*n2*n2);if(fn>=.45*sr)break;let a=Math.sin(n2*Math.PI*neck),b=Math.sin(n2*Math.PI*bridge),w=p.pickup==="neck"?a:p.pickup==="bridge"?b*2:p.pickup==="out"?a-b:(a+b)*.7,u=Math.sin(n2*Math.PI*tangent)*w,t60=T/(1+(fn/3e3)**2)*(1-.85*p.mute*Math.min(1,(n2-1)/4));modes.push([fn,t60,u]),energy+=(u*pulseMag(this.pulse,2*Math.PI*fn/sr))**2}let G=.146*(p.pickup==="out"?1.2:1)*v**1.2/Math.sqrt(Math.max(1e-12,energy));for(let[fn,t60,u]of modes)bank.add(fn,Math.max(.02,t60),u*G,1,sr);this.bank=bank,this.lp=p.tone>0?new OnePole2(p.tone,sr):void 0,this.hp=new Biquad2().set("hpf",70,.7,0,sr),[this.gl,this.gr]=panGains(p.width*clamp8((key-60)/30,-1,1))}p;sr;bank;pulse;pos=0;lp;hp;gl;gr;tmp=new Float64Array(0);releasedFlag=!1;age=0;get released(){return this.releasedFlag}noteOff(){if(this.releasedFlag)return;this.releasedFlag=!0;let plunk=hammerPulse(Math.max(2,Math.round(3e-4*this.sr)),1);for(let i=0;i<plunk.length;i+=1)plunk[i]*=-.35;this.pulse=plunk,this.pos=0;let t=clavReleaseT60(this.p.release);this.bank.damp(()=>t,this.sr)}setCents(cents){this.bank.retune(2**(cents/1200))}damp(tau){this.bank.damp(()=>LN10002*tau,this.sr)}process(out,offset,count2){this.tmp.length<count2&&(this.tmp=new Float64Array(count2));let tmp=this.tmp;tmp.fill(0,0,count2);let done=0;this.pos<this.pulse.length&&(done=Math.min(count2,this.pulse.length-this.pos),this.bank.run(tmp,0,done,this.pulse,this.pos),this.pos+=done),done<count2&&this.bank.run(tmp,done,count2-done,null,0);for(let i=0;i<count2;i+=1){let y=this.hp.process(tmp[i]);this.lp&&(y=this.lp.process(y)),out[offset+i]+=y}return this.age+=count2,this.age%256<count2&&this.bank.cull(1e-6),this.bank.n>0}};function electricVoice(note2,p,sr){return p.kind==="clav"?new ClavVoice(note2,p,sr):new TineVoice(note2,p,sr)}function electricPost(left,right,kind,rateHz,depthAt,sr,startSample2=0){if(kind==="clav")return;let block=32;for(let i=0;i<left.length;i+=block){let depth=clamp8(depthAt(i),0,1),end=Math.min(left.length,i+block);if(!(depth<=0))for(let s=i;s<end;s+=1){let lfo3=Math.sin(TAU3*rateHz*(s+startSample2)/sr);if(kind==="epiano"){let a=(depth*lfo3+1)*Math.PI/4;left[s]*=Math.SQRT2*Math.cos(a),right[s]*=Math.SQRT2*Math.sin(a)}else{let gain=1-.5*depth*(1-lfo3);left[s]*=gain,right[s]*=gain}}}}var TAU4=2*Math.PI,LOW=36,HIGH=71,QUIET=1e-9,Sympathetic=class{constructor(hzOf,amount,sr){this.amount=amount;this.factor=sr>=4e4?2:1;let rate2=sr/this.factor;this.a=Math.exp(-TAU4*4e3/rate2);let lpDelay=this.a/(1-this.a);for(let q3=LOW;q3<=HIGH;q3+=1){let hz3=hzOf(q3);if(!(hz3>0)||!Number.isFinite(hz3))continue;let d=Math.max(2,rate2/hz3-lpDelay);this.lines.push(new Float64Array(Math.ceil(d)+8)),this.delay.push(d),this.lp.push(0),this.ws.push(0),this.gDown.push(10**(-3*d/(rate2*4))),this.gUp.push(10**(-3*d/(rate2*.06)))}}amount;lines=[];delay=[];lp=[];ws=[];gUp=[];gDown=[];a;factor;step(x,pedal,out){let yl=0,yr=0,a=this.a;for(let k=0;k<this.lines.length;k+=1){let line=this.lines[k],size=line.length,w=this.ws[k],pos=w-this.delay[k],i=Math.floor(pos),at3=j=>line[(j%size+size)%size],y=hermite4(at3(i-1),at3(i),at3(i+1),at3(i+2),pos-i),f=this.lp[k]=y+a*(this.lp[k]-y);line[w%size]=x+(pedal?this.gDown[k]:this.gUp[k])*f,this.ws[k]=(w+1)%size,k&1?yr+=f:yl+=f}out[0]=yl*.5,out[1]=yr*.5}process(left,right,down){let c=.02*this.amount,out=[0,0],f=this.factor,prevL=0,prevR=0,energy=0;for(let i=0;i<left.length;i+=f){let pedal=down(i),x=0;for(let j=0;j<f&&i+j<left.length;j+=1)x+=left[i+j]+right[i+j];if(x=x/(2*f)*c,!pedal&&energy<QUIET){prevL=0,prevR=0;continue}this.step(x,pedal,out),energy=.999*energy+.001*(out[0]*out[0]+out[1]*out[1]),f===1?(left[i]+=out[0],right[i]+=out[1]):(left[i]+=.5*(prevL+out[0]),right[i]+=.5*(prevR+out[1]),i+1<left.length&&(left[i+1]+=out[0],right[i+1]+=out[1])),prevL=out[0],prevR=out[1]}}};var KEYS_LIMITS=Object.freeze({voices:64,tailSeconds:8,taperSeconds:.25,stealSeconds:.005}),LANE_PARAMS=Object.freeze(["hardness","touch","decay","release","knock","noise","felt"]);function num8(values,key){let value=values[key];return typeof value=="number"?value:0}function pianoParamsAt(track2,values,tick){let lane=name=>{let points=track2.fxAutomation?.[`keys-${name}`],base=num8(values,name);return points&&points.length>0?interpolateAutomation(points,tick,base):base},lanes=Object.fromEntries(LANE_PARAMS.map(name=>[name,lane(name)]));return{hardness:clamp8(lanes.hardness,0,1),touch:clamp8(lanes.touch,0,1),inharm:num8(values,"inharm"),unison:num8(values,"unison"),decay:clamp8(lanes.decay,.1,4),release:clamp8(lanes.release,.1,4),strike:num8(values,"strike"),after:num8(values,"after"),knock:clamp8(lanes.knock,0,1),noise:clamp8(lanes.noise,0,1),felt:clamp8(lanes.felt,0,1),prep:num8(values,"prep"),width:num8(values,"width"),stretch:num8(values,"stretch")}}function electricParamsAt(track2,values,tick,kind){let lane=name=>{let points=track2.fxAutomation?.[`keys-${name}`],base=num8(values,name);return points&&points.length>0?interpolateAutomation(points,tick,base):base},pickup=values.pickup;return{kind,hardness:clamp8(lane("hardness"),0,1),touch:clamp8(lane("touch"),0,1),decay:clamp8(lane("decay"),.1,4),release:clamp8(lane("release"),.1,4),width:num8(values,"width"),bark:num8(values,"bark"),bell:num8(values,"bell"),tone:clamp8(lane("tone"),0,12e3),pickup:pickup==="neck"||pickup==="bridge"||pickup==="out"?pickup:"both",mute:num8(values,"mute")}}function bodyOf(values){let body2=values.body;return typeof body2=="string"?body2:"grand"}function spanOf3(note2,context){let{warp:warp2,samplesPerTick}=context;if(warp2){let start2=Math.max(0,Math.floor(warp2.sample(note2.startTick))),end=Math.floor(warp2.sample(note2.startTick+note2.durationTicks));return{start:start2,off:Math.max(start2+1,end)}}let start=Math.max(0,Math.floor(note2.startTick*samplesPerTick)),length=Math.max(1,Math.floor(note2.durationTicks*samplesPerTick));return{start,off:start+length}}function renderKeysTrack(left,right,notes,track2,context){let sr=context.sampleRate,total=left.length,values=resolvedKeys(track2.instrument??"grand",track2.keys),electric=isElectricFamily(track2.instrument)?track2.instrument:void 0,trackSeed=trackSeedOf(track2.id),seedTick=context.seedTick??0,window=Math.round(KEYS_LIMITS.tailSeconds*sr),taper=Math.round(KEYS_LIMITS.taperSeconds*sr),calibrated=(context.score.calibration??0)>=1,onsets2=[];notes.forEach(note2=>{let hz3=noteHz(note2.pitch,note2.cents,context.tuning);if(!(hz3>0)||!Number.isFinite(hz3))return;let{start,off}=spanOf3(note2,context);start>=total||onsets2.push({note:note2,start,off,hz:hz3,order:0})}),onsets2.sort((a,b)=>a.start-b.start||a.note.startTick-b.note.startTick||(a.note.id<b.note.id?-1:a.note.id>b.note.id?1:0));let live2=[],block=new Float64Array(CONTROL3),next=0,order=0;for(let i=0;i<total;i+=CONTROL3){let count2=Math.min(CONTROL3,total-i);for(;next<onsets2.length&&onsets2[next].start<i+count2;){let onset=onsets2[next];next+=1;let playing=live2.filter(x=>!x.stolen);if(playing.length>=KEYS_LIMITS.voices){let released=playing.filter(x=>x.voice.released),pool=released.length>0?released:playing,victim=pool[0];for(let x of pool)x.order<victim.order&&(victim=x);victim.fadeLength=Math.max(1,Math.round(KEYS_LIMITS.stealSeconds*sr)),victim.fade=victim.fadeLength,victim.stolen=!0}let note2=onset.note,softState=track2.softPedal?pedalStateAt(track2.softPedal,note2.startTick):"up",soft=softState==="down"?1:softState==="half"?.5:0,noteOn={pitch:note2.pitch,hz:onset.hz,velocity:clamp8(note2.velocity,0,1),trackSeed,noteSeed:`${track2.id}:${note2.id}:${note2.startTick+seedTick}`,...soft>0?{soft}:{},...calibrated?{calibration:1}:{}},trim=calibrated?keysTrim(track2.keys?.preset??track2.instrument??"grand",note2.pitch):1,voice=electric?electricVoice(noteOn,electricParamsAt(track2,values,note2.startTick,electric),sr):new PianoVoice(noteOn,pianoParamsAt(track2,values,note2.startTick),sr),performance2=note2.performance,vib=num8(values,"vib"),depth=num8(values,"vibmod")*100,wow=vib>0&&depth>0&&!performance2?.replaceVibrato?t=>depth*Math.sin(2*Math.PI*vib*t):void 0,bend=performance2?.cents,cents=bend&&wow?t=>bend(t)+wow(t):bend??wow;live2.push({voice,trim,start:onset.start,off:onset.off,end:onset.off+window,order:order++,...cents?{cents}:{},...performance2?.damp?{damp:performance2.damp}:{},damped:!1,stolen:!1,fade:0,fadeLength:0})}for(let k=live2.length-1;k>=0;k-=1){let x=live2[k],from=Math.max(i,x.start),n2=i+count2-from;if(n2<=0)continue;let t=(from-x.start)/sr;x.cents&&x.voice.setCents(x.cents(t)),x.damp&&!x.damped&&t>=x.damp.from&&(x.voice.damp(x.damp.tau),x.damped=!0),!x.voice.released&&x.off<from+n2&&x.voice.noteOff(),block.fill(0,0,n2);let alive=x.voice.process(block,0,n2),{gl,gr}=x.voice;for(let s=0;s<n2;s+=1){let index=from+s,gain=1,left0=x.end-index;left0<=0?gain=0:left0<taper&&(gain=.5-.5*Math.cos(Math.PI*left0/taper)),x.stolen&&(gain*=Math.max(0,x.fade)/x.fadeLength,x.fade-=1);let y=block[s]*gain*x.trim;left[index]+=y*gl,right[index]+=y*gr}x.stolen&&x.fade<=0&&(alive=!1),from+n2>=x.end&&(alive=!1),alive||live2.splice(k,1)}}if(electric){let param2=electric==="wurli"?"trem":"vibe",points=track2.fxAutomation?.[`keys-${param2}`],base=num8(values,param2),tickOf=sample=>context.warp?context.warp.tick(sample):sample/context.samplesPerTick,depthAt=points&&points.length>0?sample=>interpolateAutomation(points,tickOf(sample),base):()=>base,rate2=electric==="wurli"?5.6:num8(values,"vibehz")||4,startSample2=Math.round(seedTick*context.samplesPerTick);electricPost(left,right,electric,rate2,depthAt,sr,startSample2),applyVolume2(left,right,track2,context);return}let sym=num8(values,"sym"),pedal=track2.pedal;if(sym>0&&pedal?.some(event=>event.state!=="up")){let bank=new Sympathetic(pitch2=>noteHz(pitch2,void 0,context.tuning),sym,sr),changes=pedal.map(event=>({at:context.warp?context.warp.sample(event.tick):event.tick*context.samplesPerTick,down:event.state!=="up"})),cursor=0,down=!1;bank.process(left,right,sample=>{for(;cursor<changes.length&&changes[cursor].at<=sample;)down=changes[cursor++].down;return down})}let body2=bodyOf(values),eqL=pianoBody(body2,sr),eqR=pianoBody(body2,sr);applyEq(left,eqL),applyEq(right,eqR),applyVolume2(left,right,track2,context)}function applyEq(buffer,filters){for(let filter of filters)for(let i=0;i<buffer.length;i+=1)buffer[i]=filter.process(buffer[i])}function applyVolume2(left,right,track2,context){let volume=clamp8(track2.volume??1,0,1),points=track2.volumeAutomation??[];if(points.length===0){if(volume===1)return;for(let i=0;i<left.length;i+=1)left[i]*=volume,right[i]*=volume;return}for(let i=0;i<left.length;i+=CONTROL3){let tick=context.warp?context.warp.tick(i):i/context.samplesPerTick,gain=volume*interpolateAutomation(points,tick,1),end=Math.min(left.length,i+CONTROL3);for(let s=i;s<end;s+=1)left[s]*=gain,right[s]*=gain}}function keysReleaseSeconds(track2,hz3){if(!(hz3>0)||!Number.isFinite(hz3))return .01;let values=resolvedKeys(track2.instrument??"grand",track2.keys);if(isElectricFamily(track2.instrument)){let release=clamp8(num8(values,"release"),.1,4),t602=track2.instrument==="clav"?clavReleaseT60(release):tineReleaseT60(physicalKey(hz3),release);return Math.max(.01,3/(2*LN10002)*t602)}let p=pianoParamsAt(track2,values,0),key=physicalKey(hz3);if(undamped(key))return KEYS_LIMITS.tailSeconds;let t60=damperT60(key,pianoF1(hz3,p),p.release);return Math.max(.01,3/(2*LN10002)*t60)}function engineFor(id){return{id,field:"keys",render(dry,dryR,notes,track2,context){let right=dryR??new Float64Array(dry.length);if(renderKeysTrack(dry,right,notes,track2,context),!dryR)for(let i=0;i<dry.length;i+=1)dry[i]=.5*(dry[i]+right[i])},tailSeconds:()=>KEYS_LIMITS.tailSeconds,releaseSeconds:(track2,_pitch,hz3)=>keysReleaseSeconds(track2,hz3),stereo:()=>!0}}var KEYS_ENGINES=Object.freeze([...["grand","upright","felt","honkytonk","prepared"].filter(id=>isPianoFamily(id)),...["epiano","wurli","clav"].filter(id=>isElectricFamily(id))].map(engineFor).concat(ORGAN_ENGINES));function bandpass(hz3,octaves,sampleRate){let w=2*Math.PI*hz3/sampleRate,s=Math.sin(w),alpha=s*Math.sinh(Math.LN2/2*octaves*w/s),a0=1+alpha;return{b0:alpha/a0,b1:0,b2:-alpha/a0,a1:-2*Math.cos(w)/a0,a2:(1-alpha)/a0}}function highpass(hz3,sampleRate){let w=2*Math.PI*hz3/sampleRate,alpha=Math.sin(w)/(2*Math.SQRT1_2),c=Math.cos(w),a0=1+alpha;return{b0:(1+c)/2/a0,b1:-(1+c)/a0,b2:(1+c)/2/a0,a1:-2*c/a0,a2:(1-alpha)/a0}}function groupDelay(f,w){let phase=x=>{let nr=f.b0+f.b1*Math.cos(x)+f.b2*Math.cos(2*x),ni=-(f.b1*Math.sin(x)+f.b2*Math.sin(2*x)),dr=1+f.a1*Math.cos(x)+f.a2*Math.cos(2*x),di=-(f.a1*Math.sin(x)+f.a2*Math.sin(2*x));return Math.atan2(ni,nr)-Math.atan2(di,dr)},dp=phase(w+1e-5)-phase(w-1e-5);for(;dp>Math.PI;)dp-=2*Math.PI;for(;dp<-Math.PI;)dp+=2*Math.PI;return-dp/(2*1e-5)}function runBiquad(f,x){let z1=0,z2=0,{b0,b1,b2,a1,a2}=f;for(let i=0;i<x.length;i+=1){let v=x[i],y=b0*v+z1;z1=b1*v-a1*y+z2,z2=b2*v-a2*y,x[i]=y}}function bandLayout(p){let n2=Math.max(2,Math.round(p.bands)),ratio2=(p.hi/p.lo)**(1/(n2-1));return{centres:Array.from({length:n2},(_,k)=>p.lo*ratio2**k),ratio:ratio2,octaves:Math.log2(ratio2)*p.width*1.55}}function bankDesign(p,sampleRate){let{centres,ratio:ratio2,octaves}=bandLayout(p);return{bands:centres.map(hz3=>{let live2=hz3<=.45*sampleRate,filter=bandpass(Math.min(hz3,.45*sampleRate),octaves,sampleRate),advance=live2?Math.round(2*groupDelay(filter,2*Math.PI*hz3/sampleRate)+(p.attack??0)*sampleRate):0;return{hz:hz3,live:live2,filter,advance}}),ratio:ratio2}}function followCoef(seconds2,sampleRate){return seconds2<=0?0:Math.exp(-1/(seconds2*sampleRate))}function follow2(x,attack,release,sampleRate,hold){let a=followCoef(attack,sampleRate),r=followCoef(release,sampleRate),out=new Float64Array(x.length),e=0;for(let i=0;i<x.length;i+=1){if(!hold||hold[i]===0){let v=Math.abs(x[i]),c=v>e?a:r;e=c*e+(1-c)*v}out[i]=e}return out}function gateCurve(x,sampleRate,thresholdDb){if(thresholdDb<=-119)return;let level2=follow2(x,.001,.05,sampleRate),out=new Float64Array(x.length),c=followCoef(.005,sampleRate),s=0;for(let i=0;i<x.length;i+=1){let db2=20*Math.log10(level2[i]+1e-12),t=Math.min(1,Math.max(0,(db2-thresholdDb)/6));s=c*s+(1-c)*t,out[i]=s}return out}function holdCurve(curve,hold){for(let i=1;i<curve.length&&i<hold.length;i+=1)hold[i]!==0&&(curve[i]=curve[i-1])}function quietHold(x,n2,sampleRate,thresholdDb,lead=.03){let level2=follow2(x,.001,.01,sampleRate),floor=10**(Math.max(thresholdDb,-50)/20),ahead=Math.max(0,Math.round(lead*sampleRate)),hold=new Uint8Array(n2),nextQuiet=1/0;for(let i=Math.min(level2.length,n2+ahead)-1;i>=0;i-=1)level2[i]<floor?((i===0||level2[i-1]>=floor)&&(nextQuiet=i),i<n2&&(hold[i]=1)):i<n2&&nextQuiet-i<=ahead&&(hold[i]=1);for(let i=level2.length;i<n2;i+=1)hold[i]=1;return hold}function autoGateDb(asset,sampleRate){let hop=Math.max(1,Math.round(.01*sampleRate)),levels=[];for(let s=0;s+hop<=asset.length;s+=hop){let e=0;for(let i=s;i<s+hop;i+=1)e+=asset[i]*asset[i];let db2=10*Math.log10(e/hop+1e-24);db2>-100&&levels.push(db2)}return levels.length===0?-120:(levels.sort((a,b)=>a-b),levels[Math.floor(levels.length*.1)]+6)}function at2(control,name,i){let curve=control.curves[name];return curve?curve[i]:control.settings[name]}function blockCurve(n2,origin,valueAt4){let out=new Float64Array(n2),phase=(origin%32+32)%32,i=0,start=-phase;for(;i<n2;){let end=Math.min(n2,start+32),value=valueAt4(start);for(;i<end;i+=1)out[i]=value;start+=32}return out}var posMod=(a,m)=>(a%m+m)%m;function periodicityCurve(x,sampleRate,origin=0){let dec=Math.max(1,Math.round(sampleRate/8e3)),dsr=sampleRate/dec,hop=Math.round(.005*sampleRate),win=Math.round(.03*dsr),lagLo=Math.round(dsr/500),lagHi=Math.round(dsr/50),out=new Float64Array(x.length),buf=new Float64Array(win+lagHi);for(let s=-posMod(origin,hop);s<x.length;s+=hop){for(let i=0;i<buf.length;i+=1){let acc=0;for(let d=0;d<dec;d+=1){let j=s+i*dec+d;acc+=j>=0&&j<x.length?x[j]:0}buf[i]=acc/dec}let e0=0;for(let i=0;i<win;i+=1)e0+=buf[i]*buf[i];let best=0;if(e0>1e-12)for(let lag=lagLo;lag<=lagHi;lag+=1){let c=0,el=0;for(let i=0;i<win;i+=1)c+=buf[i]*buf[i+lag],el+=buf[i+lag]*buf[i+lag];let r=c/Math.sqrt(e0*el+1e-20);r>best&&(best=r)}let a=s+Math.round(win*dec/2)-(hop>>1);for(let i=Math.max(0,a);i<Math.min(x.length,a+hop);i+=1)out[i]=best}let first=0;for(let i=0;i<out.length;i+=1)if(out[i]!==0){first=out[i];break}for(let i=0;i<out.length&&out[i]===0;i+=1)out[i]=first;return out}function unvoicedCurve(mod,sampleRate,sens,origin=0,gate){let hp=Float64Array.from(mod),filter=highpass(4e3,sampleRate);runBiquad(filter,hp),runBiquad(filter,hp);let high=follow2(hp,.002,.02,sampleRate),full=follow2(mod,.002,.02,sampleRate),periodic=periodicityCurve(mod,sampleRate,origin),threshold=.5-.35*sens,out=new Float64Array(mod.length),c=followCoef(.004,sampleRate),s=0;for(let i=0;i<mod.length;i+=1){let ratio2=full[i]>1e-4?high[i]/full[i]:0,share=Math.min(1,Math.max(0,(ratio2-threshold)/.15)),aperiodic=Math.min(1,Math.max(0,(.75-periodic[i])/.2)),t=share*aperiodic*(gate?gate[i]:1);s=c*s+(1-c)*t,out[i]=s}return out}function hissPath(mod,n2,sampleRate){let hp=mod.slice(0,n2);return runBiquad(highpass(5e3,sampleRate),hp),hp}function channelMakeup(bands,width){return 1.4*(bands/16)**.29/(width<=1?width**.35:width**1.1)}var REF2=.02;function noiseSample(seed,songSample){return unit3(seed,songSample,11)*2-1}function followVarying(x,attack,release,releaseCurve,sampleRate,hold){if(!releaseCurve)return follow2(x,attack,release,sampleRate,hold);let a=followCoef(attack,sampleRate),out=new Float64Array(x.length),e=0,lastRelease=Number.NaN,r=0;for(let i=0;i<x.length;i+=1){if(releaseCurve[i]!==lastRelease&&(lastRelease=releaseCurve[i],r=followCoef(lastRelease,sampleRate)),!hold||hold[i]===0){let v=Math.abs(x[i]),c=v>e?a:r;e=c*e+(1-c)*v}out[i]=e}return out}function runBand(x,filter,filterAt){if(!filterAt){runBiquad(filter,x);return}let z1=0,z2=0,f=filterAt(0);for(let i=0;i<x.length;i+=1){i%32===0&&(f=filterAt(i));let v=x[i],y=f.b0*v+z1;z1=f.b1*v-f.a1*y+z2,z2=f.b2*v-f.a2*y,x[i]=y}}function runBandTwice(x,filter,filterAt){if(filterAt){runBand(x,filter,filterAt),runBand(x,filter,filterAt);return}let{b0,b1,b2,a1,a2}=filter,p1=0,p2=0,q1=0,q22=0;for(let i=0;i<x.length;i+=1){let v=x[i],y=b0*v+p1;p1=b1*v-a1*y+p2,p2=b2*v-a2*y;let w=b0*y+q1;q1=b1*y-a1*w+q22,q22=b2*y-a2*w,x[i]=w}}function multiplyInto(e,g){for(let i=0;i<e.length;i+=1)e[i]=e[i]*g[i]}function blendUnvoiced(carrier,u,control,seed,origin,sr){let level2=follow2(carrier,.01,.1,sr),curve=control.curves.unvoiced,fixed=control.settings.unvoiced;for(let i=0;i<carrier.length;i+=1){let w=u[i]*(curve?curve[i]:fixed);if(w<=0)continue;let noise2=noiseSample(seed,origin+i);carrier[i]=carrier[i]*(1-w)+noise2*1.7*Math.max(level2[i],.05)*w}}function mixBandFixed(out,syn,ea,eb,fr,ec,depth,scale3){let n2=out.length,refPow=REF2**(1-depth);if(ec)for(let i=0;i<n2;i+=1){let e=ea[i]*(1-fr)+eb[i]*fr,g=(depth===1?e:e**depth*refPow)/(ec[i]+1e-5);out[i]+=syn[i]*Math.min(g,1e3)*scale3}else for(let i=0;i<n2;i+=1){let e=ea[i]*(1-fr)+eb[i]*fr,level2=depth===1?e:e**depth*refPow;out[i]+=syn[i]*level2*8*scale3}}function channelVocode(mod,cars,control){let{settings:p,sampleRate:sr,origin,seed}=control,n2=Math.min(mod.length,...cars.map(c=>c.length)),{bands,ratio:ratio2}=bankDesign(p,sr),nb=bands.length,widthCurve=control.curves.width,designs=new Map,filtersFor=width=>{let known=designs.get(width);if(!known){let octaves=Math.log2(ratio2)*width*1.55;known=bands.map(b=>bandpass(Math.min(b.hz,.45*sr),octaves,sr)),designs.set(width,known)}return known},filterAt=(k,offset)=>widthCurve?i=>filtersFor(widthCurve[Math.min(n2-1,i+offset)])[k]:void 0,gate=gateCurve(mod.subarray(0,n2),sr,control.gateDb);gate&&control.hold&&holdCurve(gate,control.hold);let u=p.unvoiced>0||control.curves.unvoiced!==void 0?unvoicedCurve(mod.subarray(0,n2),sr,p.sens,origin,gate):void 0,env=[],band=new Float64Array(n2);for(let k=0;k<nb;k+=1){let b=bands[k];if(!b.live){env.push(new Float64Array(n2));continue}let from=Math.min(b.advance,mod.length),take=Math.min(n2,mod.length-from);band.set(mod.subarray(from,from+take)),band.fill(0,take),runBandTwice(band,b.filter,filterAt(k,b.advance));let e=followVarying(band,p.attack,p.release,control.curves.release,sr,control.hold);gate&&multiplyInto(e,gate),env.push(e)}let shiftOf=i=>at2(control,"formant",i)/12/Math.log2(ratio2),staticShift=control.curves.formant?void 0:shiftOf(0),synthEnv=(k,i)=>{let pos=k-(staticShift??shiftOf(i)),i0=Math.floor(pos),fr=pos-i0,a=i0>=0&&i0<nb?env[i0][i]:0,b=i0+1>=0&&i0+1<nb?env[i0+1][i]:0;return a*(1-fr)+b*fr},scale3=channelMakeup(p.bands,p.width),depthCurve=control.curves.depth,shape=(e,i)=>{let depth=depthCurve?depthCurve[i]:p.depth;return depth===1?e:e**depth*REF2**(1-depth)},hiss=p.hiss>0||control.curves.hiss?hissPath(mod,n2,sr):void 0,zeros=new Float64Array(n2),outs=[];for(let car of cars){let carrier=car.slice(0,n2);u&&blendUnvoiced(carrier,u,control,seed,origin,sr);let out=new Float64Array(n2),syn=new Float64Array(n2);for(let k=0;k<nb;k+=1){let b=bands[k];if(!b.live)continue;syn.set(carrier),runBandTwice(syn,b.filter,filterAt(k,0));let ea=zeros,eb=zeros,fr=0;if(staticShift!==void 0){let pos=k-staticShift,i0=Math.floor(pos);fr=pos-i0,i0>=0&&i0<nb&&(ea=env[i0]),i0+1>=0&&i0+1<nb&&(eb=env[i0+1])}let ec=p.enhance?followVarying(syn,p.attack,p.release,control.curves.release,sr):void 0;if(staticShift!==void 0&&depthCurve===void 0)mixBandFixed(out,syn,ea,eb,fr,ec,p.depth,scale3);else for(let i=0;i<n2;i+=1){let level2=shape(synthEnv(k,i),i);if(ec){let g=level2/(ec[i]+1e-5);out[i]+=syn[i]*Math.min(g,1e3)*scale3}else out[i]+=syn[i]*level2*8*scale3}}if(hiss)for(let i=0;i<n2;i+=1)out[i]+=at2(control,"hiss",i)*hiss[i]*(gate?gate[i]:1);outs.push(out)}return outs}var UNISON=Object.freeze([0,-.73,.73,-1.67,1.67,-2.67,2.67]),FADE_SECONDS2=.004;function renderCarrierSpan(left,right,span4,settings,options){let{sampleRate}=options,end=Math.min(left.length,span4.start+span4.length),begin=Math.max(0,span4.start);if(end<=begin)return;let fade=Math.max(1,Math.round(FADE_SECONDS2*sampleRate)),level2=.3*(.4+.6*Math.max(0,Math.min(1,span4.velocity))),envelope2=i=>{let a=i-span4.start,b=span4.start+span4.length-i;return Math.min(1,a/fade,b/fade)};if(settings.carrier==="noise"){for(let i=begin;i<end;i+=1){let v=(unit3(options.seed,options.origin+i,7)*2-1)*.5,e=envelope2(i)*level2;left[i]+=v*e,right&&(right[i]+=v*e)}return}let copies=settings.carrier==="supersaw"?UNISON:[0],voices=span4.pitches.length*copies.length,norm=1/Math.sqrt(Math.max(1,voices));span4.pitches.forEach((pitch2,p)=>{let base=noteHz(pitch2,void 0,options.tuning),bend=span4.cents;copies.forEach((offset,c)=>{let hz3=base*2**(offset*settings.spread/12),dt=hz3/sampleRate;if(!(dt>0&&dt<.5))return;let phase=settings.carrier==="supersaw"?unit3(span4.seed,p*8+c,3):0;phase=span4.absolute?(phase+(options.origin+begin)*dt%1)%1:(phase+(begin-span4.start)*dt)%1;let weight=(c===0?1:.6)*norm*level2,side=c===0?0:c%2===1?-1:1;for(let i=begin;i<end;i+=1){bend&&(i-begin)%32===0&&(dt=Math.min(.49,hz3*2**(bend((i-span4.start)/sampleRate)/1200)/sampleRate));let s=(settings.carrier==="pulse"?(phase<.5?1:-1)+polyBlep(phase,dt)-polyBlep((phase+.5)%1,dt):2*phase-1-polyBlep(phase,dt))*weight*envelope2(i);!right||side===0?(left[i]+=s,right&&(right[i]+=s)):side<0?left[i]+=s*1.4:right[i]+=s*1.4,phase+=dt,phase>=1&&(phase-=1)}})})}function noteSpans(notes,span4,seedOf){return notes.map(note2=>{let{start,length}=span4(note2),cents=note2.performance?.cents;return{start,length,pitches:[note2.pitch],...cents?{cents}:{},velocity:note2.velocity,seed:seedOf(note2)}})}function chordSpans(changes,root,seed){return changes.filter(change=>change.pcs.length>0&&change.end>change.start).map(change=>({start:change.start,length:change.end-change.start,pitches:change.pcs.map(pc=>root+((pc-root)%12+12)%12),velocity:.8,seed,absolute:!0}))}function autocorrelate(x,order,r,sampleRate){for(let lag=0;lag<=order;lag+=1){let s=0;for(let i=lag;i<x.length;i+=1)s+=x[i]*x[i-lag];r[lag]=s}r[0]=r[0]*(1+1e-6)+1e-12;for(let lag=1;lag<=order;lag+=1)r[lag]=r[lag]*Math.exp(-.5*(2*Math.PI*60*lag/sampleRate)**2);return r}function levinson(r,order,a){a.fill(0),a[0]=1;let err=r[0];if(err<=0)return 0;let tmp=new Float64Array(order+1);for(let i=1;i<=order;i+=1){let acc=r[i];for(let j=1;j<i;j+=1)acc+=a[j]*r[i-j];let k=-acc/err;tmp.set(a);for(let j=1;j<i;j+=1)a[j]=tmp[j]+k*tmp[i-j];if(a[i]=k,err*=1-k*k,err<=0)return 0}return err}var TALKBOX_MAKEUP=.97,posMod2=(a,m)=>(a%m+m)%m;function talkboxVocode(mod,cars,control){let{settings:p,sampleRate:sr,origin,seed}=control,n2=Math.min(mod.length,...cars.map(c=>c.length)),N=2*Math.round(.01*sr),hop=N/2,order=Math.max(8,Math.round(sr/2e3)),corder=12,win=new Float64Array(N),sq=new Float64Array(N);for(let i=0;i<N;i+=1)win[i]=.5-.5*Math.cos(2*Math.PI*i/N),sq[i]=Math.sqrt(win[i]);let acc=cars.map(()=>new Float64Array(n2+N)),pre=new Float64Array(n2);for(let i=0;i<n2;i+=1)pre[i]=mod[i]-.97*(i>0?mod[i-1]:0);let mf=new Float64Array(N),cf=new Float64Array(N),y=new Float64Array(N),r=new Float64Array(order+1),a=new Float64Array(order+1),rc=new Float64Array(corder+1),ac=new Float64Array(corder+1),gate=gateCurve(mod.subarray(0,n2),sr,control.gateDb);gate&&control.hold&&holdCurve(gate,control.hold);let u=p.unvoiced>0||control.curves.unvoiced!==void 0?unvoicedCurve(mod.subarray(0,n2),sr,p.sens,origin,gate):void 0,heldMe0=0;for(let start=-posMod2(origin,hop)-hop;start<n2;start+=hop){let centre=Math.min(n2-1,Math.max(0,start+hop)),shift=2**(Math.max(-TALKBOX_FORMANT_MAX,Math.min(TALKBOX_FORMANT_MAX,at2(control,"formant",centre)))/12),held=heldMe0>0&&control.hold?.[centre]===1,me=held?1:0,me0=held?heldMe0:0;for(let i=0;!held&&i<N;i+=1){let j=start+i,jj=start+hop+(i-hop)*shift,k0=Math.floor(jj),fr=jj-k0,m=k0>=0&&k0+1<n2?pre[k0]*(1-fr)+pre[k0+1]*fr:0,g=gate&&j>=0&&j<n2?gate[j]:1;mf[i]=m*win[i]*g,me+=mf[i]*mf[i];let raw=(j>=0&&j<n2?mod[j]:0)*win[i]*g;me0+=raw*raw}if(!(me<1e-10||me0<1e-10)){held||(levinson(autocorrelate(mf,order,r,sr),order,a),heldMe0=me0);for(let c=0;c<cars.length;c+=1){let car=cars[c];for(let i=0;i<N;i+=1){let j=start+i,v=j>=0&&j<n2?car[j]:0;if(u&&j>=0&&j<n2){let w=u[j]*at2(control,"unvoiced",j);v=v*(1-w)+noiseSample(seed,origin+j)*.5*w}cf[i]=v*sq[i]}if(p.enhance){levinson(autocorrelate(cf,corder,rc,sr),corder,ac);for(let i=N-1;i>=0;i-=1){let s=cf[i];for(let j=1;j<=corder&&j<=i;j+=1)s+=ac[j]*cf[i-j];cf[i]=s}}let ce=0;for(let i=0;i<N;i+=1)ce+=cf[i]*cf[i];if(ce<=1e-12)continue;for(let i=0;i<N;i+=1){let s=cf[i];for(let j=1;j<=order&&j<=i;j+=1)s-=a[j]*y[i-j];y[i]=s}let ye=0,de=0;for(let i=0;i<N;i+=1){de=y[i]*sq[i]+.97*de;let v=de*sq[i];ye+=v*v}let g=ye>1e-20?Math.sqrt(me0/ye)*TALKBOX_MAKEUP:0,o=acc[c];for(let i=0;i<N;i+=1){let j=start+i;j>=0&&(o[j]+=y[i]*sq[i]*g)}}}}let hiss=p.hiss>0||control.curves.hiss?hissPath(mod,n2,sr):void 0;return acc.map(o=>{let res=new Float64Array(n2),dd=0;for(let i=0;i<n2;i+=1)dd=o[i]+.97*dd,res[i]=dd;if(hiss)for(let i=0;i<n2;i+=1)res[i]+=at2(control,"hiss",i)*hiss[i]*(gate?gate[i]:1);return res})}function peakGuard(x){for(let i=0;i<x.length;i+=1){let v=x[i],a=Math.abs(v);a>.9&&(x[i]=Math.sign(v)*(.9+.1*Math.tanh((a-.9)/.1)))}}function originOf(context){return Math.round((context.seedSeconds??0)*context.sampleRate)}function vocoderSeed(track2,settings){return settings.seed??seedHash(`vocoder:${track2.id}`)}function laneOf3(track2,param2){let points=track2.fxAutomation?.[`vocoder-${param2}`];return points&&points.length>0?points:void 0}function tickAt2(context,index){return context.warp?context.warp.tick(Math.max(0,index)):index/context.samplesPerTick}function vocoderControl(track2,n2,context,gateDb,mod){let settings=resolveVocoder(track2.vocoder),origin=originOf(context),curves2={},hold;for(let{param:param2}of VOCODER_LANE_PARAMS){let points=laneOf3(track2,param2);if(!points)continue;let fallback=param2==="freeze"?settings.freeze?1:0:settings[param2],curve=blockCurve(n2,origin,index=>interpolateAutomation(points,tickAt2(context,index),fallback));if(param2==="freeze"){hold=new Uint8Array(n2);for(let i=0;i<n2;i+=1)hold[i]=curve[i]>=.5?1:0}else curves2[param2]=curve}return!hold&&settings.freeze&&(hold=mod?quietHold(mod,n2,context.sampleRate,gateDb):new Uint8Array(n2).fill(1)),{settings,sampleRate:context.sampleRate,origin,seed:vocoderSeed(track2,settings),gateDb,curves:curves2,...hold?{hold}:{}}}function applyVocoder(dry,dryR,mod,track2,context,gateDb){let n2=dry.length,cars=dryR?[dry,dryR]:[dry],padded=mod.length>=n2?mod:(()=>{let out=new Float64Array(n2);return out.set(mod),out})(),control=vocoderControl(track2,n2,context,gateDb,padded),outs=control.settings.mode==="talkbox"?talkboxVocode(padded,cars,control):channelVocode(padded,cars,control),{curves:curves2,settings}=control;outs.forEach((out,c)=>{let car=cars[c],gain=curves2.gain;if(gain||settings.gain!==0){let fixed=10**(settings.gain/20);for(let i=0;i<n2;i+=1)out[i]=out[i]*(gain?10**(gain[i]/20):fixed)}peakGuard(out);let mix3=curves2.mix;if(mix3||settings.mix<1)for(let i=0;i<n2;i+=1){let m=mix3?mix3[i]:settings.mix;out[i]=out[i]*m+car[i]*(1-m)}car.set(out.subarray(0,n2))})}function noteSpanOf(note2,context){if(context.warp)return warpedSpan(context.warp,note2.startTick,note2.durationTicks);let perTick=60*context.sampleRate/(context.tempoBpm*context.ticksPerBeat);return{start:Math.max(0,Math.floor(note2.startTick*perTick)),length:Math.max(1,Math.floor(note2.durationTicks*perTick))}}function sampleAtTick(context,tick){return context.warp?warpedSpan(context.warp,tick,0).start:Math.max(0,Math.floor(tick*context.samplesPerTick))}var samePcs=(a,b)=>a.length===b.length&&a.every((pc,index)=>pc===b[index]);function mergeChordChanges(changes,hold){let merged=[];for(let change of changes){if(change.end<=change.start)continue;let last=merged[merged.length-1];if(last&&(samePcs(last.pcs,change.pcs)||change.pcs.length===0&&last.pcs.length>0&&change.end-change.start<hold)){last.end=change.end;continue}merged.push({...change})}return merged}function carrierSpans(notes,track2,settings,context){let seed=vocoderSeed(track2,settings);if(settings.follow==="drone")return[{start:0,length:context.samples,pitches:[settings.root],velocity:.8,seed,absolute:!0}];if(settings.follow==="chords"){let timeline=chordTimeline(context.score),changes=[],ticks=[0,...timeline.ticks.filter(tick=>tick>0)];return ticks.forEach((tick,index)=>{let next=ticks[index+1];changes.push({start:sampleAtTick(context,tick),end:next===void 0?context.samples:sampleAtTick(context,next),pcs:chordAt(timeline,tick)})}),chordSpans(mergeChordChanges(changes,Math.round(.05*context.sampleRate)),settings.root,seed)}return noteSpans(notes,note2=>noteSpanOf(note2,context),note2=>seedHash(`${seed}:${note2.id}`)).map((span4,index)=>{let cents=notes[index].cents;if(!cents)return span4;let curve=span4.cents;return{...span4,cents:curve?t=>cents+curve(t):()=>cents}})}var VOCODER_ENGINE={id:VOCODER_INSTRUMENT2,field:"vocoder",render(dry,dryR,notes,track2,context){let settings=resolveVocoder(track2.vocoder),origin=originOf(context);for(let span4 of carrierSpans(notes,track2,settings,context))renderCarrierSpan(dry,dryR,span4,settings,{sampleRate:context.sampleRate,origin,seed:span4.seed,...context.tuning?{tuning:context.tuning}:{}})},tailSeconds(track2){return vocoderTailSeconds(track2.vocoder)},stereo(track2){return resolveVocoder(track2.vocoder).carrier==="supersaw"}};function mulberry(state){let value=Math.imul(state^state>>>15,1|state);return value=value+Math.imul(value^value>>>7,61|value)^value,((value^value>>>14)>>>0)/4294967296}var Rng=class{state;noiseState;scale;constructor(seed,sampleRate=44100){this.state=seedHash(seed),this.noiseState=seedHash(`${seed}:noise`),this.scale=Math.sqrt(sampleRate/44100)}next(){return this.state=this.state+1831565813>>>0,mulberry(this.state)}noise(){return this.noiseState=this.noiseState+1831565813>>>0,(2*mulberry(this.noiseState)-1)*this.scale}bi(){return 2*this.next()-1}range(lo,hi){return lo+(hi-lo)*this.next()}wait(rate2){return-Math.log(1-this.next())/Math.max(1e-9,rate2)}},Pink=class{b0=0;b1=0;b2=0;process(white){return this.b0=.99765*this.b0+white*.099046,this.b1=.963*this.b1+white*.2965164,this.b2=.57*this.b2+white*1.0526913,(this.b0+this.b1+this.b2+white*.1848)*.25}},Brown=class{y=0;leak;constructor(sampleRate){this.leak=Math.exp(-2*Math.PI*20/sampleRate)}process(white){return this.y=this.leak*this.y+(1-this.leak)*white,this.y*7}},Lp1=class{a=1;y=0;set(hz3,sampleRate){let f=Math.min(Math.max(hz3,5),sampleRate*.49);this.a=1-Math.exp(-2*Math.PI*f/sampleRate)}process(x){return this.y+=this.a*(x-this.y),this.y}},Hp1=class{lp=new Lp1;set(hz3,sampleRate){this.lp.set(hz3,sampleRate)}process(x){return x-this.lp.process(x)}},Svf2=class{k=1;a1=1;a2=0;a3=0;ic1=0;ic2=0;low=0;band=0;high=0;set(hz3,q3,sampleRate){let f=Math.min(Math.max(hz3,10),sampleRate*.45),g=Math.tan(Math.PI*f/sampleRate);this.k=1/Math.max(.05,q3),this.a1=1/(1+g*(g+this.k)),this.a2=g*this.a1,this.a3=g*this.a2}process(x){let v3=x-this.ic2,v1=this.a1*this.ic1+this.a2*v3,v2=this.ic2+this.a2*this.ic1+this.a3*v3;return this.ic1=2*v1-this.ic1,this.ic2=2*v2-this.ic2,this.low=v2,this.band=this.k*v1,this.high=x-this.k*v1-v2,this.band}},Drift2=class{constructor(rng,start=.5){this.rng=rng;this.from=start,this.to=start}rng;from;to;at=0;span=1;step(dt,period,depth=1){this.at+=dt,this.at>=this.span&&(this.at-=this.span,this.from=this.to,this.to=.5+depth*(this.rng.next()-.5),this.span=Math.max(.02,period*(.5+this.rng.next())),this.at>this.span&&(this.at=0));let x=this.at/this.span;return this.from+(this.to-this.from)*(.5-.5*Math.cos(Math.PI*x))}},LINES=8,Fdn=class{constructor(sampleRate,delays,t60,damping2,rng){this.sampleRate=sampleRate;this.depth=Math.max(1,Math.round(.0012*sampleRate));let longest=Math.ceil(Math.max(...delays)*sampleRate)+this.depth+4,size=1;for(;size<longest;)size<<=1;this.mask=size-1;for(let i=0;i<LINES;i+=1)this.buffers.push(new Float64Array(size)),this.lengths.push(delays[i]*sampleRate),this.rates.push(rng.range(.07,.6)),this.phases.push(rng.next()),this.damp.push(0);this.setDecay(t60,damping2)}sampleRate;buffers=[];lengths=[];gains=[];damp=[];state=new Array(LINES).fill(0);rates=[];phases=[];depth;mask;write=0;y=new Float64Array(LINES);dampA=1;setDecay(t60,damping2){let t=Math.max(.05,t60);this.gains.length=0;for(let i=0;i<LINES;i+=1)this.gains.push(10**(-3*this.lengths[i]/(t*this.sampleRate)));let f=Math.min(Math.max(damping2,200),this.sampleRate*.45);this.dampA=1-Math.exp(-2*Math.PI*f/this.sampleRate)}process(input,out){let y=this.y,step2=1/this.sampleRate;for(let i=0;i<LINES;i+=1){let phase=this.phases[i]+this.rates[i]*step2;phase>=1&&(phase-=1),this.phases[i]=phase;let tri2=phase<.5?4*phase-1:3-4*phase,delay=this.lengths[i]+.5*this.depth*(1+tri2),read=this.write-delay,base=Math.floor(read),frac2=read-base,buffer=this.buffers[i],a=buffer[base&this.mask],b=buffer[base+1&this.mask],v=a+frac2*(b-a),s=this.state[i]+this.dampA*(v-this.state[i]);this.state[i]=Math.abs(s)<1e-25?0:s,v=s*this.gains[i],y[i]=v}out[0]=y[0]+y[1]+y[2]+y[3],out[1]=y[4]+y[5]+y[6]+y[7];for(let h=1;h<LINES;h<<=1)for(let i=0;i<LINES;i+=h<<1)for(let j=i;j<i+h;j+=1){let p=y[j],q3=y[j+h];y[j]=p+q3,y[j+h]=p-q3}let norm=.3535533905932738,w=this.write&this.mask;for(let i=0;i<LINES;i+=1)this.buffers[i][w]=y[i]*norm+(i&1?-input:input);this.write+=1}};function polyBlep2(t,dt){if(t<dt){let x=t/dt;return x+x-x*x-1}if(t>1-dt){let x=(t-1)/dt;return x*x+x+x+1}return 0}var TAU5=Math.PI*2,Water=class{constructor(kind,random2,rate2){this.kind=kind;this.random=random2;this.rate=rate2;this.rumble=new Brown(rate2),this.flow=new Drift2(random2),kind==="ocean"&&(this.age=random2.range(1.2,3.9),this.height=random2.range(.5,.9),this.shoreDelay=random2.range(-.087,.087))}kind;random;rate;pink=[new Pink,new Pink];rumble;foam=[new Svf2,new Svf2];sand=[new Svf2,new Svf2];bubble=new Svf2;farBubble=new Svf2;flow;nextFarBubble=0;farPan=.65;age=1.8;period=8;height=.7;count=0;group=.9;shoreDelay=.05;nextBubble=0;render(left,right,n2,controls2){let ocean=this.kind==="ocean",stream=this.kind==="stream",flow=ocean?.5:this.flow.step(n2/this.rate,stream?1.7:3.4),arrival=Math.min(1,this.age/this.period),crest=Math.exp(-28*(arrival-.36)**2),center=(ocean?550+this.height*(420+1160*crest):stream?1460+820*flow:740+520*flow)*controls2.sweep;this.foam[0].set(center,.65,this.rate),this.foam[1].set(center*1.12,.72,this.rate),ocean&&(this.sand[0].set((420+360*arrival)*controls2.sweep,1.15,this.rate),this.sand[1].set((490+380*arrival)*controls2.sweep,1.05,this.rate)),this.kind==="waterfall"&&(this.sand[0].set((1720+690*flow)*controls2.sweep,.73,this.rate),this.sand[1].set((2450-430*flow)*controls2.sweep,.81,this.rate));let channels=[left,right];for(let i=0;i<n2;i++){if(this.age+=1/this.rate,ocean&&this.age>=this.period){this.age-=this.period,this.count++%6===0&&(this.group=this.random.range(.7,1.15));let rayleigh=Math.sqrt(-2*Math.log(1-this.random.next()));this.height=.52*this.height+.48*Math.min(1.5,rayleigh*this.group),this.period=(15-9.8*controls2.density)*this.random.range(.85,1.17),this.shoreDelay=this.random.range(-.087,.087)}let phase=this.age/this.period,swell=Math.sin(Math.PI*Math.min(1,phase))**2,collapse=phase<.36?(phase/.36)**3:Math.exp(-5*(phase-.36)),bed=ocean?.12+.69*this.height*swell:stream?.4+.2*flow:.72+.23*flow,low=this.rumble.process(this.random.noise())*(ocean?(.28+swell)*this.height:stream?.11:.62+.36*flow),impulse=0;if((stream||ocean)&&--this.nextBubble<=0){let events=stream?(11+27*controls2.density)*(.76+flow*.48):5+34*collapse*this.height;this.nextBubble=this.random.wait(events)*this.rate,this.bubble.set(this.random.range(520,2700)*controls2.sweep,stream?16:5,this.rate),impulse=this.random.bi()*(stream?4.2:2.6*collapse)}let bubbles=this.bubble.process(impulse)*(.5+controls2.wear),far=0;if(stream){let hit2=0;--this.nextFarBubble<=0&&(this.nextFarBubble=this.random.wait(5+14*controls2.density)*this.rate,this.farBubble.set(this.random.range(710,1880)*controls2.sweep,13,this.rate),this.farPan=this.random.range(.54,.91),hit2=this.random.bi()*(2.2+1.7*controls2.wear)),far=this.farBubble.process(hit2)}let foamLevel=ocean?.27+collapse*this.height:stream?.86:.62;for(let channel=0;channel<2;channel++){let output2=channels[channel],pink=this.pink[channel].process(this.random.noise()),wash=foamLevel,backwash=0;if(ocean){let breakAt=.36+(channel?this.shoreDelay:0),shore=phase<breakAt?(phase/breakAt)**3:Math.exp(-5*(phase-breakAt)),retreat=Math.sin(Math.PI*Math.min(1,Math.max(0,(phase-breakAt-.09)/.49)))**2;wash=.18+shore*this.height,backwash=this.sand[channel].process(pink)*retreat*(.35+controls2.wear)*this.height}else stream||(backwash=this.sand[channel].process(pink)*(.37+flow*.42));output2[i]=pink*bed+this.foam[channel].process(pink)*wash+backwash+low+bubbles*(channel?stream?.37:.67:1)+far*(channel?this.farPan:1-this.farPan)}}}},FieldCalls=class{constructor(kind,random2,rate2){this.kind=kind;this.random=random2;this.rate=rate2;this.distantPitch=kind==="crickets"?random2.range(2870,3590):0,this.distantPeriod=kind==="crickets"?random2.range(.74,1.13):1,kind==="crickets"&&(this.distantClock=random2.range(0,this.distantPeriod))}kind;random;rate;bed=new Pink;age=0;next=0;phase=0;pitch=1800;sweep=0;pan=0;accents=3;length=.38;lastBirdPitch=0;birdAnswer=!1;distantPhase=0;distantClock=0;distantPitch;distantPeriod;render(left,right,n2,controls2){let birds=this.kind==="birds";for(let i=0;i<n2;i++){--this.next<=0&&(this.age=0,this.pan=this.random.bi()*.52,this.pitch=birds?this.random.range(1150,2750):this.random.range(3150,4880),this.sweep=this.random.bi()*(birds?1050:140),birds&&(this.birdAnswer=!this.birdAnswer,!this.birdAnswer&&this.lastBirdPitch&&(this.pitch=this.lastBirdPitch*this.random.range(.87,1.16)),this.lastBirdPitch=this.pitch),this.accents=Math.floor(this.random.range(2,birds?5:7)),this.length=birds?this.random.range(.37,.83):this.accents*.064,this.next=this.rate*(this.length+this.random.range(.09,birds?1.25:.8)/(.46+controls2.density)));let position=this.age/this.length,call=0;if(position<1){let syllable=Math.floor(position*this.accents),within=position*this.accents%1,sung=birds?Math.min(1,within/(syllable%2?.86:.73)):within,pulse2=Math.sin(Math.PI*sung)**(birds?1.65:7),bend=birds?(syllable%2?-1:1)*Math.sin(Math.PI*(sung-.18))+(this.birdAnswer?-.18:.19)*syllable:within-.5,hz3=Math.min(this.rate*.42,(this.pitch+bend*this.sweep)*controls2.sweep);this.phase=(this.phase+hz3/this.rate)%1;let carrier=Math.sin(TAU5*this.phase),harmonics=birds?2*hz3<.45*this.rate?Math.sin(TAU5*2*this.phase)*(.08+.15*controls2.wear)*(1-sung):0:this.random.noise()*(.04+controls2.wear*.13);call=(carrier+harmonics)*pulse2*Math.sin(Math.PI*position)*.55}this.age+=1/this.rate;let background=this.bed.process(this.random.noise())*(birds?.15:.08),distant=0;if(!birds){this.distantClock+=(.78+controls2.density*.43)/this.rate,this.distantClock>=this.distantPeriod&&(this.distantClock-=this.distantPeriod);let phrase=this.distantClock/this.distantPeriod;if(phrase<.38){let pulse2=Math.sin(Math.PI*phrase*12/.38)**6;this.distantPhase=(this.distantPhase+Math.min(.43,this.distantPitch*controls2.sweep/this.rate))%1,distant=Math.sin(TAU5*this.distantPhase)*Math.sin(Math.PI*phrase/.38)*pulse2*.16}}left[i]=background+call*(1-this.pan)+distant*.6,right[i]=background+call*(1+this.pan)+distant}}},CountryRoad=class{constructor(random2,rate2){this.random=random2;this.rate=rate2;this.earth=new Brown(rate2),this.motorHz=random2.range(55,76)}random;rate;earth;air=new Pink;gravel=new Svf2;tires=[new Svf2,new Svf2];age=0;duration=3.8;gap=6;heading=1;motor=0;motorHz;render(left,right,n2,controls2){this.gravel.set(720*controls2.sweep,.8,this.rate);let near=Math.sin(Math.PI*Math.min(1,this.age/this.duration));this.tires[0].set((380+920*near)*controls2.sweep,.8,this.rate),this.tires[1].set((510+1020*near)*controls2.sweep,.75,this.rate);for(let i=0;i<n2;i++){this.age+=1/this.rate,this.age>=this.duration+this.gap&&(this.age=0,this.duration=this.random.range(3.2,6.2),this.gap=(12-10*controls2.density)*this.random.range(.45,1.4),this.heading=this.random.next()<.5?-1:1,this.motorHz=this.random.range(51,83));let position=Math.min(1,this.age/this.duration),proximity=Math.sin(Math.PI*position)**3,pan2=(position*2-1)*this.heading*.65,offset=2*position-1,doppler=1-.12*offset/Math.sqrt(offset*offset+.06);this.motor=(this.motor+this.motorHz*doppler/this.rate)%1;let wind2=this.air.process(this.random.noise()),dust=this.gravel.process(this.random.noise()),car=(this.earth.process(this.random.noise())*.62+(Math.sin(TAU5*this.motor)+.38*Math.sin(2*TAU5*this.motor))*.145+dust*(.15+controls2.wear*.42))*proximity,tread=proximity*(.19+controls2.wear*.23);left[i]=wind2*.12+(car+tread*this.tires[0].process(this.random.noise()))*(1-pan2),right[i]=wind2*.12+(car+tread*this.tires[1].process(this.random.noise()))*(1+pan2)}}};var TAU6=2*Math.PI,Room=class{constructor(rng,sr){this.rng=rng;this.sr=sr;this.brownA=new Brown(sr),this.brownB=new Brown(sr),this.hpA.set(35,sr),this.hpB.set(35,sr),this.hum.set(110,.9,sr),this.creak.set(2200,9,sr),this.sway=new Drift2(rng),this.next=rng.wait(1)*sr}rng;sr;pinkA=new Pink;pinkB=new Pink;brownA;brownB;lpA=new Lp1;lpB=new Lp1;lp2A=new Lp1;lp2B=new Lp1;hpA=new Hp1;hpB=new Hp1;hum=new Svf2;creak=new Svf2;next=0;sway;render(a,b,n2,c){let sr=this.sr,cutoff2=(500+2200*c.density)*c.sweep;this.lpA.set(cutoff2,sr),this.lpB.set(cutoff2,sr),this.lp2A.set(cutoff2*1.6,sr),this.lp2B.set(cutoff2*1.6,sr);let sway=.8+.4*this.sway.step(n2/sr,4),rumble=.25+.9*c.wear,tickRate=.15+1.5*c.density;for(let i=0;i<n2;i+=1){let wa=this.rng.noise(),wb=this.rng.noise(),ba=this.brownA.process(this.rng.noise()),bb=this.brownB.process(this.rng.noise()),hum=this.hum.process(ba+bb)*rumble,x=this.lp2A.process(this.lpA.process(this.pinkA.process(wa))),y=this.lp2B.process(this.lpB.process(this.pinkB.process(wb)));x=this.hpA.process(x*sway+.25*ba*rumble)+hum,y=this.hpB.process(y*sway+.25*bb*rumble)+hum;let impulse=0;(this.next-=1)<=0&&(this.next=this.rng.wait(tickRate)*sr,this.creak.set(this.rng.range(900,3200),this.rng.range(5,14),sr),impulse=this.rng.bi()*(.6+1.4*c.wear));let creak=this.creak.process(impulse)*1.5;a[i]=x+creak,b[i]=y+creak*.6}}},MAX_DROPS=48,Rain=class{constructor(rng,sr){this.rng=rng;this.sr=sr;this.bedHpA.set(350,sr),this.shower=new Drift2(rng),this.bedHpB.set(350,sr),this.tickA.set(4200,.8,sr),this.tickB.set(4200,.8,sr)}rng;sr;shower;eave=new Svf2;nextDrip=0;dripPan=.5;pinkA=new Pink;pinkB=new Pink;bedHpA=new Hp1;bedHpB=new Hp1;bedLpA=new Svf2;bedLpB=new Svf2;tickA=new Svf2;tickB=new Svf2;phase=new Float64Array(MAX_DROPS);freq=new Float64Array(MAX_DROPS);rise=new Float64Array(MAX_DROPS);amp=new Float64Array(MAX_DROPS);decay=new Float64Array(MAX_DROPS);panL=new Float64Array(MAX_DROPS);panR=new Float64Array(MAX_DROPS);live=0;next=0;drop(wear){let r=6e-4+.0026*this.rng.next()**(2.2-1.4*wear),pan2=this.rng.bi(),left=Math.sqrt(.5*(1-pan2)),right=Math.sqrt(.5*(1+pan2)),strength=.25+.75*this.rng.next()**2;if(this.rng.next()<.45+.3*wear){let hit2=strength*(r/.002)*1.5;this.impactL+=hit2*left,this.impactR+=hit2*right;return}if(this.live>=MAX_DROPS)return;let f0=Math.min(3.29/r,this.sr*.4),d=.043*f0+.0014*f0**1.5,k=this.live;this.live+=1,this.phase[k]=0,this.freq[k]=f0/this.sr,this.rise[k]=.9*d*f0/(this.sr*this.sr),this.decay[k]=Math.exp(-d/this.sr),this.amp[k]=strength*(r/.002)**1.2*.5,this.panL[k]=left,this.panR[k]=right}impactL=0;impactR=0;render(a,b,n2,c){let sr=this.sr,shower=this.shower.step(n2/sr,3.6),rate2=(12+520*c.density*c.density)*(.4+1.2*c.shape)*(.56+.88*shower),bedHz=(2600+2600*(1-c.distance))*c.sweep;this.bedLpA.set(bedHz,.6,sr),this.bedLpB.set(bedHz,.6,sr);let bed=(.12+.3*c.density+.15*c.wear)*(.75+.49*shower);for(let i=0;i<n2;i+=1){(this.next-=1)<=0&&(this.next+=this.rng.wait(rate2)*sr,this.drop(c.wear));let l=0,r=0;for(let k=0;k<this.live;k+=1){let v=Math.sin(TAU6*this.phase[k])*this.amp[k];if(l+=v*this.panL[k],r+=v*this.panR[k],this.phase[k]+=this.freq[k],this.phase[k]>=1&&(this.phase[k]-=1),this.freq[k]+=this.rise[k],this.amp[k]*=this.decay[k],this.amp[k]<2e-4){let last=this.live-1;this.phase[k]=this.phase[last],this.freq[k]=this.freq[last],this.rise[k]=this.rise[last],this.amp[k]=this.amp[last],this.decay[k]=this.decay[last],this.panL[k]=this.panL[last],this.panR[k]=this.panR[last],this.live=last,k-=1}}l+=this.tickA.process(this.impactL),r+=this.tickB.process(this.impactR);let drip=0;--this.nextDrip<=0&&(this.nextDrip=(.16+this.rng.wait(1.1+c.density*2.1))*sr,this.eave.set(this.rng.range(380,1100)*c.sweep,8.5,sr),this.dripPan=this.rng.range(.18,.82),drip=(.7+c.wear)*this.rng.range(.65,1.55));let nearby=this.eave.process(drip);l+=nearby*(1-this.dripPan),r+=nearby*this.dripPan,this.impactL=0,this.impactR=0;let na=this.bedLpA.process(this.bedHpA.process(this.pinkA.process(this.rng.noise()))),nb=this.bedLpB.process(this.bedHpB.process(this.pinkB.process(this.rng.noise())));a[i]=l+this.bedLpA.low*bed+na*.2*bed,b[i]=r+this.bedLpB.low*bed+nb*.2*bed}}},Wind=class{constructor(rng,sr){this.rng=rng;this.sr=sr;this.brownA=new Brown(sr),this.brownB=new Brown(sr),this.gust=new Drift2(rng,.4),this.flutter=new Drift2(rng),this.skew=new Drift2(rng),this.ratio=rng.range(1.33,1.62)}rng;sr;pinkA=new Pink;pinkB=new Pink;brownA;brownB;bodyA=new Svf2;bodyB=new Svf2;airA=new Svf2;airB=new Svf2;whistle1=new Svf2;whistle2=new Svf2;gust;flutter;skew;ratio;render(a,b,n2,c){let sr=this.sr,dt=n2/sr,depth=.35+.65*c.density,g0=this.gust.step(dt,4.5-2.5*c.density,depth),fl=this.flutter.step(dt,.35-.2*c.density)-.5,g=Math.min(1,Math.max(0,g0+fl*.25*c.density)),skew=(this.skew.step(dt,3)-.5)*.3,center=(220+950*g*g)*c.sweep,q3=.7+3.2*g;this.bodyA.set(center*(1+skew),q3,sr),this.bodyB.set(center*(1-skew),q3,sr),this.airA.set(center*2.7,1.2,sr),this.airB.set(center*2.9,1.2,sr);let whistle=(600+1300*g)*c.sweep;this.whistle1.set(whistle,28+30*c.wear,sr),this.whistle2.set(whistle*this.ratio,36+30*c.wear,sr);let level2=(.25+g)**2,sing2=c.wear*c.wear*Math.max(0,g-.35)*2.2,low=.35*(1-g);for(let i=0;i<n2;i+=1){let pa=this.pinkA.process(this.rng.noise()),pb=this.pinkB.process(this.rng.noise()),ba=this.brownA.process(this.rng.noise()),bb=this.brownB.process(this.rng.noise()),white=this.rng.noise(),w=(this.whistle1.process(white)+.7*this.whistle2.process(white))*sing2;a[i]=level2*(this.bodyA.process(pa+ba)*1.6+this.airA.process(pa)*.4)+low*ba*.3+w,b[i]=level2*(this.bodyB.process(pb+bb)*1.6+this.airB.process(pb)*.4)+low*bb*.3+w*.8}}},TURN_HZ=100/3/60,Vinyl=class{constructor(rng,sr){this.rng=rng;this.sr=sr;this.clickA.set(2600,1.1,sr),this.clickB.set(2900,1.1,sr),this.popA.set(1800,sr),this.popB.set(1800,sr),this.popA2.set(1800,sr),this.popB2.set(1800,sr),this.hissA.set(3200,.5,sr),this.hissB.set(3400,.5,sr),this.brown=new Brown(sr),this.rumble.set(28,sr),this.rumble2.set(28,sr),this.turn=rng.next(),this.scratchAt=rng.next()}rng;sr;clickA=new Svf2;clickB=new Svf2;popA=new Lp1;popB=new Lp1;popA2=new Lp1;popB2=new Lp1;hissA=new Svf2;hissB=new Svf2;pinkA=new Pink;pinkB=new Pink;brown;rumble=new Lp1;rumble2=new Lp1;nextClick=0;nextPop=0;turn;scratchAt;render(a,b,n2,c){let sr=this.sr,clickRate=25+1400*c.density*c.density,popRate=.08+2.5*c.wear*c.wear,scratch=Math.max(0,c.wear-.45)*2,hiss=.1+.15*c.wear,rumble=.25+.75*c.wear,step2=TURN_HZ/sr;for(let i=0;i<n2;i+=1){let ia=0,ib=0;if((this.nextClick-=1)<=0){this.nextClick+=this.rng.wait(clickRate)*sr;let size=(.1+.25*this.rng.next()**6)*(this.rng.next()<.5?-1:1),side=this.rng.next();side<.4?ia=size:side<.8?ib=size:(ia=size,ib=size*.8)}let pa=0,pb=0;if((this.nextPop-=1)<=0){this.nextPop+=this.rng.wait(popRate)*sr;let size=.4+.5*this.rng.next();pa=size,pb=size*this.rng.range(.5,1)}let before=this.turn;this.turn+=step2,this.turn>=1&&(this.turn-=1),scratch>0&&before<this.scratchAt&&this.turn>=this.scratchAt&&(pa+=.8*scratch,pb+=.8*scratch);let turnWobble=1+.4*Math.sin(TAU6*this.turn),r=this.rumble2.process(this.rumble.process(this.brown.process(this.rng.noise())))*rumble*turnWobble*.8;a[i]=this.clickA.process(ia)*1.4+this.popA2.process(this.popA.process(pa))*1.5+this.hissA.process(this.pinkA.process(this.rng.noise()))*hiss+r,b[i]=this.clickB.process(ib)*1.4+this.popB2.process(this.popB.process(pb))*1.5+this.hissB.process(this.pinkB.process(this.rng.noise()))*hiss+r}}},Tape=class{constructor(rng,sr){this.rng=rng;this.sr=sr;this.hpA.set(500,sr),this.hpB.set(500,sr),this.bump.set(rng.range(62,82),1.4,sr),this.brown=new Brown(sr),this.wow=rng.next(),this.flutter=rng.next(),this.wowHz=rng.range(.45,.9),this.flutterHz=rng.range(6,11),this.drift=new Drift2(rng)}rng;sr;pinkA=new Pink;pinkB=new Pink;hpA=new Hp1;hpB=new Hp1;lpA=new Svf2;lpB=new Svf2;bump=new Svf2;brown;wow;flutter;wowHz;flutterHz;drift;dropout=1;dropTarget=1;nextDrop=0;dropLeft=0;render(a,b,n2,c){let sr=this.sr,top=(6800-4200*c.wear)*c.sweep;this.lpA.set(top,.6,sr),this.lpB.set(top*1.03,.6,sr);let hiss=.35+.65*c.density,depth=.08+.35*c.wear,head=.25+.6*c.wear,dropRate=.03+1.2*c.wear*c.wear,drift=.85+.3*this.drift.step(n2/sr,2.5);for(let i=0;i<n2;i+=1){this.wow+=this.wowHz/sr,this.wow>=1&&(this.wow-=1),this.flutter+=this.flutterHz/sr,this.flutter>=1&&(this.flutter-=1);let mod=1+depth*(.6*Math.sin(TAU6*this.wow)+.4*Math.sin(TAU6*this.flutter));(this.nextDrop-=1)<=0&&(this.nextDrop+=this.rng.wait(dropRate)*sr,this.dropLeft=Math.round(this.rng.range(.03,.2)*sr),this.dropTarget=this.rng.range(.15,.6)),this.dropLeft>0?this.dropLeft-=1:this.dropTarget=1,this.dropout+=.004*(this.dropTarget-this.dropout);let gain=hiss*mod*drift*this.dropout,wa=this.rng.noise(),wb=this.rng.noise(),ha=this.hpA.process(this.pinkA.process(wa)*.7+wa*.3),hb=this.hpB.process(this.pinkB.process(wb)*.7+wb*.3);this.lpA.process(ha),this.lpB.process(hb);let bump=this.bump.process(this.brown.process(this.rng.noise()))*head*mod;a[i]=this.lpA.low*gain+bump,b[i]=this.lpB.low*gain+bump}}},Hum=class{constructor(rng,sr,mains){this.rng=rng;this.sr=sr;this.mains=mains;this.count=Math.max(1,Math.min(48,Math.floor(sr*.42/mains),Math.floor(4e3/mains))),this.p=new Float64Array(this.count+1),this.q=new Float64Array(this.count+1),this.odd=new Float64Array(this.count+1);for(let h=1;h<=this.count;h+=1){let theta=TAU6*rng.next();this.p[h]=Math.cos(theta),this.q[h]=Math.sin(theta),this.odd[h]=h%2===1?1:0}this.drift=new Drift2(rng),this.flicker=new Drift2(rng),this.buzzA.set(2400,.7,sr),this.buzzB.set(2600,.7,sr)}rng;sr;mains;count;p;q;odd;phase=0;drift;flicker;buzzA=new Svf2;buzzB=new Svf2;pinkA=new Pink;pinkB=new Pink;render(a,b,n2,c){let sr=this.sr,dt=n2/sr,step2=this.mains*(1+8e-4*(this.drift.step(dt,3)-.5))/sr,flicker=1+.25*c.density*(this.flicker.step(dt,.4)-.5),amps=new Float64Array(this.count+1),tilt=1.6-.8*c.wear;for(let h=1;h<=this.count;h+=1){let even=h%2===0?1:.25+1.2*c.wear;amps[h]=even/h**tilt*(h===1?.8:1)}let buzz=(.05+.5*c.wear)*(.4+c.density),noise2=.02+.05*c.density;for(let i=0;i<n2;i+=1){this.phase+=step2,this.phase>=1&&(this.phase-=1);let theta=TAU6*this.phase,c1=Math.cos(theta),s1=Math.sin(theta),cn=c1,sn=s1,sum=0;for(let h=1;h<=this.count;h+=1){sum+=amps[h]*(sn*this.p[h]+cn*this.q[h]);let nc=cn*c1-sn*s1;sn=sn*c1+cn*s1,cn=nc}let gate=Math.abs(s1)**12,na=this.pinkA.process(this.rng.noise()),nb=this.pinkB.process(this.rng.noise()),hum=sum*flicker*.6;a[i]=hum+this.buzzA.process(this.rng.noise())*gate*buzz+na*noise2,b[i]=hum+this.buzzB.process(this.rng.noise())*gate*buzz+nb*noise2}}},MAX_CARS=6,City=class{constructor(rng,sr){this.rng=rng;this.sr=sr;this.brownA=new Brown(sr),this.brownB=new Brown(sr),this.swell=new Drift2(rng);for(let k=0;k<MAX_CARS;k+=1)this.carBody.push(new Svf2),this.carTire.push(new Svf2);this.nextCar=rng.wait(.6)*sr,this.nextClank=rng.wait(.5)*sr}rng;sr;brownA;brownB;bedA=new Lp1;bedB=new Lp1;bed2A=new Lp1;bed2B=new Lp1;swell;pink=new Pink;clank=new Svf2;nextCar=0;nextClank=0;carAge=new Float64Array(MAX_CARS);carLength=new Float64Array(MAX_CARS);carHz=new Float64Array(MAX_CARS);carDir=new Float64Array(MAX_CARS);carAmp=new Float64Array(MAX_CARS);carBody=[];carTire=[];cars=0;render(a,b,n2,c){let sr=this.sr,dt=n2/sr,swell=.6+.8*this.swell.step(dt,6),bedHz=(180+260*c.density)*c.sweep;this.bedA.set(bedHz,sr),this.bedB.set(bedHz,sr),this.bed2A.set(bedHz*1.5,sr),this.bed2B.set(bedHz*1.5,sr);let carRate=.05+.7*c.density,clankRate=.05+2*c.wear*c.wear;for(this.nextCar-=n2;this.nextCar<=0;)if(this.nextCar+=this.rng.wait(carRate)*sr,this.cars<MAX_CARS){let k=this.cars;this.cars+=1,this.carAge[k]=0,this.carLength[k]=this.rng.range(2.5,7),this.carHz[k]=this.rng.range(260,800),this.carDir[k]=this.rng.next()<.5?-1:1,this.carAmp[k]=this.rng.range(.3,1)}let carL=new Float64Array(this.cars),carR=new Float64Array(this.cars);for(let k=0;k<this.cars;k+=1){let x=this.carAge[k]/this.carLength[k],level2=Math.sin(Math.PI*x)**3*this.carAmp[k],pan2=this.carDir[k]*(2*x-1);carL[k]=level2*Math.sqrt(.5*(1-pan2)),carR[k]=level2*Math.sqrt(.5*(1+pan2));let doppler=1+.06*Math.tanh(4*(.5-x));this.carBody[k].set(this.carHz[k]*doppler*c.sweep,.9,sr),this.carTire[k].set(2600*doppler,.8,sr),this.carAge[k]+=dt}for(let i=0;i<n2;i+=1){let ba=this.brownA.process(this.rng.noise()),bb=this.brownB.process(this.rng.noise()),l=this.bed2A.process(this.bedA.process(ba))*swell*.6,r=this.bed2B.process(this.bedB.process(bb))*swell*.6;if(this.cars>0){let p=this.pink.process(this.rng.noise());for(let k=0;k<this.cars;k+=1){let v=this.carBody[k].process(p+ba*.3)*2.4+this.carTire[k].process(p)*.4;l+=v*carL[k],r+=v*carR[k]}}let impulse=0;(this.nextClank-=1)<=0&&(this.nextClank+=this.rng.wait(clankRate)*sr,this.clank.set(this.rng.range(700,2600),this.rng.range(8,20),sr),impulse=this.rng.bi()*3);let clank=this.clank.process(impulse);a[i]=l+clank*.7,b[i]=r+clank*.5}for(let k=this.cars-1;k>=0;k-=1)if(this.carAge[k]>=this.carLength[k]){let last=this.cars-1;this.carAge[k]=this.carAge[last],this.carLength[k]=this.carLength[last],this.carHz[k]=this.carHz[last],this.carDir[k]=this.carDir[last],this.carAmp[k]=this.carAmp[last];let body2=this.carBody[k],tire=this.carTire[k];this.carBody[k]=this.carBody[last],this.carTire[k]=this.carTire[last],this.carBody[last]=body2,this.carTire[last]=tire,this.cars=last}}},MAX_GRAINS2=24,VOWELS3=[[730,1090],[530,1840],[270,2290],[570,840],[300,870],[660,1720],[490,1350]],Crowd=class{constructor(rng,sr){this.rng=rng;this.sr=sr;for(let t=0;t<12;t+=1)this.talkers.push({hz:rng.next()<.5?rng.range(95,140):rng.range(170,240),pan:rng.bi(),scale:rng.range(.9,1.15)});for(let k=0;k<MAX_GRAINS2;k+=1)this.f1.push(new Svf2),this.f2.push(new Svf2);this.swell=new Drift2(rng)}rng;sr;talkers=[];f1=[];f2=[];age=new Float64Array(MAX_GRAINS2);length=new Float64Array(MAX_GRAINS2);phase=new Float64Array(MAX_GRAINS2);hz=new Float64Array(MAX_GRAINS2);amp=new Float64Array(MAX_GRAINS2);left=new Float64Array(MAX_GRAINS2);right=new Float64Array(MAX_GRAINS2);va=new Int32Array(MAX_GRAINS2);vb=new Int32Array(MAX_GRAINS2);scale=new Float64Array(MAX_GRAINS2);grains=0;next=0;lpA=new Lp1;lpB=new Lp1;swell;spawn(wear){if(this.grains>=MAX_GRAINS2)return;let k=this.grains;this.grains+=1;let talker=this.talkers[Math.floor(this.rng.next()*this.talkers.length)];this.age[k]=0,this.length[k]=this.rng.range(.07,.22)*this.sr,this.phase[k]=this.rng.next(),this.hz[k]=talker.hz*(1+.25*wear*this.rng.next())*this.rng.range(.92,1.1),this.amp[k]=(.25+.75*this.rng.next()**(1.5-wear))*.5;let pan2=Math.max(-1,Math.min(1,talker.pan+.2*this.rng.bi()));this.left[k]=Math.sqrt(.5*(1-pan2)),this.right[k]=Math.sqrt(.5*(1+pan2)),this.va[k]=Math.floor(this.rng.next()*VOWELS3.length),this.vb[k]=Math.floor(this.rng.next()*VOWELS3.length),this.scale[k]=talker.scale}retire(k){let last=this.grains-1;this.age[k]=this.age[last],this.length[k]=this.length[last],this.phase[k]=this.phase[last],this.hz[k]=this.hz[last],this.amp[k]=this.amp[last],this.left[k]=this.left[last],this.right[k]=this.right[last],this.va[k]=this.va[last],this.vb[k]=this.vb[last],this.scale[k]=this.scale[last];let f1=this.f1[k],f2=this.f2[k];this.f1[k]=this.f1[last],this.f2[k]=this.f2[last],this.f1[last]=f1,this.f2[last]=f2,this.grains=last}render(a,b,n2,c){let sr=this.sr,swell=.7+.6*this.swell.step(n2/sr,5),rate2=(3+70*c.density)*swell,top=3800*c.sweep;this.lpA.set(top,sr),this.lpB.set(top,sr);for(let k=0;k<this.grains;k+=1){let x=this.age[k]/this.length[k],A=VOWELS3[this.va[k]],B=VOWELS3[this.vb[k]],s=this.scale[k];this.f1[k].set((A[0]+(B[0]-A[0])*x)*s,5,sr),this.f2[k].set((A[1]+(B[1]-A[1])*x)*s,7,sr)}for(let i=0;i<n2;i+=1){(this.next-=1)<=0&&(this.next+=this.rng.wait(rate2)*sr,this.spawn(c.wear));let l=0,r=0;for(let k=0;k<this.grains;k+=1){let dt=this.hz[k]/sr,t=this.phase[k]+dt;t>=1&&(t-=1),this.phase[k]=t;let src=(2*t-1-polyBlep2(t,dt))*.8+this.rng.noise()*.25,x=this.age[k]/this.length[k],window=.5-.5*Math.cos(TAU6*x),v=(this.f1[k].process(src)+.6*this.f2[k].process(src))*window*this.amp[k];l+=v*this.left[k],r+=v*this.right[k],this.age[k]+=1,this.age[k]>=this.length[k]&&(this.retire(k),k-=1)}a[i]=this.lpA.process(l),b[i]=this.lpB.process(r)}}},STUTTER_SECONDS=.5,Data=class{constructor(rng,sr){this.rng=rng;this.sr=sr;let size=Math.ceil(STUTTER_SECONDS*sr);this.ringA=new Float64Array(size),this.ringB=new Float64Array(size),this.nextEvent=rng.wait(2)*sr,this.nextStutter=rng.wait(.5)*sr,this.fade=Math.max(1,Math.round(.002*sr))}rng;sr;hiss=new Pink;lpA=new Lp1;lpB=new Lp1;lp2A=new Lp1;lp2B=new Lp1;nextEvent=0;event;eventLeft=0;eventLength=1;phase=0;bitLeft=0;bit=0;baud=300;mark=1270;space=1070;hold=0;holdLeft=0;sweepFrom=300;sweepTo=8e3;tone=440;pan=0;clicksLeft=0;nextClick=0;crushBits=3;ringA;ringB;writeAt=0;sliceStart=0;sliceLength=0;sliceAt=0;repeats=0;nextStutter=0;fade;start(c){let roll=this.rng.next();this.event=roll<.3?"modem":roll<.55?"sweep":roll<.8?"clicks":"crush";let seconds2=this.event==="modem"?this.rng.range(.4,1.4):this.event==="sweep"?this.rng.range(.25,1):this.event==="clicks"?this.rng.range(.05,.4):this.rng.range(.05,.3);if(this.eventLength=Math.max(1,Math.round(seconds2*this.sr)),this.eventLeft=this.eventLength,this.pan=.6*this.rng.bi(),this.event==="modem"){let answer=this.rng.next()<.5;this.mark=answer?2225:1270,this.space=answer?2025:1070,this.baud=this.rng.next()<.6?300:1200,this.bitLeft=0}else if(this.event==="sweep"){let up=this.rng.next()<.5+.4*(c.shape-.5),lo=this.rng.range(150,600),hi=this.rng.range(3e3,9e3);this.sweepFrom=up?lo:hi,this.sweepTo=up?hi:lo,this.tone=this.rng.range(180,900)}else this.event==="clicks"?(this.clicksLeft=1+Math.floor(this.rng.next()*6),this.nextClick=0):(this.crushBits=2+Math.floor(this.rng.next()*3),this.sweepFrom=this.rng.range(800,5e3))}render(a,b,n2,c){let sr=this.sr,rate2=(.8+9*c.density)*(.4+1.2*c.shape),stutterRate=.2+2.5*c.density,flipRate=(.5+60*c.wear*c.wear)/sr,steps2=2**(Math.round(16-10*c.wear*c.wear)-1),top=Math.min(5200,4200*c.sweep);this.lpA.set(top,sr),this.lpB.set(top,sr),this.lp2A.set(top*1.2,sr),this.lp2B.set(top*1.2,sr);for(let i=0;i<n2;i+=1){this.event===void 0&&(this.nextEvent-=1)<=0&&(this.nextEvent=this.rng.wait(rate2)*sr,this.start(c));let v=this.hiss.process(this.rng.noise())*.03,left=1,right=1;if(this.event!==void 0){let x=1-this.eventLeft/this.eventLength,edge=Math.min(1,this.eventLeft/(.003*sr),x*this.eventLength/(.003*sr)),e=0;if(this.event==="modem")this.bitLeft<=0&&(this.bit=this.rng.next()<.5?1:0,this.bitLeft=sr/this.baud),this.bitLeft-=1,this.phase+=(this.bit?this.mark:this.space)/sr,this.phase>=1&&(this.phase-=1),e=Math.sin(TAU6*this.phase)*.35*edge;else if(this.event==="sweep"){let hz3=this.sweepFrom*(this.sweepTo/this.sweepFrom)**x;this.phase+=this.tone/sr,this.phase>=1&&(this.phase-=1),(this.holdLeft-=1)<=0&&(this.holdLeft+=sr/hz3,this.hold=this.phase<.5?.3:-.3),e=this.hold*edge}else if(this.event==="clicks")this.clicksLeft>0&&(this.nextClick-=1)<=0&&(this.nextClick=this.rng.range(.004,.05)*sr,this.clicksLeft-=1,e=this.rng.next()<.5?-.9:.9);else{if((this.holdLeft-=1)<=0){this.holdLeft+=sr/this.sweepFrom;let q3=2**(this.crushBits-1);this.hold=Math.round(this.rng.bi()*q3)/q3}e=this.hold*.25*edge}left=Math.sqrt(1-this.pan),right=Math.sqrt(1+this.pan),v+=e,this.eventLeft-=1,this.eventLeft<=0&&(this.event=void 0)}let l=this.lp2A.process(this.lpA.process(v*left)),r=this.lp2B.process(this.lpB.process(v*right));if(l=Math.round(l*steps2)/steps2,r=Math.round(r*steps2)/steps2,this.rng.next()<flipRate){let bit=2**(5+Math.floor(this.rng.next()*6));l=(Math.round(l*32768)^bit)/32768}let size=this.ringA.length;if(this.ringA[this.writeAt]=l,this.ringB[this.writeAt]=r,this.repeats===0&&(this.nextStutter-=1)<=0&&(this.nextStutter=this.rng.wait(stutterRate)*sr,this.sliceLength=Math.round(this.rng.range(.015,.12)*sr),this.sliceStart=(this.writeAt-this.sliceLength+size)%size,this.sliceAt=0,this.repeats=2+Math.floor(this.rng.next()*6)),this.repeats>0){let at3=(this.sliceStart+this.sliceAt)%size,f=this.fade,edge=Math.min(1,this.sliceAt/f,(this.sliceLength-this.sliceAt)/f);l=this.ringA[at3]*edge,r=this.ringB[at3]*edge,this.sliceAt+=1,this.sliceAt>=this.sliceLength&&(this.sliceAt=0,this.repeats-=1)}this.writeAt=(this.writeAt+1)%size,a[i]=l,b[i]=r}}},Air=class{constructor(rng,sr){this.rng=rng;this.sr=sr;this.shimmer=[new Drift2(rng),new Drift2(rng),new Drift2(rng)],this.centers=[rng.range(2200,2700),rng.range(3300,3900),rng.range(4700,5300)],this.nextGlint=rng.wait(1)*sr}rng;sr;bandsA=[new Svf2,new Svf2,new Svf2];bandsB=[new Svf2,new Svf2,new Svf2];shimmer;hpA=new Svf2;hpB=new Svf2;hpA2=new Svf2;hpB2=new Svf2;glint=new Svf2;nextGlint=0;centers;render(a,b,n2,c){let sr=this.sr,dt=n2/sr,period=1.6-1.2*c.density,levels=this.shimmer.map((d,k)=>{let v=d.step(dt,period*(1+.3*k));return(.35+1.3*v*v)*[1,.6,.08][k]});for(let k=0;k<3;k+=1){let hz3=this.centers[k]*c.sweep;this.bandsA[k].set(hz3,2.5,sr),this.bandsB[k].set(hz3*1.04,2.5,sr)}let hp=1600*Math.min(2,c.sweep);this.hpA.set(hp,.7,sr),this.hpB.set(hp,.7,sr),this.hpA2.set(hp,.7,sr),this.hpB2.set(hp,.7,sr);let hush=.12+.1*c.wear,glintRate=.3+6*c.density;for(let i=0;i<n2;i+=1){let wa=this.rng.noise(),wb=this.rng.noise(),l=0,r=0;this.hpA.process(wa),this.hpB.process(wb),this.hpA2.process(this.hpA.high),this.hpB2.process(this.hpB.high);let ha=this.hpA2.high,hb=this.hpB2.high;for(let k=0;k<3;k+=1)l+=this.bandsA[k].process(ha)*levels[k],r+=this.bandsB[k].process(hb)*levels[k];let impulse=0;(this.nextGlint-=1)<=0&&(this.nextGlint+=this.rng.wait(glintRate)*sr,this.glint.set(this.rng.range(2800,4800)*c.sweep,40,sr),impulse=this.rng.bi()*2);let glint=this.glint.process(impulse);a[i]=l+ha*hush*.3+glint,b[i]=r+hb*hush*.3+glint*.7}}},SnareBrush=class{constructor(rng,sr,heldSeconds,velocity){this.rng=rng;this.sr=sr;this.heldSeconds=heldSeconds;this.velocity=velocity;this.headHz=rng.range(177,191),this.headDecay=Math.exp(-1/(sr*.038)),this.rimDecay=Math.exp(-1/(sr*.022)),this.bristleDecay=Math.exp(-1/(sr*.009))}rng;sr;heldSeconds;velocity;skin=new Svf2;wires=new Svf2;wireDamping=new Svf2;headHz;headDecay;rimDecay;bristleDecay;age=0;length=0;direction=1;nextBristles=0;bristles=0;head=0;rim=0;angle=0;render(a,b,n2,c){let sr=this.sr;this.skin.set(440*c.sweep,1.1,sr),this.wires.set((1250+800*c.wear)*c.sweep,.85,sr),this.wireDamping.set((2300+1100*c.wear)*c.sweep,.62,sr);let dab=Math.max(0,1-this.heldSeconds/.38),headAngle=TAU6*this.headHz*Math.sqrt(c.sweep)/sr;for(let i=0;i<n2;i++){if(this.age>=this.length&&i<c.heldSamples){let sweepSeconds=(.77-.39*c.density)*this.rng.range(.86,1.14);this.length=Math.max(1,Math.round(Math.min(this.heldSeconds,sweepSeconds)*sr)),this.age=0,this.angle=0,this.direction*=-1;let touch=this.rng.range(.85,1.08)*(.12+.88*this.velocity);this.head=touch*(.065+.4*dab),this.rim=touch*(.035+.15*dab)}let phase=Math.min(1,this.age/this.length),arc=4*phase*(1-phase),pressure=i<c.heldSamples?.19+.81*arc:0;if(--this.nextBristles<=0){let speed=(50+105*c.density)*(.5+arc);this.nextBristles=this.rng.range(.55,1.45)*sr/speed,this.bristles=this.rng.range(.22,.62)*pressure}this.bristles*=this.bristleDecay;let noise2=this.rng.noise(),friction=noise2*(this.bristles+.48*pressure),skin=this.skin.process(friction)*.8,headWave=Math.sin(this.angle),rattle=this.head*(.5+.8*Math.abs(headWave)),wire=this.wires.process(friction+noise2*rattle);this.wireDamping.process(wire);let sweep=this.wireDamping.low*(.62+.28*c.wear),tap=this.head*headWave+this.rim*Math.sin(1.68*this.angle);this.angle+=headAngle,this.age++,this.head*=this.headDecay,this.rim*=this.rimDecay;let pan2=this.direction*(phase-.5)*.42;a[i]=tap+skin+sweep*(1-pan2),b[i]=tap+skin+sweep*(1+pan2)}}},Paper=class{constructor(rng,sr){this.rng=rng;this.sr=sr;this.grainDecay=Math.exp(-1/(sr*.0012))}rng;sr;surface=new Svf2;body=new Svf2;nextStroke=0;nextGrain=0;age=0;duration=1;pan=0;grain=0;grainDecay;render(a,b,n2,c){this.surface.set(3100*(.7+c.wear)*c.sweep,.85,this.sr),this.body.set(840*c.sweep,3.8,this.sr);for(let i=0;i<n2;i++){--this.nextStroke<=0&&i<c.heldSamples&&(this.duration=this.rng.range(.12,.38)*this.sr,this.nextStroke=this.duration+this.rng.wait(1.6+7*c.density)*this.sr,this.age=0,this.nextGrain=0,this.pan=this.rng.bi()*.48);let phase=Math.min(1,this.age++/this.duration),pressure=Math.sin(Math.PI*phase),buckle=0;if(phase<1&&--this.nextGrain<=0){let rate2=28*(.25+pressure*(.55+c.density));this.nextGrain=Math.max(1,this.rng.wait(rate2)*this.sr),this.grain+=this.rng.range(.18,.75)*pressure,buckle=this.rng.bi()*pressure*2.4}this.grain*=this.grainDecay;let noise2=this.rng.noise(),scrape=this.surface.process(noise2*(this.grain+pressure*.07)),body2=this.body.process(buckle+noise2*pressure*.11),movement2=this.pan+(phase-.5)*.22;a[i]=body2+scrape*(1-movement2),b[i]=body2+scrape*(1+movement2)}}},Porcelain=class{constructor(rng,sr){this.rng=rng;this.sr=sr;this.fundamental=rng.range(510,870),this.loss=[.29,.34,.16,.094,.048].map(seconds2=>Math.exp(-1/(sr*seconds2)))}rng;sr;modes=[1,1.006,2.51,3.87,5.43];weights=[.31,.21,.18,.09,.045];loss;y1=new Float64Array(5);y2=new Float64Array(5);coeff=new Float64Array(5);excitation=new Float64Array(5);fundamental;next=0;rebound=-1;pan=0;render(a,b,n2,c){for(let k=0;k<this.modes.length;k++){let hz3=this.fundamental*this.modes[k]*c.sweep,angle=TAU6*Math.min(.45,hz3/this.sr);this.coeff[k]=2*this.loss[k]*Math.cos(angle);let fade=Math.min(1,Math.max(0,(.48-hz3/this.sr)/.08));this.excitation[k]=Math.sin(angle)*this.weights[k]*fade*(k<2?1:.4+c.wear)}for(let i=0;i<n2;i++){let impulse=0;--this.next<=0&&i<c.heldSamples?(impulse=this.rng.range(.55,1),this.next=(.25+this.rng.wait(.7+3*c.density))*this.sr,this.rebound=Math.floor(this.rng.range(.009,.023)*this.sr),this.pan=this.rng.bi()*.42):--this.rebound===0&&(impulse=.15+.16*c.wear);let sum=0;for(let k=0;k<this.modes.length;k++){let loss=this.loss[k],y=this.coeff[k]*this.y1[k]-loss*loss*this.y2[k]+impulse*this.excitation[k];this.y2[k]=this.y1[k],this.y1[k]=y,sum+=y}a[i]=sum*(1-this.pan),b[i]=sum*(1+this.pan)-this.y1[1]*.16}}};function makeSource(type,rng,sampleRate,mains,heldSeconds,velocity){switch(type){case"brush":return new SnareBrush(rng,sampleRate,heldSeconds,velocity);case"paper":return new Paper(rng,sampleRate);case"porcelain":return new Porcelain(rng,sampleRate);case"room":return new Room(rng,sampleRate);case"rain":return new Rain(rng,sampleRate);case"wind":return new Wind(rng,sampleRate);case"vinyl":return new Vinyl(rng,sampleRate);case"tape":return new Tape(rng,sampleRate);case"hum":return new Hum(rng,sampleRate,mains);case"city":return new City(rng,sampleRate);case"crowd":return new Crowd(rng,sampleRate);case"data":return new Data(rng,sampleRate);case"air":return new Air(rng,sampleRate);case"ocean":case"stream":case"waterfall":return new Water(type,rng,sampleRate);case"crickets":case"birds":return new FieldCalls(type,rng,sampleRate);case"country-road":return new CountryRoad(rng,sampleRate)}}var TEXTURE_BLOCK=128,STEAL_FADE2=.08,TEXTURE_TRIM=Object.freeze({room:.471,rain:.882,wind:1.079,vinyl:3.146,tape:.658,hum:.31,city:1.145,crowd:1.564,data:.33,air:.374,ocean:.479,stream:.375,waterfall:.312,crickets:.672,birds:.401,"country-road":1.322,brush:.839,paper:3.37,porcelain:.731}),ROOMY=new Set(["room","city","crowd"]),ROOM_DELAYS=[.0071,.0089,.0107,.0127,.0149,.0167,.0193,.0223],STREET_DELAYS=[.0197,.0241,.0293,.0337,.0389,.0431,.0503,.0571];function fdnShape(type,distance){let delays=(type==="city"?STREET_DELAYS:ROOM_DELAYS).map(d=>d*(.7+.8*distance)),t60=type==="room"?.3+1.5*distance:type==="city"?.5+1.9*distance:type==="crowd"?.4+1.6*distance:.3+2*distance,damping2=9e3*2**(-2.2*distance);return{delays,t60,damping:damping2}}function wetOf(type,distance){return ROOMY.has(type)?.35+.6*distance:.9*distance*distance}function motionShape(motion,p){switch(motion){case"steady":return .5;case"rise":return p*p;case"fall":return(1-p)*(1-p);case"swell":{let s=Math.sin(Math.PI*p);return s*s}}}function lanesOf2(track2){let all=track2.fxAutomation,lanes=new Map;for(let{param:param2}of TEXTURE_LANE_PARAMS){let points=all?.[`texture-${param2}`];points&&points.length>0&&lanes.set(param2,points)}return lanes}function span3(note2,context){if(context.warp){let from=context.warp.sample(note2.startTick),to=context.warp.sample(note2.startTick+note2.durationTicks);return{start:Math.floor(from),length:Math.max(1,Math.floor(to-from))}}let perTick=60*context.sampleRate/(context.tempoBpm*context.ticksPerBeat);return{start:Math.floor(note2.startTick*perTick),length:Math.max(1,Math.floor(note2.durationTicks*perTick))}}var clamp01=x=>x<0?0:x>1?1:x,Voice=class{constructor(settings,plan2,velocity,sr,seed,withFdn){this.settings=settings;this.plan=plan2;this.sr=sr;let rng=new Rng(seed,sr);this.source=makeSource(settings.type,rng,sr,settings.mains,plan2.length/sr,velocity);let shape=fdnShape(settings.type,settings.distance);this.fdn=withFdn?new Fdn(sr,shape.delays,shape.t60,shape.damping,new Rng(`${seed}:fdn`)):void 0,this.attack=Math.max(1,Math.round(settings.attack*sr)),this.release=Math.max(1,Math.round(settings.release*sr)),this.level=velocity*TEXTURE_TRIM[settings.type]}settings;plan;sr;source;fdn;toneA=new Svf2;toneB=new Svf2;a=new Float64Array(TEXTURE_BLOCK);b=new Float64Array(TEXTURE_BLOCK);wet=new Float64Array(2);controls={heldSamples:0,density:.5,wear:.3,distance:.3,sweep:1,shape:.5};attack;release;level;last=-1;get silentAt(){return this.plan.length+this.release}render(left,right,offset,at3,n2,values,gain){let s=this.settings,c=this.controls;c.heldSamples=Math.max(0,Math.min(n2,this.plan.length-at3));let p=clamp01(at3/this.plan.length),shape=motionShape(s.motion,p),moving=s.motion!=="steady";c.density=clamp01(values.density??s.density),c.wear=clamp01(values.wear??s.wear),c.distance=clamp01(values.distance??s.distance),c.shape=shape,c.sweep=moving?2**(3*(shape-.6)):1;let motionLevel=moving?.15+.85*shape:1,width=.85*clamp01(values.width??s.width),widthNorm=Math.sqrt(2/(1+width*width)),level2=this.level*gain*motionLevel*Math.max(0,values.gain??s.gain),from=this.last<0?level2:this.last;this.last=level2;let ramp=(level2-from)/n2,wetSend=wetOf(s.type,c.distance),dryLevel=1-.55*wetSend,tone=Math.min(this.sr*.45,16e3*2**(-3.2*c.distance)*Math.min(1.5,c.sweep));this.toneA.set(tone,.6,this.sr),this.toneB.set(tone,.6,this.sr);let sounding=at3<this.silentAt;sounding&&this.source.render(this.a,this.b,n2,c);let fdn=this.fdn,out=this.wet,length=this.plan.length;for(let j=0;j<n2;j+=1){let t=at3+j,env=0;if(sounding&&(env=t<this.attack?.5-.5*Math.cos(Math.PI*t/this.attack):1,t>=length)){let r2=(t-length)/this.release;env*=r2>=1?0:.5+.5*Math.cos(Math.PI*r2)}this.toneA.process(env>0?this.a[j]*env:0),this.toneB.process(env>0?this.b[j]*env:0);let x=this.toneA.low,y=this.toneB.low,l=x*dryLevel,r=y*dryLevel;fdn&&(fdn.process((x+y)*.5*wetSend,out),l+=out[0]*.5,r+=out[1]*.5);let mid=.5*(l+r),side=.5*(l-r)*width,index=offset+j;if(index<0||index>=left.length)continue;let g=(from+ramp*(j+1))*widthNorm;left[index]+=(mid+side)*g,right[index]+=(mid-side)*g}}};function knee2(x){let a=Math.abs(x);return a<=.6?x:Math.sign(x)*(.6+.3*Math.tanh((a-.6)/.3))}function renderTextureTrack(left,right,notes,track2,context){let{sampleRate:sr,samples}=context,tickAt4=index=>context.warp?context.warp.tick(index):index/context.samplesPerTick,base=textureSettings(track2.texture),lanes=lanesOf2(track2),volumeLane=track2.volumeAutomation??[],volume=Math.max(0,Math.min(1,track2.volume??1)),seedTick=context.seedTick??0,distanceLane=lanes.has("distance"),withFdn=distanceLane||wetOf(base.type,base.distance)>.005,ring=Math.round((withFdn?textureTailSeconds(track2.texture,distanceLane)-base.release:.05)*sr),planned=notes.map(note2=>{let{start,length}=span3(note2,context),release=Math.max(1,Math.round(base.release*sr));return{note:note2,start,length,end:start+length+release+ring,steal:1/0}}).filter(entry=>entry.start<samples&&entry.end>0).sort((a,b)=>a.start-b.start||a.note.pitch-b.note.pitch||(a.note.id<b.note.id?-1:a.note.id>b.note.id?1:0)),fade=Math.max(1,Math.round(STEAL_FADE2*sr)),sounding=[];for(let i=0;i<planned.length;i+=1){let{start}=planned[i];for(let k=sounding.length-1;k>=0;k-=1)planned[sounding[k]].end<=start&&sounding.splice(k,1);for(;sounding.length>=MAX_TEXTURE_VOICES;){let oldest=planned[sounding.shift()];oldest.steal=start,oldest.end=Math.min(oldest.end,start+fade)}sounding.push(i)}let values={};for(let plan2 of planned){let settings=base,voice=new Voice(settings,plan2,plan2.note.velocity,sr,`${settings.seed}:${plan2.note.id}:${plan2.note.startTick+seedTick}:texture`,withFdn),stop=Math.min(samples,plan2.end),at3=plan2.start;for(;at3<stop;){let n2=TEXTURE_BLOCK,tick=tickAt4(Math.max(0,at3));for(let key of Object.keys(values))delete values[key];for(let[param2,points]of lanes)values[param2]=interpolateAutomation(points,tick,settings[param2]);let gain=volume*(volumeLane.length>0?interpolateAutomation(volumeLane,tick,1):1);if(at3+n2>plan2.steal){let k=(at3+n2-plan2.steal)/fade;gain*=k>=1?0:.5+.5*Math.cos(Math.PI*k)}voice.render(left,right,at3,at3-plan2.start,n2,values,gain),at3+=n2}}let dcL=new Hp1,dcR=new Hp1;dcL.set(12,sr),dcR.set(12,sr);for(let i=0;i<samples;i+=1)left[i]=knee2(dcL.process(left[i])),right[i]=knee2(dcR.process(right[i]))}var TEXTURE_ENGINE=Object.freeze({id:"texture",field:"texture",render(dry,dryR,notes,track2,context){let right=dryR??new Float64Array(dry.length);if(renderTextureTrack(dry,right,notes,track2,context),!dryR)for(let i=0;i<dry.length;i+=1)dry[i]=.5*(dry[i]+right[i])},tailSeconds:track2=>textureTailSeconds(track2.texture,lanesOf2(track2).has("distance")),stereo:()=>!0,assetDigests:()=>[`texture:${TEXTURE_ENGINE_VERSION}`]});var RING_OUT_FADE_SECONDS=.25,engines=new Map;function registerEngine(engine2){if(engines.has(engine2.id))throw new Error(`instrument engine "${engine2.id}" is already registered`);engines.set(engine2.id,engine2)}function engineFor2(track2){if(!track2||engines.size===0)return;let engine2=engines.get(track2.instrument);if(!engine2)return;let settings=track2[engine2.field];return typeof settings=="object"&&settings!==null&&!Array.isArray(settings)?engine2:void 0}function engineTailSeconds(track2,lowestPitch,score){let engine2=engineFor2(track2);return engine2?Math.max(0,engine2.tailSeconds(track2,lowestPitch,score)):0}registerEngine(STRING_ENGINE);registerEngine(GRANULAR_ENGINE);for(let engine2 of KEYS_ENGINES)registerEngine(engine2);registerEngine(MODAL_ENGINE);registerEngine(WIND_ENGINE);registerEngine(SING_ENGINE);registerEngine(VOCODER_ENGINE);registerEngine(TEXTURE_ENGINE);var ENGINE_LANE_PREFIX=Object.freeze({"engine.synth":"synth","engine.modal":"modal","engine.string":"string","engine.wind":"wind","engine.sing":"sing","engine.granular":"grain","engine.keys":"keys","engine.texture":"texture"}),ENGINE_FIELD=Object.freeze({"engine.synth":"synth","engine.modal":"modal","engine.string":"string","engine.wind":"wind","engine.sing":"sing","engine.granular":"granular","engine.keys":"keys","engine.texture":"texture"}),LANES=new Set(FX_LANES.map(({lane})=>lane));function isPatchTrack(track2){return track2?.instrument===PATCH_INSTRUMENT&&track2.patch!==void 0}function trackPatch(track2,library){return isPatchTrack(track2)?resolvePatch(track2.patch,library):void 0}function patchDigests(track2,library){if(!track2)return[];let out=[],own=trackPatch(track2,library);own&&out.push(`patch:${patchDigest(own,library)}`);for(let fx of track2.fxPatch??[])out.push(`fxpatch:${patchDigest(fx,library)}`);return out}function trackProgram(track2,library){let patch=trackPatch(track2,library);return patch?compilePatch(patch,library):void 0}function patchTailSeconds(track2,library){let program=trackProgram(track2,library);if(!program)return 0;let device=program.buffers.some(node2=>node2.type==="device.synth")?DEVICE_TAIL_SECONDS:0;return program.voice.ids.length===0?device:Math.max(device,program.maxRelease+.1)}function macroValues(program,track2,overrides,context,blocks){return program.macros.map(macro2=>{let fallback=overrides?.[macro2.id]??macro2.default,lane=track2.fxAutomation?.[patchLane(macro2.id)];if(!lane||lane.length===0)return fallback;let out=new Float64Array(blocks);for(let b=0;b<blocks;b+=1){let tick=tickAt3(context,b*32),position=interpolateAutomation(lane,tick,Number.NaN);out[b]=position===position?macroAt(macro2,position):fallback}return out})}function tickAt3(context,sample){let origin=context.seedTick??0;return context.warp?context.warp.tick(sample):origin+sample/context.samplesPerTick}function tempoBlocks(context,blocks){if(!context.warp)return context.tempoBpm;let out=new Float64Array(blocks);for(let b=0;b<blocks;b+=1)out[b]=tempoAtSample(context,b*32);return out}function runOptions(program,track2,overrides,context,seed){let frames=context.samples,blocks=Math.ceil(frames/32);return{frames,sampleRate:context.sampleRate,macros:macroValues(program,track2,overrides,context,blocks),tempo:tempoBlocks(context,blocks),beat0:(context.seedTick??0)/context.ticksPerBeat,beatsPerBar:context.beatsPerBar,seed,...context.side?{side:context.side}:{}}}function onsetLane(signal,base,onsets2){let points=[];for(let{tick,sample}of onsets2){let at3=Math.min(signal.length-1,Math.max(0,sample)),value=base+signal[at3],last=points[points.length-1];last&&last.tick===tick?points[points.length-1]={tick,value}:points.push({tick,value})}return points}function blockLane(signal,base,context){let points=[],tick=-1/0;for(let i=0;i<signal.length;i+=32){let at3=Math.round(tickAt3(context,i));at3<=tick||(tick=at3,points.push({tick,value:base+signal[i]}))}return points}function numberParam(node2,name){let value=node2.params[name];return typeof value=="number"?value:node2.spec.inputs.find(p=>p.name===name)?.spec?.default??0}function controlSignal(io,name,own){let cable=io.inputs[name],knob=io.bases?.[name];if(!cable&&!knob&&!(own&&typeof io.node.params[name]=="number"))return;let base=numberParam(io.node,name),out=new Float64Array(io.frames);for(let i=0;i<io.frames;i+=1)out[i]=(knob?knob[Math.min(knob.length-1,Math.floor(i/32))]:base)+(cable?cable[i]:0);return out}function wiredLanes(io,prefix,own,lane){let lanes={};for(let port2 of io.node.spec.inputs){if(port2.kind!=="control")continue;let name=`${prefix}-${port2.name}`;if(!LANES.has(name))continue;let signal=controlSignal(io,port2.name,own);signal&&(lanes[name]=lane(signal,0))}return lanes}function bufferHandler(track2,played,context,hooks,notes=[]){return io=>{let{node:node2,outputs}=io;if(node2.type==="device.fx"||node2.type==="device.synth"){runDeviceNode(io,context.devices,notes);return}if(node2.type!=="device.notes"){if(node2.type.startsWith("engine.")){if(!hooks.voice)throw new Error(`node ${node2.id}: no engine renderer`);let voiceTrack=engineTrack(track2,node2),prefix=ENGINE_LANE_PREFIX[node2.type];if(prefix&&played){let onsets2=played.map(note2=>({tick:note2.startTick,sample:Math.floor(context.warp?context.warp.sample(note2.startTick):(note2.startTick-(context.seedTick??0))*context.samplesPerTick)})),lanes=wiredLanes(io,prefix,!0,(signal,base)=>onsetLane(signal,base,onsets2));if(Object.keys(lanes).length>0){let field=ENGINE_FIELD[node2.type];voiceTrack={...voiceTrack,...field&&voiceTrack[field]===void 0?{[field]:{}}:{},fxAutomation:{...voiceTrack.fxAutomation,...lanes}}}}let left=outputs.out,right=outputs.right??new Float64Array(io.frames);hooks.voice(left,right,voiceTrack)||right.set(left);return}if(node2.type.startsWith("fx.")){if(!hooks.stage)throw new Error(`node ${node2.id}: no effect stage`);let stage=node2.type.slice(3),values={};for(let port2 of node2.spec.inputs)port2.kind==="control"&&(values[port2.name]=numberParam(node2,port2.name));for(let[name,value]of Object.entries(node2.params))typeof value!="number"&&(values[name]=value);let lanes=wiredLanes(io,stage,!1,(signal,base)=>blockLane(signal,base,context)),stageTrack=stageTrackOf(track2,stage,values,lanes),stereoStage=outputs.left!==void 0,left=stereoStage?outputs.left:outputs.out,inLeft=stereoStage?io.inputs.left:io.inputs.in;if(inLeft&&left.set(inLeft),stereoStage){let right=outputs.right,inRight=io.inputs.right??inLeft;inRight&&right.set(inRight),hooks.stage(stage,left,right,stageTrack)}else hooks.stage(stage,left,void 0,stageTrack);return}throw new Error(`node ${node2.id}: unknown buffer node ${node2.type}`)}}}function stageTrackOf(track2,stage,values,lanes){let{fx:_fx,filter:_filter,delay:_delay,reverb:_reverb,filterAutomation:_fa,resonanceAutomation:_ra,delayFeedbackAutomation:_dfa,delayMixAutomation:_dma,fxAutomation:_fxa,fxPatch:_fxPatch,...rest}=track2,base={...rest,...Object.keys(lanes).length>0?{fxAutomation:lanes}:{}};return stage==="filter"||stage==="delay"||stage==="reverb"?{...base,[stage]:values}:{...base,fx:{[stage]:values}}}function renderPatchVoice(dry,dryR,played,spans,track2,context,hooks){if(!isPatchTrack(track2))return!1;let patch=resolvePatch(track2.patch,context.library);if(!patch)return!1;let program=compilePatch(patch,context.library),given=played.map((note2,i)=>({seed:`${note2.id}:${note2.startTick}`,start:spans[i].start,end:spans[i].start+spans[i].length,pitch:spans[i].hz,note:note2.pitch,velocity:note2.velocity})),notes=noteDevice(patch)?transformPatchNotes(patch,given,context.devices,context.sampleRate):given,overrides="ref"in track2.patch?track2.patch.macros:void 0,render=runPatch(program,{...runOptions(program,track2,overrides,context,track2.id),notes,buffer:bufferHandler(track2,played,context,hooks,notes)});return writeOut(render,dry,dryR)}function writeOut(render,left,right){if(left.set(render.left.subarray(0,left.length)),!render.right||!right)return!1;let same=!0,n2=Math.min(left.length,render.right.length);for(let i=0;i<n2;i+=1)if(render.right[i]!==render.left[i]){same=!1;break}return same?!1:(right.set(render.right.subarray(0,right.length)),!0)}function effectPatches(track2,at3){return(track2.fxPatch??[]).filter(patch=>at3==="post"?patch.at==="post":patch.at!=="post")}function applyEffectPatches(left,right,track2,at3,context,hooks){for(let[index,patch]of effectPatches(track2,at3).entries()){let program=compilePatch(patch,context.library),sized={...context,samples:left.length},render=runPatch(program,{...runOptions(program,track2,void 0,sized,`${track2.id}:fx${index}:${patch.name}`),audio:left,...right?{right}:{},buffer:bufferHandler(track2,void 0,sized,hooks)});left.set(render.left),right&&right.set(render.right??render.left)}}function patchContextOf(context,bank,side){return{...bank.devices?{devices:bank.devices}:{},sampleRate:context.sampleRate,samples:context.samples,samplesPerTick:context.samplesPerTick,tempoBpm:context.tempoBpm,ticksPerBeat:context.score.ticksPerBeat,beatsPerBar:context.score.beatsPerBar,library:context.score.patches,...context.warp?{warp:context.warp}:{},...context.seedTick!==void 0?{seedTick:context.seedTick}:{},...side?{side}:{}}}function hooksFor(renderer,context,bank,played){return{voice:(dry,dryR,track2)=>renderer.voice(dry,dryR,played,track2,context,bank),stage:(stage,left,right,track2)=>renderer.stage(stage,left,right,track2,context)}}function renderPatchTrack(dry,dryR,played,track2,context,bank,renderer,side){let spans=played.map(note2=>({...renderer.span(note2,context),hz:noteHz(note2.pitch,note2.cents,context.tuning)}));return renderPatchVoice(dry,dryR,played,spans,track2,patchContextOf(context,bank,side),hooksFor(renderer,context,bank,played))}function patchStageFor(track2,context,bank,renderer,side){if(effectPatches(track2,"chain").length===0)return;let patch=patchContextOf(context,bank,side),hooks=hooksFor(renderer,context,bank,[]);return buffer=>applyEffectPatches(buffer,void 0,track2,"chain",patch,hooks)}function applyPostPatches(left,right,track2,context,bank,renderer,side){effectPatches(track2,"post").length!==0&&applyEffectPatches(left,right,track2,"post",patchContextOf(context,bank,side),hooksFor(renderer,context,bank,[]))}function readsSide(track2){return track2!==void 0&&(track2.patch?.side!==void 0||(track2.fxPatch??[]).some(patch=>patch.side!==void 0))}function patchEngine(renderer){return{id:PATCH_INSTRUMENT,field:"patch",render(dry,dryR,notes,track2,context,bank){let right=dryR??new Float64Array(dry.length);renderPatchTrack(dry,right,notes,track2,context,bank,renderer)},tailSeconds(track2,lowestPitch,score){let library=score?.patches??{};return Math.max(patchTailSeconds(track2,library),...engineTracks(track2,library).map(inner=>renderer.tail(inner,lowestPitch)))},stereo:()=>!0,assetDigests(track2,bank,score){let library=score?.patches??{};return[...patchDigests(track2,library),...engineTracks(track2,library).flatMap(inner=>renderer.digests(inner,bank,score))]}}}function nativeReverbKernel(){}var RENDER_CHANNELS=2,DEFAULT_SAMPLE_RATE=22050;function clampSampleRate(sampleRate){return Math.max(8e3,Math.min(48e3,Math.floor(sampleRate??DEFAULT_SAMPLE_RATE)))}var ONE_SHOT_TAIL_SECONDS=.35;function oneShotSeconds(loopSeconds,samplerTail,reverbTail,delayTail=0){return loopSeconds+Math.max(ONE_SHOT_TAIL_SECONDS,samplerTail)+reverbTail+delayTail}function trackGainAt(track2,tick){let trackGain=Math.max(0,Math.min(1,track2?.volume??1)),automatedGain=interpolateAutomation(track2?.volumeAutomation??[],tick,1);return trackGain*automatedGain}function noteSpan(note2,context){let{score,sampleRate,warp:warp2}=context;if(warp2)return warpedSpan(warp2,note2.startTick,note2.durationTicks);let start=Math.max(0,Math.floor(note2.startTick/score.ticksPerBeat*60/score.tempoBpm*sampleRate)),length=Math.max(1,Math.floor(note2.durationTicks/score.ticksPerBeat*60/score.tempoBpm*sampleRate));return{start,length}}function renderToneNote(target,note2,track2,context,tuning){let{sampleRate,samples,samplesPerTick}=context,instrument=track2?.instrument??"sine",{start,length}=noteSpan(note2,context),end=Math.min(samples,start+length),frequency=noteHz(note2.pitch,note2.cents,tuning);if(!(frequency>0))return;let velocity=Math.max(0,Math.min(1,note2.velocity)),performance2=note2.performance,cents=performance2?.cents,bent=0,wave2=legacyWaveFor(instrument);for(let index=start;index<end;index+=1){let elapsed=index-start,remaining=end-index,attack=Math.min(1,elapsed/Math.max(1,sampleRate*.012)),release=Math.min(1,remaining/Math.max(1,sampleRate*.09)),envelope2=Math.min(attack,release)*velocity*.28*trackGainAt(track2,context.warp?context.warp.tick(index):note2.startTick+elapsed/samplesPerTick),phase=frequency*elapsed/sampleRate;cents&&(phase=bent,bent+=frequency*2**(cents(elapsed/sampleRate)/1200)/sampleRate);let damp=performance2?.damp,t=elapsed/sampleRate,held=damp&&t>damp.from?Math.exp(-(t-damp.from)/damp.tau):1;target[index]+=wave2(phase)*envelope2*held}}function applyPan(dry,left,right,track2,context,dryRight){let lane=track2?.panAutomation??[],staticPan=track2?.pan??0,gains=pan2=>{let theta=(Math.max(-1,Math.min(1,pan2))+1)*Math.PI/4;return[Math.cos(theta),Math.sin(theta)]},[gainL,gainR]=gains(staticPan);for(let index=0;index<dry.length;index+=1){lane.length>0&&index%32===0&&([gainL,gainR]=gains(interpolateAutomation(lane,context.warp?context.warp.tick(index):index/context.samplesPerTick,staticPan)));let sample=dry[index];left[index]=sample*gainL,right[index]=(dryRight?dryRight[index]:sample)*gainR}}function toPcm(mixL,mixR,frames,dither=!1){let pcm=new Int16Array(frames*RENDER_CHANNELS);if(dither){let state=2654435769,uniform=()=>(state^=state<<13,state^=state>>>17,state^=state<<5,(state>>>0)/4294967296);for(let index=0;index<frames;index+=1)pcm[index*2]=clamp16(Math.round(mixL[index]*32767+uniform()-uniform())),pcm[index*2+1]=clamp16(Math.round(mixR[index]*32767+uniform()-uniform()));return pcm}for(let index=0;index<frames;index+=1)pcm[index*2]=clamp16(mixL[index]*32767),pcm[index*2+1]=clamp16(mixR[index]*32767);return pcm}function clamp16(value){return Math.max(-32768,Math.min(32767,Math.round(value)))}function newKitVoiceState(){return{phase:0,band:0,dark:0,metalPrevious:0,holdLeft:0,held:0}}var METAL_HZ=[205.3,304.4,369.6,522.7,540,800],hatWaves=new Map,MAX_KIT_SECONDS=Math.max(...SYNTH_KITS.map(kit2=>kit2.seconds));function kitHatWave(sampleRate,calibrated,count2){if(!Number.isInteger(sampleRate)||sampleRate<1||sampleRate>48e3)return;let key=`${sampleRate}:${calibrated}`,wave2=hatWaves.get(key);wave2||(hatWaves.size>=2&&hatWaves.delete(hatWaves.keys().next().value),wave2={samples:new Float64Array(Math.ceil(MAX_KIT_SECONDS*sampleRate)),filled:0},hatWaves.set(key,wave2));let end=Math.min(wave2.samples.length,count2);for(let index=wave2.filled;index<end;index+=1){let t=index/sampleRate,square2=0;for(let hz3 of METAL_HZ)square2+=calibrated?blepSquare(hz3,t,sampleRate):t*hz3%1<.5?1:-1;wave2.samples[index]=square2}return wave2.filled=Math.max(wave2.filled,end),wave2.samples}function body(params2,t,noise2,state,sampleRate,ratio2=1){let frequency=(params2.base+params2.sweep*Math.exp(-t*params2.sweepRate))*ratio2;return state.phase+=frequency/sampleRate,Math.sin(2*Math.PI*state.phase)*Math.exp(-t*params2.decay)*params2.level+noise2*params2.click*Math.exp(-t*params2.clickDecay)}function polyBlep3(phase,step2){if(phase<step2){let x=phase/step2;return x+x-x*x-1}if(phase>1-step2){let x=(phase-1)/step2;return x*x+x+x+1}return 0}function blepSquare(hz3,t,sampleRate){let phase=t*hz3%1,step2=Math.min(.5,hz3/sampleRate);return(phase<.5?1:-1)+polyBlep3(phase,step2)-polyBlep3((phase+.5)%1,step2)}function hat(params2,t,noise2,bright,state,sampleRate=0,cachedSquare){state.dark+=.3*(noise2-state.dark);let noisy=params2.tone*bright+(1-params2.tone)*state.dark*.8,source=noisy;if(params2.metal>0){let square2=cachedSquare??0;if(cachedSquare===void 0)for(let hz3 of METAL_HZ)square2+=sampleRate>0?blepSquare(hz3,t,sampleRate):t*hz3%1<.5?1:-1;let metal=(square2/METAL_HZ.length-state.metalPrevious)*1.6;state.metalPrevious=square2/METAL_HZ.length,source=params2.metal*metal+(1-params2.metal)*noisy}return source*params2.level*Math.exp(-t*params2.decay)}function kitDrumSample(kit2,voice,t,noise2,bright,state,sampleRate,calibrated,hatSquare){let sample,metalRate=calibrated?sampleRate:0;if(voice==="kick")sample=body(kit2.kick,t,noise2,state,sampleRate);else if(voice==="tom")sample=body(kit2.tom,t,noise2,state,sampleRate,calibrated?.tomRatio??1);else if(voice==="snare"){let p=kit2.snare;state.phase+=p.tone/sampleRate;let wires=p.snap*bright+(1-p.snap)*noise2;sample=Math.sin(2*Math.PI*state.phase)*p.toneLevel*Math.exp(-t*p.toneDecay)+wires*p.noise*Math.exp(-t*p.noiseDecay)}else if(voice==="clap"){let p=kit2.clap;state.band+=p.band*(bright-state.band);let span4=p.gap*3,burst=t<span4?Math.floor(t/p.gap)%2===0?1:.35:0;sample=state.band*p.level*(burst+.8*Math.exp(-(t-span4)*p.tail)*+(t>=span4))}else if(voice==="hat")sample=hat(kit2.hat,t,noise2,bright,state,metalRate,hatSquare);else if(voice==="openhat")sample=hat(kit2.openhat,t,noise2,bright,state,metalRate,hatSquare);else{let p=kit2.rim;sample=(Math.sin(2*Math.PI*p.high*t)*.6+Math.sin(2*Math.PI*p.low*t)*.4)*Math.exp(-t*p.decay)*p.level}if(kit2.drive>0){let amount=1+kit2.drive*4;sample=Math.tanh(sample*amount)/Math.tanh(amount)}if(kit2.bits>0){let steps2=2**(kit2.bits-1);sample=Math.round(sample*steps2)/steps2}return kit2.hold>1&&(state.holdLeft<=0&&(state.held=sample,state.holdLeft=kit2.hold),state.holdLeft-=1,sample=state.held),sample*kit2.gain}var METAL_PITCHES=Object.freeze({49:"crash",52:"crash",55:"crash",57:"crash",51:"ride",53:"ride",59:"ride",56:"cowbell"});function metalKindForPitch(pitch2){return METAL_PITCHES[pitch2]}function tomRatio(pitch2){return 2**((Math.max(35,Math.min(55,pitch2))-45)*2/3/12)}function metalSample(kind,t,bright,state,sampleRate){if(kind==="cowbell"){let tone=(blepSquare(540,t,sampleRate)+blepSquare(800,t,sampleRate))/2;state.band+=.45*(tone-state.band);let envelope2=.7*Math.exp(-t*60)+.3*Math.exp(-t*9);return state.band*.5*envelope2}let square2=0;for(let hz3 of METAL_HZ)square2+=blepSquare(hz3*1.9,t,sampleRate);let metal=(square2/METAL_HZ.length-state.metalPrevious)*1.6;if(state.metalPrevious=square2/METAL_HZ.length,kind==="crash"){let swell=Math.min(1,t/.004);return(.55*bright+.45*metal)*.42*swell*Math.exp(-t*4.2)}let ping=(.6*metal+.4*bright)*.3*Math.exp(-t*28),wash=(.35*metal+.65*bright)*.16*Math.exp(-t*3.5);return ping+wash}var METAL_SECONDS=1.4;function kitTailSeconds(score){let seconds2=0;if((score.calibration??0)>=1){let drums=new Set(soundingTracks(score).filter(track2=>isDrumInstrument(track2.instrument)).map(track2=>track2.id));score.notes.some(note2=>drums.has(note2.trackId)&&metalKindForPitch(note2.pitch)!==void 0)&&(seconds2=METAL_SECONDS)}for(let track2 of soundingTracks(score))seconds2=Math.max(seconds2,synthKit(track2.kit)?.seconds??0);return seconds2}function applyCrush(buffer,track2,values,context){let read=fxReader(track2,"crush",values,context),bits=read.param("bits"),mix3=read.param("mix"),coarse=Math.max(1,Math.round(read.number("coarse"))),levels=2**(bits.at(0)-1),wet=mix3.at(0),held=0;for(let index=0;index<buffer.length;index+=1){index%32===0&&(bits.automated&&(levels=2**(bits.at(index)-1)),mix3.automated&&(wet=mix3.at(index)));let input=buffer[index];index%coarse===0&&(held=input);let crushed=Math.round(held*levels)/levels;buffer[index]=input+(crushed-input)*wet}}function shapeCurve(type,x,amount){switch(type){case"hard":return clamp2(x,-1,1);case"cubic":{let y=clamp2(x,-1.5,1.5);return y-y*y*y/6.75}case"diode":return x>=0?Math.tanh(1.5*x)/1.2:Math.tanh(.7*x)/.85;case"asym":return Math.tanh(x+.3)-Math.tanh(.3);case"fold":{let folded=((x+1)%4+4)%4;return folded<2?folded-1:3-folded}case"sinefold":return Math.sin(Math.PI/2*x);case"chebyshev":{let y=Math.tanh(x);return .6*y+.4*(4*y*y*y-3*y)}case"scurve":return 2/Math.PI*Math.atan(x*1.4);case"shape":{let a=Math.min(.99,amount),k=2*a/(1-a);return(1+k)*x/(1+k*Math.abs(x))}default:return Math.tanh(x)}}var COMPENSATION_LEVEL=.25,COMPENSATION_RMS=COMPENSATION_LEVEL/Math.SQRT2,COMPENSATION_POINTS=64,COMPENSATION_INPUTS=Float64Array.from({length:COMPENSATION_POINTS},(_,index)=>COMPENSATION_LEVEL*Math.sin(2*Math.PI*index/COMPENSATION_POINTS));function applyDistort(buffer,track2,values,context){let read=fxReader(track2,"distort",values,context),drive=read.param("drive"),tone=read.param("tone"),mix3=read.param("mix"),type=read.text("type"),postgain=read.number("postgain"),setDrive=value=>{let amount=value/10,pregain=type==="shape"?1:2**(value*.6),sum=0;for(let k=0;k<COMPENSATION_POINTS;k+=1){let x=COMPENSATION_INPUTS[k];sum+=shapeCurve(type,pregain*x,amount)**2}let reference2=Math.sqrt(sum/COMPENSATION_POINTS),compensation=clamp2(COMPENSATION_RMS/Math.max(.001,reference2),.05,1.5);return{amount,pregain,compensation}},driveValue=drive.at(0),state=setDrive(driveValue),lowpass=new OnePole(tone.at(0),context.sampleRate),wet=mix3.at(0);for(let index=0;index<buffer.length;index+=1){if(index%32===0){if(drive.automated){let next=drive.at(index);Object.is(next,driveValue)||(driveValue=next,state=setDrive(next))}tone.automated&&lowpass.set(tone.at(index),context.sampleRate),mix3.automated&&(wet=mix3.at(index))}let input=buffer[index],shaped=shapeCurve(type,input*state.pregain,state.amount)*state.compensation,output2=lowpass.process(shaped)*postgain;buffer[index]=input+(output2-input)*wet}}var CENTS_TO_LOG=Math.LN2/1200;function readAt2(x,position){let last=x.length-1;if(last<0)return 0;let p=clamp2(position,0,last),i=Math.floor(p),t=p-i,a=x[Math.max(0,i-1)],b=x[i],c=x[Math.min(last,i+1)],d=x[Math.min(last,i+2)],c1=.5*(c-a),c2=a-2.5*b+2*c-.5*d;return(((.5*(d-a)+1.5*(b-c))*t+c2)*t+c1)*t+b}var WOBBLE_MAX_OFFSET=.015;function wobbleShape(depth,rate2,drift,seed){let r=seededRandom(`wobble:${seed}`),phase=[r(),r(),r()].map(x=>x*2*Math.PI),ratio2=[1,.61+.1*r(),1.53+.2*r()],d=clamp2(drift,0,1),weight=[1-d,.6*d,.4*d],norm=weight[0]+weight[1]+weight[2],hz3=ratio2.map(k=>Math.max(.01,rate2)*k),amp=hz3.map((f,k)=>weight[k]/norm*depth*CENTS_TO_LOG/(2*Math.PI*f));return{span:amp[0]+amp[1]+amp[2],offset:t=>{let s=0;for(let k=0;k<3;k+=1)s+=amp[k]*Math.sin(2*Math.PI*hz3[k]*t+phase[k]);return s},cents:t=>{let s=0;for(let k=0;k<3;k+=1)s+=amp[k]*2*Math.PI*hz3[k]*Math.cos(2*Math.PI*hz3[k]*t+phase[k]);return s/CENTS_TO_LOG}}}function applyWobble(buffer,track2,values,context){let read=fxReader(track2,"wobble",values,context),depth=read.param("depth"),rate2=read.number("rate"),drift=read.number("drift"),sr=context.sampleRate;if((depth.automated?100:depth.at(0))<=0||buffer.length===0)return;let shape=wobbleShape(1,rate2,drift,track2.id),most=shape.span>0?WOBBLE_MAX_OFFSET/shape.span:1/0,source=buffer.slice(),scale3=Math.min(most,depth.at(0));for(let index=0;index<buffer.length;index+=1){depth.automated&&index%32===0&&(scale3=Math.min(most,depth.at(index)));let t=index/sr;buffer[index]=readAt2(source,index+scale3*shape.offset(t)*sr)}}function applyBloom(buffer,track2,values,context){let notes=context.notes;if(!notes||notes.length===0)return;let read=fxReader(track2,"bloom",values,context),amount=read.number("amount");if(amount<=0)return;let harm=read.number("harm"),sr=context.sampleRate,delay=Math.round(read.number("delay")*sr),grow=Math.max(.05,read.number("time")),release=Math.round(.08*sr),fade=Math.max(1,Math.round(.02*sr)),follow3=new Float64Array(buffer.length),up=1-Math.exp(-1/(.05*sr)),down=1-Math.exp(-1/(Math.max(.1,grow)*sr)),power=0;for(let index=0;index<buffer.length;index+=1){let x2=buffer[index]*buffer[index];power+=(x2>power?up:down)*(x2-power),follow3[index]=Math.sqrt(2*power)}let sorted=notes.filter(note2=>note2.length>delay).sort((x,y)=>x.start-y.start||y.hz-x.hz),loops=[],active=[],next=0,current;for(let block=0;block<buffer.length;block+=BLOCK3){for(;next<sorted.length&&sorted[next].start<=block;)active.push(sorted[next++]);for(let k=active.length-1;k>=0;k-=1)active[k].start+active[k].length<=block&&active.splice(k,1);let top;for(let note2 of active)note2.start+delay<=block&&(!top||note2.hz>top.hz)&&(top=note2);if(top!==current){for(let loop of loops)loop.note!==top&&(loop.rising=!1);if(top&&!loops.some(loop=>loop.note===top)){let r=seededRandom(`bloom:${track2.id}:${top.id}`);loops.push({note:top,phase:r()*2*Math.PI,driftHz:.2+.3*r(),level:Math.min(.5,.6*amount*(.5+.5*top.velocity)),gain:current?0:1,rising:!0})}current=top}let end=Math.min(buffer.length,block+BLOCK3);for(let k=loops.length-1;k>=0;k-=1){let loop=loops[k],from=loop.note.start+delay,off=loop.note.start+loop.note.length;for(let index=block;index<end;index+=1){let t=(index-from)/sr,cents=3*Math.sin(2*Math.PI*loop.driftHz*t);loop.phase+=2*Math.PI*harm*loop.note.hz*2**(cents/1200)/sr,loop.gain=loop.rising?Math.min(1,loop.gain+1/fade):Math.max(0,loop.gain-1/fade);let env=follow3[index]*loop.level*loop.gain*(1-Math.exp(-t/grow));index>off&&(env*=Math.max(0,1-(index-off)/release)),buffer[index]+=env*Math.sin(loop.phase)}(loop.gain<=0||end>off+release)&&(loops.splice(k,1),current===loop.note&&(current=void 0))}}}var BLOCK3=32;function onsets(notes,sr){let gap=.04*sr,out=[];for(let start of notes.map(note2=>note2.start).sort((a,b)=>a-b))(out.length===0||start-out[out.length-1]>gap)&&out.push(start);return out}function applySwell(buffer,track2,values,context){let notes=context.notes;if(!notes||notes.length===0)return;let read=fxReader(track2,"swell",values,context),mix3=read.param("mix"),sr=context.sampleRate,tau=Math.max(.01,read.number("time"))/3*sr,duck=.006*sr,starts=onsets(notes,sr),next=0,last=Number.NEGATIVE_INFINITY,g=1,from=0,fall=0,wet=mix3.at(0);for(let index=0;index<buffer.length;index+=1){for(mix3.automated&&index%32===0&&(wet=mix3.at(index));next<starts.length&&starts[next]<=index;)from=last===Number.NEGATIVE_INFINITY?0:g,fall=Math.round(duck*from),last=starts[next++];if(last!==Number.NEGATIVE_INFINITY){let elapsed=index-last;g=elapsed<fall?from*(1-elapsed/fall):1-Math.exp(-(elapsed-fall)/tau)}buffer[index]=buffer[index]*(1-wet+wet*g*g)}}function secondTake(x,time,drift,seed,sr){let r=seededRandom(`double:${seed}`),ph1=r()*2*Math.PI,ph2=r()*2*Math.PI,f1=.35+.3*r(),f2=.11+.1*r(),tilt=new OnePole2(5500,sr),out=new Float64Array(x.length),d=time/1e3*sr;for(let index=0;index<x.length;index+=1){if(index%32===0){let t=index/sr,wander=.65*Math.sin(2*Math.PI*f1*t+ph1)+.35*Math.sin(2*Math.PI*f2*t+ph2);d=(time+drift*wander)/1e3*sr}let position=index-d;out[index]=tilt.process(position<0?0:readAt2(x,position))}return out}function applyDouble(left,right,track2,values,context){let read=fxReader(track2,"double",values,context),time=read.number("time"),drift=read.number("drift"),width=clamp2(read.number("width"),0,1),sr=context.sampleRate,copyL=secondTake(left,time,drift,track2.id,sr),copyR=secondTake(right,time,drift,track2.id,sr);for(let index=0;index<left.length;index+=1){let l=left[index],r=right[index],cl=copyL[index],cr=copyR[index];left[index]=.5*(l+cl)+.5*width*(l-cl),right[index]=.5*(r+cr)-.5*width*(r-cr)}}function skewCycle(phase,skew){let cycle=phase-Math.floor(phase),s=Math.min(.99,Math.max(.01,skew));return cycle<s?.5*cycle/s:.5+.5*(cycle-s)/(1-s)}function applyTremolo(buffer,track2,values,context){let read=fxReader(track2,"tremolo",values,context),rate2=read.param("rate"),depth=read.param("depth"),sync2=read.number("sync"),shape=read.text("shape"),skew=read.number("skew"),phasor=new Phasor(read.number("phase")),amount=depth.at(0);for(let index=0;index<buffer.length;index+=1){index%32===0&&(phasor.setHz(lfoHz(sync2,rate2.at(index),tempoAtSample(context,index)),context.sampleRate),depth.automated&&(amount=depth.at(index)));let u=(lfo(shape,skewCycle(phasor.next(),skew)+.25)+1)/2;buffer[index]=buffer[index]*(1-amount*(1-u))}}function applyGate(buffer,track2,values,context){let read=fxReader(track2,"gate",values,context),pattern=GATE_PATTERNS[read.text("pattern")]??"x",step2=Math.max(.001,read.number("step")),length=read.number("length"),depth=read.param("depth"),{sampleRate,samplesPerTick,tempoBpm}=context,coefficient=seconds2=>1-Math.exp(-1/Math.max(1,seconds2*sampleRate)),rise=coefficient(read.number("attack")),fall=coefficient(read.number("release")),beatsPerTick=samplesPerTick*tempoBpm/(60*sampleRate),origin=context.warp?0:Math.round((context.seedSeconds??0)*sampleRate),beatAt=index=>context.warp?tickAtSample(context,index)*beatsPerTick:(index+origin)*tempoBpm/(60*sampleRate),amount=depth.at(0),gain=-1;for(let index=0;index<buffer.length;index+=1){depth.automated&&index%32===0&&(amount=depth.at(index));let steps2=beatAt(index)/step2,which=Math.floor(steps2),target=pattern[(which%pattern.length+pattern.length)%pattern.length]==="x"&&steps2-which<length?1:1-amount;gain<0?gain=target:gain+=(target-gain)*(target>gain?rise:fall),buffer[index]=buffer[index]*gain}}function applyCompressor(buffer,track2,values,context){let read=fxReader(track2,"compressor",values,context),threshold=read.param("threshold"),makeup=read.param("makeup"),ratio2=read.number("ratio"),knee3=read.number("knee"),{sampleRate}=context,coefficient=seconds2=>Math.exp(-1/Math.max(1,seconds2*sampleRate)),attack=coefficient(read.number("attack")),release=coefficient(read.number("release")),detector=coefficient(.005),slope=1-1/ratio2,thresholdDb=threshold.at(0),makeupGain=dbToGain(makeup.at(0)),power=0,reduction=0;for(let index=0;index<buffer.length;index+=1){index%32===0&&(threshold.automated&&(thresholdDb=threshold.at(index)),makeup.automated&&(makeupGain=dbToGain(makeup.at(index))));let input=buffer[index],magnitude=Math.abs(input);power=magnitude>power?magnitude:detector*power;let over=20*Math.log10(power+1e-12)-thresholdDb,target=0;2*over>=knee3?target=slope*over:knee3>0&&2*over>-knee3&&(target=slope*(over+knee3/2)**2/(2*knee3)),reduction=target>reduction?attack*reduction+(1-attack)*target:release*reduction+(1-release)*target,buffer[index]=input*dbToGain(-reduction)*makeupGain}}function applyPostgain(left,right,track2,values,context){let gain=fxReader(track2,"postgain",values,context).param("gain"),value=gain.at(0);for(let index=0;index<left.length;index+=1)gain.automated&&index%32===0&&(value=gain.at(index)),left[index]*=value,right[index]*=value}var BUTTERWORTH_Q12=.5412,BUTTERWORTH_Q2_SCALE=1.3066/.707,SlopeFilter=class{constructor(type,slope,sampleRate){this.type=type;this.slope=slope;this.sampleRate=sampleRate}type;slope;sampleRate;first=new Biquad;second=new Biquad;ladder=new Float64Array(4);ladderG=0;ladderK=0;get isLadder(){return this.slope==="ladder"&&this.type==="lpf"}update(cutoff2,resonance){if(this.isLadder){let frequency=clamp2(cutoff2,20,this.sampleRate*.45);this.ladderG=1-Math.exp(-2*Math.PI*frequency/this.sampleRate),this.ladderK=3.9*clamp2(resonance,0,1);return}if(this.slope==="12db"){this.first.set(this.type,cutoff2,resonanceQ(resonance),this.sampleRate);return}this.first.set(this.type,cutoff2,BUTTERWORTH_Q12,this.sampleRate),this.second.set(this.type,cutoff2,resonanceQ(resonance)*BUTTERWORTH_Q2_SCALE,this.sampleRate)}process(input){if(this.isLadder){let stages=this.ladder,g=this.ladderG,k=this.ladderK,driven=Math.tanh(input-k*stages[3]);return stages[0]+=g*(driven-stages[0]),stages[1]+=g*(stages[0]-stages[1]),stages[2]+=g*(stages[1]-stages[2]),stages[3]+=g*(stages[2]-stages[3]),stages[3]*(1+.5*k)}let once=this.first.process(input);return this.slope==="12db"?once:this.second.process(once)}};function applyTrackFilter(buffer,track2,context){let automation=track2.filterAutomation??[],resonanceLane=track2.resonanceAutomation??[];if(!track2.filter&&automation.length===0&&resonanceLane.length===0)return;let{sampleRate}=context,staticCutoff=track2.filter?.cutoff??SCORE_LIMITS.maxFilterCutoff,staticResonance=track2.filter?.resonance??0,automated=automation.length>0||resonanceLane.length>0,filter=new SlopeFilter(track2.filter?.type??"lpf",track2.filter?.ftype??"12db",sampleRate);filter.update(staticCutoff,staticResonance);for(let index=0;index<buffer.length;index+=1){if(automated&&index%32===0){let tick=tickAtSample(context,index);filter.update(interpolateAutomation(automation,tick,staticCutoff),interpolateAutomation(resonanceLane,tick,staticResonance))}buffer[index]=filter.process(buffer[index])}}var DJ_HPF_MAX_HZ=1e4;function djCutoff(value){return value<.5?{type:"lpf",cutoff:20*1e3**(value/.5)}:{type:"hpf",cutoff:Math.min(DJ_HPF_MAX_HZ,20*1e3**((value-.5)/.5))}}function applyDjFilter(buffer,track2,values,context){let value=fxReader(track2,"djf",values,context).param("value"),lowpass=new Biquad,highpass2=new Biquad,position=-1;for(let index=0;index<buffer.length;index+=1){if(index%32===0){let next=value.at(index);if(next!==position){position=next;let{type,cutoff:cutoff2}=djCutoff(position);lowpass.set("lpf",type==="lpf"?cutoff2:2e4,.8,context.sampleRate),highpass2.set("hpf",type==="hpf"?cutoff2:20,.8,context.sampleRate)}}buffer[index]=highpass2.process(lowpass.process(buffer[index]))}}function applyAutoFilter(buffer,track2,values,context){let read=fxReader(track2,"autofilter",values,context),cutoff2=read.param("cutoff"),resonance=read.param("resonance"),depth=read.param("depth"),follow3=read.param("follow"),rate2=read.param("rate"),sync2=read.number("sync"),shape=read.text("shape"),filter=new SlopeFilter(read.text("type"),"12db",context.sampleRate),phasor=new Phasor(read.number("phase")),attack=Math.exp(-1/(.005*context.sampleRate)),release=Math.exp(-1/(.12*context.sampleRate)),envelope2=0,followOctaves=follow3.at(0);for(let index=0;index<buffer.length;index+=1){let input=buffer[index],level2=Math.abs(input);if(envelope2=level2>envelope2?attack*envelope2+(1-attack)*level2:release*envelope2+(1-release)*level2,index%32===0){phasor.setHz(lfoHz(sync2,rate2.at(index),tempoAtSample(context,index)),context.sampleRate),followOctaves=follow3.at(index);let sweep=lfo(shape,phasor.phase,24301)*depth.at(index)*.5,envelopeOctaves=followOctaves*Math.min(1,envelope2*2);filter.update(cutoff2.at(index)*2**(sweep+envelopeOctaves),resonance.at(index))}phasor.next(),buffer[index]=filter.process(input)}}var VOWEL_GAIN=2.2;function applyVowel(buffer,track2,values,context){let read=fxReader(track2,"vowel",values,context),formants=VOWEL_FORMANTS[read.text("vowel")]??VOWEL_FORMANTS.a,mix3=read.param("mix"),bank=formants.map(([frequency,level2,bandwidth])=>{let filter=new Biquad;return filter.set("bpf",frequency,frequency/bandwidth,context.sampleRate),{filter,gain:10**(level2/20)}}),toName=values.to,to=toName===void 0?void 0:VOWEL_FORMANTS[toName],morph=to?new Param(values.morph??0,track2.fxAutomation?.["vowel-morph"],context.samplesPerTick,context.warp):void 0,moving=morph!==void 0&&(morph.automated||morph.fallback>0),at3=-1,retune=position=>{position!==at3&&(at3=position,morphFormants(formants,to,position).forEach(([frequency,level2,bandwidth],index)=>{let band=bank[index];band.filter.set("bpf",frequency,frequency/bandwidth,context.sampleRate),band.gain=10**(level2/20)}))};moving&&retune(morph.at(0));let tilt=new OnePole(8e3,context.sampleRate),wet=mix3.at(0);for(let index=0;index<buffer.length;index+=1){mix3.automated&&index%32===0&&(wet=mix3.at(index)),moving&&morph.automated&&index%32===0&&retune(morph.at(index));let input=buffer[index],emphasized=input+.5*(input-tilt.process(input)),sum=0;for(let band of bank)sum+=band.filter.process(emphasized)*band.gain;buffer[index]=input+(sum*VOWEL_GAIN-input)*wet}}var SHELF_S=1,PEAK_Q=.9;function setEqBand(filter,band,frequency,gainDb,sampleRate){let f=clamp2(frequency,20,sampleRate*.45),a=10**(gainDb/40),omega=2*Math.PI*f/sampleRate,cos=Math.cos(omega),sin=Math.sin(omega),b0,b1,b2,a0,a1,a2;if(band==="peak"){let alpha=sin/(2*PEAK_Q);b0=1+alpha*a,b1=-2*cos,b2=1-alpha*a,a0=1+alpha/a,a1=-2*cos,a2=1-alpha/a}else{let alpha=sin/2*Math.sqrt((a+1/a)*(1/SHELF_S-1)+2),root=2*Math.sqrt(a)*alpha,sign=band==="low"?-1:1;b0=a*(a+1+sign*(a-1)*cos+root),b1=-2*sign*a*(a-1+sign*(a+1)*cos),b2=a*(a+1+sign*(a-1)*cos-root),a0=a+1-sign*(a-1)*cos+root,a1=2*sign*(a-1-sign*(a+1)*cos),a2=a+1-sign*(a-1)*cos-root}filter.b0=b0/a0,filter.b1=b1/a0,filter.b2=b2/a0,filter.a1=a1/a0,filter.a2=a2/a0}function applyEq2(buffer,track2,values,context){let read=fxReader(track2,"eq",values,context),live2=[{band:"low",gain:read.param("low"),freq:read.number("lowfreq")},{band:"peak",gain:read.param("mid"),freq:read.param("midfreq")},{band:"high",gain:read.param("high"),freq:read.number("highfreq")}].filter(({gain})=>gain.automated||gain.at(0)!==0).map(spec=>({...spec,filter:new Biquad,gainDb:NaN,hz:NaN}));if(live2.length!==0)for(let index=0;index<buffer.length;index+=1){if(index%32===0)for(let stage of live2){let gainDb=stage.gain.at(index),hz3=typeof stage.freq=="number"?stage.freq:stage.freq.at(index);gainDb===stage.gainDb&&hz3===stage.hz||(stage.gainDb=gainDb,stage.hz=hz3,setEqBand(stage.filter,stage.band,hz3,gainDb,context.sampleRate))}let sample=buffer[index];for(let stage of live2)sample=stage.filter.process(sample);buffer[index]=sample}}var MAX_GAIN=10**(24/20),LIFTER_PERIODS=.75,LIFTER_MIN_SECONDS=.001,LIFTER_MAX_SECONDS=.002,F0_MEDIAN=5,F0_MIN_HZ=60,F0_MAX_HZ=1500,VOICED2=.45,FIRST_PEAK=.85;function formantFrame(sampleRate){return sampleRate>24e3?2048:1024}var analyses=new Map;function analysisFor(sampleRate){let a=analyses.get(sampleRate);if(a)return a;let n2=formantFrame(sampleRate),win=hann(n2),minLag=Math.floor(sampleRate/F0_MAX_HZ),maxLag=Math.min(n2/2-1,Math.ceil(sampleRate/F0_MIN_HZ)),wac=new Float64Array(maxLag+1);for(let t=0;t<=maxLag;t+=1){let sum=0;for(let i=0;i+t<n2;i+=1)sum+=win[i]*win[i+t];wac[t]=sum}return a={n:n2,hop:n2/4,win,wac,minLag,maxLag},analyses.set(sampleRate,a),a}function frameF0(mag,a,sampleRate,re,im){let{n:n2,wac,minLag,maxLag}=a,half=n2/2;for(let k=0;k<=half;k+=1)re[k]=mag[k]*mag[k],im[k]=0,k>0&&k<half&&(re[n2-k]=re[k],im[n2-k]=0);fftInPlace(re,im,!0);let r0=re[0];if(r0<=1e-12)return 0;let w0=wac[0]/r0;for(let t=minLag-1;t<=maxLag;t+=1)re[t]=re[t]*w0/wac[t];let best=0;for(let t=minLag;t<=maxLag;t+=1)best=Math.max(best,re[t]);if(best<VOICED2)return 0;for(let t=minLag+1;t<maxLag;t+=1){let v=re[t];if(v>=FIRST_PEAK*best&&v>=re[t-1]&&v>=re[t+1]){let l=re[t-1],r=re[t+1],d=l-2*v+r,offset=d<0?.5*(l-r)/d:0;return sampleRate/(t+offset)}}return 0}function formantShift(x,sampleRate,shift,options={}){if(shift===0)return Float64Array.from(x);let a=analysisFor(sampleRate),{n:n2,hop,win}=a,half=n2/2,origin=Math.round(options.origin??0),out=new Float64Array(x.length),re=new Float64Array(n2),im=new Float64Array(n2),acRe=new Float64Array(n2),acIm=new Float64Array(n2),mag=new Float64Array(half+1),env=new Float64Array(half+1),scratch=envelopeScratch(n2),history=new Float64Array(F0_MEDIAN),sorted=new Float64Array(F0_MEDIAN),frames=0,ola=1/HANN_SQUARED_OLA_QUARTER,auto=typeof shift=="function",firstAbs=Math.floor((origin-n2+1+(hop-1))/hop)*hop;for(let start=firstAbs-origin;start<x.length;start+=hop){let st=auto?shift(Math.max(0,start+half)):shift;for(let i=0;i<n2;i+=1){let j=start+i;re[i]=j>=0&&j<x.length?x[j]*win[i]:0,im[i]=0}fftInPlace(re,im);for(let k=0;k<=half;k+=1)mag[k]=Math.hypot(re[k],im[k]);if(history[frames%F0_MEDIAN]=frameF0(mag,a,sampleRate,acRe,acIm),frames+=1,st===0)fftInPlace(re,im,!0);else{let m=Math.min(frames,F0_MEDIAN);for(let i=0;i<m;i+=1)sorted[i]=history[i];for(let i=1;i<m;i+=1)for(let j=i;j>0&&sorted[j-1]>sorted[j];j-=1){let tmp=sorted[j];sorted[j]=sorted[j-1],sorted[j-1]=tmp}let f0=sorted[m>>1],seconds2=f0>0?Math.min(LIFTER_MAX_SECONDS,Math.max(LIFTER_MIN_SECONDS,LIFTER_PERIODS/f0)):LIFTER_MIN_SECONDS,lifter=Math.max(4,Math.round(seconds2*sampleRate));cepstralEnvelope(mag,n2,lifter,env,scratch);let ratio2=2**(-st/12);for(let k=0;k<=half;k+=1){let source=k*ratio2,i0=Math.floor(source),f=source-i0,e=i0>=half?env[half]:env[i0]+(env[Math.min(half,i0+1)]-env[i0])*f,g=Math.min(MAX_GAIN,Math.max(1/MAX_GAIN,e/Math.max(env[k],1e-12)));re[k]=re[k]*g,im[k]=im[k]*g,k>0&&k<half&&(re[n2-k]=re[k],im[n2-k]=-im[k])}fftInPlace(re,im,!0)}for(let i=0;i<n2;i+=1){let j=start+i;j>=0&&j<x.length&&(out[j]=out[j]+re[i]/n2*win[i]*ola)}}let mix3=options.mix??1;if(typeof mix3=="function")for(let i=0;i<x.length;i+=1)out[i]=x[i]+(out[i]-x[i])*mix3(i);else if(mix3<1)for(let i=0;i<x.length;i+=1)out[i]=x[i]+(out[i]-x[i])*mix3;return out}function applyFormant(buffer,track2,values,context){let read=fxReader(track2,"formant",values,context),shift=read.param("shift"),mix3=read.param("mix");if(!shift.automated&&shift.fallback===0||!mix3.automated&&mix3.fallback<=0)return;let origin=context.seedSeconds?Math.round(context.seedSeconds*context.sampleRate):0,out=formantShift(buffer,context.sampleRate,shift.automated?index=>shift.at(index):shift.fallback,{origin,mix:mix3.automated?index=>mix3.at(index):mix3.fallback});buffer.set(out)}var PHASER_STAGES=4,PHASER_FEEDBACK=.3;function applyPhaser(left,right,track2,values,context){let read=fxReader(track2,"phaser",values,context),rate2=read.param("rate"),depth=read.param("depth"),sync2=read.number("sync"),center=read.number("center"),sweep=read.number("sweep"),{sampleRate}=context,states=[new Float64Array(PHASER_STAGES),new Float64Array(PHASER_STAGES)],feedback=[0,0],phasor=new Phasor(0),coefficient=0,amount=depth.at(0),channel=(side,input)=>{let state=states[side],signal=input+feedback[side]*PHASER_FEEDBACK;for(let stage=0;stage<PHASER_STAGES;stage+=1){let output2=coefficient*signal+state[stage];state[stage]=signal-coefficient*output2,signal=output2}return feedback[side]=signal,input*(1-amount/2)+signal*(amount/2)};for(let index=0;index<left.length;index+=1){if(index%32===0){phasor.setHz(lfoHz(sync2,rate2.at(index),tempoAtSample(context,index)),sampleRate),depth.automated&&(amount=depth.at(index));let frequency=clamp2(center+sweep/2*Math.sin(2*Math.PI*phasor.phase),20,sampleRate*.45),t=Math.tan(Math.PI*frequency/sampleRate);coefficient=(t-1)/(t+1)}phasor.next(),left[index]=channel(0,left[index]),right[index]=channel(1,right[index])}}var CHORUS_BASE_MS=12,CHORUS_SWING_MS=6;function applyChorus(left,right,track2,values,context){let read=fxReader(track2,"chorus",values,context),rate2=read.param("rate"),depth=read.param("depth"),mix3=read.param("mix"),{sampleRate}=context,size=Math.ceil((CHORUS_BASE_MS+CHORUS_SWING_MS)/1e3*sampleRate)+4,lines=[new Float64Array(size),new Float64Array(size)],phasor=new Phasor(0),base=CHORUS_BASE_MS/1e3*sampleRate,swing=CHORUS_SWING_MS/1e3*sampleRate,amount=depth.at(0),wet=mix3.at(0);for(let index=0;index<left.length;index+=1){index%32===0&&(phasor.setHz(rate2.at(index),sampleRate),depth.automated&&(amount=depth.at(index)),mix3.automated&&(wet=mix3.at(index)));let phase=phasor.next(),write=index%size;for(let side=0;side<2;side+=1){let buffer=side===0?left:right,line=lines[side],input=buffer[index];line[write]=input;let delay=base+swing*amount*.5*(1+Math.sin(2*Math.PI*(phase+side*.25))),delayed=readFractional(line,write,delay);buffer[index]=input*(1-wet)+delayed*wet}}}var LESLIE_BASE_MS=3,LESLIE_DOPPLER_MS=1.5,LESLIE_AM=.35;function applyLeslie(left,right,track2,values,context){let read=fxReader(track2,"leslie",values,context),rate2=read.param("rate"),mix3=read.param("mix"),size=read.number("size"),{sampleRate}=context,base=LESLIE_BASE_MS/1e3*sampleRate,doppler=LESLIE_DOPPLER_MS/1e3*sampleRate*size,length=Math.ceil(base+doppler)+4,line=new Float64Array(length),phasor=new Phasor(0),wet=mix3.at(0);for(let index=0;index<left.length;index+=1){index%32===0&&(phasor.setHz(rate2.at(index),sampleRate),mix3.automated&&(wet=mix3.at(index)));let angle=2*Math.PI*phasor.next(),write=index%length,dryL=left[index],dryR=right[index];line[write]=(dryL+dryR)/2;let sin=Math.sin(angle),cos=Math.cos(angle),hornL=readFractional(line,write,base+doppler*.5*(1+sin)),hornR=readFractional(line,write,base+doppler*.5*(1-sin)),wetL=hornL*(1+LESLIE_AM*cos),wetR=hornR*(1-LESLIE_AM*cos);left[index]=dryL*(1-wet)+wetL*wet,right[index]=dryR*(1-wet)+wetR*wet}}function clamp9(x,lo,hi){return x<lo?lo:x>hi?hi:x}function dbToGain2(db2){return 10**(db2/20)}var Rbj=class{b0=1;b1=0;b2=0;a1=0;a2=0;z1=0;z2=0;constructor(type,hz3,q3,sr,db2=0){this.set(type,hz3,q3,sr,db2)}set(type,hz3,q3,sr,db2=0){let w=2*Math.PI*clamp9(hz3,10,sr*.49)/sr,cw=Math.cos(w),alpha=Math.sin(w)/(2*q3),A=10**(db2/40),b0,b1,b2,a0,a1,a2;switch(type){case"lpf":b0=(1-cw)/2,b1=1-cw,b2=b0,a0=1+alpha,a1=-2*cw,a2=1-alpha;break;case"hpf":b0=(1+cw)/2,b1=-(1+cw),b2=b0,a0=1+alpha,a1=-2*cw,a2=1-alpha;break;case"peak":b0=1+alpha*A,b1=-2*cw,b2=1-alpha*A,a0=1+alpha/A,a1=-2*cw,a2=1-alpha/A;break;case"lowshelf":{let s=2*Math.sqrt(A)*alpha;b0=A*(A+1-(A-1)*cw+s),b1=2*A*(A-1-(A+1)*cw),b2=A*(A+1-(A-1)*cw-s),a0=A+1+(A-1)*cw+s,a1=-2*(A-1+(A+1)*cw),a2=A+1+(A-1)*cw-s;break}case"highshelf":{let s=2*Math.sqrt(A)*alpha;b0=A*(A+1+(A-1)*cw+s),b1=-2*A*(A-1+(A+1)*cw),b2=A*(A+1+(A-1)*cw-s),a0=A+1-(A-1)*cw+s,a1=2*(A-1-(A+1)*cw),a2=A+1-(A-1)*cw-s;break}}this.b0=b0/a0,this.b1=b1/a0,this.b2=b2/a0,this.a1=a1/a0,this.a2=a2/a0}process(x){let y=this.b0*x+this.z1;return this.z1=this.b1*x-this.a1*y+this.z2,this.z2=this.b2*x-this.a2*y,y}},Lp12=class{p=0;y=0;constructor(hz3,sr){this.set(hz3,sr)}set(hz3,sr){this.p=Math.exp(-2*Math.PI*clamp9(hz3,1,sr*.49)/sr)}process(x){return this.y=x+this.p*(this.y-x),this.y}},Hp12=class{p=0;x1=0;y1=0;constructor(hz3,sr){this.p=Math.exp(-2*Math.PI*clamp9(hz3,1,sr*.49)/sr)}process(x){let y=(1+this.p)/2*(x-this.x1)+this.p*this.y1;return this.x1=x,this.y1=y,y}},Dc=class{r;x1=0;y1=0;constructor(sr,hz3){this.r=Math.exp(-2*Math.PI*hz3/sr)}process(x){let y=x-this.x1+this.r*this.y1;return this.x1=x,this.y1=y,y}};var CABS={"1x12":{hp:75,low:[115,1.4,3],peaks:[[2100,2,3],[3600,3,2]],lp:5200},"2x12":{hp:70,low:[105,1.3,3.5],peaks:[[1200,1.5,-2],[2800,2.2,4.5]],lp:6200},"4x12":{hp:65,low:[95,1.2,5],peaks:[[700,1,-2.5],[2400,2,4],[3900,3,2]],lp:4700},"1x10":{hp:120,low:[160,1.5,2],peaks:[[1500,1.5,3]],lp:4300},open:{hp:90,low:[120,.9,1],peaks:[[2500,1.2,2]],lp:7e3},"8x10":{hp:45,low:[80,1,3],peaks:[[800,1.2,-2],[2500,2,3]],lp:4500},"1x15":{hp:40,low:[70,1.2,4],peaks:[[1e3,1,-1.5],[2e3,1.5,2]],lp:3500},di:{hp:20,low:[100,.7,0],peaks:[],lp:0}};function cabFilters(type,mic,sr){let m=CABS[type]??CABS["2x12"];if(m.lp===0)return[new Rbj("hpf",m.hp,.707,sr)];let edge=clamp9(mic,0,1);return[new Rbj("hpf",m.hp,.707,sr),new Rbj("peak",m.low[0],m.low[1],sr,m.low[2]),...m.peaks.map(([f,q3,db2])=>new Rbj("peak",f,q3,sr,db2*(1-.6*edge))),new Rbj("highshelf",3e3,.7,sr,2-8*edge),new Rbj("lpf",m.lp*(1-.3*edge),.54,sr),new Rbj("lpf",m.lp*(1-.3*edge),1.31,sr)]}function applyGate2(buffer,thresholdDb,sampleRate){let open=10**(thresholdDb/20),close=10**((thresholdDb-6)/20),peakRelease=Math.exp(-1/(.01*sampleRate)),attack=1-Math.exp(-1/(.001*sampleRate)),release=1-Math.exp(-1/(.08*sampleRate)),holdSamples2=Math.round(.05*sampleRate),peak=0,gain=0,isOpen=!1,hold=0;for(let i=0;i<buffer.length;i+=1){let x=buffer[i],level2=Math.abs(x);peak=level2>peak?level2:peak*peakRelease,peak>=open?(isOpen=!0,hold=holdSamples2):peak<close&&(hold>0?hold-=1:isOpen=!1);let target=isOpen?1:0;gain+=(target-gain)*(target>gain?attack:release),buffer[i]=x*gain}}function sectionFactor(sampleRate){return sampleRate<=32e3?4:2}function oversampler(factor){return factor===4?new Oversample4x:new Oversample2x}var latencies=new Map;function sectionLatency(factor){let known=latencies.get(factor);if(known!==void 0)return known;let os=oversampler(factor),peak=0,at3=0;for(let i=0;i<256;i+=1){let y=Math.abs(os.process(i===0?1:0,x=>x));y>peak&&(peak=y,at3=i)}return latencies.set(factor,at3),at3}function runSection(buffer,factor,fn,control){let os=oversampler(factor),latency=sectionLatency(factor),n2=buffer.length;for(let i=0;i<n2+latency;i+=1){control&&i<n2&&control(i);let y=os.process(i<n2?buffer[i]:0,fn);i>=latency&&(buffer[i-latency]=y)}}var ASYM_B=.35,ASYM_T=Math.tanh(ASYM_B),asymF=x=>Math.tanh(x+ASYM_B)-ASYM_T,asymAF=x=>logCosh(x+ASYM_B)-ASYM_T*x,adaaTanh=()=>new Adaa1(Math.tanh,logCosh),adaaTriode=()=>new Adaa1(asymF,asymAF),adaaRectify=()=>new Adaa1(x=>Math.abs(x),x=>.5*x*Math.abs(x)),ratClip=x=>Math.tanh(x+.18*x*x*x);var STACKS={fender:{C1:25e-11,C2:2e-8,C3:2e-8,R1:25e4,R2:1e6,R3:25e3,R4:56e3},marshall:{C1:47e-11,C2:22e-9,C3:22e-9,R1:22e4,R2:1e6,R3:22e3,R4:33e3},vox:{C1:1e-10,C2:47e-9,C3:22e-9,R1:22e4,R2:1e6,R3:1e4,R4:1e5}};function stackAnalog(v,t,m,l){let{C1,C2,C3,R1,R2,R3,R4}=v,b1=t*C1*R1+m*C3*R3+l*(C1*R2+C2*R2)+(C1*R3+C2*R3),b2=t*(C1*C2*R1*R4+C1*C3*R1*R4)-m*m*(C1*C3*R3*R3+C2*C3*R3*R3)+m*(C1*C3*R1*R3+C1*C3*R3*R3+C2*C3*R3*R3)+l*(C1*C2*R1*R2+C1*C2*R2*R4+C1*C3*R2*R4)+l*m*(C1*C3*R2*R3+C2*C3*R2*R3)+(C1*C2*R1*R3+C1*C2*R3*R4+C1*C3*R3*R4),b3=l*m*(C1*C2*C3*R1*R2*R3+C1*C2*C3*R2*R3*R4)-m*m*(C1*C2*C3*R1*R3*R3+C1*C2*C3*R3*R3*R4)+m*(C1*C2*C3*R1*R3*R3+C1*C2*C3*R3*R3*R4)+t*C1*C2*C3*R1*R3*R4-t*m*C1*C2*C3*R1*R3*R4+t*l*C1*C2*C3*R1*R2*R4,a1=C1*R1+C1*R3+C2*R3+C2*R4+C3*R4+m*C3*R3+l*(C1*R2+C2*R2),a2=m*(C1*C3*R1*R3-C2*C3*R3*R4+C1*C3*R3*R3+C2*C3*R3*R3)+l*m*(C1*C3*R2*R3+C2*C3*R2*R3)-m*m*(C1*C3*R3*R3+C2*C3*R3*R3)+l*(C1*C2*R2*R4+C1*C2*R1*R2+C1*C3*R2*R4+C2*C3*R2*R4)+(C1*C2*R1*R4+C1*C3*R1*R4+C1*C2*R3*R4+C1*C2*R1*R3+C1*C3*R3*R4+C2*C3*R3*R4),a3=l*m*(C1*C2*C3*R1*R2*R3+C1*C2*C3*R2*R3*R4)-m*m*(C1*C2*C3*R1*R3*R3+C1*C2*C3*R3*R3*R4)+m*(C1*C2*C3*R3*R3*R4+C1*C2*C3*R1*R3*R3-C1*C2*C3*R1*R3*R4)+l*C1*C2*C3*R1*R2*R4+C1*C2*C3*R1*R3*R4;return{b:[0,b1,b2,b3],a:[1,a1,a2,a3]}}var ToneStack=class{constructor(values,t,m,l,sr){this.values=values;this.sr=sr;this.set(t,m,l)}values;sr;b=[0,0,0,0];a=[1,0,0,0];z0=0;z1=0;z2=0;set(t,m,l){let{b,a}=stackAnalog(this.values,clamp9(t,0,1),clamp9(m,0,1),clamp9(l,0,1)),c=2*this.sr,c2=c*c,c3=c2*c,B0=-b[1]*c-b[2]*c2-b[3]*c3,B1=-b[1]*c+b[2]*c2+3*b[3]*c3,B2=b[1]*c+b[2]*c2-3*b[3]*c3,B3=b[1]*c-b[2]*c2+b[3]*c3,A0=-1-a[1]*c-a[2]*c2-a[3]*c3,A1=-3-a[1]*c+a[2]*c2+3*a[3]*c3,A2=-3+a[1]*c+a[2]*c2-3*a[3]*c3,A3=-1+a[1]*c-a[2]*c2+a[3]*c3;this.b=[B0/A0,B1/A0,B2/A0,B3/A0],this.a=[1,A1/A0,A2/A0,A3/A0]}process(x){let{b,a}=this,y=b[0]*x+this.z0;return this.z0=b[1]*x-a[1]*y+this.z1,this.z1=b[2]*x-a[2]*y+this.z2,this.z2=b[3]*x-a[3]*y,y}},audioTaper=k=>k<=0?0:(10**(2*clamp9(k,0,1))-1)/99,HEADS={clean:{stages:1,stack:"fender",stageGain:6,miller:9e3,coupling:20,bright:4,power:.6,sag:.2},chime:{stages:2,stack:"vox",stageGain:5,miller:8e3,coupling:60,bright:3,power:1.4,sag:.45},crunch:{stages:2,stack:"marshall",stageGain:14,miller:7e3,coupling:80,bright:2,power:1,sag:.3},lead:{stages:3,stack:"marshall",stageGain:18,miller:6500,coupling:120,bright:1,power:1,sag:.25},high:{stages:4,stack:"marshall",stageGain:20,miller:6e3,coupling:160,bright:0,power:1.2,sag:.2},solid:{stages:1,stack:"fender",stageGain:3,miller:12e3,coupling:20,bright:2,power:.4,sag:0,symmetric:!0},bass:{stages:2,stack:"fender",stageGain:8,miller:5e3,coupling:15,bright:0,power:1,sag:.35}},HeadCircuit=class{constructor(settings,sr,factor){this.sr=sr;this.model=HEADS[settings.type]??HEADS.crunch,this.control=32*factor,this.inHp=new Hp12(30,sr),this.bright=new Rbj("highshelf",2500,.7,sr,0);for(let s=0;s<this.model.stages;s+=1)this.stages.push({pre:1,shaper:this.model.symmetric?adaaTanh():adaaTriode(),hp:new Hp12(s===0?20:this.model.coupling,sr),lp:new Lp12(this.model.miller,sr)});this.stack=new ToneStack(STACKS[this.model.stack],.5,.5,.5,sr),this.presence=new Rbj("highshelf",3200,.7,sr,0),this.env=new Lp12(6,sr),this.dc=new Dc(sr,10),this.set(settings),this.setTone(settings)}sr;model;inHp;bright;stages=[];stack;power=adaaTanh();presence;env;dc;drive=1;sagAmount=0;headroom=1;envLevel=0;count=0;control;set(p){let model=this.model,g=clamp9(p.gain/10,0,1);this.bright.set("highshelf",2500,.7,this.sr,model.bright*(1-g));for(let s=0;s<this.stages.length;s+=1)this.stages[s].pre=s===0?.6+model.stageGain*g*g*1.6:model.stageGain*(.3+.7*g);this.drive=model.power*(.25+.18*clamp9(p.master,0,10)),this.sagAmount=clamp9(p.sag??model.sag,0,1)}setTone(p){this.stack.set(clamp9(p.treble/10,0,1),clamp9(p.mid/10,0,1),audioTaper(p.bass/10)),this.presence.set("highshelf",3200,.7,this.sr,(clamp9(p.presence,0,10)-5)*1.6)}process(input){let x=this.bright.process(this.inHp.process(input)),stages=this.stages;for(let s=0;s<stages.length;s+=1){let st=stages[s];x=st.lp.process(st.shaper.process(st.hp.process(x)*st.pre)),x=-x}x=this.stack.process(x)*4.5,this.count%this.control===0&&(this.headroom=1/(1+2.5*this.sagAmount*this.envLevel)),this.count+=1;let u=this.power.process(x*this.drive/this.headroom)*this.headroom;return this.envLevel=this.env.process(Math.abs(u)),this.dc.process(this.presence.process(u))*.5}},CALIBRATION_HZ=196,CALIBRATION_DBFS=-30,makeups2=new Map;function headMakeup(settings,sampleRate,factor){let key=`${sampleRate}|${factor}|${settings.type}|${settings.gain}|${settings.bass}|${settings.mid}|${settings.treble}|${settings.presence}|${settings.master}|${settings.sag??""}`,known=makeups2.get(key);if(known!==void 0)return known;let amplitude=10**(CALIBRATION_DBFS/20)*Math.SQRT2,settle=Math.round(sampleRate*.1),length=settle+Math.round(sampleRate*.1),buffer=new Float64Array(length),w=2*Math.PI*CALIBRATION_HZ/sampleRate;for(let i=0;i<length;i+=1)buffer[i]=amplitude*Math.sin(w*i);let head=new HeadCircuit(settings,sampleRate*factor,factor);runSection(buffer,factor,x=>head.process(x));let sum=0;for(let i=settle;i<length;i+=1)sum+=buffer[i]*buffer[i];let rms=Math.sqrt(sum/(length-settle)),target=10**(CALIBRATION_DBFS/20),makeup=rms>1e-12?target/rms:1;return makeups2.set(key,makeup),makeups2.size>4096&&makeups2.delete(makeups2.keys().next().value),makeup}var GRID2=11,grids=new Map;function headMakeupAt(settings,sampleRate,factor){let key=`${sampleRate}|${factor}|${settings.type}|${settings.bass}|${settings.mid}|${settings.treble}|${settings.presence}|${settings.sag??""}`,grid2=grids.get(key);grid2||(grid2=new Float64Array(GRID2*GRID2).fill(Number.NaN),grids.set(key,grid2),grids.size>256&&grids.delete(grids.keys().next().value));let g=clamp9(settings.gain,0,10),m=clamp9(settings.master,0,10),g0=Math.min(GRID2-2,Math.floor(g)),m0=Math.min(GRID2-2,Math.floor(m)),point=(gi,mi)=>{let at3=gi*GRID2+mi,value=grid2[at3];return Number.isNaN(value)&&(value=headMakeup({...settings,gain:gi,master:mi},sampleRate,factor),grid2[at3]=value),value},fg=g-g0,fm=m-m0,a=point(g0,m0)+(point(g0,m0+1)-point(g0,m0))*fm,b=point(g0+1,m0)+(point(g0+1,m0+1)-point(g0+1,m0))*fm;return a+(b-a)*fg}function stompCircuit(type,initial,sr){switch(type){case"fuzz":return fuzz(initial,sr);case"face":return face(initial,sr);case"rat":return rat(initial,sr);case"octave":return octave(initial,sr);default:return od(initial,sr)}}function fuzz(initial,sr){let hp=new Hp12(90,sr),s1=adaaTanh(),s2=adaaTanh(),lpA=new Lp12(3200,sr),hpB=new Hp12(60,sr),lpB=new Lp12(2600,sr),toneLp=new Lp12(800,sr),toneHp=new Hp12(1600,sr),pre=1,tone=.5,out=1,set=p=>{pre=2**(.5+.55*p.gain),tone=clamp9(p.tone,0,1),out=dbToGain2(p.level)*.7};return set(initial),{set,process(input){let x=hp.process(input)*pre;return x=lpA.process(s1.process(x))*6,x=lpB.process(s2.process(hpB.process(x))),((1-tone)*toneLp.process(x)+tone*toneHp.process(x)*1.6)*out}}}function face(initial,sr){let hp=new Hp12(40,sr),s=adaaTriode(),dc=new Dc(sr,12),lp2=new Lp12(2500,sr),pre=1,out=1,set=p=>{pre=2**(.3+.5*p.gain),lp2.set(2500+4e3*clamp9(p.tone,0,1),sr),out=dbToGain2(p.level)*.8};return set(initial),{set,process(input){return lp2.process(dc.process(s.process(hp.process(input)*pre)))*out}}}function od(initial,sr){let hp=new Hp12(720,sr),lpGain=new Lp12(5600,sr),s=adaaTanh(),tone=new Lp12(700,sr),pre=1,out=1,set=p=>{pre=1+10**(p.gain/5),tone.set(700*2**(3*clamp9(p.tone,0,1)),sr),out=dbToGain2(p.level)*.6};return set(initial),{set,process(x){let y=x+s.process(lpGain.process(hp.process(x)*pre))*.5;return tone.process(y)*out}}}function rat(initial,sr){let hp=new Hp12(60,sr),lpOp=new Lp12(2e4,sr),filter=new Lp12(475,sr),gain=1,out=1,set=p=>{gain=Math.min(1+2**(.67*p.gain+1.5),2e3),lpOp.set(clamp9(1e6/3/gain,900,2e4),sr),filter.set(475*2**(6*clamp9(p.tone,0,1)),sr),out=dbToGain2(p.level)*.55};return set(initial),{set,process(input){let x=lpOp.process(hp.process(input)*gain*.02);return filter.process(ratClip(x))*out}}}function octave(initial,sr){let hp=new Hp12(120,sr),rect=adaaRectify(),dc=new Dc(sr,20),s=adaaTanh(),lp2=new Lp12(3e3,sr),pre=1,mix3=.7,out=1,set=p=>{pre=2**(.5+.5*p.gain),lp2.set(3e3+4e3*clamp9(p.tone,0,1),sr),mix3=clamp9(p.octave,0,1),out=dbToGain2(p.level)*.7};return set(initial),{set,process(input){let x=hp.process(input),o=dc.process(rect.process(x*2))*2;return lp2.process(s.process(((1-mix3)*x+mix3*o)*pre))*out}}}var STOMP_CALIBRATION_DBFS=-18,stompMakeups=new Map;function stompMakeup(type,settings,sampleRate,factor){let key=`${sampleRate}|${factor}|${type}|${settings.gain}|${settings.tone}|${settings.octave}`,known=stompMakeups.get(key);if(known!==void 0)return known;let amplitude=10**(STOMP_CALIBRATION_DBFS/20)*Math.SQRT2,settle=Math.round(sampleRate*.1),length=settle+Math.round(sampleRate*.1),buffer=new Float64Array(length),w=2*Math.PI*196/sampleRate;for(let i=0;i<length;i+=1)buffer[i]=amplitude*Math.sin(w*i);let circuit=stompCircuit(type,{...settings,level:0},sampleRate*factor);runSection(buffer,factor,x=>circuit.process(x));let sum=0;for(let i=settle;i<length;i+=1)sum+=buffer[i]*buffer[i];let rms=Math.sqrt(sum/(length-settle)),target=10**(STOMP_CALIBRATION_DBFS/20),makeup=rms>1e-12?target/rms:1;return stompMakeups.set(key,makeup),stompMakeups.size>4096&&stompMakeups.delete(stompMakeups.keys().next().value),makeup}function stompMakeupAt(type,settings,sampleRate,factor){let g=clamp9(settings.gain,0,10),g0=Math.min(9,Math.floor(g)),at3=gain=>stompMakeup(type,{...settings,gain},sampleRate,factor),a=at3(g0);return a+(at3(g0+1)-a)*(g-g0)}function blend(buffer,dry,mix3){for(let i=0;i<buffer.length;i+=1){let wet=clamp9(mix3(i),0,1);wet<1&&(buffer[i]=dry[i]+(buffer[i]-dry[i])*wet)}}function applyStomp(buffer,track2,values,context){let read=fxReader(track2,"stomp",values,context),gain=read.param("gain"),tone=read.param("tone"),mix3=read.param("mix"),settings={gain:gain.at(0),tone:tone.at(0),level:read.number("level"),octave:read.number("octave")},factor=sectionFactor(context.sampleRate),circuit=stompCircuit(read.text("type"),settings,context.sampleRate*factor),dry=mix3.automated||mix3.at(0)<1?Float64Array.from(buffer):void 0,automated=gain.automated||tone.automated,type=read.text("type"),blocks=automated?new Float64Array(Math.ceil(buffer.length/32)+1):void 0;if(runSection(buffer,factor,x=>circuit.process(x),blocks?i=>{i%32===0&&(settings.gain=gain.at(i),settings.tone=tone.at(i),circuit.set(settings),blocks[i/32]=stompMakeupAt(type,settings,context.sampleRate,factor))}:void 0),blocks)for(let i=0;i<buffer.length;i+=1)buffer[i]=buffer[i]*blocks[Math.floor(i/32)];else{let makeup=stompMakeup(type,settings,context.sampleRate,factor);for(let i=0;i<buffer.length;i+=1)buffer[i]=buffer[i]*makeup}dry&&blend(buffer,dry,i=>mix3.at(i))}function applyHead(buffer,track2,values,context){let read=fxReader(track2,"head",values,context),sr=context.sampleRate,gain=read.param("gain"),master=read.param("master"),gate=values.gate;gate!==void 0&&applyGate2(buffer,gate,sr);let sag=values.sag,settings={type:read.text("type"),gain:gain.at(0),bass:read.number("bass"),mid:read.number("mid"),treble:read.number("treble"),presence:read.number("presence"),master:master.at(0),...sag===void 0?{}:{sag}},factor=sectionFactor(sr),level2=dbToGain2(read.number("level")),head=new HeadCircuit(settings,sr*factor,factor);if(!(gain.automated||master.automated)){let makeup=headMakeup(settings,sr,factor)*level2;runSection(buffer,factor,x=>head.process(x));for(let i=0;i<buffer.length;i+=1)buffer[i]=buffer[i]*makeup;return}let blocks=new Float64Array(Math.ceil(buffer.length/32)+1);runSection(buffer,factor,x=>head.process(x),i=>{i%32===0&&(settings.gain=gain.at(i),settings.master=master.at(i),head.set(settings),blocks[i/32]=headMakeupAt(settings,sr,factor)*level2)});for(let i=0;i<buffer.length;i+=1)buffer[i]=buffer[i]*blocks[Math.floor(i/32)]}function applyCab(buffer,track2,values,context){let read=fxReader(track2,"cab",values,context),mix3=read.param("mix"),chain=cabFilters(read.text("type"),read.number("mic"),context.sampleRate),constant3=mix3.automated?void 0:clamp9(mix3.at(0),0,1);for(let i=0;i<buffer.length;i+=1){let dry=buffer[i],x=dry;for(let filter of chain)x=filter.process(x);let wet=constant3??clamp9(mix3.at(i),0,1);buffer[i]=wet===1?x:dry+(x-dry)*wet}}function delaySeconds(track2,tempoBpm){let delay=track2.delay;return delay?delay.time!==void 0&&delay.time>0?delay.time:delay.beats*60/tempoBpm:0}function applyDelay(left,right,track2,context,wetOnly=!1){let delay=track2.delay;if(!delay)return;let feedbackLane=track2.delayFeedbackAutomation??[],mixLane=track2.delayMixAutomation??[];if(delay.mix<=0&&mixLane.length===0)return;let{sampleRate}=context,synced=!(delay.time!==void 0&&delay.time>0);if(context.warp&&synced){applyWarpedDelay(left,right,track2,context,wetOnly);return}let length=Math.max(1,Math.round(delaySeconds(track2,context.tempoBpm)*sampleRate)),lineL=new Float64Array(length),lineR=new Float64Array(length),feedback=delay.feedback,mix3=delay.mix,automated=feedbackLane.length>0||mixLane.length>0,pingpong=delay.pingpong===!0,highcut=delay.highcut===void 0?void 0:[new OnePole(delay.highcut,sampleRate),new OnePole(delay.highcut,sampleRate)];for(let index=0;index<left.length;index+=1){if(automated&&index%32===0){let tick=tickAtSample(context,index);feedback=interpolateAutomation(feedbackLane,tick,delay.feedback),mix3=interpolateAutomation(mixLane,tick,delay.mix)}let slot=index%length,wetL=lineL[slot],wetR=lineR[slot],dryL=left[index],dryR=right[index],writeL,writeR;pingpong?(writeL=(dryL+dryR)*.5+wetR*feedback,writeR=wetL*feedback):(writeL=dryL+wetR*feedback,writeR=dryR+wetL*feedback),highcut&&(writeL=highcut[0].process(writeL),writeR=highcut[1].process(writeR)),lineL[slot]=writeL,lineR[slot]=writeR,left[index]=(wetOnly?0:dryL)+wetL*mix3,right[index]=(wetOnly?0:dryR)+wetR*mix3}}function applyWarpedDelay(left,right,track2,context,wetOnly){let delay=track2.delay,warp2=context.warp,{sampleRate}=context,feedbackLane=track2.delayFeedbackAutomation??[],mixLane=track2.delayMixAutomation??[],ticksPerBeat=Math.round(sampleRate*60/(context.tempoBpm*context.samplesPerTick)),lag=delay.beats*ticksPerBeat,lagAt=index=>Math.max(2,index-warp2.sample(warp2.tick(index)-lag)),longest=1;for(let index=0;index<=left.length;index+=32)longest=Math.max(longest,lagAt(index));let size=Math.ceil(longest)+2,lineL=new Float64Array(size),lineR=new Float64Array(size),pingpong=delay.pingpong===!0,highcut=delay.highcut===void 0?void 0:[new OnePole(delay.highcut,sampleRate),new OnePole(delay.highcut,sampleRate)],feedback=delay.feedback,mix3=delay.mix,lagNow=lagAt(0),lagStep=0;for(let index=0;index<left.length;index+=1){if(index%32===0){let tick=tickAtSample(context,index);feedback=interpolateAutomation(feedbackLane,tick,delay.feedback),mix3=interpolateAutomation(mixLane,tick,delay.mix),lagNow=lagAt(index),lagStep=(lagAt(index+32)-lagNow)/32}else lagNow+=lagStep;let read=index-Math.min(size-2,lagNow),base=Math.floor(read),fraction=read-base,at3=(line,position)=>position<0?0:line[position%size],wetL=at3(lineL,base)*(1-fraction)+at3(lineL,base+1)*fraction,wetR=at3(lineR,base)*(1-fraction)+at3(lineR,base+1)*fraction,dryL=left[index],dryR=right[index],writeL,writeR;pingpong?(writeL=(dryL+dryR)*.5+wetR*feedback,writeR=wetL*feedback):(writeL=dryL+wetR*feedback,writeR=dryR+wetL*feedback),highcut&&(writeL=highcut[0].process(writeL),writeR=highcut[1].process(writeR)),lineL[index%size]=writeL,lineR[index%size]=writeR,left[index]=(wetOnly?0:dryL)+wetL*mix3,right[index]=(wetOnly?0:dryR)+wetR*mix3}}function delayTailFor(track2,tempoBpm){if(!track2.delay)return 0;let feedback=Math.max(track2.delay.feedback,...(track2.delayFeedbackAutomation??[]).map(point=>point.value)),repeats=feedback<=.001?1:Math.min(64,Math.log(.001)/Math.log(feedback));return delaySeconds(track2,tempoBpm)*(repeats+1)}var COMB_TUNING=[1116,1188,1277,1356,1422,1491,1557,1617],ALLPASS_TUNING=[556,441,341,225],STEREO_SPREAD=23,REVERB_INPUT_GAIN=.015,REVERB_WET_SCALE=3,IR_WET_SCALE=2.1,SAMPLE_IMPULSES=new Map,MAX_SAMPLE_IMPULSES=8;function reverbImpulse(track2,sampleRate,irs){let ir=track2.reverb?.ir;if(!ir)return;if(ir.src.startsWith("builtin:"))return builtinImpulse(ir.src.slice(8),sampleRate);let sample=irs?.get(track2.id);if(!sample)return;let key=`${sample.sha256}@${sampleRate}`,impulse=SAMPLE_IMPULSES.get(key);return impulse||(impulse=sampleImpulse(`${ir.src}#${sample.sha256}`,sample.mono,sample.sampleRate,sampleRate),SAMPLE_IMPULSES.size>=MAX_SAMPLE_IMPULSES&&SAMPLE_IMPULSES.delete(SAMPLE_IMPULSES.keys().next().value),SAMPLE_IMPULSES.set(key,impulse)),impulse}function reverbTailFor(track2,sampleRate=44100,irs){let reverb=track2.reverb,lane=track2.fxAutomation?.["reverb-mix"]??[];if(!reverb||reverb.mix<=0&&lane.length===0)return 0;let impulse=reverbImpulse(track2,sampleRate,irs),decay=impulse?impulse.left.length/sampleRate:reverb.fade??1+3*reverb.size;return Math.min(20,decay+(reverb.predelay??0))}function applyReverb(left,right,track2,context,wetOnly=!1){let wet=reverbWet(left,right,track2,context);wet&&addReverbWet(left,right,wet,track2,context,wetOnly)}function mixParamOf(track2,context){return new Param(track2.reverb?.mix??0,track2.fxAutomation?.["reverb-mix"],context.samplesPerTick,context.warp)}function reverbActive(track2){let reverb=track2.reverb;return reverb?reverb.mix>0||(track2.fxAutomation?.["reverb-mix"]??[]).length>0:!1}function reverbWet(left,right,track2,context){let reverb=track2.reverb;if(!reverb||!reverbActive(track2))return;let{sampleRate}=context,impulse=reverbImpulse(track2,sampleRate,context.irs);return impulse?convolutionWet(left,right,track2,context,impulse):algorithmicReverbWet(left,right,reverb,sampleRate,context.reverbKernel?.())}function algorithmicReverbWet(left,right,reverb,sampleRate,kernel2){if(kernel2&&left.length===right.length){let wet=nativeAlgorithmicReverb(left,right,reverb,sampleRate,kernel2);if(wet)return wet}let scale3=sampleRate/44100,sizeFeedback=.7+.28*reverb.size,damp=reverb.dim===void 0?.2+.3*reverb.size:Math.exp(-2*Math.PI*Math.min(reverb.dim,sampleRate*.45)/sampleRate),channel=spread=>({combs:COMB_TUNING.map(tuning=>{let length=Math.max(1,Math.round((tuning+spread)*scale3));return{buffer:new Float64Array(length),index:0,store:0,feedback:reverb.fade===void 0?sizeFeedback:Math.min(.995,10**(-3*length/sampleRate/reverb.fade))}}),allpasses:ALLPASS_TUNING.map(tuning=>({buffer:new Float64Array(Math.max(1,Math.round((tuning+spread)*scale3))),index:0}))}),sides=[channel(0),channel(STEREO_SPREAD)],process2=(side,input)=>{let output2=0;for(let comb of side.combs){let delayed=comb.buffer[comb.index];comb.store=delayed*(1-damp)+comb.store*damp,comb.buffer[comb.index]=input+comb.store*comb.feedback,comb.index=comb.index+1===comb.buffer.length?0:comb.index+1,output2+=delayed}for(let allpass of side.allpasses){let delayed=allpass.buffer[allpass.index];allpass.buffer[allpass.index]=output2+delayed*.5,output2=delayed-output2,allpass.index=allpass.index+1===allpass.buffer.length?0:allpass.index+1}return output2},inputFilter=reverb.lowpass===void 0?void 0:new OnePole(reverb.lowpass,sampleRate),predelaySamples=Math.round((reverb.predelay??0)*sampleRate),predelay=predelaySamples>0?new Float64Array(predelaySamples):void 0,wetL=new Float64Array(left.length),wetR=new Float64Array(left.length);for(let index=0;index<left.length;index+=1){let input=(left[index]+right[index])*REVERB_INPUT_GAIN;if(inputFilter&&(input=inputFilter.process(input)),predelay){let slot=index%predelaySamples,delayed=predelay[slot];predelay[slot]=input,input=delayed}wetL[index]=process2(sides[0],input),wetR[index]=process2(sides[1],input)}return{left:wetL,right:wetR}}function nativeAlgorithmicReverb(left,right,reverb,sampleRate,kernel2){let scale3=sampleRate/44100,lengths=new Uint32Array(24),gains=new Float64Array(16),tuning=[...COMB_TUNING,...ALLPASS_TUNING];for(let side=0;side<2;side+=1)for(let j=0;j<12;j+=1){let length=Math.max(1,Math.round((tuning[j]+side*STEREO_SPREAD)*scale3));lengths[side*12+j]=length,j<8&&(gains[side*8+j]=reverb.fade===void 0?.7+.28*reverb.size:Math.min(.995,10**(-3*length/sampleRate/reverb.fade)))}let damp=reverb.dim===void 0?.2+.3*reverb.size:Math.exp(-2*Math.PI*Math.min(reverb.dim,sampleRate*.45)/sampleRate),filter=reverb.lowpass===void 0?void 0:new OnePole(reverb.lowpass,sampleRate),pre=Math.round((reverb.predelay??0)*sampleRate),delay=pre>0?new Float64Array(pre):void 0,input=new Float64Array(left.length);for(let i=0;i<input.length;i+=1){let value=(left[i]+right[i])*REVERB_INPUT_GAIN;if(filter&&(value=filter.process(value)),delay){let slot=i%pre,previous=delay[slot];delay[slot]=value,value=previous}input[i]=value}let wetL=new Float64Array(left.length),wetR=new Float64Array(left.length);return kernel2(input,wetL,wetR,lengths,gains,damp)?{left:wetL,right:wetR}:void 0}function centerGains(tail,center){if(!center)return[1,1];let el=0,er=0;for(let i=0;i<tail.left.length;i+=1)el+=tail.left[i]*tail.left[i],er+=tail.right[i]*tail.right[i];if(!(el>0&&er>0))return[1,1];let mean=(el+er)/2;return[(mean/el)**(center/2),(mean/er)**(center/2)]}function addReverbWet(left,right,tail,track2,context,wetOnly=!1){let mixParam=mixParamOf(track2,context);if(tail.scale!==void 0){if(wetOnly&&(left.fill(0),right.fill(0)),tail.scale===0)return;let wet2=mixParam.fallback*IR_WET_SCALE;addConvolved(tail.left,tail.right,tail.scale,left,right,wet2,mixParam.automated?index=>(index%32===0&&(wet2=mixParam.at(index)*IR_WET_SCALE),wet2):void 0);return}let wet=mixParam.fallback*REVERB_WET_SCALE,[gl,gr]=centerGains(tail,track2.reverb?.center);for(let index=0;index<left.length;index+=1)mixParam.automated&&index%32===0&&(wet=mixParam.at(index)*REVERB_WET_SCALE),wetOnly?(left[index]=tail.left[index]*wet*gl,right[index]=tail.right[index]*wet*gr):(left[index]+=tail.left[index]*wet*gl,right[index]+=tail.right[index]*wet*gr)}function convolutionWet(left,right,track2,context,impulse){let reverb=track2.reverb,{sampleRate}=context,input=new Float64Array(left.length),inputFilter=reverb.lowpass===void 0?void 0:new OnePole(reverb.lowpass,sampleRate),offset=Math.round((reverb.predelay??0)*sampleRate);for(let index=0;index+offset<left.length;index+=1){let value=(left[index]+right[index])*.5;inputFilter&&(value=inputFilter.process(value)),input[index+offset]=value}let wetL=new Float64Array(left.length),wetR=new Float64Array(left.length),scale3=convolveRaw(input,impulse,wetL,wetR);return{left:wetL,right:wetR,scale:scale3}}function needsEffectNotes(track2){return!!(track2?.fx?.bloom||track2?.fx?.swell)}var MONO=Object.freeze({djf:applyDjFilter,autofilter:applyAutoFilter,formant:applyFormant,vowel:applyVowel,crush:applyCrush,distort:applyDistort,stomp:applyStomp,head:applyHead,cab:applyCab,eq:applyEq2,wobble:applyWobble,bloom:applyBloom,swell:applySwell,tremolo:applyTremolo,gate:applyGate,compressor:applyCompressor}),STEREO=Object.freeze({double:applyDouble,phaser:applyPhaser,chorus:applyChorus,leslie:applyLeslie,postgain:applyPostgain}),PAN_INDEX=FX_CHAIN.indexOf("pan");function applyMonoChain(buffer,track2,context){for(let stage of FX_CHAIN.slice(0,PAN_INDEX)){if(stage==="filter"){applyTrackFilter(buffer,track2,context);continue}let values=track2.fx?.[stage],apply=MONO[stage];values&&apply&&apply(buffer,track2,values,context),stage==="distort"&&context.patchStage?.(buffer)}}function applyStereoChain(left,right,track2,context,sends=!0,reverb=sends){for(let stage of FX_CHAIN.slice(PAN_INDEX+1))if(stage==="delay")sends&&applyDelay(left,right,track2,context);else if(stage==="reverb")reverb&&applyReverb(left,right,track2,context);else{let values=track2.fx?.[stage],apply=STEREO[stage];values&&apply&&apply(left,right,track2,values,context)}}function sharedOrbitOf(track2){let orbit=track2?.fx?.orbit;return orbit?.shared===!0?Number(orbit.orbit):void 0}function createOrbitBus(orbit,samples){return{orbit,delayL:new Float64Array(samples),delayR:new Float64Array(samples),reverbL:new Float64Array(samples),reverbR:new Float64Array(samples),keys:[]}}function send(outL,outR,stemL,stemR,base,lane,context){if(base<=0&&lane.length===0)return;let level2=base;for(let index=0;index<outL.length;index+=1)lane.length>0&&index%32===0&&(level2=interpolateAutomation(lane,tickAtSample(context,index),base)),outL[index]+=stemL[index]*level2,outR[index]+=stemR[index]*level2}function sendToBus(bus,track2,stemL,stemR,context,key){bus.keys.push(key),track2.delay&&(bus.delayLead??=track2,send(bus.delayL,bus.delayR,stemL,stemR,track2.delay.mix,track2.delayMixAutomation??[],context)),track2.reverb&&(bus.reverbLead??=track2,send(bus.reverbL,bus.reverbR,stemL,stemR,track2.reverb.mix,track2.fxAutomation?.["reverb-mix"]??[],context))}function renderOrbitBus(bus,context){let left=new Float64Array(bus.delayL.length),right=new Float64Array(bus.delayL.length),lead=bus.delayLead;if(lead?.delay){let unity={...lead,delay:{...lead.delay,mix:1},delayMixAutomation:[]};applyDelay(bus.delayL,bus.delayR,unity,context,!0);for(let index=0;index<left.length;index+=1)left[index]+=bus.delayL[index],right[index]+=bus.delayR[index]}let room=bus.reverbLead;if(room?.reverb){let{"reverb-mix":_lane,...fxAutomation}=room.fxAutomation??{},unity={...room,reverb:{...room.reverb,mix:1},fxAutomation};applyReverb(bus.reverbL,bus.reverbR,unity,context,!0);for(let index=0;index<left.length;index+=1)left[index]+=bus.reverbL[index],right[index]+=bus.reverbR[index]}return{left,right}}function recovery(curve,p){return curve==="exp"?(1-p)**3:curve==="pump"?1-p*p:1-p}function orbitOf(track2){let orbit=track2?.fx?.orbit?.orbit;return typeof orbit=="number"?orbit:1}function duckSettings(track2,secondsPerBeat=.5){let duck=track2?.fx?.duck;if(!duck)return;let number=(key,fallback)=>typeof duck[key]=="number"?duck[key]:fallback,sync2=number("sync",0),curve=duck.curve;return{target:number("orbit",1),depth:number("depth",1),attack:sync2>0?sync2*secondsPerBeat:number("attack",.1),onset:number("onset",.003),...curve==="exp"||curve==="pump"?{curve}:{},hold:duck.hold===!0}}function duckEnvelope(ducker,samples,sampleRate,loopFrames2){let marks=new Uint8Array(samples),holds=ducker.ends?new Float64Array(samples):void 0,repeats=loopFrames2&&loopFrames2>0?Math.ceil(samples/loopFrames2):1;ducker.onsets.forEach((onset,which)=>{for(let pass2=0;pass2<repeats;pass2+=1){let shift=pass2*(loopFrames2??0),at3=onset+shift;at3<0||at3>=samples||(marks[at3]=1,holds&&(holds[at3]=Math.max(holds[at3],ducker.ends[which]+shift)))}});let envelope2=new Float64Array(samples),riseSamples=Math.max(1,ducker.onset*sampleRate),fallSamples=Math.max(1,ducker.attack*sampleRate),fallStep=1/fallSamples,curve=ducker.curve??"linear",level2=0,rising=!1,riseFrom=0,riseAt=0,heldTo=-1,fallFrom=0,fallAt=0;for(let index=0;index<samples;index+=1){if(marks[index]===1&&(rising=!0,riseFrom=level2,riseAt=0,holds&&(heldTo=Math.max(heldTo,holds[index]))),rising){riseAt+=1;let progress=Math.min(1,riseAt/riseSamples);level2=riseFrom+(1-riseFrom)*progress,progress>=1&&(rising=!1),fallFrom=level2,fallAt=0}else if(index<heldTo)level2=1,fallFrom=1,fallAt=0;else if(level2>0)if(curve==="linear")level2=Math.max(0,level2-fallStep);else{fallAt+=1;let p=Math.min(1,fallAt/(fallSamples*fallFrom));level2=fallFrom*recovery(curve,p)}envelope2[index]=level2}return envelope2}function duckGains(tracks,duckers,samples,sampleRate,loopFrames2){let gains=new Map;if(duckers.length===0)return gains;let envelopes=duckers.map(ducker=>duckEnvelope(ducker,samples,sampleRate,loopFrames2));for(let track2 of tracks){let gain;duckers.forEach((ducker,which)=>{if(ducker.target!==track2.orbit||ducker.trackId===track2.id||ducker.depth<=0)return;gain||(gain=new Float64Array(samples).fill(1));let envelope2=envelopes[which];for(let index=0;index<samples;index+=1)gain[index]*=1-ducker.depth*envelope2[index]}),gain&&gains.set(track2.id,gain)}return gains}var ABSOLUTE_GATE_LUFS=-70,RELATIVE_GATE_LU=-10;var LOUDNESS_STEP_SECONDS=.1,MOMENTARY_SECONDS=.4;var TAPS_PER_PHASE=32;function powerToLufs(power){return power>0?-.691+10*Math.log10(power):-1/0}function gainToDb(gain){return gain>0?20*Math.log10(gain):-1/0}function kWeighting(sampleRate){let f0=1681.974450955533,gain=3.999843853973347,q3=.7071752369554196,k=Math.tan(Math.PI*f0/sampleRate),vh=10**(gain/20),vb=vh**.4996667741545416,a0=1+k/q3+k*k,shelf={b0:(vh+vb*k/q3+k*k)/a0,b1:2*(k*k-vh)/a0,b2:(vh-vb*k/q3+k*k)/a0,a1:2*(k*k-1)/a0,a2:(1-k/q3+k*k)/a0};f0=38.13547087602444,q3=.5003270373238773,k=Math.tan(Math.PI*f0/sampleRate),a0=1+k/q3+k*k;let highPass={b0:1,b1:-2,b2:1,a1:2*(k*k-1)/a0,a2:(1-k/q3+k*k)/a0};return[shelf,highPass]}function weightedPower(left,right,sampleRate,loop){let n2=left.length,power=new Float64Array(n2),[shelf,highPass]=kWeighting(sampleRate);for(let channel of[left,right]){let s1=0,s2=0,h1=0,h2=0;for(let pass2=loop?0:1;pass2<2;pass2+=1)for(let index=0;index<n2;index+=1){let x=channel[index],y=shelf.b0*x+s1;s1=shelf.b1*x-shelf.a1*y+s2,s2=shelf.b2*x-shelf.a2*y;let z=highPass.b0*y+h1;h1=highPass.b1*y-highPass.a1*z+h2,h2=highPass.b2*y-highPass.a2*z,pass2===1&&(power[index]+=z*z)}}return power}function prefixSums(values){let sums=new Float64Array(values.length+1),total=0;for(let index=0;index<values.length;index+=1)total+=values[index],sums[index+1]=total;return sums}function windowPower(sums,end,width,loop){let n2=sums.length-1;if(n2===0||width<=0)return 0;if(!loop){let start=Math.max(0,end-width);return(sums[end]-sums[start])/width}let total=0,remaining=width,stop=end;for(;remaining>0;){let take=Math.min(remaining,stop);total+=sums[stop]-sums[stop-take],remaining-=take,stop=stop-take===0?n2:stop-take}return total/width}function gatedLoudness(powers,relative=RELATIVE_GATE_LU){let sum=0,count2=0;for(let power of powers)powerToLufs(power)>ABSOLUTE_GATE_LUFS&&(sum+=power,count2+=1);if(count2===0)return-1/0;let gate=powerToLufs(sum/count2)+relative;sum=0,count2=0;for(let power of powers)powerToLufs(power)>ABSOLUTE_GATE_LUFS&&powerToLufs(power)>gate&&(sum+=power,count2+=1);return count2===0?-1/0:powerToLufs(sum/count2)}var TRUE_PEAK_BETA=8;function besselI04(x){let sum=1,term=1;for(let k=1;k<40;k+=1)term*=(x/(2*k))**2,sum+=term;return sum}var phases;function truePeakPhases(){return phases??=[1,3,5,7,2,4,6].map(eighth=>{let frac2=eighth/8,taps=new Float64Array(TAPS_PER_PHASE),before=TAPS_PER_PHASE/2-1,norm=besselI04(TRUE_PEAK_BETA);for(let tap=0;tap<TAPS_PER_PHASE;tap+=1){let x=tap-before-frac2,m=x/(TAPS_PER_PHASE/2),window=Math.abs(m)<=1?besselI04(TRUE_PEAK_BETA*Math.sqrt(1-m*m))/norm:0;taps[tap]=Math.sin(Math.PI*x)/(Math.PI*x)*window}return taps}),phases}var interleaved;function interleavedPhases(){if(interleaved)return interleaved;let branches=truePeakPhases(),flat=new Float64Array(TAPS_PER_PHASE*branches.length);return branches.forEach((taps,phase)=>{for(let tap=0;tap<TAPS_PER_PHASE;tap+=1)flat[tap*branches.length+phase]=taps[tap]}),interleaved=flat}function interSamplePeaks(channel,loop,out){let n2=channel.length,branches=truePeakPhases(),flat=interleavedPhases(),before=TAPS_PER_PHASE/2-1,at3=index=>index>=0&&index<n2?channel[index]:!loop||n2===0?0:channel[(index%n2+n2)%n2];for(let index=0;index<n2;index+=1){let peak=Math.abs(channel[index]),next=Math.abs(at3(index+1));next>peak&&(peak=next);let base=index-before;if(base>=0&&base+TAPS_PER_PHASE<=n2){let s0=0,s1=0,s2=0,s3=0,s4=0,s5=0,s6=0;for(let tap=0;tap<TAPS_PER_PHASE;tap+=1){let x=channel[base+tap],k=tap*7;s0+=x*flat[k],s1+=x*flat[k+1],s2+=x*flat[k+2],s3+=x*flat[k+3],s4+=x*flat[k+4],s5+=x*flat[k+5],s6+=x*flat[k+6]}peak=Math.max(peak,Math.abs(s0),Math.abs(s1),Math.abs(s2),Math.abs(s3),Math.abs(s4),Math.abs(s5),Math.abs(s6))}else for(let taps of branches){let sum=0;for(let tap=0;tap<TAPS_PER_PHASE;tap+=1)sum+=at3(base+tap)*taps[tap];let magnitude=Math.abs(sum);magnitude>peak&&(peak=magnitude)}peak>out[index]&&(out[index]=peak)}}function truePeakGain(left,right,loop=!1){let peaks=new Float64Array(left.length);interSamplePeaks(left,loop,peaks),interSamplePeaks(right,loop,peaks);let max=0;for(let peak of peaks)peak>max&&(max=peak);return max}function integratedLoudness(left,right,sampleRate,loop=!1){let sums=prefixSums(weightedPower(left,right,sampleRate,loop));return gatedLoudness(blockPowers(sums,sampleRate,loop,MOMENTARY_SECONDS))}function stepEnds(n2,sampleRate,loop){let step2=sampleRate*LOUDNESS_STEP_SECONDS,count2=loop?Math.max(1,Math.round(n2/step2)):Math.floor(n2/step2+1e-9),ends=[];for(let k=1;k<=count2;k+=1)ends.push(Math.round(loop?k*n2/count2:k*step2));return ends}function blockPowers(sums,sampleRate,loop,seconds2){let n2=sums.length-1,width=Math.round(seconds2*sampleRate),powers=[];for(let end of stepEnds(n2,sampleRate,loop))(loop||end>=width)&&powers.push(windowPower(sums,end,width,loop));return powers}var MIX_BANDS=Object.freeze([{name:"sub",low:20,high:60},{name:"bass",low:60,high:250},{name:"low-mid",low:250,high:2e3},{name:"high-mid",low:2e3,high:6e3},{name:"high",low:6e3,high:2e4}]);var LOOP_WARMUP_SECONDS=2,TARGET_TOLERANCE_LU=.05,TARGET_ITERATIONS=8,PLATEAU_SLOPE=.05,MAX_TARGET_STEP=12,TRUE_PEAK_PAD=18;function applyMaster(mixL,mixR,frames,sampleRate,master,loop,inputPcm,preview){if(!masterActive(master)||frames<=0)return;let song3=master,lookahead=song3.limiter?Math.max(1,Math.round(Number(song3.limiter.lookahead)*sampleRate/1e3)):0,whole=loop?Math.ceil(LOOP_WARMUP_SECONDS*sampleRate/frames)*frames:0,tail=loop&&preview?.warmSeconds!==void 0?Math.ceil(Math.max(LOOP_WARMUP_SECONDS,preview.warmSeconds)*sampleRate):whole,warm=Math.min(whole,tail),length=warm+frames+lookahead+TRUE_PEAK_PAD,left=new Float64Array(length),right=new Float64Array(length),lead=(frames-warm%frames)%frames;for(let index=0;index<length;index+=1){let source=loop?(index+lead)%frames:index;source<frames&&(left[index]=inputPcm?inputPcm[source*2]/32767:mixL[source],right[index]=inputPcm?inputPcm[source*2+1]/32767:mixR[source])}song3.trim&&applyTrim(left,right,song3.trim,sampleRate,warm,frames,loop),song3.eq&&applyEq3(left,right,song3.eq,sampleRate),song3.tone&&applyTone(left,right,song3.tone,sampleRate),song3.mseq&&applyMsEq(left,right,song3.mseq,sampleRate),song3.glue&&applyGlue(left,right,song3.glue,sampleRate),song3.multiband&&applyMultiband(left,right,song3.multiband,sampleRate),song3.tape&&applyTape(left,right,song3.tape,sampleRate),song3.width&&applyWidth(left,right,song3.width,sampleRate);let kept=buffer=>buffer.subarray(warm,warm+frames);if(song3.clip&&song3.clip.target===!0&&song3.target!==void 0)return clipDrivenMaster(left,right,song3,sampleRate,loop,kept,preview);song3.clip&&applyClip(left,right,song3.clip),song3.limiter&&blockDc(left,right,sampleRate);let gainDb=0,runs=0,outL,outR,measured,peakKept;if(song3.limiter){let limiter=new Limiter(left,right,song3.limiter,sampleRate),drive=Number(song3.limiter.gain),lastRun,run=gain=>{gain!==lastRun&&(limiter.run(gain),lastRun=gain,runs+=1)};if(song3.target===void 0)gainDb=drive;else{let before=integratedLoudness(kept(left),kept(right),sampleRate,loop);gainDb=Number.isFinite(before)?seekTarget(song3.target,song3.target-before,gain=>{run(gain);let loudness=integratedLoudness(kept(limiter.left),kept(limiter.right),sampleRate,loop);return measured={gain,loudness},loudness}):0}(measured?.gain!==lastRun||lastRun!==gainDb)&&(measured=void 0),run(gainDb),song3.limiter.dcblock===!0&&(blockDc(limiter.left,limiter.right,sampleRate),measured=void 0),outL=kept(limiter.left),outR=kept(limiter.right);let trimmed=trimToCeiling(outL,outR,Number(song3.limiter.ceiling),loop,song3.limiter.truepeak!==!1);trimmed.scaled?measured=void 0:peakKept=trimmed.truePeak}else if(outL=kept(left),outR=kept(right),song3.target!==void 0){let before=integratedLoudness(outL,outR,sampleRate,loop);if(Number.isFinite(before)){let peak=gainToDb(truePeakGain(outL,outR,loop));gainDb=clampGain(Math.min(song3.target-before,MASTER_LIMITS.safeCeiling-peak)),scale2(outL,outR,10**(gainDb/20))}}let integrated=measured?.loudness??integratedLoudness(outL,outR,sampleRate,loop),report={gainDb,integrated,truePeak:gainToDb(peakKept??truePeakGain(outL,outR,loop)),...song3.target===void 0?{}:{target:song3.target,reached:Math.abs(integrated-song3.target)<=.5},...song3.limiter&&song3.target!==void 0?{runs}:{}};return Object.freeze({left:outL,right:outR,report})}function clipDrivenMaster(left,right,song3,sampleRate,loop,kept,preview){let clipL=new Float64Array(left.length),clipR=new Float64Array(right.length),target=song3.target,outL=kept(clipL),outR=kept(clipR),runs=0,lastRun,limited,run=gain=>{if(gain===lastRun)return;lastRun=gain,runs+=1;let scaleBy=10**(gain/20);for(let index=0;index<left.length;index+=1)clipL[index]=left[index]*scaleBy,clipR[index]=right[index]*scaleBy;if(applyClip(clipL,clipR,song3.clip),song3.limiter){blockDc(clipL,clipR,sampleRate);let limiter=new Limiter(clipL,clipR,song3.limiter,sampleRate);limiter.run(Number(song3.limiter.gain)),limited=limiter,outL=kept(limiter.left),outR=kept(limiter.right)}else outL=kept(clipL),outR=kept(clipR)},measure=()=>integratedLoudness(outL,outR,sampleRate,loop),before=integratedLoudness(kept(left),kept(right),sampleRate,loop),limiterGain=song3.limiter?Number(song3.limiter.gain):0,gainDb=0;Number.isFinite(before)&&(gainDb=seekTarget(target,target-before-limiterGain,gain=>(run(gain),measure()))),run(gainDb),limited&&song3.limiter?.dcblock===!0&&blockDc(limited.left,limited.right,sampleRate);let peakKept;if(song3.limiter){let trimmed=trimToCeiling(outL,outR,Number(song3.limiter.ceiling),loop,song3.limiter.truepeak!==!1);preview&&(peakKept=trimmed.truePeak)}let integrated=measure();return Object.freeze({left:outL,right:outR,report:{gainDb,integrated,truePeak:gainToDb(peakKept??truePeakGain(outL,outR,loop)),target,reached:Math.abs(integrated-target)<=.5,runs}})}function applyMasterPcm(pcm,frames,sampleRate,master,loop,preview){return applyMaster(EMPTY_INPUT,EMPTY_INPUT,frames,sampleRate,master,loop,pcm,preview)}var EMPTY_INPUT=new Float64Array(0);function applyMonitorMaster(pcm,sampleRate,song3){if(!song3||!masterActive(song3))return pcm;let frames=pcm.length/2,left=new Float64Array(frames),right=new Float64Array(frames);for(let i=0;i<frames;i++)left[i]=pcm[i*2]/32767,right[i]=pcm[i*2+1]/32767;let monitorGain=Number(song3.trim?.monitor??0);monitorGain&&scale2(left,right,10**(monitorGain/20)),song3.eq&&applyEq3(left,right,song3.eq,sampleRate),song3.tone&&applyTone(left,right,song3.tone,sampleRate),song3.mseq&&applyMsEq(left,right,song3.mseq,sampleRate),song3.glue&&applyGlue(left,right,song3.glue,sampleRate),song3.multiband&&applyMultiband(left,right,song3.multiband,sampleRate),song3.tape&&applyTape(left,right,song3.tape,sampleRate),song3.width&&applyWidth(left,right,song3.width,sampleRate),song3.clip&&applyClip(left,right,song3.clip),song3.limiter&&blockDc(left,right,sampleRate);let outputL=left,outputR=right;if(song3.limiter){let limiter=new Limiter(left,right,song3.limiter,sampleRate);limiter.run(Number(song3.limiter.gain)),song3.limiter.dcblock===!0&&(blockDc(limiter.left,limiter.right,sampleRate),trimToCeiling(limiter.left,limiter.right,Number(song3.limiter.ceiling),!1,song3.limiter.truepeak!==!1)),outputL=limiter.left,outputR=limiter.right}let out=new Int16Array(pcm.length);for(let i=0;i<frames;i++)out[i*2]=Math.round(Math.max(-1,Math.min(1,outputL[i]))*32767),out[i*2+1]=Math.round(Math.max(-1,Math.min(1,outputR[i]))*32767);return out}function clampGain(gainDb){return Math.max(-MASTER_LIMITS.maxTargetGain,Math.min(MASTER_LIMITS.maxTargetGain,gainDb))}function seekTarget(target,guess,measure){let seen=[],probe=gain=>{let point2={gain,loudness:measure(gain)};return seen.push(point2),point2},off=point2=>Math.abs(point2.loudness-target),best=()=>seen.reduce((a,b)=>off(b)<off(a)||off(b)===off(a)&&b.gain<a.gain?b:a),point=probe(clampGain(guess));if(!Number.isFinite(point.loudness))return 0;let low=point.loudness<target?point:void 0,high=point.loudness<target?void 0:point;for(;seen.length<TARGET_ITERATIONS&&off(point)>TARGET_TOLERANCE_LU&&(low===void 0||high===void 0);){let previous=seen.length>=2?seen[seen.length-2]:void 0,slope=previous===void 0?1:(point.loudness-previous.loudness)/(point.gain-previous.gain);if(high===void 0&&previous!==void 0&&!(slope>=PLATEAU_SLOPE))break;let step2=Math.min(MAX_TARGET_STEP,Math.max(.25,1.25*off(point)/Math.max(slope,PLATEAU_SLOPE))),next=clampGain(point.gain+(high===void 0?step2:-step2));if(next===point.gain)break;point=probe(next),point.loudness<target?low=point:high=point}if(low!==void 0&&high!==void 0&&off(point)>TARGET_TOLERANCE_LU){let fLow=low.loudness-target,fHigh=high.loudness-target,side=0;for(;seen.length<TARGET_ITERATIONS&&high.gain-low.gain>.01;){let gain=(low.gain*fHigh-high.gain*fLow)/(fHigh-fLow);point=probe(gain);let f=point.loudness-target;if(Math.abs(f)<=TARGET_TOLERANCE_LU)break;f<0?(low=point,fLow=f,side===-1&&(fHigh/=2),side=-1):(high=point,fHigh=f,side===1&&(fLow/=2),side=1)}}return best().gain}function applyTrim(left,right,values,sampleRate,warm,frames,loop){let before=integratedLoudness(left.subarray(warm,warm+frames),right.subarray(warm,warm+frames),sampleRate,loop);values.dcblock===!0&&dcBlock(left,right,sampleRate),Number.isFinite(before)&&scale2(left,right,10**(clampGain(Number(values.lufs)-before)/20))}function dcBlock(left,right,sampleRate){let r=Math.exp(-2*Math.PI*5/sampleRate);for(let channel of[left,right]){let x1=0,y1=0;for(let i=0;i<channel.length;i+=1){let x=channel[i];y1=x-x1+r*y1,x1=x,channel[i]=y1}}}function applyClip(left,right,values){let drive=10**(Number(values.drive)/20),ceiling=10**(Number(values.ceiling)/20),knee3=ceiling*10**(-6*Number(values.softness)/20),room=ceiling-knee3,shape=x=>{let a=Math.abs(x),y=a<=knee3?a:room<=0?ceiling:knee3+room*Math.tanh((a-knee3)/room);return x<0?-y:y};if(values.oversample===!0){for(let channel of[left,right]){for(let index=0;index<channel.length;index+=1)channel[index]*=drive;oversampledShape(channel,shape,knee3)}return}for(let index=0;index<left.length;index+=1)left[index]=shape(left[index]*drive),right[index]=shape(right[index]*drive)}var OVERSAMPLE_HALF=32,oversampleKernel;function oversampleFilter(){if(oversampleKernel)return oversampleKernel;let half=OVERSAMPLE_HALF*4,taps=new Float64Array(2*half+1),bessel=x=>{let sum=1,term=1;for(let k=1;k<40;k+=1)term*=(x/(2*k))**2,sum+=term;return sum},beta=8,norm=bessel(beta),total=0;for(let t=-half;t<=half;t+=1){let x=t/4,sinc=t===0?1:Math.sin(Math.PI*x)/(Math.PI*x),r=t/half,window=bessel(beta*Math.sqrt(Math.max(0,1-r*r)))/norm;taps[t+half]=sinc*window,total+=sinc*window}for(let index=0;index<taps.length;index+=1)taps[index]/=total;return oversampleKernel=taps,taps}function oversampledShape(channel,shape,knee3){let taps=oversampleFilter(),half=OVERSAMPLE_HALF*4,n2=channel.length,delta=new Float64Array(n2),gate=knee3*.5,scatter=(m,e)=>{let first=Math.max(0,Math.ceil((m-half)/4)),last=Math.min(n2-1,Math.floor((m+half)/4));for(let k=first;k<=last;k+=1)delta[k]+=e*taps[4*k-m+half]};for(let index=0;index<n2;index+=1){let near=0;for(let j=index-1;j<=index+2;j+=1)j>=0&&j<n2&&(near=Math.max(near,Math.abs(channel[j])));if(near<=gate)continue;let x=channel[index],e0=shape(x)-x;e0!==0&&scatter(4*index,e0);for(let phase=1;phase<4;phase+=1){let u=0,from=Math.max(0,index-OVERSAMPLE_HALF+1),to=Math.min(n2-1,index+OVERSAMPLE_HALF);for(let k=from;k<=to;k+=1)u+=channel[k]*taps[4*(index-k)+phase+half];u*=4;let e=shape(u)-u;e!==0&&scatter(4*index+phase,e)}}for(let index=0;index<n2;index+=1)channel[index]+=delta[index]}function blockDc(left,right,sampleRate){let pole=Math.exp(-2*Math.PI*5/sampleRate);for(let channel of[left,right]){let input=0,output2=0;for(let index=0;index<channel.length;index+=1){let x=channel[index];output2=x-input+pole*output2,input=x,channel[index]=output2}}}function scale2(left,right,gain){for(let index=0;index<left.length;index+=1)left[index]*=gain,right[index]*=gain}function trimToCeiling(left,right,ceilingDb,loop,truePeak){let ceiling=10**(ceilingDb/20),peak=0;if(truePeak)peak=truePeakGain(left,right,loop);else for(let index=0;index<left.length;index+=1)peak=Math.max(peak,Math.abs(left[index]),Math.abs(right[index]));return peak>ceiling?(scale2(left,right,ceiling/peak),{scaled:!0,...truePeak&&Number.isFinite(peak)?{truePeak:ceiling}:{}}):{scaled:!1,...truePeak?{truePeak:peak}:{}}}var Section=class{constructor(b0,b1,b2,a1,a2){this.b0=b0;this.b1=b1;this.b2=b2;this.a1=a1;this.a2=a2}b0;b1;b2;a1;a2;z1=0;z2=0;process(input){let output2=this.b0*input+this.z1;return this.z1=this.b1*input-this.a1*output2+this.z2,this.z2=this.b2*input-this.a2*output2,output2}run(buffer){for(let index=0;index<buffer.length;index+=1)buffer[index]=this.process(buffer[index])}responseDb(frequency,sampleRate){let w=2*Math.PI*frequency/sampleRate,c1=Math.cos(w),s1=Math.sin(w),c2=Math.cos(2*w),s2=Math.sin(2*w),nr=this.b0+this.b1*c1+this.b2*c2,ni=-(this.b1*s1+this.b2*s2),dr=1+this.a1*c1+this.a2*c2,di=-(this.a1*s1+this.a2*s2);return 10*Math.log10((nr*nr+ni*ni)/(dr*dr+di*di))}};function cookbook(kind,frequency,sampleRate,gainDb=0,q3=Math.SQRT1_2){let f=Math.max(10,Math.min(frequency,sampleRate*.45)),w0=2*Math.PI*f/sampleRate,cos=Math.cos(w0),sin=Math.sin(w0),a=10**(gainDb/40),b0,b1,b2,a0,a1,a2;if(kind==="bell"){let alpha=sin/(2*q3);b0=1+alpha*a,b1=-2*cos,b2=1-alpha*a,a0=1+alpha/a,a1=-2*cos,a2=1-alpha/a}else if(kind==="low"||kind==="high"){let alpha=sin/Math.SQRT2,root=2*Math.sqrt(a)*alpha,sign=kind==="low"?1:-1;b0=a*(a+1-sign*(a-1)*cos+root),b1=sign*2*a*(a-1-sign*(a+1)*cos),b2=a*(a+1-sign*(a-1)*cos-root),a0=a+1+sign*(a-1)*cos+root,a1=-sign*2*(a-1+sign*(a+1)*cos),a2=a+1+sign*(a-1)*cos-root}else if(kind==="allpass"){let alpha=sin/(2*q3);b0=1-alpha,b1=-2*cos,b2=1+alpha,a0=1+alpha,a1=-2*cos,a2=1-alpha}else{let alpha=sin/(2*q3),low=kind==="lowpass";b0=low?(1-cos)/2:(1+cos)/2,b1=low?1-cos:-(1+cos),b2=b0,a0=1+alpha,a1=-2*cos,a2=1-alpha}return new Section(b0/a0,b1/a0,b2/a0,a1/a0,a2/a0)}function applyEq3(left,right,values,sampleRate){let value=key=>Number(values[key]),bands=[["low",value("low"),value("lowfreq"),Math.SQRT1_2],["bell",value("bell1"),value("bell1freq"),value("bell1q")],["bell",value("bell2"),value("bell2freq"),value("bell2q")],["high",value("high"),value("highfreq"),Math.SQRT1_2]];for(let[kind,gain,frequency,q3]of bands)if(gain!==0)for(let channel of[left,right])cookbook(kind,frequency,sampleRate,gain,q3).run(channel)}var TONE_Q=1.4;function toneFilter(index,sampleRate){let centre=Math.min(TONE_BANDS[index][1],sampleRate*.45);return index===0?{kind:"low",frequency:centre*Math.SQRT2,q:Math.SQRT1_2}:index===TONE_BANDS.length-1?{kind:"high",frequency:centre/Math.SQRT2,q:Math.SQRT1_2}:{kind:"bell",frequency:centre,q:TONE_Q}}function toneSection(index,sampleRate,gain){let{kind,frequency,q:q3}=toneFilter(index,sampleRate);return cookbook(kind,frequency,sampleRate,gain,q3)}function solveTone(values,sampleRate){let reach=toneReach(sampleRate),want=reach.map(i=>Number(values[TONE_BANDS[i][0]]??0));if(want.every(gain=>gain===0))return[];let freqs=reach.map(i=>Math.min(TONE_BANDS[i][1],sampleRate*.45)),n2=freqs.length,response=gains2=>freqs.map(f=>gains2.reduce((sum,gain,j)=>gain===0?sum:sum+toneSection(reach[j],sampleRate,gain).responseDb(f,sampleRate),0)),matrix=freqs.map(f=>reach.map(index=>toneSection(index,sampleRate,1).responseDb(f,sampleRate))),solve=rhs=>{let a=matrix.map((row2,i)=>[...row2,rhs[i]]);for(let col=0;col<n2;col+=1){let pivot=col;for(let row2=col+1;row2<n2;row2+=1)Math.abs(a[row2][col])>Math.abs(a[pivot][col])&&(pivot=row2);[a[col],a[pivot]]=[a[pivot],a[col]];for(let row2=0;row2<n2;row2+=1){if(row2===col)continue;let factor=a[row2][col]/a[col][col];for(let k=col;k<=n2;k+=1)a[row2][k]-=factor*a[col][k]}}return a.map((row2,i)=>row2[n2]/row2[i])},gains=solve(want).map(gain=>Math.max(-15,Math.min(15,gain)));for(let pass2=0;pass2<2;pass2+=1){let got=response(gains),step2=solve(want.map((w,i)=>w-got[i]));gains=gains.map((gain,i)=>Math.max(-15,Math.min(15,gain+step2[i])))}return gains.map((gain,j)=>{let index=reach[j];return{index,...toneFilter(index,sampleRate),gain}}).filter(({gain})=>Math.abs(gain)>1e-6)}function applyTone(left,right,values,sampleRate){for(let{index,gain}of solveTone(values,sampleRate))for(let channel of[left,right])toneSection(index,sampleRate,gain).run(channel)}var MULTIBAND_RMS_MS=[12,6,3,1.5];function applyMultiband(left,right,values,sampleRate){let value=key=>Number(values[key]),f1=value("lowfreq"),f2=Math.max(f1*1.5,value("midfreq")),f3=Math.max(f2*1.5,value("highfreq")),knee3=value("knee"),range=value("range"),coefficient=ms2=>Math.exp(-1/Math.max(1,ms2/1e3*sampleRate)),bands=MULTIBAND_BANDS.map((band,i)=>({threshold:value(`${band}threshold`),slope:1-1/value(`${band}ratio`),attack:coefficient(value(`${band}attack`)),release:coefficient(value(`${band}release`)),makeup:10**(value(`${band}gain`)/20),rms:coefficient(MULTIBAND_RMS_MS[i]),power:0,reduction:0})),lr4=(kind,f)=>[cookbook(kind,f,sampleRate),cookbook(kind,f,sampleRate)],run=(sections,x)=>{for(let section of sections)x=section.process(x);return x},filters=()=>({lo2:lr4("lowpass",f2),hi2:lr4("highpass",f2),ap3:[cookbook("allpass",f3,sampleRate)],lo1:lr4("lowpass",f1),hi1:lr4("highpass",f1),ap1:[cookbook("allpass",f1,sampleRate)],lo3:lr4("lowpass",f3),hi3:lr4("highpass",f3)}),fl=filters(),fr=filters(),split=(f,x,out)=>{let low=run(f.ap3,run(f.lo2,x)),high=run(f.ap1,run(f.hi2,x));out[0]=run(f.lo1,low),out[1]=run(f.hi1,low),out[2]=run(f.lo3,high),out[3]=run(f.hi3,high)},bl=[0,0,0,0],br=[0,0,0,0];for(let index=0;index<left.length;index+=1){split(fl,left[index],bl),split(fr,right[index],br);let outL=0,outR=0;for(let b=0;b<4;b+=1){let band=bands[b],l=bl[b],r=br[b];band.power=band.rms*band.power+(1-band.rms)*((l*l+r*r)/2);let over=10*Math.log10(band.power+1e-24)+3.01-band.threshold,target=0;2*over>=knee3?target=band.slope*over:knee3>0&&2*over>-knee3&&(target=band.slope*(over+knee3/2)**2/(2*knee3)),target>range&&(target=range),band.reduction=target>band.reduction?band.attack*band.reduction+(1-band.attack)*target:band.release*band.reduction+(1-band.release)*target;let gain=10**(-band.reduction/20)*band.makeup;outL+=l*gain,outR+=r*gain}left[index]=outL,right[index]=outR}}function applyMsEq(left,right,values,sampleRate){let value=key=>Number(values[key]??0),bands=prefix=>[["low",value(`${prefix}low`),value(`${prefix}lowfreq`),Math.SQRT1_2],["bell",value(`${prefix}bell`),value(`${prefix}bellfreq`),value(`${prefix}bellq`)||1],["high",value(`${prefix}high`),value(`${prefix}highfreq`),Math.SQRT1_2]],mid=bands("mid").filter(([,gain])=>gain!==0),side=bands("side").filter(([,gain])=>gain!==0);if(mid.length===0&&side.length===0)return;let m=new Float64Array(left.length),s=new Float64Array(left.length);for(let i=0;i<left.length;i+=1)m[i]=(left[i]+right[i])/2,s[i]=(left[i]-right[i])/2;for(let[kind,gain,frequency,q3]of mid)cookbook(kind,frequency,sampleRate,gain,q3).run(m);for(let[kind,gain,frequency,q3]of side)cookbook(kind,frequency,sampleRate,gain,q3).run(s);for(let i=0;i<left.length;i+=1)left[i]=m[i]+s[i],right[i]=m[i]-s[i]}function applyGlue(left,right,values,sampleRate){let threshold=Number(values.threshold),ratio2=Number(values.ratio),knee3=Number(values.knee),mix3=Number(values.mix),hpf=Number(values.hpf),slope=1-1/ratio2,auto=values.auto!==!1?slope*Math.max(0,-threshold)/2:0,makeup=10**((Number(values.makeup)+auto)/20),coefficient=ms2=>Math.exp(-1/Math.max(1,ms2/1e3*sampleRate)),attack=coefficient(Number(values.attack)),release=coefficient(Number(values.release)),sideL=hpf>0?cookbook("highpass",hpf,sampleRate):void 0,sideR=hpf>0?cookbook("highpass",hpf,sampleRate):void 0,reduction=0;for(let index=0;index<left.length;index+=1){let l=left[index],r=right[index],detectL=sideL?sideL.process(l):l,detectR=sideR?sideR.process(r):r,over=20*Math.log10(Math.max(Math.abs(detectL),Math.abs(detectR))+1e-12)-threshold,target=0;2*over>=knee3?target=slope*over:knee3>0&&2*over>-knee3&&(target=slope*(over+knee3/2)**2/(2*knee3)),reduction=target>reduction?attack*reduction+(1-attack)*target:release*reduction+(1-release)*target;let gain=10**(-reduction/20)*makeup;left[index]=l*(1-mix3)+l*gain*mix3,right[index]=r*(1-mix3)+r*gain*mix3}}function logCosh2(u){let a=Math.abs(u);return a+Math.log1p(Math.exp(-2*a))-Math.LN2}var TAPE_COMPENSATION=.85;function applyTape(left,right,values,sampleRate){let drive=10**(Number(values.drive)/20),bias=Number(values.bias),tone=Number(values.tone),mix3=Number(values.mix),centre=Math.tanh(bias),norm=Math.max(Math.tanh(drive+bias)-centre,centre-Math.tanh(bias-drive)),dcPole=Math.exp(-2*Math.PI*5/sampleRate),toneOn=tone<Math.min(2e4,sampleRate*.45);for(let channel of[left,right]){let previousU=bias,previousF=logCosh2(bias),previousX=0,compensated=0,dcIn=0,dcOut=0,lowpass=toneOn?cookbook("lowpass",tone,sampleRate):void 0;for(let index=0;index<channel.length;index+=1){let x=channel[index],u=drive*x+bias,f=logCosh2(u),delta=u-previousU,shaped=Math.abs(delta)>1e-9?(f-previousF)/delta:Math.tanh((u+previousU)/2);previousU=u,previousF=f;let wet=(shaped-centre)/norm,blocked=wet-dcIn+dcPole*dcOut;dcIn=wet,dcOut=blocked,wet=lowpass?lowpass.process(blocked):blocked;let dry=(x+previousX)/2;previousX=x;let mixed=dry*(1-mix3)+wet*mix3;compensated=(1+TAPE_COMPENSATION)*mixed-TAPE_COMPENSATION*compensated,channel[index]=compensated}}}function applyWidth(left,right,values,sampleRate){let width=Number(values.width),mono=Number(values.mono);if(width===1&&mono===0)return;let crossover=mono>0,lr4=kind=>[cookbook(kind,mono,sampleRate),cookbook(kind,mono,sampleRate)],midLow=crossover?lr4("lowpass"):[],midHigh=crossover?lr4("highpass"):[],sideHigh=crossover?lr4("highpass"):[];for(let index=0;index<left.length;index+=1){let mid=(left[index]+right[index])/2,side=(left[index]-right[index])/2*width;crossover&&(mid=midLow[1].process(midLow[0].process(mid))+midHigh[1].process(midHigh[0].process(mid)),side=sideHigh[1].process(sideHigh[0].process(side))),left[index]=mid+side,right[index]=mid-side}}var Limiter=class{constructor(inputL,inputR,values,sampleRate){this.inputL=inputL;this.inputR=inputR;let n2=inputL.length;if(this.left=new Float64Array(n2),this.right=new Float64Array(n2),this.ceiling=10**(Number(values.ceiling)/20),this.window=Math.max(1,Math.round(Number(values.lookahead)*sampleRate/1e3)),this.release=Math.exp(-1/Math.max(1,Number(values.release)/1e3*sampleRate)),this.peaks=new Float64Array(n2),values.truepeak!==!1){interSamplePeaks(inputL,!1,this.peaks),interSamplePeaks(inputR,!1,this.peaks);for(let index=n2-1;index>0;index-=1)this.peaks[index-1]>this.peaks[index]&&(this.peaks[index]=this.peaks[index-1])}else for(let index=0;index<n2;index+=1)this.peaks[index]=Math.max(Math.abs(inputL[index]),Math.abs(inputR[index]))}inputL;inputR;left;right;peaks;window;release;ceiling;run(gainDb){let drive=10**(gainDb/20),n2=this.inputL.length,{peaks,window,ceiling}=this,capacity=window+1,slots=new Int32Array(capacity),values=new Float64Array(capacity),head=0,size=0,history=new Float64Array(window),released=1,sum=0;for(let ahead=0;ahead<n2+window-1;ahead+=1){let index=ahead-window+1;for(;size>0&&slots[head]<index;)head=(head+1)%capacity,size-=1;let peak=ahead<n2?peaks[ahead]*drive:0,need=peak>ceiling?ceiling/peak:1;for(;size>0&&values[(head+size-1)%capacity]>=need;)size-=1;let slot=(head+size)%capacity;if(slots[slot]=ahead,values[slot]=need,size+=1,index<0)continue;let target=values[head];index===0&&(released=target,history.fill(target),sum=window*target),released=target<released?target:target-this.release*(target-released);let at3=index%window;sum+=released-history[at3],history[at3]=released;let gain=Math.min(1,sum/window)*drive;this.left[index]=this.inputL[index]*gain,this.right[index]=this.inputR[index]*gain}}};function scrubNonFinite(buffer){let count2=0;for(let i=0;i<buffer.length;i+=1)Number.isFinite(buffer[i])||(buffer[i]=0,count2+=1);return count2}var AVAILABLE_INSTRUMENTS=Object.freeze(["sine","piano","pluck","bass","saw","square","triangle","wavetable","kit","sawtooth","supersaw","pulse","user","white","pink","brown","crackle","z_sine","z_triangle","z_sawtooth","z_square","z_tan","z_noise","granular","modal","texture","vocal"]),AVAILABLE_EFFECTS=Object.freeze(["pan(-1..1 equal-power)",...EFFECT_NAMES.map(name=>{let spec=effectSpec(name);return`${name}(${spec.simple.join(" ")})`})]),AVAILABLE_FX_PRESETS=Object.freeze(Object.fromEntries(EFFECT_NAMES.filter(name=>FX_PRESETS[name]).map(name=>[name,Object.keys(FX_PRESETS[name]).join(" ")]))),MAX_DRUM_SECONDS=.6;function oneShotDelayTail(score){return Math.min(MAX_LOOP_TAIL_SECONDS,Math.max(0,...score.tracks.map(track2=>delayTailFor(track2,slowestBpmOf(score)))))}var MAX_LOOP_TAIL_SECONDS=8,MAX_ENGINE_TAIL_SECONDS=30;function oneShotEngineTail(score,ringing=!1){let tail=0;for(let track2 of score.tracks){let engine2=engineFor2(track2);if(!engine2||ringing&&engine2.ringOut?.(track2)!==!0)continue;let lowest;for(let note2 of score.notes)note2.trackId===track2.id&&(lowest===void 0||note2.pitch<lowest)&&(lowest=note2.pitch);tail=Math.max(tail,engineTailSeconds(track2,lowest,score))}return Math.min(MAX_ENGINE_TAIL_SECONDS,tail)}function loopFrames(score,sampleRate){return score.time?loopSecondsOf(score)*sampleRate:score.bars*score.beatsPerBar*60*sampleRate/score.tempoBpm}var DEFAULT_STEM_CACHE_BYTES=256*1024*1024,GUIDE_LEVEL=.25,StemRenderer=class{maxCacheBytes;stems=new Map;buses=new Map;cacheBytes=0;renders=0;voicePasses=[];ran=new Set;modSources=new Map;scratch={dry:new Float64Array(0),dryR:new Float64Array(0),left:new Float64Array(0),right:new Float64Array(0),mixL:new Float64Array(0),mixR:new Float64Array(0)};store_;breath;constructor(options={}){this.breath=options.breathe,this.maxCacheBytes=Math.max(0,options.maxCacheBytes??DEFAULT_STEM_CACHE_BYTES),this.store_=options.store}breathe(){this.breath?.()}get rendered(){return this.voicePasses}takeRendered(){let ran=[...this.ran];return this.ran.clear(),ran}get cache(){return{stems:this.stems.size,bytes:this.cacheBytes}}oneShotSeconds(score,options={}){let sampleRate=clampSampleRate(options.sampleRate),bank=options.samples??EMPTY_SAMPLE_BANK,reverbTail=Math.max(0,...score.tracks.map(track2=>reverbTailFor(track2,sampleRate,bank.irs))),samplerTail=Math.min(MAX_LOOP_TAIL_SECONDS,Math.max(samplerTailSeconds(score,bank,sampleRate),...score.tracks.map(synthTailSeconds),...score.tracks.map(track2=>engineTailSeconds(track2,void 0,score))));return oneShotSeconds(loopSecondsOf(score),Math.max(samplerTail,oneShotEngineTail(score)),reverbTail,oneShotDelayTail(score))}render(score,options={}){let caching=this.maxCacheBytes>0&&options.cacheStems!==!1;caching||(this.stems.clear(),this.cacheBytes=0,this.buses.clear());let sampleRate=clampSampleRate(options.sampleRate),maxSeconds=Math.max(1,Math.min(60,options.maxSeconds??30)),loopSeconds=loopSecondsOf(score),bank=options.samples??EMPTY_SAMPLE_BANK,warp2=sampleWarpFor(score,sampleRate),reverbTail=Math.max(0,...score.tracks.map(track2=>reverbTailFor(track2,sampleRate,bank.irs))),samplerTail=Math.min(MAX_LOOP_TAIL_SECONDS,Math.max(samplerTailSeconds(score,bank,sampleRate),...score.tracks.map(synthTailSeconds),...score.tracks.map(track2=>engineTailSeconds(track2,void 0,score)))),frames,samples;if(options.loop){frames=Math.max(1,Math.min(Math.round(loopFrames(score,sampleRate)),Math.ceil(maxSeconds*sampleRate)));let tailSeconds=Math.min(MAX_LOOP_TAIL_SECONDS,Math.max(MAX_DRUM_SECONDS,samplerTail,kitTailSeconds(score))+.1+reverbTail+Math.max(0,...score.tracks.map(track2=>delayTailFor(track2,slowestBpmOf(score)))));samples=frames+Math.ceil(tailSeconds*sampleRate)}else{let seconds2=Math.min(maxSeconds,oneShotSeconds(loopSeconds,Math.max(samplerTail,oneShotEngineTail(score)),reverbTail,oneShotDelayTail(score)));frames=Math.max(1,Math.ceil(seconds2*sampleRate)),samples=frames}let context={reverbKernel:nativeReverbKernel,score,sampleRate,samples,samplesPerTick:sampleRate*60/(score.tempoBpm*score.ticksPerBeat),tempoBpm:score.tempoBpm,...bank.irs?{irs:bank.irs}:{},...warp2?{warp:warp2}:{},...options.seedTick?{seedTick:options.seedTick}:{},...options.seedSeconds?{seedSeconds:options.seedSeconds}:{},...options.seedState?{seedState:options.seedState}:{},...options.quantChord?{quantChord:options.quantChord}:{}};this.renders+=1,this.voicePasses=[];let disk=this.store_&&!options.quantChord?{store:this.store_,scope:storeScope(score,options)}:void 0,taps=options.taps,ringFade=options.loop&&samples>frames&&oneShotEngineTail(score,!0)>(samples-frames)/sampleRate?Math.round(RING_OUT_FADE_SECONDS*sampleRate):0,tap=(id,left2,right2,gain)=>options.loop&&taps.unfolded?taps.unfolded.stem(id,left2,right2,gain,samples,ringFade):options.loop?tapLoopStem(taps,id,left2,right2,frames,samples,gain,ringFade):tapStem(taps,id,left2,right2,frames,gain),{dry,dryR,left,right,mixL,mixR}=this.scratchFor(samples),nonFinite={samples:0,tracks:[]};mixL.fill(0),mixR.fill(0);let tracks=new Map(score.tracks.map(track2=>[track2.id,track2])),groups=new Map;for(let note2 of performedNotes(score)){let group=groups.get(note2.trackId);group?group.push(note2):groups.set(note2.trackId,[note2])}for(let track2 of score.tracks)hasClips(track2)&&!groups.has(track2.id)&&groups.set(track2.id,[]);for(let track2 of score.tracks)!groups.has(track2.id)&&vocoderPlaysWithoutNotes(track2)&&groups.set(track2.id,[]);let timing=performanceTimingFor(score),performed=new Map;for(let[trackId,notes]of groups){let track2=tracks.get(trackId);performed.set(trackId,performNotes(track2,notes,tunedTiming(timing,score,track2)))}let duckers=[];for(let[trackId]of groups){let settings=duckSettings(tracks.get(trackId),60/score.tempoBpm);if(settings&&isTrackAudible(score,trackId)){let{hold,...duck}=settings,spans=performed.get(trackId).map(note2=>noteSpan(note2,context));duckers.push({trackId,...duck,onsets:spans.map(span4=>span4.start),...hold&&{ends:spans.map(span4=>span4.start+span4.length)}})}}let ducked=duckGains([...groups.keys()].map(id=>({id,orbit:orbitOf(tracks.get(id))})),duckers,samples,sampleRate,options.loop?frames:void 0),buses=new Map;for(let[trackId,notes]of groups){if(!isTrackAudible(score,trackId))continue;let track2=tracks.get(trackId),played=performed.get(trackId),busOrbit=sharedOrbitOf(track2),sampler=isSamplerInstrument(track2?.instrument),engine2=engineFor2(track2),clipDigest=track2?clipsDigest(track2,bank,options.guide===!0):void 0,baseDigests=engine2&&track2?[...engine2.assetDigests?.(track2,bank,score)??[],`key:${score.key??""}`,...clipDigest===void 0?[]:[`clips:${clipDigest}`]]:clipDigest===void 0?void 0:[`clips:${clipDigest}`],vocoderSource=track2?.vocoder?vocoderSourceOf(track2,groups,performed,context,bank):void 0,withVocoder=vocoderSource?[...baseDigests??[],vocoderSource.key]:baseDigests,tunedDigests=track2?.autotune?[...withVocoder??[],...autotuneStemDigests(track2,score)]:withVocoder,sideSource=readsSide(track2)?sideSourceOf(track2,groups,performed,context,bank):void 0,patchKeys=[...track2&&engine2?.id!==PATCH_INSTRUMENT?patchDigests(track2,score.patches):[],...sideSource?[sideSource.key]:[]],engineDigests=patchKeys.length>0?[...tunedDigests??[],...patchKeys]:tunedDigests,wavetable=track2?wavetableHook(track2,bank,context):void 0,tuning=resolveTuning(score.tuning,track2?.tuning,score.key),key=stemKey(track2,notes,context,sampler?bank:void 0,wavetable?.id,track2?reverbImpulse(track2,sampleRate,bank.irs)?.id:void 0,engineDigests),stem=this.stems.get(trackId),room=caching&&track2&&busOrbit===void 0&&reverbActive(track2)&&effectPatches(track2,"post").length===0?stemKey(roomTrack(track2),notes,context,sampler?bank:void 0,wavetable?.id,reverbImpulse(track2,sampleRate,bank.irs)?.id,engineDigests):void 0,diskKey=disk?stemStoreKey(disk.scope,"stem",key):"",stored=disk&&stem?.key!==key?disk.store.get(diskKey):void 0;if(stem?.key===key)stem.used=this.renders;else if(stored&&stored.left.length===samples)stem={key,left:stored.left,right:stored.right,bytes:stored.left.byteLength*2,used:this.renders,...stored.nonFinite?{nonFinite:stored.nonFinite}:{}},caching&&this.store(trackId,stem);else if(track2&&room!==void 0&&stem?.room?.key===room){let{pre,wet}=stem.room,target={left:Float64Array.from(pre.left),right:Float64Array.from(pre.right)};addReverbWet(target.left,target.right,wet,track2,context),stem={...stem,key,left:target.left,right:target.right,used:this.renders},this.store(trackId,stem)}else{let target=caching?{left:new Float64Array(samples),right:new Float64Array(samples)}:{left,right},voiceKey=disk?.store.voices?stemStoreKey(disk.scope,"voice",stemKey(track2?dryTrack(track2):void 0,notes,context,sampler?bank:void 0,wavetable?.id,void 0,engineDigests)):void 0,voice=voiceKey!==void 0?disk.store.voices.get(voiceKey):void 0,voiceHit=voice!==void 0&&voice.left.length===samples&&(voice.right===void 0||voice.right.length===samples),side=sideSource&&(!voiceHit||(track2?.fxPatch??[]).length>0)?this.vocoderTap(sideSource,context,bank):void 0,stereo,bad;if(voiceHit)dry.set(voice.left),stereo=voice.right!==void 0,voice.right&&dryR.set(voice.right),bad=voice.nonFinite??0;else{this.voicePasses.push(trackId),this.ran.add(trackId),dry.fill(0);let voiceTrack=track2&&vocoderSource?{...track2,volume:1,volumeAutomation:[]}:track2;stereo=renderVoiceInto(dry,dryR,played,voiceTrack,context,score,bank,engine2,sampler,wavetable,tuning,options.guide===!0,side),track2&&vocoderSource&&applyVocoder(dry,stereo?dryR:void 0,this.vocoderTap(vocoderSource,context,bank),track2,context,vocoderSource.gateDb),track2&&vocoderSource&&applyTrackGain(dry,stereo?dryR:void 0,track2,context),bad=scrubNonFinite(dry)+(stereo?scrubNonFinite(dryR):0),voiceKey!==void 0&&disk.store.voices.set(voiceKey,{left:dry,...stereo?{right:dryR}:{},...bad>0?{nonFinite:bad}:{}})}let noted=track2&&needsEffectNotes(track2)?{...context,notes:effectNotes(played,context,tuning)}:context,patchStage=track2?patchStageFor(track2,context,bank,PATCH_RENDERER,side):void 0,chain=patchStage?{...noted,patchStage}:noted;track2&&applyMonoChain(dry,track2,chain),stereo&&track2&&applyMonoChain(dryR,track2,chain),applyPan(dry,target.left,target.right,track2,context,stereo?dryR:void 0);let saved;if(track2&&room!==void 0){applyStereoChain(target.left,target.right,track2,chain,!0,!1),bad+=scrubNonFinite(target.left)+scrubNonFinite(target.right);let pre={left:Float64Array.from(target.left),right:Float64Array.from(target.right)},wet=reverbWet(target.left,target.right,track2,context);wet&&(addReverbWet(target.left,target.right,wet,track2,context),saved={key:room,pre,wet})}else track2&&applyStereoChain(target.left,target.right,track2,chain,busOrbit===void 0);track2&&applyPostPatches(target.left,target.right,track2,context,bank,PATCH_RENDERER,side),bad+=scrubNonFinite(target.left)+scrubNonFinite(target.right),stem={key,left:target.left,right:target.right,bytes:target.left.byteLength*(saved?6:2),used:this.renders,...saved?{room:saved}:{},...bad>0?{nonFinite:bad}:{}},caching&&this.store(trackId,stem),disk?.store.set(diskKey,{left:stem.left,right:stem.right,...bad>0?{nonFinite:bad}:{},...caching?{kept:!0}:{borrowed:!0}})}if(stem.nonFinite&&(nonFinite.samples+=stem.nonFinite,nonFinite.tracks.push(trackId)),track2&&busOrbit!==void 0){let bus=buses.get(busOrbit);bus||buses.set(busOrbit,bus=createOrbitBus(busOrbit,samples)),sendToBus(bus,track2,stem.left,stem.right,context,key)}addStem(mixL,mixR,stem.left,stem.right,samples,ducked.get(trackId)),taps&&tap(trackId,stem.left,stem.right,ducked.get(trackId))}let busGains=duckGains([...buses.keys()].map(orbit=>({id:`bus:${orbit}`,orbit})),duckers,samples,sampleRate,options.loop?frames:void 0);for(let orbit of[...buses.keys()].sort((a,b)=>a-b)){let bus=buses.get(orbit),key=JSON.stringify(bus.keys),wet=this.buses.get(orbit);if(wet?.key!==key){let diskKey=disk?stemStoreKey(disk.scope,"bus",key):"",stored=disk?.store.get(diskKey);wet=stored&&stored.left.length===samples?{key,left:stored.left,right:stored.right}:{key,...renderOrbitBus(bus,context)},disk&&!stored&&disk.store.set(diskKey,{left:wet.left,right:wet.right,...caching?{kept:!0}:{}}),caching&&this.buses.set(orbit,wet)}addStem(mixL,mixR,wet.left,wet.right,samples,busGains.get(`bus:${orbit}`)),taps&&tap(`bus:${orbit}`,wet.left,wet.right,busGains.get(`bus:${orbit}`))}for(let orbit of[...this.buses.keys()])buses.has(orbit)||this.buses.delete(orbit);for(let trackId of[...this.stems.keys()])groups.has(trackId)||this.evict(trackId);if(ringFade>0&&fadeEnd(mixL,mixR,samples,ringFade),options.loop&&taps?.unfolded)return taps.unfolded.mix(mixL,mixR,frames,samples),Object.freeze({sampleRate,channels:RENDER_CHANNELS,frames:0,pcm:new Int16Array(0),...nonFinite.samples>0?{nonFinite:Object.freeze({samples:nonFinite.samples,tracks:Object.freeze([...nonFinite.tracks])})}:{}});samples>frames&&foldTail(mixL,mixR,frames,samples);let busBad=scrubNonFinite(mixL)+scrubNonFinite(mixR);busBad>0&&(nonFinite.samples+=busBad,nonFinite.tracks.push("bus")),taps?.mix?.(mixL.subarray(0,frames),mixR.subarray(0,frames));let mastered=applyMaster(mixL,mixR,frames,sampleRate,score.master,options.loop===!0,void 0,options.masterPreview),pcm=mastered?toPcm(mastered.left,mastered.right,frames,!0):toPcm(mixL,mixR,frames);return Object.freeze({sampleRate,channels:RENDER_CHANNELS,frames,pcm,...mastered?{master:mastered.report}:{},...nonFinite.samples>0?{nonFinite:Object.freeze({samples:nonFinite.samples,tracks:Object.freeze([...nonFinite.tracks])})}:{}})}vocoderTap(source,context,bank){let known=this.modSources.get(source.key);if(known&&known.tap.length===context.samples)return known.used=this.renders,known.tap;let tap=renderVocoderTap(source,context,bank);for(let[key,entry]of this.modSources)entry.used<this.renders-1&&this.modSources.delete(key);return this.maxCacheBytes>0&&this.modSources.set(source.key,{tap,used:this.renders}),tap}scratchFor(samples){this.scratch.dry.length<samples&&(this.scratch={dry:new Float64Array(samples),dryR:new Float64Array(samples),left:new Float64Array(samples),right:new Float64Array(samples),mixL:new Float64Array(samples),mixR:new Float64Array(samples)});let view=buffer=>buffer.subarray(0,samples);return{dry:view(this.scratch.dry),dryR:view(this.scratch.dryR),left:view(this.scratch.left),right:view(this.scratch.right),mixL:view(this.scratch.mixL),mixR:view(this.scratch.mixR)}}store(trackId,stem){for(this.evict(trackId);this.cacheBytes+stem.bytes>this.maxCacheBytes&&this.stems.size>0;){let oldest;for(let[id,candidate]of this.stems)candidate.used!==this.renders&&(oldest===void 0||candidate.used<this.stems.get(oldest).used)&&(oldest=id);if(oldest===void 0)break;this.evict(oldest)}this.cacheBytes+stem.bytes>this.maxCacheBytes||(this.stems.set(trackId,stem),this.cacheBytes+=stem.bytes)}evict(trackId){let stem=this.stems.get(trackId);stem&&(this.stems.delete(trackId),this.cacheBytes-=stem.bytes)}};function tapStem(taps,id,left,right,frames,gain){if(!gain){taps.stem(id,left.subarray(0,frames),right.subarray(0,frames));return}let l=new Float64Array(frames),r=new Float64Array(frames);for(let index=0;index<frames;index+=1)l[index]=left[index]*gain[index],r[index]=right[index]*gain[index];taps.stem(id,l,r)}function tapLoopStem(taps,id,left,right,frames,samples,gain,ringFade){let l=new Float64Array(frames),r=new Float64Array(frames),fade=Math.min(ringFade,samples),fadeFrom=samples-fade;for(let index=0;index<samples;index+=1){let g=gain?gain[index]:1;index>=fadeFrom&&(g*=(samples-1-index)/fade),l[index%frames]+=left[index]*g,r[index%frames]+=right[index]*g}taps.stem(id,l,r)}function storeScope(score,options){let{tracks:_t,notes:_n,master:_m,...globals}=score.toJSON();return JSON.stringify([globals,options.guide===!0])}function stemStoreKey(scope,kind,key){return createHash3("sha256").update(kind).update("\0").update(scope).update("\0").update(key).digest("hex")}function addStem(mixL,mixR,left,right,samples,gain){if(gain)for(let index=0;index<samples;index+=1)mixL[index]+=left[index]*gain[index],mixR[index]+=right[index]*gain[index];else for(let index=0;index<samples;index+=1)mixL[index]+=left[index],mixR[index]+=right[index]}function fadeEnd(mixL,mixR,samples,fade){let n2=Math.min(fade,samples);for(let i=0;i<n2;i+=1){let gain=(n2-1-i)/n2;mixL[samples-n2+i]*=gain,mixR[samples-n2+i]*=gain}}function foldTail(mixL,mixR,frames,samples){for(let index=frames;index<samples;index+=1)mixL[index%frames]+=mixL[index],mixR[index%frames]+=mixR[index]}function masterSummedPcm(pcm,frames,sampleRate,master,loop,preview){let mastered=applyMasterPcm(pcm,frames,sampleRate,master,loop,preview);if(mastered)return{pcm:toPcm(mastered.left,mastered.right,frames,!0),report:mastered.report}}function roomTrack(track2){let lanes={...track2.fxAutomation};return delete lanes["reverb-mix"],{...track2,reverb:{...track2.reverb,mix:1},fxAutomation:lanes}}var CHAIN_LANE_STAGE=new Map(FX_LANES.filter(({effect})=>effect==="reverb"||FX_NAMES.includes(effect)).map(({lane,effect})=>[lane,effect])),CHAIN_LANES=new Set(CHAIN_LANE_STAGE.keys());function dryTrack(track2){let lanes=track2.fxAutomation,kept=lanes?Object.fromEntries(Object.entries(lanes).filter(([lane])=>!CHAIN_LANES.has(lane))):void 0,{fx:_fx,fxAutomation:_lanes,...rest}=track2;return{...rest,...kept&&Object.keys(kept).length>0?{fxAutomation:kept}:{}}}function stemKey(track2,notes,context,bank,wavetableId,impulseId,engineDigests){let settings=null;if(track2){let{muted:_muted,solo:_solo,...rest}=track2;settings=rest}return JSON.stringify([settings,notes,context.score.tempoBpm,context.score.ticksPerBeat,context.score.beatsPerBar,context.sampleRate,context.samples,...context.score.time?[context.score.time]:[],...bank&&track2?.sampler?[samplerVoiceDigest(track2,bank)]:[],...wavetableId?[wavetableId]:[],...impulseId?[impulseId]:[],...engineDigests?[engineDigests]:[],...context.score.tuning||track2?.tuning?[context.score.tuning??null,context.score.key]:[],...context.score.calibration?[`cal:${context.score.calibration}`]:[],...context.seedTick?[`seed:${context.seedTick}`]:[],...context.seedSeconds?[`at:${context.seedSeconds}`]:[],...track2&&context.seedState?.[track2.id]?[`state:${context.seedState[track2.id]}`]:[]])}function samplerVoiceDigest(track2,bank){return Object.keys(track2.sampler?.voices??{}).sort().map(voice=>{let sample=bank.voices.get(sampleKey(track2.id,voice));return sample?`${voice}:${sample.sha256}:${sample.sampleRate}:${sample.frames}`:`${voice}:-`})}var TAP_END=FX_CHAIN.indexOf("pan");function sideSourceOf(track2,groups,performed,context,bank){let src=(isPatchTrack(track2)?track2.patch.side:void 0)??(track2.fxPatch??[]).find(patch=>patch.side!==void 0)?.side;if(src===void 0)return;let source=vocoderSourceOf({...track2,vocoder:{src,tap:"dry",gate:0}},groups,performed,context,bank);return source?{...source,key:`side:${source.key}`}:void 0}function vocoderPlaysWithoutNotes(track2){if(!track2.vocoder||track2.instrument!==VOCODER_INSTRUMENT2)return!1;let follow3=resolveVocoder(track2.vocoder).follow;return follow3==="chords"||follow3==="drone"}var assetGates=new WeakMap;function sourceGateDb(source,bank){let gate;for(let voice of Object.keys(source.sampler?.voices??{}).sort()){let sample=bank.voices.get(sampleKey(source.id,voice));if(!sample)continue;let level2=assetGates.get(sample);level2===void 0&&(level2=autoGateDb(Float64Array.from(sample.mono),sample.sampleRate),assetGates.set(sample,level2)),level2>-120&&(gate=gate===void 0?level2:Math.min(gate,level2))}return gate??-120}function vocoderSourceOf(track2,groups,performed,context,bank){let ref=track2.vocoder?.src;if(ref===void 0)return;let source=resolveTrackRef(context.score,ref);if(!source||source.id===track2.id)return;let settings=resolveVocoder(track2.vocoder),notes=groups.get(source.id)??[],engine2=engineFor2(source),{vocoder:_vocoder,pan:_pan,volume:_volume,volumeAutomation:_volumeAutomation,panAutomation:_panAutomation,delay:_delay,delayFeedbackAutomation:_delayFeedback,delayMixAutomation:_delayMix,reverb:_reverb,...kept}=source,tapped=settings.tap==="chain"?FX_CHAIN.slice(0,TAP_END):[],fx=kept.fx?Object.fromEntries(Object.entries(kept.fx).filter(([stage])=>tapped.includes(stage)||!FX_CHAIN.includes(stage))):void 0,lanes=kept.fxAutomation?Object.fromEntries(Object.entries(kept.fxAutomation).filter(([lane])=>{let stage=CHAIN_LANE_STAGE.get(lane);return stage===void 0||tapped.includes(stage)})):void 0,stripped={...kept,fx:fx&&Object.keys(fx).length>0?fx:void 0,fxAutomation:lanes&&Object.keys(lanes).length>0?lanes:void 0},gateDb=settings.gate==="auto"?sourceGateDb(source,bank):settings.gate,clipDigest=clipsDigest(source,bank,!1),clipKeys=[...clipDigest===void 0?[]:[`clips:${clipDigest}`],...source.autotune?autotuneStemDigests(source,context.score):[]],key=stemKey(stripped,notes,context,isSamplerInstrument(source.instrument)?bank:void 0,wavetableHook(source,bank,context)?.id,void 0,engine2?[...engine2.assetDigests?.(source,bank,context.score)??[],`key:${context.score.key??""}`,...clipKeys]:clipKeys.length>0?clipKeys:void 0);return{track:source,played:performed.get(source.id)??[],tap:settings.tap,key:`vocsrc:${settings.tap}:${gateDb}:${key}`,gateDb}}function renderVocoderTap(source,context,bank){let{played}=source,track2={...source.track,volume:1,volumeAutomation:[]},{score}=context,dry=new Float64Array(context.samples),dryR=new Float64Array(context.samples),tuning=resolveTuning(score.tuning,track2.tuning,score.key),stereo=renderVoiceInto(dry,dryR,played,track2,context,score,bank,engineFor2(track2),isSamplerInstrument(track2.instrument),wavetableHook(track2,bank,context),tuning,!1);if(source.tap==="chain"){let chain=needsEffectNotes(track2)?{...context,notes:effectNotes(played,context,tuning)}:context;applyMonoChain(dry,track2,chain),stereo&&applyMonoChain(dryR,track2,chain)}if(stereo)for(let i=0;i<dry.length;i+=1)dry[i]=(dry[i]+dryR[i])/2;return dry}function renderVoiceInto(dry,dryR,played,track2,context,score,bank,engine2,sampler,wavetable,tuning,guide,side){let synthVoice=!engine2&&!sampler&&usesSynthVoice(track2),stereo=engine2?engine2.stereo(track2):synthVoice&&isStereoVoice(track2);if(stereo&&dryR.fill(0),engine2&&track2&&isPatchTrack(track2))dryR.fill(0),stereo=renderPatchTrack(dry,dryR,played,track2,{...context,...tuning?{tuning}:{}},bank,PATCH_RENDERER,side);else if(engine2&&track2)engine2.render(dry,stereo?dryR:void 0,played,track2,{...context,ticksPerBeat:score.ticksPerBeat,...tuning?{tuning}:{}},bank);else if(sampler)track2&&(stereo=renderSamplerNotes(dry,played,track2,context,bank,dryR));else if(synthVoice&&track2){let gainAt=tick=>trackGainAt(track2,tick),voice={...context,ticksPerBeat:score.ticksPerBeat,...wavetable?{oscillatorFor:wavetable.oscillatorFor}:{},...tuning?{tuning}:{}},warp2=context.warp;for(let note2 of played){let{start,length}=noteSpan(note2,context);renderSynthNote(dry,stereo?dryR:void 0,note2,track2,start,length,voice,warp2?tick=>gainAt(warp2.tick(start+(tick-note2.startTick)*context.samplesPerTick)):gainAt)}}else if(track2?.clips&&isGuideInstrument(track2.instrument)){if(guide)for(let note2 of played)renderToneNote(dry,{...note2,velocity:note2.velocity*GUIDE_LEVEL},{...track2,instrument:"sine"},context,tuning)}else{let drums=isDrumInstrument(track2?.instrument),chokes=drums&&(context.score.calibration??0)>=1?hatChokes(played,context):void 0;for(let note2 of played)drums?renderDrumNote(dry,note2,track2,context,chokes?.get(note2)):renderToneNote(dry,note2,track2,context,tuning)}if(track2?.clips){let gainAt=tick=>trackGainAt(track2,tick);renderClips(dry,track2,context,bank,gainAt,score),stereo&&renderClips(dryR,track2,context,bank,gainAt,score)}return stereo}function renderSamplerNotes(target,notes,track2,context,bank,targetRight){let timing={score:context.score,sampleRate:context.sampleRate,...context.warp?{warp:context.warp}:{}},voices=planSamplerVoices(track2,notes,bank,timing),gainAt=tick=>trackGainAt(track2,tick);return voices.some(voice=>voice.stereo)?(targetRight.fill(0),renderSamplerVoices(target,voices,timing,gainAt,"left"),renderSamplerVoices(targetRight,voices,timing,gainAt,"right"),!0):(renderSamplerVoices(target,voices,timing,gainAt),!1)}function applyTrackGain(left,right,track2,context){let fixed=(track2.volumeAutomation??[]).length===0,flat=trackGainAt(track2,0);for(let index=0;index<left.length;index+=1){let gain=fixed?flat:trackGainAt(track2,context.warp?context.warp.tick(index):index/context.samplesPerTick);left[index]*=gain,right&&(right[index]*=gain)}}function effectNotes(notes,context,tuning){return notes.map(note2=>{let{start,length}=noteSpan(note2,context);return{id:note2.id,start,length,hz:noteHz(note2.pitch,note2.cents,tuning),velocity:note2.velocity}})}var CHOKING_HATS=new Set([42,44]),CHOKE_SECONDS2=.008;function hatChokes(notes,context){let closers=notes.filter(note2=>CHOKING_HATS.has(note2.pitch)).map(note2=>noteSpan(note2,context).start).sort((a,b)=>a-b),chokes=new Map;if(closers.length===0)return chokes;for(let note2 of notes){if(note2.pitch!==46)continue;let start=noteSpan(note2,context).start,next=closers.find(closer=>closer>start);next!==void 0&&chokes.set(note2,next)}return chokes}function renderDrumNote(target,note2,track2,context,chokeAt){let{sampleRate,samples,samplesPerTick}=context,{start}=noteSpan(note2,context),kit2=synthKit(track2?.kit),kitState=kit2?newKitVoiceState():void 0,calibrated=(context.score.calibration??0)>=1,metal=calibrated?metalKindForPitch(note2.pitch):void 0,metalState=metal?newKitVoiceState():void 0,ratio2=calibrated?tomRatio(note2.pitch):1,chokeEnd=chokeAt===void 0?Number.POSITIVE_INFINITY:chokeAt+Math.ceil(CHOKE_SECONDS2*sampleRate),end=Math.min(samples,chokeEnd,start+Math.ceil((metal?METAL_SECONDS:kit2?.seconds??MAX_DRUM_SECONDS)*sampleRate)),voice=drumVoiceForPitch(note2.pitch),hatWave=kit2&&(voice==="hat"||voice==="openhat")&&kit2[voice].metal>0?kitHatWave(sampleRate,calibrated,end-start):void 0,random2=seededRandom(`${note2.id}:${note2.startTick+(context.seedTick??0)}`),velocity=Math.max(0,Math.min(1,note2.velocity)),phase=0,previousNoise=0,band=0;for(let index=start;index<end;index+=1){let t=(index-start)/sampleRate,noise2=random2()*2-1,bright=noise2-previousNoise;previousNoise=noise2;let sample=0;if(metal&&metalState)sample=metalSample(metal,t,bright,metalState,sampleRate),kit2&&(sample*=kit2.gain);else if(kit2&&kitState)sample=kitDrumSample(kit2,voice,t,noise2,bright,kitState,sampleRate,calibrated?{tomRatio:ratio2}:void 0,hatWave?.[index-start]);else if(voice==="kick"){let frequency=45+105*Math.exp(-t*28);phase+=frequency/sampleRate,sample=Math.sin(2*Math.PI*phase)*Math.exp(-t*7.5)+noise2*.12*Math.exp(-t*300)}else if(voice==="tom"){let frequency=(105+95*Math.exp(-t*18))*ratio2;phase+=frequency/sampleRate,sample=Math.sin(2*Math.PI*phase)*Math.exp(-t*9)}else if(voice==="snare")phase+=185/sampleRate,sample=Math.sin(2*Math.PI*phase)*.45*Math.exp(-t*22)+noise2*.7*Math.exp(-t*16);else if(voice==="clap"){band+=.35*(bright-band);let burst=t<.03?Math.floor(t/.01)%2===0?1:.35:0;sample=band*(burst+.8*Math.exp(-(t-.03)*18)*+(t>=.03))}else voice==="hat"?sample=bright*.42*Math.exp(-t*60):voice==="openhat"?sample=bright*.36*Math.exp(-t*9):sample=(Math.sin(2*Math.PI*1700*t)*.6+Math.sin(2*Math.PI*820*t)*.4)*Math.exp(-t*90);let attack=Math.min(1,(index-start)/Math.max(1,sampleRate*.001)),release=chokeAt!==void 0&&index>=chokeAt?Math.max(0,chokeEnd-index)/Math.max(1,chokeEnd-chokeAt):Math.min(1,(end-index)/Math.max(1,sampleRate*.005));target[index]+=sample*attack*release*velocity*.5*trackGainAt(track2,context.warp?context.warp.tick(index):note2.startTick+(index-start)/samplesPerTick)}}function wavetableHook(track2,bank,context){if(!isWavetableInstrument(track2.instrument))return;let settings=wavetableOf(track2),table2=tableFor2(track2,settings,bank.wavetables);if(!table2)return{id:`missing:${settings.table.src}`,oscillatorFor:()=>()=>()=>0};let lane=track2.wtAutomation??[],positionAt=lane.length>0?tick=>interpolateAutomation(lane,tick,settings.wt??0):void 0,warp2=context.warp;return{id:table2.id,oscillatorFor:note2=>{let span4=noteSpan(note2,context);return wavetableOscillator(table2,settings,note2,{sampleRate:context.sampleRate,samplesPerTick:context.samplesPerTick,secondsPerTick:context.samplesPerTick/context.sampleRate,gate:span4.length/context.sampleRate,positionAt:warp2&&positionAt?tick=>positionAt(warp2.tick(span4.start+(tick-note2.startTick)*context.samplesPerTick)):positionAt})}}}var PATCH_RENDERER={voice(dry,dryR,played,track2,context,bank){let{score}=context;return renderVoiceInto(dry,dryR,played,track2,context,score,bank,engineFor2(track2),isSamplerInstrument(track2.instrument),wavetableHook(track2,bank,context),resolveTuning(score.tuning,track2.tuning,score.key),!1)},stage(stage,left,right,track2,context){right===void 0?applyMonoChain(left,track2,context):applyStereoChain(left,right,track2,context)},digests(track2,bank,score){let engine2=engineFor2(track2);return[`engine:${track2.instrument}`,...engine2?.assetDigests?.(track2,bank,score)??[],...track2.sampler?samplerVoiceDigest(track2,bank):[],...track2.wavetable?[JSON.stringify(track2.wavetable)]:[],...track2.clips?[`clips:${clipsDigest(track2,bank,!1)??""}`]:[]]},span:noteSpan,tail:(track2,lowestPitch)=>Math.max(synthTailSeconds(track2),engineTailSeconds(track2,lowestPitch))};registerEngine(patchEngine(PATCH_RENDERER));import{createHash as createHash5}from"node:crypto";import{createHash as createHash4}from"node:crypto";var DEFAULT_LOOP_CACHE_BYTES=64*1024*1024;function loopCacheKey(score,sampleRate,samples){return createHash4("sha256").update(JSON.stringify(score.toJSON())).update(JSON.stringify([sampleRate,[...samples?.voices??[]].map(([key,sample])=>[key,sample.sha256]),[...samples?.wavetables??[]].map(([key,table2])=>[key,table2.id]),[...samples?.irs??[]].map(([key,sample])=>[key,sample.sha256])])).digest("hex")}var DEFAULT_WINDOW_CACHE_BYTES=64*1024*1024,WINDOW_RENDER_VERSION=1;function windowCacheKey(score,options){return createHash5("sha256").update(loopCacheKey(score,options.sampleRate??22050,options.samples)).update(JSON.stringify([WINDOW_RENDER_VERSION,options.loop===!0,options.guide===!0,options.maxSeconds,options.seedTick,options.seedSeconds,options.seedState,options.quantChord?.tick,options.quantChord?.score.toJSON()])).digest("hex")}function replayWindowStems(window,taps){for(let stem of window.stems){let left=new Float64Array(stem.length),right=new Float64Array(stem.length);left.set(stem.headLeft,stem.headFrom),right.set(stem.headRight,stem.headFrom);let body2=stem.headFrom+stem.headLeft.length;left.set(stem.bodyLeft,body2),right.set(stem.bodyRight,body2),taps.stem(stem.id,left,right)}}var MONITOR_GRID_SECONDS=1,QUICK_PREROLL_SECONDS=1,DEFAULT_PASS_SECONDS=30,SINGLE_PASS_SECONDS=45,WINDOW_SECONDS=20,OVERHANG_SECONDS=8,SEAM_FADE_SECONDS=.05,WINDOW_BUDGET_SECONDS=50;function loopedSection(score){if(score.loop){let startBar=Math.min(score.loop.startBar,score.bars-1),bars=Math.max(1,Math.min(score.loop.bars,score.bars-startBar));return{name:"loop",startBar,bars}}return score.loopSection===void 0?void 0:findSection(score,score.loopSection)}function playbackTime(score){let section=loopedSection(score);if(section)return sectionScore(score,section);let segments=formSegments(score);if(segments.length===0)return score;let ticks=barTicks(score),timed=sliceSongTime(score,segments.map(segment=>({from:segment.section.startBar*ticks,to:(segment.section.startBar+segment.bars)*ticks,offset:segment.startBar*ticks})));return{tempoBpm:timed.tempoBpm,beatsPerBar:score.beatsPerBar,bars:arrangedBars(score),ticksPerBeat:score.ticksPerBeat,...timed.time?{time:timed.time}:{}}}function renderArranged(renderer,score,options={}){return score=withClipLengths(score,options.samples),options.monitorFrame===void 0&&!(options.loop&&loopedSection(score))&&formSegments(score).length===0&&applySectionChanges(score)===score&&fitsOnePass(renderer,score,options)?renderer.render(score,options):withNoteCap(BAKED_NOTE_CAP,()=>renderArrangedBaked(renderer,score,options))}function renderArrangedBaked(renderer,score,options){score=bakeTrackTime(score);let section=options.loop?loopedSection(score):void 0;if(!section&&formSegments(score).length>0)return renderForm(renderer,score,options);let played=section?sectionScore(score,section):applySectionChanges(score);if(options.monitorFrame===void 0&&played===score&&fitsOnePass(renderer,score,options))return renderer.render(score,options);let ticks=barTicks(played),seconds2=secondsAtTick(played,played.bars*ticks);if(seconds2>MAX_SONG_SECONDS)throw new ScoreValidationError(`the song plays ${Math.round(seconds2)} s; the limit is ${MAX_SONG_SECONDS} s`,"score-limit");return options.monitorFrame===void 0&&seconds2<=SINGLE_PASS_SECONDS?renderer.render(played,{...options,maxSeconds:60}):(played=bakeTrackTime(played,{always:!0}),renderWindows(renderer,played,played,played.bars,(from,to)=>played.notes.filter(note2=>note2.startTick>=from*ticks&¬e2.startTick<to*ticks),(from,bars)=>sectionScore(played,{name:"window",startBar:from,bars}),options))}function fitsOnePass(renderer,score,options){return options.maxSeconds!==void 0?!0:options.loop?loopSecondsOf(score)<=DEFAULT_PASS_SECONDS:renderer.oneShotSeconds(score,options)<=DEFAULT_PASS_SECONDS}function renderForm(renderer,score,options){let total=arrangedBars(score),timeline=playbackTime(score),seconds2=secondsAtTick(timeline,total*barTicks(score));if(seconds2>MAX_SONG_SECONDS)throw new ScoreValidationError(`the form plays ${Math.round(seconds2)} s; the limit is ${MAX_SONG_SECONDS} s`,"score-limit");return renderWindows(renderer,score,timeline,total,(from,to)=>arrangedNotes(score,from,to),(from,bars)=>arrangedSlice(score,from,bars,0),options)}function renderArrangedPcm(score,options={}){let{cache:cache4,...rest}=options;return cache4&&!rest.windowCache&&!rest.stemSink&&(rest.windowCache=cache4.windows),renderArranged(new StemRenderer({maxCacheBytes:0,...cache4?{store:cache4}:{}}),score,rest)}function renderMonitorWindow(renderer,score,timeline,notesIn,frame,options){let sampleRate=clampSampleRate(options.sampleRate),ticks=barTicks(score),totalTicks=loopTicksOf(timeline),loopFrames2=Math.max(1,Math.round(loopSecondsOf(timeline)*sampleRate)),target=(Math.floor(options.monitorFrame)%loopFrames2+loopFrames2)%loopFrames2,span4=Math.max(1,Math.round(Math.min(16,Math.max(1,options.monitorSeconds??4))*sampleRate)),grid2=Math.max(1,Math.round(MONITOR_GRID_SECONDS*sampleRate)),start=Math.floor(target/grid2)*grid2,end=Math.min(loopFrames2,Math.ceil((target+span4)/grid2)*grid2),quick=options.monitorQuick===!0,frameAt=tick=>Math.round(secondsAtTick(timeline,tick)*sampleRate),tickAt4=sample=>tickAtSeconds(timeline,sample/sampleRate),overhang=Math.max(quick?QUICK_PREROLL_SECONDS:OVERHANG_SECONDS,...score.tracks.map(track2=>vocoderPrerollSeconds(track2.vocoder))),beforeHold=tick=>{let result=Math.max(0,Math.floor(tick)),holds=timeline.time?.fermatas??[];for(let index=holds.length-1;index>=0;index--){let hold=holds[index];hold.tick<=result&&hold.tick+fermataSpan(timeline,hold.tick)>result&&(result=Math.min(result,hold.tick))}return result},preTick=beforeHold(tickAt4(Math.max(0,start-overhang*sampleRate))),startTick=tickAt4(start),last=end===loopFrames2,noteEnd=Math.min(totalTicks,Math.ceil(tickAt4(end))+ticks),all=notesIn(Math.max(0,startTick/ticks-SCORE_LIMITS.maxBars),noteEnd/ticks),earliest=Math.max(0,quick?start-overhang*sampleRate:end-WINDOW_BUDGET_SECONDS*sampleRate);for(let note2 of all){let candidate=beforeHold(note2.startTick);note2.startTick<startTick&&frameAt(note2.startTick+note2.durationTicks)+overhang*sampleRate>start&&frameAt(candidate)>=earliest&&(preTick=Math.min(preTick,candidate))}let preFrame=frameAt(preTick),notes=[];for(let note2 of all){if(note2.startTick>=noteEnd)continue;let stop=note2.startTick+note2.durationTicks;note2.startTick>=preTick?notes.push({...note2,startTick:note2.startTick-preTick}):stop>preTick&¬es.push({...note2,startTick:0,durationTicks:stop-preTick})}let bars=Math.max(1,Math.ceil((noteEnd-preTick)/ticks)),window=withNoteCap(BAKED_NOTE_CAP,()=>new TrackScore({...frame(preTick/ticks,bars).toJSON(),notes,master:null})),seedState={};if(preTick>0&&window.tracks.some(track2=>engineFor2(track2)?.windowSeed)){let history=frame(0,Math.max(1,Math.ceil(preTick/ticks)));for(let track2 of history.tracks){let seed=engineFor2(track2)?.windowSeed?.(history,track2,preFrame,sampleRate);seed!==void 0&&(seedState[track2.id]=seed)}}let windowOptions={...options,cacheStems:options.cacheStems??!1,sampleRate,loop:!1,seedTick:preTick,...preTick>0?{seedSeconds:secondsAtTick(timeline,preTick)}:{},...Object.keys(seedState).length?{seedState}:{},maxSeconds:Math.min(60,(end-preFrame)/sampleRate+(last?overhang:quick?.25:1))},key=options.windowCache?windowCacheKey(window,windowOptions):void 0,cached=key===void 0?void 0:options.windowCache?.get(key),audio=cached??renderer.render(window,windowOptions);if(!cached&&key!==void 0&&options.windowCache?.set(key,audio),options.monitorTailOnly){let tail=audio.pcm.slice(Math.max(0,loopFrames2-preFrame)*RENDER_CHANNELS);return{sampleRate,channels:RENDER_CHANNELS,frames:tail.length/RENDER_CHANNELS,pcm:tail}}let input=audio.pcm;if(options.loop&&!quick&&preFrame<overhang*sampleRate){let tail=renderMonitorWindow(renderer,score,timeline,notesIn,frame,{...options,monitorFrame:loopFrames2-1,monitorTailOnly:!0}),from=preFrame*RENDER_CHANNELS;if(from<tail.pcm.length){input=input.slice();let take=Math.min(input.length,tail.pcm.length-from);for(let i=0;i<take;i++)input[i]=Math.max(-32768,Math.min(32767,input[i]+tail.pcm[from+i]))}}let monitored=applyMonitorMaster(input,sampleRate,score.master),overlap=Math.min(Math.round(SEAM_FADE_SECONDS*sampleRate),start-preFrame),begin=start-preFrame-overlap,frames=Math.min(end-start+overlap,audio.frames-begin);if(begin<0||frames<=0||start-overlap+frames<=target)throw new ScoreValidationError("monitor render did not cover the requested frame","score-limit");let pcm=monitored.slice(begin*RENDER_CHANNELS,(begin+frames)*RENDER_CHANNELS),nonFinite=audio.nonFinite;if(start>0&&last&&target+span4>loopFrames2){let head=renderMonitorWindow(renderer,score,timeline,notesIn,frame,{...options,monitorFrame:0,monitorSeconds:void 0}),headFrames=Math.min(head.frames,start+2*span4-loopFrames2),joined=new Int16Array(pcm.length+headFrames*RENDER_CHANNELS);joined.set(pcm),joined.set(head.pcm.subarray(0,headFrames*RENDER_CHANNELS),pcm.length),pcm=joined,frames+=headFrames,head.nonFinite&&(nonFinite={samples:(nonFinite?.samples??0)+head.nonFinite.samples,tracks:[...new Set([...nonFinite?.tracks??[],...head.nonFinite.tracks])]})}return{sampleRate,channels:RENDER_CHANNELS,frames,pcm,monitor:{startFrame:start-overlap,loopFrames:loopFrames2},...nonFinite?{nonFinite}:{}}}function renderWindows(renderer,score,timeline,totalBars,notesIn,frame,options){if(options.monitorFrame!==void 0)return renderMonitorWindow(renderer,score,timeline,notesIn,frame,options);let sampleRate=clampSampleRate(options.sampleRate),ticks=barTicks(score),bpms=[score.tempoBpm,...(timeline.time?.tempo??[]).map(e=>e.bpm)],fermataStretch=timeline.time?.fermatas?2:1,beatsPerBar=score.beatsPerBar,fastBar=beatsPerBar*60/Math.max(...bpms),slowBar=beatsPerBar*60/Math.min(...bpms)*fermataStretch,frameAt=bar=>Math.round(secondsAtTick(timeline,bar*ticks)*sampleRate),overhang=Math.max(OVERHANG_SECONDS,...score.tracks.map(track2=>vocoderPrerollSeconds(track2.vocoder))),ring=Math.max(1,Math.ceil(overhang/fastBar)),ringTicks=Math.ceil(overhang/fastBar*ticks),bank=options.samples,samplers=new Map(score.tracks.filter(t=>t.sampler).map(t=>[t.id,t])),sounding=new Map,soundsUntil=note2=>{let stop=note2.startTick+note2.durationTicks,track2=samplers.get(note2.trackId);if(!bank||!track2)return stop;let key=`${note2.trackId}:${note2.pitch}:${note2.velocity}:${note2.durationTicks}`,seconds2=sounding.get(key);seconds2===void 0&&(seconds2=samplerNoteSeconds(score,track2,{...note2,startTick:0},bank,sampleRate),sounding.set(key,seconds2));let end=tickAtSeconds(timeline,secondsAtTick(timeline,note2.startTick)+seconds2);return Math.max(stop,end)},budget=Math.max(1,Math.floor(WINDOW_BUDGET_SECONDS/slowBar)),reach=budget-1,most=Math.max(1,Math.floor(WINDOW_SECONDS/slowBar)),master=score.master,look=SCORE_LIMITS.maxBars,parts=[],nonFinite={samples:0,tracks:[]};for(let start=0;start<totalBars;){let startTick=start*ticks,all=notesIn(Math.max(0,start-look),start+most+1),pre=Math.max(0,start-Math.min(ring,reach));for(let note2 of all)note2.startTick<startTick&&soundsUntil(note2)+ringTicks>startTick&&Math.floor(note2.startTick/ticks)>=start-reach&&(pre=Math.min(pre,Math.floor(note2.startTick/ticks)));pre=Math.max(pre,start-reach);let end=Math.min(totalBars,start+most,Math.max(start+1,pre+budget)),last=end>=totalBars,noteTo=last?end:Math.min(totalBars,end+1),preTick=pre*ticks,notes=[],restarted=!1;for(let note2 of all){if(note2.startTick>=noteTo*ticks)continue;let stop=note2.startTick+note2.durationTicks;note2.startTick>=preTick?notes.push({...note2,startTick:note2.startTick-preTick}):stop>preTick&&stop+ringTicks>startTick&&(notes.push({...note2,startTick:0,durationTicks:stop-preTick}),restarted=!0)}let bars=(last?end:noteTo)-pre+(last&&options.loop?ring:0),window=new TrackScore({...frame(pre,bars).toJSON(),notes,master:null}),seedState={};if(pre>0&&window.tracks.some(track2=>engineFor2(track2)?.windowSeed)){let history=frame(0,pre);for(let track2 of history.tracks){let seed=engineFor2(track2)?.windowSeed?.(history,track2,frameAt(pre),sampleRate);seed!==void 0&&(seedState[track2.id]=seed)}}let windowOptions={...options,cacheStems:options.cacheStems??!1,sampleRate,loop:!1,seedTick:preTick,...pre>0?{seedSeconds:secondsAtTick(timeline,pre*ticks)}:{},...Object.keys(seedState).length>0?{seedState}:{},maxSeconds:last?60:Math.min(60,secondsAtTick(timeline,noteTo*ticks)-secondsAtTick(timeline,pre*ticks))},sink=options.stemSink,tapOptions=windowOptions;if(sink){let previous=parts.at(-1),seam=restarted&&previous?Math.max(0,Math.min(Math.round(SEAM_FADE_SECONDS*sampleRate),frameAt(start)-frameAt(pre),previous.frames)):0;seam>0&&previous&&sink.fadeOut(previous.offset+previous.frames,seam);let from2=frameAt(start)-frameAt(pre)-seam,offset=frameAt(start)-seam,until=frames=>last?frames:Math.min(frames,frameAt(end)-frameAt(pre));tapOptions={...windowOptions,taps:{stem:(id,left,right)=>sink.add(id,offset,left,right,from2,until(left.length),seam)}}}if(options.windowPlans){options.windowPlans.push({key:windowCacheKey(window,windowOptions),score:window,options:windowOptions,keep:{from:frameAt(start)-frameAt(pre),...last?{}:{to:frameAt(end)-frameAt(pre)},seam:Math.round(SEAM_FADE_SECONDS*sampleRate)},restarted}),start=end;continue}let key=options.windowCache&&!sink?windowCacheKey(window,windowOptions):void 0,cached=key===void 0?void 0:options.windowCache?.get(key),tapped=sink&&options.windowStems?options.windowStems.get(windowCacheKey(window,windowOptions)):void 0;tapped&&replayWindowStems(tapped,tapOptions.taps);let audio=cached??tapped?.audio??renderer.render(window,tapOptions);if(!cached&&key!==void 0&&options.windowCache?.set(key,audio),audio.nonFinite){nonFinite.samples+=audio.nonFinite.samples;for(let id of audio.nonFinite.tracks)nonFinite.tracks.includes(id)||nonFinite.tracks.push(id)}let fade=restarted&&parts.length>0?Math.max(0,Math.min(Math.round(SEAM_FADE_SECONDS*sampleRate),frameAt(start)-frameAt(pre),parts.at(-1).frames)):0,from=frameAt(start)-frameAt(pre)-fade,to=last?audio.frames:Math.min(audio.frames,frameAt(end)-frameAt(pre));fade>0&&(parts.at(-1).fadeOut=fade),parts.push({offset:frameAt(start)-fade,pcm:audio.pcm.subarray(from*RENDER_CHANNELS,to*RENDER_CHANNELS),frames:Math.max(0,to-from),fadeIn:fade,fadeOut:0}),renderer.breathe(),start=end}if(options.windowPlans)return{sampleRate,channels:RENDER_CHANNELS,frames:0,pcm:new Int16Array(0)};let loopLength=Math.max(1,frameAt(totalBars)),length=Math.max(...parts.map(part=>part.offset+part.frames)),mix3=new Int32Array(length*RENDER_CHANNELS);for(let{offset,pcm:pcm2,frames,fadeIn,fadeOut}of parts){let base=offset*RENDER_CHANNELS;for(let frame2=0;frame2<frames;frame2+=1){let gain=frame2<fadeIn?(frame2+.5)/fadeIn:frame2>=frames-fadeOut?1-(frame2-(frames-fadeOut)+.5)/fadeOut:1;for(let channel=0;channel<RENDER_CHANNELS;channel+=1){let index=frame2*RENDER_CHANNELS+channel;mix3[base+index]+=gain===1?pcm2[index]:Math.round(pcm2[index]*gain)}}}if(options.loop){for(let index=loopLength*RENDER_CHANNELS;index<mix3.length;index+=1)mix3[index%(loopLength*RENDER_CHANNELS)]+=mix3[index];length=loopLength}let pcm=new Int16Array(length*RENDER_CHANNELS);for(let index=0;index<pcm.length;index+=1)pcm[index]=Math.max(-32768,Math.min(32767,mix3[index]));options.stemSink?.setPreMasterPcm(pcm,length),renderer.breathe();let mastered=masterSummedPcm(pcm,length,sampleRate,master,options.loop===!0,options.masterPreview),report=nonFinite.samples>0?{nonFinite:{samples:nonFinite.samples,tracks:[...nonFinite.tracks]}}:{};return mastered?{sampleRate,channels:RENDER_CHANNELS,frames:length,pcm:mastered.pcm,master:mastered.report,...report}:{sampleRate,channels:RENDER_CHANNELS,frames:length,pcm,...report}}var MASTER_SAMPLE_RATE=48e3;function exportSampleRate(score){return score.master?MASTER_SAMPLE_RATE:DEFAULT_SAMPLE_RATE}function sectionDensity(m){let step2=m.tpb/4,slots=new Set;for(let n2 of m.json.notes)m.json.tracks.find(x=>x.id===n2.trackId)?.muted||slots.add(Math.round(n2.startTick/step2));for(let n2 of m.sung)n2.syl!=="~"&&slots.add(Math.round(n2.tick/step2));let perBar=new Float64Array(m.bars);for(let s of slots){let bar=Math.floor(s*step2/m.tpBar);bar>=0&&bar<m.bars&&(perBar[bar]+=1)}let barSec=m.bpb*m.spb;return{perBar,sections:m.sections.map(s=>{let sum=0;for(let b=s.start;b<Math.min(m.bars,s.start+s.bars);b++)sum+=perBar[b];return{section:s,onsetsPerSec:sum/(s.bars*barSec)}})}}function densityRules(m,style2,emit){let{perBar,sections}=sectionDensity(m),d=style2.density,allowed=rule=>(m.config.allow??[]).some(a=>a.rule!==void 0&&(rule===a.rule||rule.startsWith(`${a.rule}.`))),chorus=sections.filter(s=>s.section.kind==="chorus"),verse=sections.filter(s=>s.section.kind==="verse");if(!allowed("density.chorus"))for(let c of chorus){let[lo,hi]=d.chorusOnsetsPerSec;(c.onsetsPerSec<lo||c.onsetsPerSec>hi)&&emit({rule:"density.chorus",severity:"warn",where:{bar:c.section.start,section:c.section.name},message:`${c.section.name}: ${c.onsetsPerSec.toFixed(1)} score onsets/s (${lo}\u2013${hi})`,fix:c.onsetsPerSec<lo?"the chorus is sparse: add a moving part (hats, arp, chops)":"the chorus is crowded: thin a layer"})}let mean=xs=>xs.reduce((s,x)=>s+x.onsetsPerSec,0)/xs.length;if(chorus.length&&verse.length&&!allowed("density.chorus-vs-verse")){let c=mean(chorus),v=mean(verse);c<v*d.chorusVsVerse&&emit({rule:"density.chorus-vs-verse",severity:"warn",where:{section:chorus[0].section.name},message:`choruses average ${c.toFixed(1)} onsets/s against the verses' ${v.toFixed(1)}`,fix:"the chorus should be at least as busy as the verse: add a part or thin the verse"})}let run=0;for(let b=0;b<m.bars-1;b++)run=perBar[b]===0?run+1:0,run===d.maxEmptyBars+1&&!allowed("density.hole")&&emit({rule:"density.hole",severity:"info",where:{bar:b-d.maxEmptyBars},message:`${run} bars with no new onset from bar ${b-d.maxEmptyBars}`,fix:"a deliberate silence is fine; otherwise keep something moving"})}var LANES2=["volumeAutomation","panAutomation","filterAutomation","resonanceAutomation","delayFeedbackAutomation","delayMixAutomation","wtAutomation"];function budgetRules(m,style2,emit){let notes=m.json.notes.length;notes>style2.budgets.maxNotes&&emit({rule:"budget.notes",severity:"error",where:{},message:`${notes} notes (budget ${style2.budgets.maxNotes})`,fix:"use loops, patterns or sampler phrases for repeats"});for(let t of m.json.tracks){let lanes=[];for(let k of LANES2){let v=t[k];Array.isArray(v)&&lanes.push([k,v])}for(let[k,v]of Object.entries(t.fxAutomation??{}))Array.isArray(v)&&lanes.push([k,v]);for(let[lane,pts]of lanes)pts.length>style2.budgets.maxLanePoints&&emit({rule:"budget.lane",severity:"error",where:{track:t.id},message:`${t.id} ${lane}: ${pts.length} points (budget ${style2.budgets.maxLanePoints})`,fix:"thin the lane (ramps need two points) or use an LFO"})}}function detectTricks(m){let found=new Map,add=(id,bar)=>(found.get(id)??found.set(id,new Set).get(id)).add(bar),byTrack=new Map(m.json.tracks.map(t=>[t.id,t])),hits=new Map,keyed=new Map;for(let n2 of m.json.notes){let t=byTrack.get(n2.trackId),sampler=t?.sampler;if(!t||t.muted||!sampler)continue;let bar=Math.floor(n2.startTick/m.tpBar);if(sampler.mode==="oneshot"){let name=Object.keys(sampler.voices).sort((a,b)=>a<b?-1:a>b?1:0)[n2.pitch-36],ref=name===void 0?void 0:sampler.voices[name];if(!ref)continue;ref.accelerate&&add(ref.accelerate<0?"tape-stop":"tape-spin",bar),Number(ref.speed??1)<0&&add("reverse",bar);let k=`${t.id}|${name}`;(hits.get(k)??hits.set(k,[]).get(k)).push(n2.startTick)}else(keyed.get(t.id)??keyed.set(t.id,[]).get(t.id)).push({tick:n2.startTick,pitch:n2.pitch})}for(let ticks of hits.values()){ticks.sort((a,b)=>a-b);let run=1;for(let i=1;i<ticks.length;i++)run=ticks[i]-ticks[i-1]<=m.tpb/4?run+1:1,run===4&&add("stutter",Math.floor(ticks[i]/m.tpBar))}for(let notes of keyed.values()){notes.sort((a,b)=>a.tick-b.tick);for(let i=0;i+4<=notes.length;i++){let w=notes.slice(i,i+4);w.every((x,j)=>j===0||x.tick-w[j-1].tick<=m.tpb/8)&&new Set(w.map(x=>x.pitch)).size>=3&&add("chop-roll",Math.floor(w[0].tick/m.tpBar))}}return[...found].map(([id,bars])=>({id,bars:[...bars].sort((a,b)=>a-b)}))}var featuredTricks=m=>(m.config.tricks??[]).filter(t=>t.featured!==!1);function trickRules(m,style2,emit){let ledger=featuredTricks(m),ids=new Map;for(let t of ledger)ids.set(t.id,(ids.get(t.id)??0)+1);for(let[id,n2]of ids)n2>1&&emit({rule:"tricks.repeat",severity:"error",where:{},message:`the ledger features ${id} ${n2} times`,fix:"feature a trick once; a second use is a new trick or a foundation idiom (featured: false)"});if(ledger.length){let[lo,hi]=style2.tricks.featured;(ledger.length<lo||ledger.length>hi)&&emit({rule:"tricks.count",severity:"info",where:{},message:`${ledger.length} featured tricks (${style2.archetype} songs feature ${lo}\u2013${hi})`,fix:ledger.length<lo?"add a featured moment":"drop a trick: too many reads as chaotic"})}for(let d of detectTricks(m)){let entries=ledger.filter(t=>t.id===d.id||t.id.startsWith(`${d.id}-`)),spans=entries.map(t=>t.bars).filter(b=>b!==void 0);if(!entries.length||!spans.length)continue;let outside=d.bars.filter(b=>!spans.some(([a,z])=>b>=a&&b<z));outside.length&&emit({rule:"tricks.repeat",severity:"warn",where:{bar:outside[0]},message:`${d.id} also plays at bar${outside.length===1?"":"s"} ${outside.slice(0,6).join(", ")}, outside its ledger bars`,fix:"a featured trick plays where the ledger puts it; widen its bars or remove the repeat"})}}var FUNCTION=new Set(`a an the and but or nor so if as of to in on at by for from with into
|
|
558
|
+
onto up out off than then that this these those there here is am are was were be been
|
|
559
|
+
being do does did has have had will would can could shall should may might must i i'm
|
|
560
|
+
i'll i've i'd you you're you'll you've me my mine your yours he him his she her hers it
|
|
561
|
+
it's its we us our they them their what when where who how not no just`.split(/\s+/)),VOCABLES=new Set(["ah","oh","ooh","mm","hm","la","na","oo","uh"]),quantile=(xs,q3)=>{let s=[...xs].sort((a,b)=>a-b);if(!s.length)return NaN;let i=(s.length-1)*q3,lo=Math.floor(i);return s[lo]+(s[Math.min(s.length-1,lo+1)]-s[lo])*(i-lo)},leadLines=m=>m.lines.filter(l=>m.lead.has(l.track)),leadNotes=m=>leadLines(m).flatMap(l=>l.notes).filter(n2=>n2.syl!=="~"||!0),severityFor=(style2,s)=>!style2.calibrated&&s==="error"?"warn":s,partAllowed=(m,rule,line)=>(m.config.allow??[]).some(a=>{let scope=a.rule;return!(scope===void 0||!(rule===scope||rule.startsWith(`${scope}.`))||a.part!==void 0&&!new RegExp(`^(${a.part})$`).test(line.part)||a.track!==void 0&&!new RegExp(`^(${a.track})$`).test(line.track))});function registerRules(m,style2,emit){let notes=leadNotes(m);if(notes.length<8)return;let kindOf=n2=>m.sectionAt(Math.floor(n2.tick/m.tpBar))?.kind,verse=notes.filter(n2=>kindOf(n2)==="verse").map(n2=>n2.pitch),chorus=notes.filter(n2=>kindOf(n2)==="chorus").map(n2=>n2.pitch),r=style2.register,sev=severityFor(style2,"error"),allowed=rule=>(m.config.allow??[]).some(a=>a.rule!==void 0&&(rule===a.rule||rule.startsWith(`${a.rule}.`)));if(verse.length>=8&&!allowed("register.verse")){let med=quantile(verse,.5),out=verse.filter(p=>p<r.verseWindow[0]||p>r.verseWindow[1]).length/verse.length;(med<r.verseMidi[0]||med>r.verseMidi[1])&&emit({rule:"register.verse",severity:sev,where:{},message:`verse lead median ${med.toFixed(1)} is outside ${r.verseMidi[0]}\u2013${r.verseMidi[1]}`,fix:`transpose the verse lines ${med>r.verseMidi[1]?"down":"up"} toward ${Math.round((r.verseMidi[0]+r.verseMidi[1])/2)} (verses sit low; the chorus lifts)`}),out>r.verseOutsideShare&&emit({rule:"register.verse",severity:"warn",where:{},message:`${(out*100).toFixed(0)}% of verse notes leave ${r.verseWindow[0]}\u2013${r.verseWindow[1]}`,fix:"keep verse peaks for a key word; move the rest into the window"})}if(chorus.length>=8&&!allowed("register.chorus")){let med=quantile(chorus,.5);(med<r.chorusMedianMidi[0]||med>r.chorusMedianMidi[1])&&emit({rule:"register.chorus",severity:sev,where:{},message:`chorus lead median ${med.toFixed(1)} is outside ${r.chorusMedianMidi[0]}\u2013${r.chorusMedianMidi[1]}`,fix:med>r.chorusMedianMidi[1]?"move the chorus down: above this range the vocal reads as too high":"move the chorus up: below this range it does not lift over the verse"}),verse.length>=8&&med<quantile(verse,.5)&&emit({rule:"register.chorus",severity:"warn",where:{},message:`the chorus (median ${med.toFixed(1)}) sits below the verse (median ${quantile(verse,.5).toFixed(1)})`,fix:"lift the chorus a third or more over the verse"})}let all=notes.map(n2=>n2.pitch),p90=quantile(all,.9);p90>r.p90Max&&!allowed("register.p90")&&emit({rule:"register.p90",severity:sev,where:{},message:`lead p90 ${p90.toFixed(1)} is over ${r.p90Max}`,fix:"bring the top tenth of the line down; keep one peak per chorus"})}function silentShare(m,notes=leadNotes(m)){let step2=m.tpb/4,slots=Math.ceil(m.bars*m.tpBar/step2),on=new Uint8Array(slots);for(let n2 of notes)for(let s=Math.floor(n2.tick/step2);s<Math.min(slots,Math.ceil((n2.tick+n2.ticks)/step2));s++)on[s]=1;let perBar=m.tpBar/step2,spans=m.sections.length?m.sections:[{start:0,bars:m.bars}],total=0,sung=0;for(let sec of spans){let c=0;for(let s=sec.start*perBar;s<Math.min(slots,(sec.start+sec.bars)*perBar);s++)c+=on[s];c!==0&&(total+=sec.bars*perBar,sung+=c)}return total?1-sung/total:1}function silenceRules(m,style2,emit){let notes=leadNotes(m);if(notes.length<8)return;let share=silentShare(m,notes),[lo,hi]=style2.silence.share,allowed=(m.config.allow??[]).some(a=>a.rule==="vocal"||a.rule==="vocal.silence");(share<lo||share>hi)&&!allowed&&emit({rule:"vocal.silence",severity:"warn",where:{},message:`the lead is silent ${(share*100).toFixed(0)}% of the sections it sings in (${(lo*100).toFixed(0)}\u2013${(hi*100).toFixed(0)}%)`,fix:share<lo?"leave rests between lines and an instrumental peak":"the song needs more singing, or a shorter intro/instrumental"})}var LONG_VOWEL=/ee|oo|ai|ay|oa|ou|ow|igh|ie|ea|ei|ey|oy|oi|ue|ui|[aeiou][^aeiouy]e$/;function estimate(text2){let t=text2.toLowerCase().replace(/[^a-z']/g,""),onset=Math.min(3,/^[^aeiouy]*/.exec(t)[0].length),coda=0;for(;coda<3&&coda<t.length&&!"aeiouy".includes(t[t.length-coda-1]);)coda++;return{onset:t.length?onset:1,coda,long:LONG_VOWEL.test(t)}}function syllables(notes){let syls=notes.filter(n2=>n2.syl!=="~"),words=[],cur=[];for(let n2 of syls)cur.push(n2),String(n2.syl??"").endsWith("-")||(words.push(cur),cur=[]);cur.length&&words.push(cur);let out=[];return words.forEach((w,wi)=>{let bare=w.map(x=>String(x.syl??"").replace(/-$/,"")).join("").toLowerCase().replace(/[^a-z']/g,""),k=w.length,func=k===1&&FUNCTION.has(bare);w.forEach((n2,j)=>{let st=n2.stress,est=estimate(String(n2.syl??"")),stress=st?st[0]:0;k===1&&(stress=func?0:2),out.push({word:wi,k:j,n:k,stress,onset:st?st[1]:est.onset,coda:st?st[2]:est.coda,long:st?st[3]===1:est.long,func,known:k===1||st!==void 0,text:String(n2.syl??"").replace(/-$/,"")})})}),out}function metric(beat2,bpb=4){let q3=(Math.round(beat2*4)%(bpb*4)+bpb*4)%(bpb*4);return q3===0?4:bpb===4&&q3===8?3:q3%4===0?2:q3%2===0?1:0}function effective(beat2,end,bpb=4){let m=metric(beat2,bpb),x=Math.floor(beat2*4+1e-6)/4+.25;for(;x<Math.min(end,beat2+.5)-1e-6;){if(metric(x,bpb)>m)return Math.max(m,metric(x,bpb)-1);x+=.25}return m}var minMs=s=>45*s.onset+35*s.coda+(s.stress===2?130:s.stress===1?110:70)+(s.long?30:0);function lintLine(notes,m,style2){let spb=m.spb*1e3,S=syllables(notes),beat2=n2=>n2.tick/m.tpb,idx=notes.map((n2,i)=>n2.syl!=="~"?i:-1).filter(i=>i>=0),on=idx.map(i=>beat2(notes[i])),last=notes[notes.length-1],lens=idx.map((i,j)=>j+1<idx.length?beat2(notes[idx[j+1]])-beat2(notes[i]):beat2(last)+last.ticks/m.tpb-beat2(notes[i])),eff=on.map((b,i)=>effective(b,b+lens[i],m.bpb)),probs=[],p=style2.prosody;S.forEach((s,i)=>{let ms2=lens[i]*spb;i===0&&s.n===1&&ms2<p.firstSyllableMs?probs.push({kind:"short",index:i,message:`line-opening '${s.text}' ${ms2.toFixed(0)} ms < ${p.firstSyllableMs} ms (heard as part of the next word)`}):ms2<.85*minMs(s)&&probs.push({kind:"short",index:i,message:`'${s.text}' ${ms2.toFixed(0)} ms < ${minMs(s)} ms to say`}),s.known&&s.stress===2&&!s.func&&eff[i]===0&&s.n>1&&probs.push({kind:"weak",index:i,message:`stressed '${s.text}' on a 16th`})});for(let i=0;i<S.length-1;i++){let a=S[i],b=S[i+1];a.word!==b.word||!a.known||(a.stress>b.stress&&eff[i]<metric(on[i+1],m.bpb)&&probs.push({kind:"stress",index:i,message:`'${a.text}-${b.text}': stressed '${a.text}' weaker than '${b.text}'`}),b.stress>a.stress&&eff[i+1]<eff[i]&&probs.push({kind:"stress",index:i+1,message:`'${a.text}-${b.text}': stressed '${b.text}' weaker than '${a.text}'`}),a.stress>b.stress&&i+1<S.length-1&&lens[i]*1.2<lens[i+1]&&lens[i]*spb<200&&probs.push({kind:"shape",index:i,message:`'${a.text}-${b.text}' short-long against its stress`}))}let run=0;for(let i=0;i<lens.length-1;i++)run=lens[i]*spb<p.shortMs?run+1:0,run===p.max16thRun+1&&probs.push({kind:"rush",index:i,message:`${run} syllables under ${p.shortMs} ms in a row ending '${S[i].text}'`});if(on.length>3){let span4=(on[on.length-1]-on[0])*spb/1e3,rate2=span4>0?(on.length-1)/span4:99;rate2>p.maxSylPerSec&&probs.push({kind:"rate",index:0,message:`${rate2.toFixed(1)} syllables/s`})}let first=S.findIndex(s=>s.stress===2&&!s.func&&s.known);return first>=0&&eff[first]<2&&probs.push({kind:"anchor",index:first,message:`first stress '${S[first].text}' is off the beat`}),probs}var PROSODY_RULE={short:"prosody.short",weak:"prosody.stress",stress:"prosody.stress",shape:"prosody.stress",rush:"prosody.rush",rate:"prosody.rate",anchor:"prosody.anchor"},singable=l=>{let words=l.notes.filter(n2=>n2.syl!==void 0&&n2.syl!=="~");return words.length<3?!1:!words.every(n2=>VOCABLES.has(String(n2.syl).replace(/-$/,"").toLowerCase()))};function prosodyRules(m,style2,emit){let seen=new Set,runs=m.config.runs?new RegExp(`^(${m.config.runs})$`):void 0,ordered=[...m.lines].sort((a,b)=>Number(m.lead.has(b.track))-Number(m.lead.has(a.track)));for(let l of ordered){if(!singable(l))continue;let key=l.part.startsWith("line")?`${l.track}:${l.id}`:l.part;if(seen.has(key))continue;seen.add(key);let bar=Math.floor(l.notes[0].tick/m.tpBar);for(let p of lintLine(l.notes,m,style2)){let rule=PROSODY_RULE[p.kind],isRun=runs?.test(l.part)??!1;if(partAllowed(m,rule,l))continue;let severity=isRun?"info":p.kind==="anchor"||p.kind==="shape"?"warn":severityFor(style2,"error"),n2=l.notes.filter(x=>x.syl!=="~")[p.index]??l.notes[0],nb=Math.floor(n2.tick/m.tpBar);emit({rule,severity,where:{bar:nb,beat:Math.round((n2.tick-nb*m.tpBar)/m.tpb*100)/100,track:l.track,part:l.part,...m.sectionAt(bar)?{section:m.sectionAt(bar).name}:{}},message:`${l.part}: ${p.message}${isRun?" (declared run)":""}`,fix:p.kind==="short"||p.kind==="rush"||p.kind==="rate"?"give the syllables time to be said: fewer syllables, or spread them over the line's span (prosody set/rechart)":p.kind==="anchor"?"start the line so its first stressed word lands on a beat":"put the stressed syllable on the stronger position (or push into it)"})}}}function contour(notes,tpb,count2=8){let ns=notes.filter(n2=>n2.syl!=="~").slice(0,count2),out=[];for(let i=1;i<ns.length;i++)out.push(`${ns[i].pitch-ns[i-1].pitch}/${Math.round((ns[i].tick-ns[i-1].tick)*4/tpb)}`);return out.join(" ")}function lineText(notes){let text2="";for(let n2 of notes){if(n2.syl===void 0||n2.syl==="~")continue;let s=n2.syl.toLowerCase();text2+=s.endsWith("-")?s.slice(0,-1):`${s} `}return text2.replace(/[^a-z' ]/g,"").replace(/\s+/g," ").trim()}function hookRules(m,style2,emit){let choruses=m.sections.filter(s=>s.kind==="chorus");if(choruses.length<2)return;let lines=leadLines(m).filter(l=>l.notes.filter(n2=>n2.syl!=="~").length>=2),keys=choruses.map(c=>{let set=new Set;for(let l of lines){let bar=Math.floor(l.notes[0].tick/m.tpBar);if(bar<c.start||bar>=c.start+c.bars)continue;let text2=lineText(l.notes);set.add(`"${text2}"`),l.notes.filter(n2=>n2.syl!=="~").length>=4&&set.add(`shape ${contour(l.notes,m.tpb,5)}`)}return set}),sungIn=choruses.filter((_,i)=>keys[i].size>0);if(sungIn.length<2)return;let count2=new Map;for(let s of keys)for(let k of s)count2.set(k,(count2.get(k)??0)+1);let best=[...count2].sort((x,y)=>y[1]-x[1]||Number(y[0].startsWith('"'))-Number(x[0].startsWith('"')))[0],words=k=>new Set(k.slice(1,-1).split(" ")),hookWords=best[0].startsWith('"')?words(best[0]):void 0,carries=set=>set.has(best[0])||hookWords!==void 0&&[...set].some(k=>{if(!k.startsWith('"'))return!1;let w=words(k),n2=0;for(let x of w)hookWords.has(x)&&n2++;return n2/(w.size+hookWords.size-n2)>=.5}),carried=keys.filter(k=>k.size>0&&carries(k)).length,presence=carried/sungIn.length;if(best[1]<2||presence<style2.hook.presence){let missing=choruses.filter((_,i)=>keys[i].size>0&&!carries(keys[i])).map(c=>c.name);emit({rule:"hook.presence",severity:"warn",where:{section:missing[0]??choruses[0].name},message:best[1]<2?`no line recurs across the ${sungIn.length} sung choruses`:`the hook (${best[0]}) is in ${carried} of ${sungIn.length} sung choruses (missing: ${missing.join(", ")})`,fix:"sing the hook line, its words or its shape, in every chorus (a key lift keeps its intervals)"})}}function lyricRules(m,style2,emit){let lines=leadLines(m).map(l=>({l,text:lineText(l.notes)})).filter(x=>x.text.split(" ").length>=2),verse=lines.filter(({l})=>{let kind=m.sectionAt(Math.floor(l.notes[0].tick/m.tpBar))?.kind;return kind!=="chorus"&&kind!=="post"&&kind!=="outro"}),allowedRep=(m.config.allow??[]).some(a=>a.rule==="lyrics"||a.rule==="lyrics.repetition");if(verse.length>=6&&!allowedRep){let ratio2=new Set(verse.map(x=>x.text)).size/verse.length;ratio2<style2.lyrics.distinctLineRatio&&emit({rule:"lyrics.repetition",severity:"warn",where:{},message:`only ${(ratio2*100).toFixed(0)}% of lines outside the chorus are distinct`,fix:"write new verse lines: repetition belongs to the hook"})}glossaryRules(m,lines.map(x=>({text:x.text,line:x.l})),style2,emit)}function glossaryRules(m,lines,style2,emit){let seen=new Set;for(let{text:text2,line}of lines){let words=text2.split(" "),at3={bar:Math.floor(line.notes[0].tick/m.tpBar),track:line.track,part:line.part};for(let w of words){let us=Object.hasOwn(style2.lyrics.spelling,w)?style2.lyrics.spelling[w]:void 0;!us||seen.has(`s:${w}`)||(seen.add(`s:${w}`),partAllowed(m,"glossary.spelling",line)||emit({rule:"glossary.spelling",severity:"warn",where:at3,message:`"${w}" is not the glossary's spelling`,fix:`write "${us}"`}))}let padded=` ${text2} `;for(let phrase of style2.lyrics.banned)!padded.includes(` ${phrase} `)||seen.has(`b:${phrase}:${line.part}`)||(seen.add(`b:${phrase}:${line.part}`),partAllowed(m,"glossary.banned",line)||emit({rule:"glossary.banned",severity:"error",where:at3,message:`"${phrase}" is not in the glossary ("${text2}")`,fix:(Object.hasOwn(style2.lyrics.bannedFix,phrase)?style2.lyrics.bannedFix[phrase]:void 0)??'use other words, or declare it: allow { rule: "glossary.banned", reason }'}))}}var UNPITCHED_ID=/^(kick|snare|clap|hats?|perc|shak|tamb|rim|tom|crash|ride|cym|riser|drop|noise|sweep|impact|tear|fx|whoosh|vinyl|crackle|room|tape)/,UNPITCHED_PATCH=/noise|riser|sub-drop|impact|sweep|whoosh|crash|kit/,DRUM_INSTRUMENTS2=/^(kit|drums?|808|909|tr-?\d+)$/,PC_NAMES=["C","Db","D","Eb","E","F","Gb","G","Ab","A","Bb","B"],NAMES2={C:0,"C#":1,Db:1,D:2,"D#":3,Eb:3,E:4,F:5,"F#":6,Gb:6,G:7,"G#":8,Ab:8,A:9,"A#":10,Bb:10,B:11},mod123=n2=>(n2%12+12)%12,pcName=pc=>PC_NAMES[mod123(pc)];function pcOf(name){let pc=NAMES2[name];if(pc===void 0)throw new Error(`lint: unknown pitch class ${name}`);return pc}function keyScale(key){let m=/^([A-G][b#]?)(m?)$/.exec(key.trim());if(m){let tonic=NAMES2[m[1]];return(m[2]?[0,2,3,5,7,8,10]:[0,2,4,5,7,9,11]).map(i=>(tonic+i)%12)}let parsed=parseKey2(key);if(!parsed)throw new Error(`lint: unknown key ${key}`);return scaleOf2(parsed)}function usesHitNotation(track2){return track2.kit||DRUM_INSTRUMENTS2.test(String(track2.instrument??""))||UNPITCHED_ID.test(track2.id)?!0:UNPITCHED_PATCH.test(JSON.stringify(track2.patch??""))}function isUnpitched(track2){let instrument=track2.instrument??"",sound=SOUND_ALIASES[instrument]??instrument;return track2.kit||isDrumInstrument(instrument)||instrument==="texture"||["white","pink","brown","crackle","z_noise"].includes(sound)?!0:SYNTH_SOUNDS.includes(sound)||["string","modal","wind","sing","keys","wavetable","sampler"].includes(instrument)||resolveInstrumentWord2(instrument)?!1:usesHitNotation(track2)}function sectionKind(name){let n2=name.toLowerCase();return/pre/.test(n2)?"pre":/post/.test(n2)?"post":/chorus|hook|refrain|drop/.test(n2)?"chorus":/verse|^v\d/.test(n2)?"verse":/bridge|middle/.test(n2)?"bridge":/intro/.test(n2)?"intro":/outro|coda|end/.test(n2)?"outro":/break|inst|interlude|fake|build|thesis/.test(n2)?"break":"other"}function chordOf(value){if(!value)return;if(typeof value!="string")return value;let chord2=parseChord2(value);if(!chord2)throw new Error(`lint: unknown chord ${value}`);return{bass:chord2.bass??chord2.root,tones:chordPitchClasses(chord2)}}var allowMatches=(allow,rule,track2,bar)=>!(!(allow.rule===void 0?["key","harmony"]:[allow.rule]).some(s=>rule===s||rule.startsWith(`${s}.`))||allow.track!==void 0&&(track2===void 0||!new RegExp(`^(${allow.track})$`).test(track2))||allow.bars&&bar!==void 0&&(bar<allow.bars[0]||bar>=allow.bars[1]));function flatten2(json,unpitched,detuneOk,centsOk){let notes=[],tuning=[],byTrack=new Map(json.tracks.map(t=>[t.id,t]));for(let n2 of json.notes){let track2=byTrack.get(n2.trackId);if(!track2||track2.muted||unpitched.has(track2.id))continue;let sampler=track2.sampler;if(sampler?.mode==="oneshot")continue;let pitch2=n2.pitch+Number(track2.transpose??0),cents=Number(n2.cents??0);if(sampler){let voices=Object.values(sampler.voices).sort((a,b)=>(a.root??60)-(b.root??60)),ref=voices[0];if(!ref)continue;for(let v of voices)(v.root??60)<=n2.pitch&&(ref=v);if(ref.accelerate||ref.squiz||/drum|kit|perc|kick|snare|hat|clap|noise/.test(ref.src))continue;pitch2+=Number(ref.shift??0),cents+=1200*Math.log2(Math.abs(Number(ref.speed??1)))}let bend=n2.bend;bend?.length&&(cents+=bend[bend.length-1].cents);let whole=Math.round(cents/100),out={track:n2.trackId,tick:n2.startTick,ticks:n2.durationTicks,pitch:pitch2+whole,cents:cents-whole*100,velocity:n2.velocity??.8};n2.lyric!==void 0&&(out.sung=!0,out.syl=n2.lyric==="_"?"~":n2.lyric),notes.push(out)}for(let track2 of json.tracks){let syn=track2.synth;if(track2.muted||!syn||unpitched.has(track2.id))continue;(syn.unison??1)>1&&(syn.detune??0)>2*detuneOk/100&&tuning.push({track:track2.id,cents:syn.detune/2*100,detail:`unison detune ${syn.detune} st spreads \xB1${(syn.detune/2*100).toFixed(0)} cents`}),(syn.vib??0)>0&&(syn.vibmod??.5)>.6&&tuning.push({track:track2.id,cents:(syn.vibmod??.5)*100,detail:`vibrato ${syn.vibmod} st deep, \xB1${((syn.vibmod??.5)*100).toFixed(0)} cents`});let held=(syn.penv??0)*(syn.psustain??1)*(1-(syn.panchor??syn.psustain??1));Math.abs(held-Math.round(held))>centsOk/100&&tuning.push({track:track2.id,cents:(held-Math.round(held))*100,detail:`pitch envelope holds ${(held*100).toFixed(0)} cents off the note`})}for(let track2 of json.tracks)if(!(track2.muted||track2.sampler?.mode!=="oneshot"))for(let[name,ref]of Object.entries(track2.sampler.voices)){if(ref.accelerate||ref.squiz)continue;let c=1200*Math.log2(Math.abs(Number(ref.speed??1))),off=c-100*Math.round(c/100);Math.abs(off)>centsOk&&tuning.push({track:track2.id,cents:off,detail:`voice ${name} speed ${ref.speed} is ${off.toFixed(0)} cents off the grid`})}return{notes,tuning}}var bookId=src=>src.split("/").pop().replace(/\.(wav|flac|mp3|ogg)$/i,"");function placeBooks(json,books){let tpb=json.ticksPerBeat,tpBar=tpb*(json.beatsPerBar??4),out=[],byTrack=new Map(json.tracks.map(t=>[t.id,t])),names=new Map;for(let n2 of json.notes){let track2=byTrack.get(n2.trackId),sampler=track2?.sampler;if(!track2||track2.muted||sampler?.mode!=="oneshot")continue;let sorted=names.get(track2.id);sorted||(sorted=Object.keys(sampler.voices).sort((a,b)=>a<b?-1:a>b?1:0),names.set(track2.id,sorted));let name=sorted[n2.pitch-36],ref=name===void 0?void 0:sampler.voices[name];if(!ref||ref.accelerate||ref.squiz)continue;let book=books[bookId(String(ref.src))],part=book?.parts[name];if(!book||!part)continue;let shift=Number(ref.shift??0),speed=Math.abs(Number(ref.speed??1)),c=1200*Math.log2(speed),whole=Math.round(c/100),lead=(book.lead??.25)*tpb,line={id:`${track2.id}:${name}@${Math.floor(n2.startTick/tpBar)}`,track:track2.id,part:name,notes:[]},k=0;for(let[beat2,midi2,len,syl]of part.notes){let isSyl=syl!==void 0&&syl!=="~",stress=isSyl?part.stress?.[k]:void 0;isSyl&&k++;let tick=n2.startTick+lead+beat2*tpb/speed;if(tick>=n2.startTick+n2.durationTicks)continue;let s={track:track2.id,tick,ticks:Math.min(len*tpb/speed,n2.startTick+n2.durationTicks-tick),pitch:midi2+shift+whole,cents:c-whole*100,velocity:n2.velocity??.8,sung:!0,line:line.id};syl!==void 0&&(s.syl=syl),stress&&(s.stress=stress),line.notes.push(s)}line.notes.length&&out.push(line)}return out}function lyricLines(notes,tpb){let byTrack=new Map;for(let n2 of notes)n2.sung&&(byTrack.get(n2.track)??byTrack.set(n2.track,[]).get(n2.track)).push(n2);let out=[];for(let[track2,list]of byTrack){list.sort((a,b)=>a.tick-b.tick||b.pitch-a.pitch);let cur,end=-1/0,k=0;for(let n2 of list)cur&&n2.tick===cur.notes[cur.notes.length-1].tick||((!cur||n2.tick-end>=tpb)&&(cur={id:`${track2}:line${++k}@${n2.tick}`,track:track2,part:`line${k}`,notes:[]},out.push(cur)),n2.line=cur.id,cur.notes.push(n2),end=Math.max(end,n2.tick+n2.ticks))}return out}function inferHarmony(notes,bars,tpb,tpBar){let byTrack=new Map;for(let n2 of notes)n2.sung||(byTrack.get(n2.track)??byTrack.set(n2.track,[]).get(n2.track)).push(n2.ticks);let bed=new Set;for(let[track2,lens]of byTrack){let sorted=[...lens].sort((a,b)=>a-b);sorted[Math.floor(sorted.length/2)]>=tpb&&bed.add(track2)}let out=new Array(bars).fill(void 0),weight=Array.from({length:bars},()=>new Float64Array(12)),low=new Array(bars).fill(1/0);for(let n2 of notes){if(n2.sung)continue;let first=Math.floor(n2.tick/tpBar),last=Math.min(bars-1,Math.floor((n2.tick+n2.ticks-1)/tpBar));for(let b=Math.max(0,first);b<=last;b++){let from=Math.max(n2.tick,b*tpBar),to=Math.min(n2.tick+n2.ticks,(b+1)*tpBar);from<=b*tpBar+tpb/2&&n2.pitch<60&&(low[b]=Math.min(low[b],n2.pitch)),bed.has(n2.track)&&to-from>=tpb&&(weight[b][mod123(n2.pitch)]+=to-from)}}for(let b=0;b<bars;b++){let w=weight[b],max=Math.max(...w);if(!(max>0)||!Number.isFinite(low[b]))continue;let tones=[];for(let pc=0;pc<12;pc++)w[pc]>=max*.25&&tones.push(pc);out[b]={bass:low[b],tones}}return out}function songModel(score,options={}){let json=readScore(score),config=options.config??{},tpb=json.ticksPerBeat,bpb=json.beatsPerBar??4,tpBar=tpb*bpb,lastTick=json.notes.reduce((m,n2)=>Math.max(m,n2.startTick+n2.durationTicks),0),bars=Math.max(json.bars??0,Math.ceil(lastTick/tpBar)),unpitched=new Set(json.tracks.filter(t=>isUnpitched(t)).map(t=>t.id)),{notes,tuning}=flatten2(json,unpitched,options.detuneOk??25,options.centsOk??12),bookLines=placeBooks(json,options.books??{}),lines=[...bookLines,...lyricLines(notes,tpb)].sort((a,b)=>a.notes[0].tick-b.notes[0].tick),sung=[...bookLines.flatMap(l=>l.notes),...notes.filter(n2=>n2.sung)],lead=new Set,trackIds=new Set(lines.map(l=>l.track));if(config.lead?.length)for(let id of trackIds)config.lead.some(re=>new RegExp(`^(${re})$`).test(id))&&lead.add(id);else{let count2=new Map;for(let n2 of sung)n2.syl!=="~"&&count2.set(n2.track,(count2.get(n2.track)??0)+1);let max=Math.max(0,...count2.values()),named=/^(vox|lead|vocals?|voice)$/,top=[...count2].filter(([,c])=>c>=.75*max).sort((a,b)=>Number(named.test(b[0]))-Number(named.test(a[0]))||b[1]-a[1])[0];top&&lead.add(top[0])}let sections=(json.sections??[]).map(s=>({name:s.name,kind:sectionKind(s.name),start:s.startBar,bars:s.bars})).sort((a,b)=>a.start-b.start),sectionOf=new Array(bars).fill(void 0);for(let s of sections)for(let b=s.start;b<Math.min(bars,s.start+s.bars);b++)sectionOf[b]=s;let declared=config.harmony?.map(chordOf),chords=declared??inferHarmony(notes,bars,tpb,tpBar),baseKey=json.key??"C",keyChanges=[...config.keys??[]].sort((a,b)=>a.bar-b.bar),keyAt=bar=>{let key=baseKey;for(let k of keyChanges)k.bar<=bar&&(key=k.key);return key},scales=new Map,scaleAt=bar=>{let key=keyAt(bar),s=scales.get(key);return s||scales.set(key,s=new Set(keyScale(key))),s};return Object.freeze({id:options.id??"song",json,tpb,bpb,tpBar,bars,bpm:json.tempoBpm,spb:60/json.tempoBpm,key:baseKey,notes:notes.filter(n2=>!n2.sung),sung,lines,lead,sections,sectionAt:bar=>sectionOf[bar],chordAt:bar=>chords[bar]??void 0,declaredHarmony:declared!==void 0,keyAt,scaleAt,config,unpitched,tuning})}function isRecord5(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function readScore(value){if(!isRecord5(value))throw new Error("lint: score must be an object");let{tempoBpm,ticksPerBeat,tracks,notes}=value;if(typeof tempoBpm!="number"||!(tempoBpm>0))throw new Error("lint: score tempoBpm must be a positive number");if(typeof ticksPerBeat!="number"||!(ticksPerBeat>0))throw new Error("lint: score ticksPerBeat must be a positive number");if(!Array.isArray(tracks)||!tracks.every(t=>isRecord5(t)&&typeof t.id=="string"))throw new Error("lint: score tracks must be objects with ids");if(!Array.isArray(notes)||!notes.every(n2=>isRecord5(n2)&&typeof n2.trackId=="string"&&typeof n2.startTick=="number"&&typeof n2.durationTicks=="number"&&typeof n2.pitch=="number"))throw new Error("lint: score notes must have trackId, startTick, durationTicks and pitch");return value}var AGAINST_BASS={1:"a minor ninth",6:"a tritone",11:"a bare major seventh"};function allowedPc(m,rule,track2,bar,pc){return(m.config.allow??[]).some(a=>allowMatches(a,rule,track2,bar)?a.pcs?pc!==void 0&&a.pcs.some(p=>pcOf(p)===pc):a.rule!==void 0&&a.cents===void 0:!1)}var where=(m,n2,tick=n2.tick)=>{let bar=Math.floor(tick/m.tpBar);return{bar,beat:Math.round((tick-bar*m.tpBar)/m.tpb*100)/100,track:n2.track,...m.sectionAt(bar)?{section:m.sectionAt(bar).name}:{},...n2.line?{part:n2.line.split(":")[1].split("@")[0]}:{}}},chordPcs=(m,bar)=>{let ch=m.chordAt(bar);return new Set(ch?[ch.bass,...ch.tones].map(mod123):[])};function keyRules(m,style2,emit){let centsOk=track2=>Math.max(style2.key.centsOk,...(m.config.allow??[]).filter(a=>a.cents!==void 0&&a.track!==void 0&&new RegExp(`^(${a.track})$`).test(track2)).map(a=>a.cents));for(let t of m.tuning)Math.abs(t.cents)>centsOk(t.track)&&emit({rule:"key.tuning",severity:"error",where:{track:t.track},message:`${t.track}: ${t.detail}`,fix:`retune it onto the semitone grid, or declare it: allow { track: "${t.track}", cents: ${Math.ceil(Math.abs(t.cents))}, reason }`});for(let n2 of[...m.notes,...m.sung]){let w=where(m,n2),{bar}=w,pc=mod123(n2.pitch);Math.abs(n2.cents)>centsOk(n2.track)&&emit({rule:"key.tuning",severity:"error",where:w,pitch:n2.pitch,message:`${pcName(pc)} sounds ${n2.cents.toFixed(0)} cents off`,fix:"use a whole-semitone shift or speed, or declare the detune with allow { cents }"});let scale3=m.scaleAt(bar),tones=m.declaredHarmony?chordPcs(m,bar):new Set;if(!scale3.has(pc)&&!tones.has(pc)){allowedPc(m,"key.scale",n2.track,bar,pc)||emit({rule:"key.scale",severity:"error",where:w,pitch:n2.pitch,message:`${pcName(pc)} is outside ${m.keyAt(bar)}${n2.sung?" (sung)":""}`,fix:`move it to a scale or chord tone, or declare it: allow { track: "${n2.track}", pcs: ["${pcName(pc)}"], bars: [${bar}, ${bar+1}], reason }`});continue}for(let b=bar;b*m.tpBar<n2.tick+n2.ticks;b++){let from=Math.max(n2.tick,b*m.tpBar),to=Math.min(n2.tick+n2.ticks,(b+1)*m.tpBar);if(to-from<style2.key.clashBeats*m.tpb)continue;let ch=m.chordAt(b);if(!ch)continue;let pcs=new Set([ch.bass,...ch.tones].map(mod123));if(pcs.has(pc)||allowedPc(m,"key.clash",n2.track,b,pc))continue;let under=mod123(ch.bass),over=mod123(pc-under),name=AGAINST_BASS[over];if(!name||n2.sung&&over===11)continue;let next=m.chordAt(b+1);next&&from>=(b+1)*m.tpBar-m.tpb&&[next.bass,...next.tones].some(t=>mod123(t)===pc)||emit({rule:"key.clash",severity:m.declaredHarmony?"error":"warn",where:{...w,bar:b,beat:b===bar?w.beat:0},pitch:n2.pitch,message:`${pcName(pc)} held ${((to-from)/m.tpb).toFixed(2)} beats, ${name} over the bass ${pcName(under)} (chord ${[...pcs].map(pcName).join(" ")})`,fix:"make it a chord tone, shorten it under a beat, or declare it in allow with a reason"})}}}function lowSecondRules(m,_style,emit){let minHold=m.tpb/2,notes=[...m.notes,...m.sung].filter(n2=>n2.pitch<=60&&n2.ticks>=minHold&&n2.velocity>0).sort((a,b)=>a.tick-b.tick||a.pitch-b.pitch||a.track.localeCompare(b.track)),active=new Map,reported=new Set,name=pitch2=>pcName(pitch2)+(Math.floor(pitch2/12)-1),rule="harmony.low-second";for(let n2 of notes){let end=n2.tick+n2.ticks;for(let delta of[-2,-1,1,2]){let nearby=active.get(n2.pitch+delta);if(nearby)for(let[track2,other]of nearby){let until=Math.min(end,other.tick+other.ticks);if(other.tick+other.ticks<n2.tick+minHold){nearby.delete(track2);continue}let low=n2.pitch<other.pitch?n2:other,high=n2.pitch<other.pitch?other:n2;if(low.pitch>=60||low.pitch>=48&&Math.abs(delta)!==1)continue;let hold=low.pitch<48?minHold:m.tpb,from=n2.tick;for(;until-from>=hold;){let bar=Math.floor(from/m.tpBar);if(allowedPc(m,rule,low.track,bar,mod123(low.pitch))||allowedPc(m,rule,high.track,bar,mod123(high.pitch))){from=(bar+1)*m.tpBar;continue}let key=JSON.stringify([bar,low.track,high.track,low.pitch,high.pitch]);reported.has(key)||(reported.add(key),emit({rule,severity:"warn",where:where(m,high,from),pitch:high.pitch,message:`${low.track} (${name(low.pitch)}) and ${high.track} (${name(high.pitch)}) overlap for ${((until-from)/m.tpb).toFixed(2)} beats, a ${Math.abs(delta)===1?"semitone":"whole tone"} in the ${low.pitch<48?"bass":"lower middle register"}`,fix:`raise ${high.track}'s ${name(high.pitch)} an octave, shorten the overlap, or allow this voicing with a reason`}));break}}}let atPitch=active.get(n2.pitch)??new Map,held=atPitch.get(n2.track);(!held||held.tick+held.ticks<end)&&atPitch.set(n2.track,n2),active.set(n2.pitch,atPitch)}}function rubRules(m,_style,emit){let tpb=m.tpb,long=[...m.notes,...m.sung].filter(n2=>n2.ticks>=tpb/2&&n2.pitch>=48&&n2.syl!=="~"),byStart=[...long].sort((a,b)=>a.tick-b.tick),slop=tpb/8,strongTicks=new Map;for(let o of long){let first=Math.ceil((o.tick-slop)/(2*tpb)),last=Math.floor((o.tick+o.ticks-slop-1)/(2*tpb));for(let k=first;k<=last;k++)(strongTicks.get(k)??strongTicks.set(k,[]).get(k)).push(o)}let found=new Map;for(let n2 of byStart){let rel=n2.tick%(2*tpb);if(rel>slop&&rel<2*tpb-slop)continue;let k=Math.round(n2.tick/(2*tpb)),beatTick=k*2*tpb,bar=Math.floor(beatTick/m.tpBar),pcs=chordPcs(m,bar),pc=mod123(n2.pitch);for(let o of strongTicks.get(k)??[]){if(o===n2||o.track===n2.track||n2.sung&&o.sung||!(o.tick<=beatTick+slop&&o.tick+o.ticks>beatTick+slop))continue;let d=mod123(n2.pitch-o.pitch);if(d!==1&&d!==11)continue;let opc=mod123(o.pitch);if(pcs.has(pc)&&pcs.has(opc)||!n2.sung&&pcs.has(pc))continue;let rule=n2.sung||o.sung?"harmony.vocal-rub":"harmony.part-rub";if(allowedPc(m,rule,n2.track,bar,pc)||allowedPc(m,rule,o.track,bar,opc))continue;let singerLeans=n2.sung&&pcs.has(opc)&&!pcs.has(pc),severity=singerLeans?n2.ticks>=tpb&&!m.scaleAt(bar).has(pc)?"warn":"info":m.declaredHarmony?"error":"warn",key=`${rule}|${beatTick}|${pc}|${opc}`,hit2=found.get(key);if(hit2){hit2.others.add(o.track);continue}let culprit=singerLeans?n2.track:n2.sung?o.track:n2.track;found.set(key,{others:new Set([o.track]),f:{rule,severity,where:where(m,n2,beatTick),pitch:n2.pitch,message:`${pcName(pc)}${n2.sung?" (sung)":""} against ${pcName(opc)}${o.sung?" (sung)":""}, a semitone on the beat`,fix:singerLeans?"a sung lean on the beat: resolve it sooner, or move the syllable off the beat":`move ${culprit}'s ${pcName(n2.sung?opc:pc)} to a chord tone at that beat, start it off the beat, or declare it in allow { rule: "${rule}", track: "${culprit}", bars, reason }`}})}}for(let{f,others}of found.values())emit({...f,message:f.message.replace(" against ",` against ${[...others].join("/")}'s `)})}function voiceLeadingRules(m,style2,emit){let byTrack=new Map;for(let n2 of m.notes)(byTrack.get(n2.track)??byTrack.set(n2.track,[]).get(n2.track)).push(n2);let bassLine=[],bassLow=1/0;for(let[track2,notes]of byTrack){let groups=new Map;for(let n2 of notes)(groups.get(n2.tick)??groups.set(n2.tick,[]).get(n2.tick)).push(n2);let chords=[...groups].filter(([,g])=>g.length>=3&&g.every(n2=>n2.ticks>=m.tpb)).sort((a,b)=>a[0]-b[0]).map(([tick,g])=>({tick,pitches:g.map(n2=>n2.pitch).sort((a,b)=>a-b)})),avg=notes.reduce((s,n2)=>s+n2.pitch,0)/notes.length;if(chords.length<.5*groups.size||chords.length<4){avg<52&&avg<bassLow&&[...groups.values()].every(g=>g.length<=2)&&(bassLow=avg,bassLine=[...groups].sort((a,b)=>a[0]-b[0]).map(([tick,g])=>({tick,pitch:Math.min(...g.map(n2=>n2.pitch))})));continue}let motions=[],leaps=0,firstLeap;for(let i=1;i<chords.length;i++){let a=chords[i-1].pitches,b=chords[i].pitches;if(a.join()===b.join())continue;if(a.length!==b.length){motions.push(Math.abs(b[0]-a[0])+Math.abs(b[b.length-1]-a[a.length-1]));continue}let sum=0;for(let v=0;v<a.length;v++){let d=Math.abs(b[v]-a[v]);sum+=d,v>0&&v<a.length-1&&d>style2.voiceLeading.innerLeapMax&&(leaps++,firstLeap??={tick:chords[i].tick,d})}motions.push(sum/Math.max(1,a.length/3))}if(motions.length>=4){let sorted=[...motions].sort((x,y)=>x-y),median=sorted[Math.floor(sorted.length/2)];median>style2.voiceLeading.medianMotionMax&&emit({rule:"voice.motion",severity:"info",where:{track:track2},message:`${track2}: chord changes move a median ${median.toFixed(1)} semitones (block chords jump)`,fix:"voice each chord to the nearest inversion of the last (minimal motion), e.g. voiceChord(..., { lead: 'smooth' })"})}leaps&&emit({rule:"voice.leap",severity:"info",where:{...whereTick(m,firstLeap.tick),track:track2},message:`${track2}: ${leaps} inner-voice leap${leaps===1?"":"s"} over ${style2.voiceLeading.innerLeapMax} semitones (first ${firstLeap.d})`,fix:"keep inner voices within a fourth or fifth per change"}),style2.voiceLeading.parallels&&bassLine.length&&track2!=="bass"&¶llelsAgainst(m,track2,chords,bassLine,emit)}}var whereTick=(m,tick)=>{let bar=Math.floor(tick/m.tpBar);return{bar,beat:Math.round((tick-bar*m.tpBar)/m.tpb*100)/100}};function parallelsAgainst(m,track2,chords,bass,emit){let bassAt=tick=>{let p;for(let b of bass){if(b.tick>tick)break;p=b.pitch}return p},count2=0,first;for(let i=1;i<chords.length;i++){let a=chords[i-1],b=chords[i],ba=bassAt(a.tick),bb=bassAt(b.tick);if(ba===void 0||bb===void 0||ba===bb)continue;let ta=a.pitches[a.pitches.length-1],tb=b.pitches[b.pitches.length-1];if(ta===tb)continue;let ia=mod123(ta-ba),ib=mod123(tb-bb);ia===ib&&(ia===7||ia===0)&&Math.sign(tb-ta)===Math.sign(bb-ba)&&(count2++,first??=b.tick)}count2&&emit({rule:"voice.parallel",severity:"info",where:{...whereTick(m,first),track:track2},message:`${track2}: ${count2} parallel fifth/octave${count2===1?"":"s"} between the bass and the top voice`,fix:"move the top voice by step or in contrary motion to the bass (fine in a power-chord idiom)"})}var UNFITTED=Object.freeze({calibrated:!1,patch:{}}),CALIBRATION=Object.freeze({base:{key:{centsOk:15,detuneOk:30,clashBeats:1},voiceLeading:{medianMotionMax:7,innerLeapMax:12,parallels:!1},register:{verseMidi:[48,72],verseWindow:[43,79],verseOutsideShare:.25,chorusMedianMidi:[48,79],p90Max:84},silence:{share:[0,.9]},prosody:{maxSylPerSec:8,max16thRun:4,shortMs:100,firstSyllableMs:100,maxSylPerBeat:4},density:{chorusOnsetsPerSec:[.5,24],chorusVsVerse:.5,maxEmptyBars:8},hook:{presence:.5},lyrics:{distinctLineRatio:.34,banned:[],bannedFix:{},spelling:{}},tricks:{featured:[0,64]},budgets:{maxNotes:4096,maxLanePoints:256},sameness:{maxSharedClasses:4,contourR:.97,melodicJaccard:.3,lyricOverlap:.15}},archetypes:{banger:UNFITTED,ballad:UNFITTED,anthem:UNFITTED,lullaby:UNFITTED,interlude:UNFITTED}});var LINT_ARCHETYPES=Object.freeze(["banger","ballad","anthem","lullaby","interlude"]);function merge(base,patch){if(!patch)return base;let out={...base};for(let[group,value]of Object.entries(patch))value===void 0||!(group in base)||(out[group]=Object.freeze({...base[group],...value}));return out}function lintStyle(archetype="banger",overrides,calibration=CALIBRATION){let entry=calibration.archetypes[archetype],parent=entry.parent?calibration.archetypes[entry.parent].patch:void 0,base={...calibration.base,archetype,calibrated:entry.calibrated};return Object.freeze(merge(merge(merge(base,parent),entry.patch),overrides))}var LINT_RULES=Object.freeze(["key.scale","key.clash","key.tuning","harmony.low-second","harmony.part-rub","harmony.vocal-rub","voice.motion","voice.parallel","voice.leap","register.verse","register.chorus","register.p90","vocal.silence","prosody.short","prosody.stress","prosody.rush","prosody.rate","prosody.anchor","density.chorus","density.chorus-vs-verse","density.hole","hook.presence","lyrics.repetition","glossary.spelling","glossary.banned","tricks.repeat","tricks.count","budget.notes","budget.lane","album.sameness","album.contour","album.melody","album.lyrics","album.trick"]),RULE_GROUPS=Object.freeze(["key","harmony","voice","register","vocal","prosody","density","hook","lyrics","glossary","tricks","budget","album"]);var RULES2=[[["key"],keyRules],[["harmony"],rubRules],[["harmony"],lowSecondRules],[["voice"],voiceLeadingRules],[["register"],registerRules],[["vocal"],silenceRules],[["prosody"],prosodyRules],[["density"],densityRules],[["hook"],hookRules],[["lyrics","glossary"],lyricRules],[["tricks"],trickRules],[["budget"],budgetRules]],counts=fs=>{let c={error:0,warn:0,info:0};for(let f of fs)c[f.severity]++;return c};function lintSong(score,options={}){let started=performance.now(),config=options.config??{},style2=lintStyle(config.archetype,{...config.style,...options.style},options.calibration),model=songModel(score,{id:options.id??"song",config,...options.books?{books:options.books}:{},centsOk:style2.key.centsOk,detuneOk:style2.key.detuneOk}),findings=[],want=options.rules?new Set(options.rules):void 0,blanket=(config.allow??[]).filter(a=>a.rule!==void 0&&!a.pcs&&a.cents===void 0),allowed=f=>blanket.some(a=>allowMatches(a,f.rule,f.where.track,f.where.bar)&&(a.part===void 0||f.where.part!==void 0&&new RegExp(`^(${a.part})$`).test(f.where.part)));for(let[groups,rule]of RULES2)(!want||groups.some(g=>want.has(g)))&&rule(model,style2,f=>{allowed(f)||findings.push(f)});let c=counts(findings);return{id:model.id,ok:c.error===0,archetype:style2.archetype,findings,counts:c,ms:Math.round(performance.now()-started),stats:{leadTracks:[...model.lead],sungLines:model.lines.length,harmony:model.declaredHarmony?"declared":"inferred",sectionOnsetsPerSec:sectionDensity(model).sections.map(s=>({section:s.section.name,kind:s.section.kind,onsetsPerSec:Math.round(s.onsetsPerSec*100)/100})),tricksDetected:detectTricks(model).map(t=>`${t.id}@${t.bars.slice(0,4).join(",")}`)},model}}export{DawnSdkError,SONG_CALIBRATION_LATEST,ScoreValidationError,ambientVoicing,ambientVoicingNames,chord,exportSampleRate,hit,lintSong,note,progression,renderArrangedPcm,scoreFromJSON,song,track};
|