{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "audio-visualizer-wave",
  "title": "Audio Visualizer Wave",
  "description": "Shader aura audio visualizer with optional dithering: swirling ribbons of turbulent light that animate between the shared visualizer lifecycle states (connecting, silent, speaking, thinking), with the aura swelling on live volume. Ships its own Shadertoy-compatible WebGL runtime. Headless view for any MediaStreamTrack, plus a Pipecat-connected wrapper.",
  "dependencies": [
    "@pipecat-ai/client-js@^1.14.0",
    "@pipecat-ai/client-react@^1.9.0",
    "motion@^13.2.0"
  ],
  "files": [
    {
      "path": "src/components/audio-visualizer-wave.tsx",
      "content": "\"use client\";\nimport { usePipecatClientMediaTrack } from \"@pipecat-ai/client-react\";\nimport {\n  animate,\n  motionValue,\n  type MotionValue,\n  type ValueAnimationTransition,\n} from \"motion/react\";\nimport {\n  memo,\n  useEffect,\n  useMemo,\n  useRef,\n  useState,\n  type RefObject,\n} from \"react\";\n\nimport { WaveShader } from \"@/components/pipecat/wave-shader\";\nimport {\n  createVisualizerAnalyser,\n  resolveVisualizerColor,\n  type VisualizerState,\n} from \"@/lib/visualizer\";\n\nexport type { VisualizerState };\n\ntype ParticipantType = Parameters<typeof usePipecatClientMediaTrack>[1];\n\nexport type DitherMethod = \"bayer2\" | \"bayer4\" | \"bayer8\" | \"ign\" | \"noise\";\n\nexport interface DitherOptions {\n  /** Threshold pattern (default \"bayer8\"). */\n  method?: DitherMethod;\n  /** Pixel grid size in CSS px (1–4096, default 3). */\n  pixelSize?: number;\n  /** Color steps per channel (rounded to 2–256, default 4). */\n  levels?: number;\n  /** Alpha steps (rounded to 2–256, defaults to levels). */\n  alphaLevels?: number;\n  /** Pattern strength (0–1, default 1); 0 gives plain posterization. */\n  strength?: number;\n}\n\nexport interface AudioVisualizerWaveViewProps {\n  /** Audio track to visualize. Rests as a calm drifting aura when null. */\n  track?: MediaStreamTrack | null;\n  /**\n   * Aura color. Any CSS color, \"currentColor\", or a \"--css-var\" name.\n   * Defaults to a vivid cyan — the aura is made of light, so near-black\n   * colors wash out to gray.\n   */\n  color?: string;\n  /** Second CSS color; pins the palette and disables speech-driven hue spreading. */\n  accentColor?: string;\n  /** Palette banding frequency (default 0.05); hue range is controlled by hueSpread. */\n  colorShift?: number;\n  /** Accent hue offset as a fraction of the color wheel (default 0.18). Ignored with accentColor. */\n  hueSpread?: number;\n  /** Visualizer size in px (square, default 224). */\n  size?: number;\n  /** Animation speed multiplier over the state's base pace (default 1). */\n  speed?: number;\n  /** Edge-deformation multiplier over the state's base depth (default 1). */\n  amplitude?: number;\n  /** Brightness multiplier over the state's base glow (default 1). */\n  glow?: number;\n  /** Edge blur/softness of the aura (default 0.2). */\n  softness?: number;\n  /** Body fill: 0 for contour wisps, 1 for a solid orb (default 0.4). */\n  fill?: number;\n  /** Layer falloff relative to sample travel (0–1, default 0.28); higher values soften banding. */\n  smoothing?: number;\n  /**\n   * Ink gain before tone mapping (default 0.55). The tone curve saturates\n   * hard, so a lower density keeps the mid-tones inside its responsive\n   * range and the contours visible; raise it for a denser, hotter aura.\n   */\n  density?: number;\n  /**\n   * Brightness at the very centre of the hollow (0–1, default 0.1). 0\n   * empties the middle completely; raise it to keep a glow in there.\n   */\n  core?: number;\n  /**\n   * Fraction of the radius left open in the middle (0–1, default 0.3).\n   * The ink ramps from `core` at this radius up to full at the surface,\n   * so the orb reads as a shell with a void you can see into.\n   */\n  hollow?: number;\n  /** Shell depth as a fraction of the radius (0–1, default 0.22). */\n  depth?: number;\n  /**\n   * Specular highlight strength (default 0.2; 0 removes it). Kept low now\n   * that the middle is hollow — it sits over the void, where it reads\n   * much more strongly than it did against a filled body.\n   */\n  highlight?: number;\n  /** Remove the specular shine over the hollow. */\n  noHighlight?: boolean;\n  /**\n   * Shine tint. Any CSS color, \"currentColor\", or a \"--css-var\" name.\n   * Defaults to white warmed a little toward the aura color.\n   */\n  highlightColor?: string;\n  /** Ribbon count (default 24). Changing it recompiles the shader; GPU cost scales linearly. */\n  iterations?: number;\n  /**\n   * Optional pixel grid and palette quantization (default false).\n   * Toggling or changing method recompiles; numeric options update as uniforms.\n   */\n  dither?: boolean | DitherOptions;\n  /**\n   * Background optimization: \"dark\" composites tonemapped light, \"light\"\n   * boosts saturation. Defaults to detecting the root element's \"dark\"\n   * class, tracked live.\n   */\n  themeMode?: \"dark\" | \"light\";\n  /**\n   * Override the speech level computed from the track (0–1) — stands in\n   * for both the phrase envelope and the gain-following pulse.\n   */\n  volume?: number;\n  /** Connecting takes precedence over thinking and ignores the audio track. */\n  isConnecting?: boolean;\n  /**\n   * Override: the bot is working on a response — the aura pulses deeply.\n   * The track is ignored while set.\n   */\n  isThinking?: boolean;\n  className?: string;\n}\n\n/** Ignore frame gaps longer than this (tab was backgrounded). */\nconst MAX_FRAME_SECONDS = 0.1;\n\n/**\n * Band the level is measured over. Speech lives here, and the near-silent\n * top of the spectrum would otherwise drag the average down to a fraction\n * of its range — which reads as an aura that barely responds.\n */\nconst ENERGY_BAND_HZ = { low: 200, high: 8000 };\n\n/** Band RMS at conversational level, which maps to a full-scale 1. */\nconst ENERGY_REFERENCE_RMS = 0.3;\n/** Envelope time constants in seconds; a slower release smooths gaps between phrases. */\nconst ENERGY_ATTACK_SECONDS = 0.32;\nconst ENERGY_RELEASE_SECONDS = 1.3;\n\n/** A faster envelope makes body scale follow syllables while other parameters follow phrases. */\nconst PULSE_ATTACK_SECONDS = 0.06;\nconst PULSE_RELEASE_SECONDS = 0.28;\n\n/** Radians per second at speed 1. Integrate phase so pace changes do not jump the pattern. */\nconst PHASE_RATE = 0.05;\n\n/**\n * Hue rotations per second at speed 1. Integrated at the same speed as the\n * phase, so the palette barely creeps at rest and visibly travels while\n * the bot is talking.\n */\nconst HUE_RATE = 0.0018;\n\nconst DEFAULT_TRANSITION: ValueAnimationTransition = {\n  duration: 0.5,\n  ease: \"easeOut\",\n};\nconst DEFAULT_PULSE_TRANSITION: ValueAnimationTransition = {\n  duration: 0.35,\n  ease: \"easeOut\",\n  repeat: Infinity,\n  repeatType: \"mirror\",\n};\n\ninterface AuraStateParams {\n  speed: number;\n  scale: number;\n  amplitude: number;\n  frequency: number;\n  variance: number;\n  brightness: number;\n}\n\n/** Speaking starts at the quiet baseline; ENERGY_GAIN adds the response to live speech. */\nconst STATE_PARAMS: Record<VisualizerState, AuraStateParams> = {\n  silent: {\n    speed: 6,\n    scale: 0.22,\n    amplitude: 0.35,\n    frequency: 0.35,\n    variance: 0.06,\n    brightness: 1.15,\n  },\n  connecting: {\n    speed: 20,\n    scale: 0.26,\n    amplitude: 0.45,\n    frequency: 0.7,\n    variance: 0.1,\n    brightness: 1.5,\n  },\n  thinking: {\n    speed: 30,\n    scale: 0.26,\n    amplitude: 0.4,\n    frequency: 1.0,\n    variance: 0.2,\n    brightness: 1.5,\n  },\n  speaking: {\n    speed: 8,\n    scale: 0.25,\n    amplitude: 0.35,\n    frequency: 0.45,\n    variance: 0.08,\n    brightness: 1.25,\n  },\n};\n\n/** Full-speech gains. Scale uses the fast pulse envelope; other parameters use slow energy. */\nconst ENERGY_GAIN = {\n  /** ~35% of the resting radius at full gain. */\n  scale: 0.085,\n  speed: 70,\n  amplitude: 1.0,\n  frequency: 1.0,\n  variance: 0.7,\n  /** Fraction of extra glow at full energy. */\n  brightness: 0.9,\n  /** Multiplier on the caller's colorShift at full energy. */\n  colorShift: 1.6,\n  /**\n   * Multiplier on the caller's hueSpread at full energy. Speech pushes the\n   * two tones further apart — more color in the orb — without ever adding\n   * a third.\n   */\n  hueSpread: 0.6,\n};\n\n/** The two waiting states breathe; the rest hold a steady glow. */\nconst PULSE_BRIGHTNESS: Partial<Record<VisualizerState, number[]>> = {\n  connecting: [1.7, 2.3],\n  thinking: [0.8, 2.8],\n};\n\n/**\n * Displacement budget of the turbulence, in units of amplitude/frequency:\n * each of the 4 layers pushes along the swirl matrix's first column\n * (length ≈ 0.65) at 1.4× the previous layer's frequency (Σ 1.4⁻ⁱ ≈ 2.58).\n */\nconst TURB_REACH = 0.65 * 2.58;\n/** Visible fraction of the worst-case bound, calibrated against the shader at full speech energy. */\nconst TURB_VISIBLE_REACH = 0.74;\n\n/** Fit full-energy speech to the canvas; the resting margin leaves room for swelling. */\nfunction auraLogicalSpan(amplitudeProp: number, softness: number): number {\n  const atFullEnergy = {\n    scale: STATE_PARAMS.speaking.scale + ENERGY_GAIN.scale,\n    amplitude: STATE_PARAMS.speaking.amplitude + ENERGY_GAIN.amplitude,\n    frequency: STATE_PARAMS.speaking.frequency + ENERGY_GAIN.frequency,\n  };\n  const params = [...Object.values(STATE_PARAMS), atFullEnergy];\n  const maxScale = Math.max(...params.map((p) => p.scale));\n  // Displacement is amplitude over the shader's mix(2, 15, uFrequency).\n  const maxTurb = Math.max(\n    ...params.map((p) => p.amplitude / (2 + 13 * p.frequency)),\n  );\n  const churn = maxTurb * amplitudeProp * TURB_REACH * TURB_VISIBLE_REACH;\n  // The blurred edge glows a little past the surface.\n  const glow = 0.05 * softness + 0.005;\n  return 2 * (maxScale + churn + glow);\n}\n\n// #1FD5F9 as shader RGB — the fallback when a color can't be parsed.\nconst DEFAULT_RGB: [number, number, number] = [0.121, 0.835, 0.976];\n\n/** Resolved CSS color → RGB floats for the shader uniform. */\nfunction colorToRgb(color: string): [number, number, number] {\n  const ctx = document.createElement(\"canvas\").getContext(\"2d\");\n  if (!ctx) return DEFAULT_RGB;\n  ctx.fillStyle = color;\n  const normalized = String(ctx.fillStyle);\n  if (normalized.startsWith(\"#\")) {\n    const n = parseInt(normalized.slice(1, 7), 16);\n    return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];\n  }\n  const parts = normalized.match(/[\\d.]+/g);\n  if (parts && parts.length >= 3) {\n    return [\n      Number(parts[0]) / 255,\n      Number(parts[1]) / 255,\n      Number(parts[2]) / 255,\n    ];\n  }\n  return DEFAULT_RGB;\n}\n\n/**\n * RGB floats → HSV floats, the inverse of the shader's hsv2rgb. The\n * palette endpoints are resolved here so the shader never has to convert\n * a color forward per pixel.\n */\nfunction rgbToHsv([r, g, b]: [number, number, number]): [\n  number,\n  number,\n  number,\n] {\n  const max = Math.max(r, g, b);\n  const d = max - Math.min(r, g, b);\n  let h = 0;\n  if (d > 0) {\n    if (max === r) h = ((g - b) / d + 6) % 6;\n    else if (max === g) h = (b - r) / d + 2;\n    else h = (r - g) / d + 4;\n    h /= 6;\n  }\n  return [h, max === 0 ? 0 : d / max, max];\n}\n\nconst DITHER_DEFAULTS = {\n  method: \"bayer8\",\n  pixelSize: 3,\n  levels: 4,\n  strength: 1,\n} as const satisfies Required<Omit<DitherOptions, \"alphaLevels\">>;\n\nconst DITHER_PATTERN: Record<DitherMethod, string> = {\n  bayer2: \"b2(c)\",\n  bayer4: \"b4(c)\",\n  bayer8: \"b8(c)\",\n  ign: \"fract(52.9829189 * fract(dot(c, vec2(0.06711056, 0.00583715))))\",\n  noise: \"rf(c).x\",\n};\n\nfunction ditherValue(\n  value: number | undefined,\n  fallback: number,\n  min: number,\n  max: number,\n) {\n  return Math.min(\n    max,\n    Math.max(\n      min,\n      value !== undefined && Number.isFinite(value) ? value : fallback,\n    ),\n  );\n}\n\nconst makeDitherSource = (method: DitherMethod) => `\nfloat b2(vec2 a) {\n  a = mod(floor(a), 2.0);\n  return fract(a.x * 0.5 + a.y * a.y * 0.75);\n}\nfloat b4(vec2 a) { return b2(a * 0.5) * 0.25 + b2(a); }\nfloat b8(vec2 a) { return b4(a * 0.5) * 0.25 + b2(a); }\n\nfloat dt(vec2 c) {\n  return mix(0.5, ${DITHER_PATTERN[method]}, uDitherStrength);\n}\n\nfloat qz(float x, float l, float t) {\n  float s = max(l - 1.0, 1.0);\n  return floor(clamp(x, 0.0, 1.0) * s + t) / s;\n}\n\n`;\n\n/** Ribbon count and dither method are compile-time constants; disabled dither adds no fragment work. */\nconst makeShaderSource = (iterations: number, dither: DitherMethod | null) => {\n  const antiBanding = dither ? \"\" : \"    cl += (rf(I).x - 0.5) / 255.0;\\n\";\n  return `\nconst float T = 6.283185;\nconst float N = ${iterations.toFixed(1)};\n\nvec2 rf(vec2 p) {\n  p = fract(p * vec2(443.897, 441.423));\n  p += dot(p, p.yx + 19.19);\n  return fract((p.xx + p.yx) * p.xy);\n}\n\nvec3 tm(vec3 x) {\n  x *= 4.0;\n  return x / (1.0 + x);\n}\n\nfloat lm(vec3 cl) {\n  return dot(cl, vec3(0.299, 0.587, 0.114));\n}\n\nvec3 hr(vec3 c) {\n  vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);\n  vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);\n  return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);\n}\n\nfloat sc(vec2 st, float r) {\n  return length(st) - r;\n}\n\nvec2 tb(vec2 q, float t, float it) {\n\n  mat2 m0 = mat2(0.6, -0.25, 0.25, 0.9);\n\n  mat2 m1 = mat2(0.6, -0.8, 0.8, 0.6);\n\n  float f = mix(2.0, 15.0, uFrequency);\n  float a = uAmplitude;\n  float g = 1.4;\n  float at = t;\n\n  const int L = 4;\n  for(int i = 0; i < L; i++) {\n\n    vec2 rp = q * m0;\n    vec2 w = sin(f * rp + float(i) * at + it);\n\n    q += (a / f) * m0[0] * w;\n\n    m0 *= m1;\n    a *= mix(1.0, max(w.x, w.y), uVariance);\n    f *= g;\n  }\n\n  return q;\n}\n\n${dither ? makeDitherSource(dither) : \"\"}void mainImage(out vec4 O, in vec2 I) {\n${\n  dither\n    ? `  vec2 c = floor(I / uPixelSize);\n  I = (c + 0.5) * uPixelSize;\n`\n    : \"\"\n}  vec2 uv = I / iResolution.xy;\n\n  vec3 pp = vec3(0.0);\n\n  float t = uPhase;\n\n  vec2 q = (uv - 0.5) * uSpan;\n\n  vec2 pv = tb(q, t, 0.0 - 1.0 / N);\n  float sp = mix(1.0, T, 0.5);\n\n  float rn = length(q) / max(uScale, 1e-5);\n\n  float ho = mix(uCore, 1.0, smoothstep(uHollow, 1.0, rn));\n\n  for(float i = 1.0; i < N + 1.0; i++) {\n    float k = i / N;\n    vec2 st = tb(q, t, k * sp);\n\n    float sd = sc(st, uScale * (1.0 - uDepth * k));\n    float d = abs(sd);\n    float pd = distance(st, pv);\n    pv = st;\n\n    float db = exp2(pd * 2.0 * 1.4426950408889634) - 1.0;\n    float e = uBlur * 0.05 + max(db * uSmoothing, 0.001);\n\n    float sh = smoothstep(0.0, e, d) - 1.0;\n    float bd = smoothstep(0.0, e, max(sd, 0.0)) - 1.0;\n    float ik = mix(sh, bd, uFill) * ho;\n\n    vec3 cl = uColor;\n    if(dot(abs(uHsvDelta), vec3(1.0)) > 0.001) {\n\n      float w = 0.5 + 0.5 * sin(T * (uHueDrift + k * uColorShift * 1.5));\n\n      vec3 hs = uColorHsv + uHsvDelta * smoothstep(0.2, 0.8, w);\n      hs.x = fract(hs.x);\n      hs.yz = clamp(hs.yz, 0.0, 1.0);\n      cl = hr(hs);\n    }\n\n    pp += ik * cl;\n  }\n\n  pp *= 1.0 / N;\n\n  vec2 hp = q - vec2(-0.3, 0.3) * uScale;\n  float ss = uHighlight * exp(-dot(hp, hp) / max(uScale * uScale * 0.07, 1e-6));\n  vec3 hl = ss * uHighlightColor;\n\n  vec3 cl;\n\n  if(uMode < 0.5) {\n    cl = (-pp * uDensity) * 1.2 + hl;\n${antiBanding}    cl = tm(cl);\n    float al = lm(cl) * uMix;\n    O = vec4(cl * uMix, al);\n  }\n\n  else {\n    cl = -pp * uDensity + hl;\n${antiBanding}\n    float br = length(cl);\n    vec3 di = br > 0.0 ? cl / br : cl;\n\n    float fa = 2.0;\n    float mb = (br * fa) / (1.0 + br * fa);\n    cl = di * mb;\n\n    float gr = dot(cl, vec3(0.2, 0.5, 0.1));\n    float sb = 3.0;\n    cl = mix(vec3(gr), cl, sb);\n\n    cl = clamp(cl, 0.0, 1.0);\n\n    float al = mb * clamp(uMix, 1.0, 2.0);\n    O = vec4(cl, al);\n  }\n${\n  dither\n    ? `\n  float th = dt(c);\n  O = vec4(\n    qz(O.r, uDitherLevels, th),\n    qz(O.g, uDitherLevels, th),\n    qz(O.b, uDitherLevels, th),\n    qz(O.a, uDitherAlphaLevels, th)\n  );\n`\n    : \"\"\n}}`;\n};\n\n/**\n * The mutable uniform store behind one shader instance. WaveShader\n * reads each .value fresh every frame, so animation writes land here\n * directly — React never re-renders on the hot path.\n */\ntype AuraUniformStore = {\n  /** Accumulated wave phase, advanced per frame at the current pace. */\n  uPhase: { type: \"1f\"; value: number };\n  /** Fit full-energy speech to the canvas; the resting margin leaves room for swelling. */\n  uSpan: { type: \"1f\"; value: number };\n  /** Edge blur/softness. */\n  uBlur: { type: \"1f\"; value: number };\n  /** Orb radius in shader space (state base + pulse swell). */\n  uScale: { type: \"1f\"; value: number };\n  /** Wave frequency and complexity. */\n  uFrequency: { type: \"1f\"; value: number };\n  /** Turbulence amplitude (state base + energy, × amplitude prop). */\n  uAmplitude: { type: \"1f\"; value: number };\n  /** Brightness of the aurora (state base × energy boost × glow prop). */\n  uMix: { type: \"1f\"; value: number };\n  /** Amplitude variation across layers (0–1) — the churn's raggedness. */\n  uVariance: { type: \"1f\"; value: number };\n  /** Layer falloff relative to sample travel (0–1, default 0.28); higher values soften banding. */\n  uSmoothing: { type: \"1f\"; value: number };\n  /** Ink gain before tone mapping; low leaves headroom for gradients. */\n  uDensity: { type: \"1f\"; value: number };\n  /** 0 = open contour wisps, 1 = a filled body. */\n  uFill: { type: \"1f\"; value: number };\n  /** Brightness at the very centre (0–1); the floor of the hollow. */\n  uCore: { type: \"1f\"; value: number };\n  /** Fraction of the radius left open in the middle (0–1). */\n  uHollow: { type: \"1f\"; value: number };\n  /** How far the innermost layer recedes, as a fraction of the radius. */\n  uDepth: { type: \"1f\"; value: number };\n  /** Specular highlight strength. */\n  uHighlight: { type: \"1f\"; value: number };\n  /** Rotating hue offset, advanced per frame with the phase. */\n  uHueDrift: { type: \"1f\"; value: number };\n  /** How often the palette crosses between its two tones, per layer. */\n  uColorShift: { type: \"1f\"; value: number };\n  /** HSV step from the base color to its accent tone. */\n  uHsvDelta: { type: \"3fv\"; value: [number, number, number] };\n  /** Display mode: 0=dark background, 1=light background. */\n  uMode: { type: \"1f\"; value: number };\n  /** Aura color as shader RGB floats. */\n  uColor: { type: \"3fv\"; value: [number, number, number] };\n  /** The aura color again, pre-converted to HSV for the palette blend. */\n  uColorHsv: { type: \"3fv\"; value: [number, number, number] };\n  /** Shine tint as shader RGB floats. */\n  uHighlightColor: { type: \"3fv\"; value: [number, number, number] };\n  uPixelSize: { type: \"1f\"; value: number };\n  uDitherLevels: { type: \"1f\"; value: number };\n  uDitherAlphaLevels: { type: \"1f\"; value: number };\n  uDitherStrength: { type: \"1f\"; value: number };\n};\n\ninterface AuraEngine {\n  speed: MotionValue<number>;\n  scale: MotionValue<number>;\n  amplitude: MotionValue<number>;\n  frequency: MotionValue<number>;\n  variance: MotionValue<number>;\n  brightness: MotionValue<number>;\n  /** Accumulated wave phase (see PHASE_RATE). */\n  phase: number;\n  /** Rotating hue offset 0–1 (see HUE_RATE). */\n  hueDrift: number;\n  uniforms: AuraUniformStore;\n}\n\n/**\n * Motion values plus the uniform store they feed; created once per\n * mounted visualizer, seeded so the mount animation eases into the\n * silent baseline.\n */\nfunction createAuraEngine(): AuraEngine {\n  return {\n    speed: motionValue(STATE_PARAMS.silent.speed),\n    scale: motionValue(0.2),\n    amplitude: motionValue(1.0),\n    frequency: motionValue(0.35),\n    variance: motionValue(0.06),\n    brightness: motionValue(0.9),\n    phase: 0,\n    hueDrift: 0,\n    uniforms: {\n      uPhase: { type: \"1f\", value: 0 },\n      uSpan: { type: \"1f\", value: auraLogicalSpan(1, 0.2) },\n      uBlur: { type: \"1f\", value: 0.2 },\n      uScale: { type: \"1f\", value: 0.2 },\n      uFrequency: { type: \"1f\", value: 0.35 },\n      uAmplitude: { type: \"1f\", value: 1.0 },\n      uMix: { type: \"1f\", value: 0.9 },\n      uVariance: { type: \"1f\", value: 0.06 },\n      uSmoothing: { type: \"1f\", value: 0.28 },\n      uDensity: { type: \"1f\", value: 0.55 },\n      uFill: { type: \"1f\", value: 0.4 },\n      uCore: { type: \"1f\", value: 0.1 },\n      uHollow: { type: \"1f\", value: 0.3 },\n      uDepth: { type: \"1f\", value: 0.22 },\n      uHighlight: { type: \"1f\", value: 0.2 },\n      uHueDrift: { type: \"1f\", value: 0 },\n      uColorShift: { type: \"1f\", value: 0.05 },\n      uHsvDelta: { type: \"3fv\", value: [0.18, 0, 0] },\n      uMode: { type: \"1f\", value: 1.0 },\n      uColor: { type: \"3fv\", value: [...DEFAULT_RGB] },\n      uColorHsv: { type: \"3fv\", value: rgbToHsv(DEFAULT_RGB) },\n      uHighlightColor: { type: \"3fv\", value: defaultHighlightRgb(DEFAULT_RGB) },\n      uPixelSize: { type: \"1f\", value: DITHER_DEFAULTS.pixelSize },\n      uDitherLevels: { type: \"1f\", value: DITHER_DEFAULTS.levels },\n      uDitherAlphaLevels: { type: \"1f\", value: DITHER_DEFAULTS.levels },\n      uDitherStrength: { type: \"1f\", value: DITHER_DEFAULTS.strength },\n    },\n  };\n}\n\n/** The default shine tint: white warmed a little toward the aura color. */\nfunction defaultHighlightRgb(\n  rgb: [number, number, number],\n): [number, number, number] {\n  return [0.65 + 0.35 * rgb[0], 0.65 + 0.35 * rgb[1], 0.65 + 0.35 * rgb[2]];\n}\n\n/** A live analyser and the speech envelopes integrated over it. */\ninterface AuraAudio {\n  analyser: AnalyserNode;\n  data: Uint8Array<ArrayBuffer>;\n  firstBin: number;\n  lastBin: number;\n  binCount: number;\n  /** Phrase-shaped energy: slow to rise, slower to fall. */\n  energy: number;\n  /** Gain-following level for the body's swell. */\n  pulse: number;\n}\n\n/** Per-frame inputs the compositor reads without re-subscribing. */\ninterface AuraFrameInputs {\n  state: VisualizerState;\n  volume?: number;\n  speed: number;\n  amplitude: number;\n  glow: number;\n  colorShift: number;\n  hueSpread: number;\n}\n\n/** One rAF loop updates uniforms without React renders. Energy follows phrases; pulse follows syllables. Envelopes use elapsed time. */\nfunction useAuraUniforms(opts: {\n  state: VisualizerState;\n  track: MediaStreamTrack | null;\n  volume?: number;\n  color: string;\n  accentColor?: string;\n  colorShift: number;\n  hueSpread: number;\n  speed: number;\n  amplitude: number;\n  glow: number;\n  softness: number;\n  fill: number;\n  core: number;\n  hollow: number;\n  depth: number;\n  smoothing: number;\n  density: number;\n  highlight: number;\n  noHighlight: boolean;\n  highlightColor?: string;\n  ditherPixelSize: number;\n  ditherLevels: number;\n  ditherAlphaLevels: number;\n  ditherStrength: number;\n  themeMode?: \"dark\" | \"light\";\n  className?: string;\n  rootRef: RefObject<HTMLDivElement | null>;\n}): AuraUniformStore {\n  const {\n    state,\n    track,\n    volume,\n    color,\n    accentColor,\n    colorShift,\n    hueSpread,\n    speed,\n    amplitude,\n    glow,\n    softness,\n    fill,\n    core,\n    hollow,\n    depth,\n    smoothing,\n    density,\n    highlight,\n    noHighlight,\n    highlightColor,\n    ditherPixelSize,\n    ditherLevels,\n    ditherAlphaLevels,\n    ditherStrength,\n    themeMode,\n    className,\n    rootRef,\n  } = opts;\n  const [engine] = useState(createAuraEngine);\n  const audioRef = useRef<AuraAudio | null>(null);\n  // The HSV step to an explicit accentColor; null derives it from\n  // hueSpread instead.\n  const accentDeltaRef = useRef<[number, number, number] | null>(null);\n  const frameInputsRef = useRef<AuraFrameInputs>({\n    state,\n    volume,\n    speed,\n    amplitude,\n    glow,\n    colorShift,\n    hueSpread,\n  });\n\n  useEffect(() => {\n    frameInputsRef.current = {\n      state,\n      volume,\n      speed,\n      amplitude,\n      glow,\n      colorShift,\n      hueSpread,\n    };\n  });\n\n  // The compositor: one always-on rAF loop for everything per-frame.\n  // Unmount cancels it and parks the motion values — the infinite pulse\n  // animations would otherwise tick forever.\n  useEffect(() => {\n    const { uniforms } = engine;\n    let rafId = 0;\n    let last = performance.now();\n    const tick = (now: number) => {\n      const delta = Math.min((now - last) / 1000, MAX_FRAME_SECONDS);\n      last = now;\n      const inputs = frameInputsRef.current;\n      const audio = audioRef.current;\n      const speaking = inputs.state === \"speaking\";\n\n      // Only speech drives the boost; the other states are self-animated.\n      // An explicit volume override stands in for both envelopes.\n      let energy = 0;\n      let pulse = 0;\n      if (speaking && inputs.volume !== undefined) {\n        energy = pulse = inputs.volume;\n      } else if (speaking && audio) {\n        audio.analyser.getByteFrequencyData(audio.data);\n        let sum = 0;\n        for (let i = audio.firstBin; i <= audio.lastBin; i++) {\n          const v = (audio.data[i] ?? 0) / 255;\n          sum += v * v;\n        }\n        const rms = Math.sqrt(sum / audio.binCount);\n        const level = Math.min(1, rms / ENERGY_REFERENCE_RMS);\n\n        const seconds =\n          level > audio.energy ? ENERGY_ATTACK_SECONDS : ENERGY_RELEASE_SECONDS;\n        audio.energy +=\n          (level - audio.energy) * (1 - Math.exp(-delta / seconds));\n        const pulseSeconds =\n          level > audio.pulse ? PULSE_ATTACK_SECONDS : PULSE_RELEASE_SECONDS;\n        audio.pulse +=\n          (level - audio.pulse) * (1 - Math.exp(-delta / pulseSeconds));\n        energy = audio.energy;\n        pulse = audio.pulse;\n      }\n\n      // Both phases integrate at the current pace, so the churn and the\n      // color rotation accelerate together when the voice picks up.\n      const pace =\n        (engine.speed.get() + ENERGY_GAIN.speed * energy) * inputs.speed;\n      engine.phase += delta * PHASE_RATE * pace;\n      engine.hueDrift = (engine.hueDrift + delta * HUE_RATE * pace) % 1;\n\n      // Energy rides on top of the animated baselines, so the two\n      // compose: state changes still ease, and the voice moves the aura\n      // within a state.\n      uniforms.uPhase.value = engine.phase;\n      uniforms.uHueDrift.value = engine.hueDrift;\n      uniforms.uScale.value = engine.scale.get() + ENERGY_GAIN.scale * pulse;\n      uniforms.uAmplitude.value =\n        (engine.amplitude.get() + ENERGY_GAIN.amplitude * energy) *\n        inputs.amplitude;\n      uniforms.uFrequency.value =\n        engine.frequency.get() + ENERGY_GAIN.frequency * energy;\n      uniforms.uVariance.value =\n        engine.variance.get() + ENERGY_GAIN.variance * energy;\n      uniforms.uMix.value =\n        engine.brightness.get() *\n        (1 + ENERGY_GAIN.brightness * energy) *\n        inputs.glow;\n      // Speech interleaves the two tones more finely through the orb and,\n      // when the accent is derived from hueSpread, pushes them further\n      // apart; an explicit accentColor pins the pair instead.\n      uniforms.uColorShift.value =\n        inputs.colorShift * (1 + ENERGY_GAIN.colorShift * energy);\n      const hsvDelta = uniforms.uHsvDelta.value;\n      const accentDelta = accentDeltaRef.current;\n      if (accentDelta) {\n        hsvDelta[0] = accentDelta[0];\n        hsvDelta[1] = accentDelta[1];\n        hsvDelta[2] = accentDelta[2];\n      } else {\n        hsvDelta[0] = inputs.hueSpread * (1 + ENERGY_GAIN.hueSpread * energy);\n        hsvDelta[1] = 0;\n        hsvDelta[2] = 0;\n      }\n\n      rafId = requestAnimationFrame(tick);\n    };\n    rafId = requestAnimationFrame(tick);\n    return () => {\n      cancelAnimationFrame(rafId);\n      engine.speed.stop();\n      engine.scale.stop();\n      engine.amplitude.stop();\n      engine.frequency.stop();\n      engine.variance.stop();\n      engine.brightness.stop();\n    };\n  }, [engine]);\n\n  // The analyser only exists while speaking without a volume override.\n  // Its envelopes live with it, so a new speaking session starts from\n  // silence rather than inheriting a stale level.\n  useEffect(() => {\n    if (state !== \"speaking\" || !track || volume !== undefined) return;\n    const { analyser, dispose } = createVisualizerAnalyser(track);\n    analyser.fftSize = 512;\n    analyser.smoothingTimeConstant = 0.55;\n    const data = new Uint8Array(analyser.frequencyBinCount);\n\n    // Bin range covering ENERGY_BAND_HZ.\n    const binHz = analyser.context.sampleRate / 2 / analyser.frequencyBinCount;\n    const firstBin = Math.max(1, Math.floor(ENERGY_BAND_HZ.low / binHz));\n    const lastBin = Math.min(\n      data.length - 1,\n      Math.ceil(ENERGY_BAND_HZ.high / binHz),\n    );\n    audioRef.current = {\n      analyser,\n      data,\n      firstBin,\n      lastBin,\n      binCount: Math.max(1, lastBin - firstBin + 1),\n      energy: 0,\n      pulse: 0,\n    };\n    return () => {\n      audioRef.current = null;\n      dispose();\n    };\n  }, [state, track, volume]);\n\n  useEffect(() => {\n    const base = STATE_PARAMS[state];\n    const scaleTransition: ValueAnimationTransition =\n      state === \"connecting\"\n        ? { type: \"spring\", duration: 1.0, bounce: 0.35 }\n        : DEFAULT_TRANSITION;\n    const pulse = PULSE_BRIGHTNESS[state];\n\n    animate(engine.speed, base.speed, DEFAULT_TRANSITION);\n    animate(engine.scale, base.scale, scaleTransition);\n    animate(engine.amplitude, base.amplitude, DEFAULT_TRANSITION);\n    animate(engine.frequency, base.frequency, DEFAULT_TRANSITION);\n    animate(engine.variance, base.variance, DEFAULT_TRANSITION);\n    animate(\n      engine.brightness,\n      pulse ?? base.brightness,\n      pulse ? DEFAULT_PULSE_TRANSITION : DEFAULT_TRANSITION,\n    );\n  }, [engine, state]);\n\n  useEffect(() => {\n    const { uniforms } = engine;\n    uniforms.uSpan.value = auraLogicalSpan(amplitude, softness);\n    uniforms.uBlur.value = softness;\n    uniforms.uFill.value = fill;\n    uniforms.uCore.value = core;\n    uniforms.uHollow.value = hollow;\n    uniforms.uDepth.value = depth;\n    uniforms.uSmoothing.value = smoothing;\n    uniforms.uDensity.value = density;\n    uniforms.uHighlight.value = noHighlight ? 0 : highlight;\n    uniforms.uPixelSize.value = ditherPixelSize;\n    uniforms.uDitherLevels.value = ditherLevels;\n    uniforms.uDitherAlphaLevels.value = ditherAlphaLevels;\n    uniforms.uDitherStrength.value = ditherStrength;\n  }, [\n    engine,\n    amplitude,\n    softness,\n    fill,\n    core,\n    hollow,\n    depth,\n    smoothing,\n    density,\n    highlight,\n    noHighlight,\n    ditherPixelSize,\n    ditherLevels,\n    ditherAlphaLevels,\n    ditherStrength,\n  ]);\n\n  // Resolve CSS-flavored colors to shader RGB. className is a dependency\n  // because it can change what currentColor resolves to.\n  useEffect(() => {\n    const { uniforms } = engine;\n    const rgb = colorToRgb(resolveVisualizerColor(color, rootRef.current));\n    const baseHsv = rgbToHsv(rgb);\n    uniforms.uColor.value = rgb;\n    uniforms.uColorHsv.value = baseHsv;\n\n    if (accentColor) {\n      const accentHsv = rgbToHsv(\n        colorToRgb(resolveVisualizerColor(accentColor, rootRef.current)),\n      );\n      // Hue takes the short way around the wheel.\n      let hue = accentHsv[0] - baseHsv[0];\n      hue -= Math.round(hue);\n      accentDeltaRef.current = [\n        hue,\n        accentHsv[1] - baseHsv[1],\n        accentHsv[2] - baseHsv[2],\n      ];\n    } else {\n      accentDeltaRef.current = null;\n    }\n\n    uniforms.uHighlightColor.value = highlightColor\n      ? colorToRgb(resolveVisualizerColor(highlightColor, rootRef.current))\n      : defaultHighlightRgb(rgb);\n  }, [engine, color, accentColor, highlightColor, className, rootRef]);\n\n  // Without an explicit themeMode, follow the documentElement's \"dark\"\n  // class live.\n  useEffect(() => {\n    if (themeMode) {\n      engine.uniforms.uMode.value = themeMode === \"light\" ? 1.0 : 0.0;\n      return;\n    }\n    const root = document.documentElement;\n    const apply = () => {\n      engine.uniforms.uMode.value = root.classList.contains(\"dark\") ? 0.0 : 1.0;\n    };\n    apply();\n    const observer = new MutationObserver(apply);\n    observer.observe(root, { attributes: true, attributeFilter: [\"class\"] });\n    return () => observer.disconnect();\n  }, [engine, themeMode]);\n\n  return engine.uniforms;\n}\n\n// MSAA does nothing for a fullscreen quad and the shader needs no depth\n// buffer. Alpha stays on — both shader modes composite via destination\n// alpha.\nconst AURA_CONTEXT_ATTRIBUTES = { antialias: false, depth: false };\n\n// The aura is soft by design, so supersampling past 1.5x is invisible —\n// and fragment cost is quadratic in the pixel ratio.\nconst MAX_PIXEL_RATIO = 1.5;\n\n/** Track-reactive shader aura; connecting and thinking override track state. Requires WebGL. */\nexport const AudioVisualizerWaveView = memo(function AudioVisualizerWaveView({\n  track = null,\n  color = \"#1FD5F9\",\n  accentColor,\n  colorShift = 0.05,\n  hueSpread = 0.18,\n  size = 224,\n  speed = 1,\n  amplitude = 1,\n  glow = 1,\n  softness = 0.2,\n  fill = 0.4,\n  core = 0.1,\n  hollow = 0.3,\n  depth = 0.22,\n  smoothing = 0.28,\n  density = 0.55,\n  highlight = 0.2,\n  noHighlight = false,\n  highlightColor,\n  iterations = 24,\n  dither = false,\n  themeMode,\n  volume,\n  isConnecting = false,\n  isThinking = false,\n  className,\n}: AudioVisualizerWaveViewProps) {\n  const rootRef = useRef<HTMLDivElement>(null);\n\n  const ditherOpts = typeof dither === \"object\" ? dither : undefined;\n  const method = ditherOpts?.method ?? DITHER_DEFAULTS.method;\n  const ditherMethod = dither\n    ? Object.hasOwn(DITHER_PATTERN, method)\n      ? method\n      : DITHER_DEFAULTS.method\n    : null;\n  const ditherPixelSize = ditherValue(\n    ditherOpts?.pixelSize,\n    DITHER_DEFAULTS.pixelSize,\n    1,\n    4096,\n  );\n  const ditherLevels = Math.round(\n    ditherValue(ditherOpts?.levels, DITHER_DEFAULTS.levels, 2, 256),\n  );\n  const ditherAlphaLevels = Math.round(\n    ditherValue(ditherOpts?.alphaLevels, ditherLevels, 2, 256),\n  );\n  const ditherStrength = ditherValue(\n    ditherOpts?.strength,\n    DITHER_DEFAULTS.strength,\n    0,\n    1,\n  );\n\n  const state: VisualizerState = isConnecting\n    ? \"connecting\"\n    : isThinking\n      ? \"thinking\"\n      : track\n        ? \"speaking\"\n        : \"silent\";\n\n  const uniforms = useAuraUniforms({\n    state,\n    track,\n    volume,\n    color,\n    accentColor,\n    colorShift,\n    hueSpread,\n    speed,\n    amplitude,\n    glow,\n    softness,\n    fill,\n    core,\n    hollow,\n    depth,\n    smoothing,\n    density,\n    highlight,\n    noHighlight,\n    highlightColor,\n    ditherPixelSize,\n    ditherLevels,\n    ditherAlphaLevels,\n    ditherStrength,\n    themeMode,\n    className,\n    rootRef,\n  });\n\n  const ribbonCount = Math.max(1, Math.round(iterations));\n  const shaderSource = useMemo(\n    () => makeShaderSource(ribbonCount, ditherMethod),\n    [ribbonCount, ditherMethod],\n  );\n\n  return (\n    <div\n      ref={rootRef}\n      data-slot=\"audio-visualizer-wave\"\n      data-state={state}\n      style={{ width: size, height: size }}\n      className={className}\n    >\n      <WaveShader\n        key={`${ribbonCount}:${ditherMethod ?? \"off\"}`}\n        fs={shaderSource}\n        devicePixelRatio={\n          ditherMethod\n            ? 1\n            : Math.min(globalThis.devicePixelRatio ?? 1, MAX_PIXEL_RATIO)\n        }\n        uniforms={uniforms}\n        contextAttributes={AURA_CONTEXT_ATTRIBUTES}\n        onError={(error) => {\n          console.error(\"Shader error:\", error);\n        }}\n        onWarning={(warning) => {\n          console.warn(\"Shader warning:\", warning);\n        }}\n        style={{ width: \"100%\", height: \"100%\" }}\n      />\n    </div>\n  );\n});\n\nexport interface AudioVisualizerWaveProps extends Omit<\n  AudioVisualizerWaveViewProps,\n  \"track\"\n> {\n  /** Which participant's audio to visualize. */\n  participantType: ParticipantType;\n}\n\n/** Requires PipecatClientProvider; silence and speech follow the participant track. */\nexport function AudioVisualizerWave({\n  participantType,\n  ...props\n}: AudioVisualizerWaveProps) {\n  const track = usePipecatClientMediaTrack(\"audio\", participantType);\n  return <AudioVisualizerWaveView track={track} {...props} />;\n}\n",
      "type": "registry:component",
      "target": "components/pipecat/audio-visualizer-wave.tsx"
    },
    {
      "path": "src/components/wave-shader.tsx",
      "content": "import React, { useEffect, useRef, type ComponentPropsWithoutRef } from \"react\";\n\nconst PRECISIONS = [\"lowp\", \"mediump\", \"highp\"];\nconst FS_MAIN_SHADER = `\\nvoid main(void){\n    vec4 color = vec4(0.0,0.0,0.0,1.0);\n    mainImage( color, gl_FragCoord.xy );\n    gl_FragColor = color;\n}`;\nconst BASIC_FS = `void mainImage( out vec4 fragColor, in vec2 fragCoord ) {\n    vec2 uv = fragCoord/iResolution.xy;\n    vec3 col = 0.5 + 0.5*cos(iTime+uv.xyx+vec3(0,2,4));\n    fragColor = vec4(col,1.0);\n}`;\nconst BASIC_VS = `attribute vec3 aVertexPosition;\nvoid main(void) {\n    gl_Position = vec4(aVertexPosition, 1.0);\n}`;\nconst UNIFORM_TIME = \"iTime\";\nconst UNIFORM_TIMEDELTA = \"iTimeDelta\";\nconst UNIFORM_DATE = \"iDate\";\nconst UNIFORM_FRAME = \"iFrame\";\nconst UNIFORM_MOUSE = \"iMouse\";\nconst UNIFORM_RESOLUTION = \"iResolution\";\nconst UNIFORM_CHANNEL = \"iChannel\";\nconst UNIFORM_CHANNELRESOLUTION = \"iChannelResolution\";\nconst UNIFORM_DEVICEORIENTATION = \"iDeviceOrientation\";\n\ntype Vector4<T = number> = [T, T, T, T];\ntype UniformType = keyof Uniforms;\n\nfunction isMatrixType(t: string, v: number[] | number): v is number[] {\n  return t.includes(\"Matrix\") && Array.isArray(v);\n}\nfunction isVectorListType(t: string, v: number[] | number): v is number[] {\n  return (\n    t.includes(\"v\") &&\n    Array.isArray(v) &&\n    v.length > Number.parseInt(t.charAt(0))\n  );\n}\nfunction isVectorType(t: string, v: number[] | number): v is Vector4 {\n  return (\n    !t.includes(\"v\") &&\n    Array.isArray(v) &&\n    v.length >= Number.parseInt(t.charAt(0))\n  );\n}\nconst processUniform = <T extends UniformType>(\n  gl: WebGLRenderingContext,\n  location: WebGLUniformLocation,\n  t: T,\n  value: number | number[],\n) => {\n  if (isVectorType(t, value)) {\n    switch (t) {\n      case \"2f\":\n        return gl.uniform2f(location, value[0], value[1]);\n      case \"3f\":\n        return gl.uniform3f(location, value[0], value[1], value[2]);\n      case \"4f\":\n        return gl.uniform4f(location, value[0], value[1], value[2], value[3]);\n      case \"2i\":\n        return gl.uniform2i(location, value[0], value[1]);\n      case \"3i\":\n        return gl.uniform3i(location, value[0], value[1], value[2]);\n      case \"4i\":\n        return gl.uniform4i(location, value[0], value[1], value[2], value[3]);\n    }\n  }\n  if (typeof value === \"number\") {\n    switch (t) {\n      case \"1i\":\n        return gl.uniform1i(location, value);\n      default:\n        return gl.uniform1f(location, value);\n    }\n  }\n  switch (t) {\n    case \"1iv\":\n      return gl.uniform1iv(location, value);\n    case \"2iv\":\n      return gl.uniform2iv(location, value);\n    case \"3iv\":\n      return gl.uniform3iv(location, value);\n    case \"4iv\":\n      return gl.uniform4iv(location, value);\n    case \"1fv\":\n      return gl.uniform1fv(location, value);\n    case \"2fv\":\n      return gl.uniform2fv(location, value);\n    case \"3fv\":\n      return gl.uniform3fv(location, value);\n    case \"4fv\":\n      return gl.uniform4fv(location, value);\n    case \"Matrix2fv\":\n      return gl.uniformMatrix2fv(location, false, value);\n    case \"Matrix3fv\":\n      return gl.uniformMatrix3fv(location, false, value);\n    case \"Matrix4fv\":\n      return gl.uniformMatrix4fv(location, false, value);\n  }\n};\n\nconst uniformTypeToGLSLType = (t: string) => {\n  switch (t) {\n    case \"1f\":\n      return \"float\";\n    case \"2f\":\n      return \"vec2\";\n    case \"3f\":\n      return \"vec3\";\n    case \"4f\":\n      return \"vec4\";\n    case \"1i\":\n      return \"int\";\n    case \"2i\":\n      return \"ivec2\";\n    case \"3i\":\n      return \"ivec3\";\n    case \"4i\":\n      return \"ivec4\";\n    case \"1iv\":\n      return \"int\";\n    case \"2iv\":\n      return \"ivec2\";\n    case \"3iv\":\n      return \"ivec3\";\n    case \"4iv\":\n      return \"ivec4\";\n    case \"1fv\":\n      return \"float\";\n    case \"2fv\":\n      return \"vec2\";\n    case \"3fv\":\n      return \"vec3\";\n    case \"4fv\":\n      return \"vec4\";\n    case \"Matrix2fv\":\n      return \"mat2\";\n    case \"Matrix3fv\":\n      return \"mat3\";\n    case \"Matrix4fv\":\n      return \"mat4\";\n    default:\n      console.error(\n        log(\n          `The uniform type \"${t}\" is not valid, please make sure your uniform type is valid`,\n        ),\n      );\n  }\n};\n\nconst LinearFilter = 9729;\nconst NearestFilter = 9728;\nconst LinearMipMapLinearFilter = 9987;\nconst ClampToEdgeWrapping = 33071;\nconst RepeatWrapping = 10497;\n\nclass Texture {\n  gl: WebGLRenderingContext;\n  url?: string;\n  wrapS?: number;\n  wrapT?: number;\n  minFilter?: number;\n  magFilter?: number;\n  source?: HTMLImageElement | HTMLVideoElement;\n  pow2canvas?: HTMLCanvasElement;\n  isLoaded = false;\n  isVideo = false;\n  flipY = -1;\n  width = 0;\n  height = 0;\n  _webglTexture: WebGLTexture | null = null;\n  constructor(gl: WebGLRenderingContext) {\n    this.gl = gl;\n  }\n  updateTexture = (\n    texture: WebGLTexture,\n    video: HTMLVideoElement,\n    flipY: number,\n  ) => {\n    const { gl } = this;\n    const level = 0;\n    const internalFormat = gl.RGBA;\n    const srcFormat = gl.RGBA;\n    const srcType = gl.UNSIGNED_BYTE;\n    gl.bindTexture(gl.TEXTURE_2D, texture);\n    gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY);\n    gl.texImage2D(\n      gl.TEXTURE_2D,\n      level,\n      internalFormat,\n      srcFormat,\n      srcType,\n      video,\n    );\n  };\n  setupVideo = (url: string) => {\n    const video = document.createElement(\"video\");\n    let playing = false;\n    let timeupdate = false;\n    video.autoplay = true;\n    video.muted = true;\n    video.loop = true;\n    video.crossOrigin = \"anonymous\";\n    const checkReady = () => {\n      if (playing && timeupdate) {\n        this.isLoaded = true;\n      }\n    };\n    video.addEventListener(\n      \"playing\",\n      () => {\n        playing = true;\n        this.width = video.videoWidth || 0;\n        this.height = video.videoHeight || 0;\n        checkReady();\n      },\n      true,\n    );\n    video.addEventListener(\n      \"timeupdate\",\n      () => {\n        timeupdate = true;\n        checkReady();\n      },\n      true,\n    );\n    video.src = url;\n    return video;\n  };\n  makePowerOf2 = <T extends HTMLCanvasElement | HTMLImageElement | ImageBitmap>(\n    image: T,\n  ): T => {\n    if (\n      image instanceof HTMLImageElement ||\n      image instanceof HTMLCanvasElement ||\n      image instanceof ImageBitmap\n    ) {\n      if (this.pow2canvas === undefined)\n        this.pow2canvas = document.createElement(\"canvas\");\n      this.pow2canvas.width = 2 ** Math.floor(Math.log(image.width) / Math.LN2);\n      this.pow2canvas.height =\n        2 ** Math.floor(Math.log(image.height) / Math.LN2);\n      const context = this.pow2canvas.getContext(\"2d\");\n      context?.drawImage(\n        image,\n        0,\n        0,\n        this.pow2canvas.width,\n        this.pow2canvas.height,\n      );\n      console.warn(\n        log(\n          `Image is not power of two ${image.width} x ${image.height}. Resized to ${this.pow2canvas.width} x ${this.pow2canvas.height};`,\n        ),\n      );\n      return this.pow2canvas as T;\n    }\n    return image;\n  };\n  load = async (textureArgs: TextureParams) => {\n    const { gl } = this;\n    const {\n      url,\n      wrapS,\n      wrapT,\n      minFilter,\n      magFilter,\n      flipY = -1,\n    }: TextureParams = textureArgs;\n    if (!url) {\n      return Promise.reject(\n        new Error(\n          log(\n            \"Missing url, please make sure to pass the url of your texture { url: ... }\",\n          ),\n        ),\n      );\n    }\n    const isImage = /(\\.jpg|\\.jpeg|\\.png|\\.gif|\\.bmp)$/i.exec(url);\n    const isVideo = /(\\.mp4|\\.3gp|\\.webm|\\.ogv)$/i.exec(url);\n    if (isImage === null && isVideo === null) {\n      return Promise.reject(\n        new Error(\n          log(\n            `Please upload a video or an image with a valid format (url: ${url})`,\n          ),\n        ),\n      );\n    }\n    Object.assign(this, { url, wrapS, wrapT, minFilter, magFilter, flipY });\n    const level = 0;\n    const internalFormat = gl.RGBA;\n    const width = 1;\n    const height = 1;\n    const border = 0;\n    const srcFormat = gl.RGBA;\n    const srcType = gl.UNSIGNED_BYTE;\n    const pixel = new Uint8Array([255, 255, 255, 0]);\n    const texture = gl.createTexture();\n    gl.bindTexture(gl.TEXTURE_2D, texture);\n    gl.texImage2D(\n      gl.TEXTURE_2D,\n      level,\n      internalFormat,\n      width,\n      height,\n      border,\n      srcFormat,\n      srcType,\n      pixel,\n    );\n    if (isVideo) {\n      const video = this.setupVideo(url);\n      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n      this._webglTexture = texture;\n      this.source = video;\n      this.isVideo = true;\n      return video.play().then(() => this);\n    }\n    async function loadImage() {\n      return new Promise((resolve, reject) => {\n        const image = new Image();\n        image.crossOrigin = \"anonymous\";\n        image.onload = () => {\n          resolve(image);\n        };\n        image.onerror = () => {\n          reject(new Error(log(`failed loading url: ${url}`)));\n        };\n        image.src = url ?? \"\";\n      });\n    }\n    let image = (await loadImage()) as HTMLImageElement;\n    let isPowerOf2 =\n      (image.width & (image.width - 1)) === 0 &&\n      (image.height & (image.height - 1)) === 0;\n    if (\n      (textureArgs.wrapS !== ClampToEdgeWrapping ||\n        textureArgs.wrapT !== ClampToEdgeWrapping ||\n        (textureArgs.minFilter !== NearestFilter &&\n          textureArgs.minFilter !== LinearFilter)) &&\n      !isPowerOf2\n    ) {\n      image = this.makePowerOf2(image);\n      isPowerOf2 = true;\n    }\n    gl.bindTexture(gl.TEXTURE_2D, texture);\n    gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY);\n    gl.texImage2D(\n      gl.TEXTURE_2D,\n      level,\n      internalFormat,\n      srcFormat,\n      srcType,\n      image,\n    );\n    if (\n      isPowerOf2 &&\n      textureArgs.minFilter !== NearestFilter &&\n      textureArgs.minFilter !== LinearFilter\n    ) {\n      gl.generateMipmap(gl.TEXTURE_2D);\n    }\n    gl.texParameteri(\n      gl.TEXTURE_2D,\n      gl.TEXTURE_WRAP_S,\n      this.wrapS || RepeatWrapping,\n    );\n    gl.texParameteri(\n      gl.TEXTURE_2D,\n      gl.TEXTURE_WRAP_T,\n      this.wrapT || RepeatWrapping,\n    );\n    gl.texParameteri(\n      gl.TEXTURE_2D,\n      gl.TEXTURE_MIN_FILTER,\n      this.minFilter || LinearMipMapLinearFilter,\n    );\n    gl.texParameteri(\n      gl.TEXTURE_2D,\n      gl.TEXTURE_MAG_FILTER,\n      this.magFilter || LinearFilter,\n    );\n    this._webglTexture = texture;\n    this.source = image;\n    this.isVideo = false;\n    this.isLoaded = true;\n    this.width = image.width || 0;\n    this.height = image.height || 0;\n    return this;\n  };\n}\n\nconst log = (text: string) => `WaveShader: ${text}`;\n\nconst latestPointerClientCoords = (e: MouseEvent | TouchEvent) => {\n  if (\"changedTouches\" in e) {\n    const t = e.changedTouches[0];\n    return [t?.clientX ?? 0, t?.clientY ?? 0];\n  }\n  return [e.clientX, e.clientY];\n};\n\nconst lerpVal = (v0: number, v1: number, t: number) => v0 * (1 - t) + v1 * t;\nconst insertStringAtIndex = (\n  currentString: string,\n  string: string,\n  index: number,\n) =>\n  index > 0\n    ? currentString.substring(0, index) +\n      string +\n      currentString.substring(index, currentString.length)\n    : string + currentString;\n\ntype Uniform = { type: string; value: number[] | number };\ntype Uniforms = Record<string, Uniform>;\ntype TextureParams = {\n  url: string;\n  wrapS?: number;\n  wrapT?: number;\n  minFilter?: number;\n  magFilter?: number;\n  flipY?: number;\n};\n\nexport interface WaveShaderProps {\n  /** Fragment shader GLSL code. */\n  fs: string;\n\n  /** Vertex shader GLSL code. */\n  vs?: string;\n\n  /** Textures are resized to power-of-two dimensions for mipmaps and repeat wrapping. */\n  textures?: TextureParams[];\n\n  /** Custom uniform values, read each frame. */\n  uniforms?: Uniforms;\n\n  /** RGBA canvas clear color. */\n  clearColor?: Vector4;\n\n  /**\n   * GLSL precision qualifier. Defaults to `'highp'`. Balance between\n   * performance and quality.\n   */\n  precision?: \"highp\" | \"lowp\" | \"mediump\";\n\n  style?: React.CSSProperties;\n\n  /** Customize WebGL context attributes. See [the WebGL docs](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getContextAttributes) for details. */\n  contextAttributes?: Record<string, unknown>;\n\n  /** Lerp value for `iMouse` built-in uniform. Must be between 0 and 1. */\n  lerp?: number;\n\n  devicePixelRatio?: number;\n\n  /**\n   * Callback for when the textures are done loading. Useful if you want to do\n   * something like e.g. hide the canvas until textures are done loading.\n   */\n  onDoneLoadingTextures?: () => void;\n\n  /** Custom callback to handle errors. Defaults to `console.error`. */\n  onError?: (error: string) => void;\n\n  /** Custom callback to handle warnings. Defaults to `console.warn`. */\n  onWarning?: (warning: string) => void;\n\n  /**\n   * When true, the animation loop runs even when the canvas is not visible in the viewport.\n   * When false (default), animation runs only while visible (uses Intersection Observer),\n   * reducing CPU/GPU usage when the shader is off-screen.\n   */\n  animateWhenNotVisible?: boolean;\n}\n\nexport function WaveShader({\n  fs,\n  vs = BASIC_VS,\n  textures = [],\n  uniforms: propUniforms,\n  clearColor = [0, 0, 0, 1],\n  precision = \"highp\",\n  style,\n  contextAttributes = {},\n  lerp = 1,\n  devicePixelRatio = 1,\n  onDoneLoadingTextures,\n  onError = console.error,\n  onWarning = console.warn,\n  animateWhenNotVisible = false,\n  ...canvasProps\n}: WaveShaderProps & ComponentPropsWithoutRef<\"canvas\">) {\n  const canvasRef = useRef<HTMLCanvasElement>(null);\n  const glRef = useRef<WebGLRenderingContext | null>(null);\n  const squareVerticesBufferRef = useRef<WebGLBuffer | null>(null);\n  const shaderProgramRef = useRef<WebGLProgram | null>(null);\n  const vertexPositionAttributeRef = useRef<number | undefined>(undefined);\n  const drawFrameRef = useRef<FrameRequestCallback | null>(null);\n  const animFrameIdRef = useRef<number | undefined>(undefined);\n  const initFrameIdRef = useRef<number | undefined>(undefined);\n  const isVisibleRef = useRef(true);\n  const animateWhenNotVisibleRef = useRef(animateWhenNotVisible);\n  const mousedownRef = useRef(false);\n  const canvasPositionRef = useRef<DOMRect | undefined>(undefined);\n  const timerRef = useRef(0);\n  const lastMouseArrRef = useRef<number[]>([0, 0]);\n  const texturesArrRef = useRef<Texture[]>([]);\n  const lastTimeRef = useRef(0);\n  const resizeObserverRef = useRef<ResizeObserver | undefined>(undefined);\n  // Cache uniform locations after linking, outside the frame loop.\n  const uniformLocationsRef = useRef<\n    Record<string, WebGLUniformLocation | null>\n  >({});\n  const uniformsRef = useRef<\n    Record<\n      string,\n      {\n        type: string;\n        isNeeded: boolean;\n        value?: number[] | number;\n        arraySize?: string;\n      }\n    >\n  >({\n    [UNIFORM_TIME]: { type: \"float\", isNeeded: false, value: 0 },\n    [UNIFORM_TIMEDELTA]: { type: \"float\", isNeeded: false, value: 0 },\n    [UNIFORM_DATE]: { type: \"vec4\", isNeeded: false, value: [0, 0, 0, 0] },\n    [UNIFORM_MOUSE]: { type: \"vec4\", isNeeded: false, value: [0, 0, 0, 0] },\n    [UNIFORM_RESOLUTION]: { type: \"vec2\", isNeeded: false, value: [0, 0] },\n    [UNIFORM_FRAME]: { type: \"int\", isNeeded: false, value: 0 },\n    [UNIFORM_DEVICEORIENTATION]: {\n      type: \"vec4\",\n      isNeeded: false,\n      value: [0, 0, 0, 0],\n    },\n  });\n  const propsUniformsRef = useRef<Uniforms | undefined>(propUniforms);\n\n  const setupChannelRes = (texture: TextureParams | Texture, id: number) => {\n    const width = \"width\" in texture ? (texture.width ?? 0) : 0;\n    const height = \"height\" in texture ? (texture.height ?? 0) : 0;\n    const channelResUniform = uniformsRef.current.iChannelResolution;\n    if (!channelResUniform) return;\n    const channelResValue = Array.isArray(channelResUniform.value)\n      ? channelResUniform.value\n      : (channelResUniform.value = []);\n    channelResValue[id * 3] = width * devicePixelRatio;\n    channelResValue[id * 3 + 1] = height * devicePixelRatio;\n    channelResValue[id * 3 + 2] = 0;\n  };\n\n  const initWebGL = () => {\n    if (!canvasRef.current) return;\n    glRef.current = (canvasRef.current.getContext(\"webgl\", contextAttributes) ||\n      canvasRef.current.getContext(\n        \"experimental-webgl\",\n        contextAttributes,\n      )) as WebGLRenderingContext | null;\n    glRef.current?.getExtension(\"OES_standard_derivatives\");\n    glRef.current?.getExtension(\"EXT_shader_texture_lod\");\n  };\n\n  const initBuffers = () => {\n    const gl = glRef.current;\n    squareVerticesBufferRef.current = gl?.createBuffer() ?? null;\n    gl?.bindBuffer(gl.ARRAY_BUFFER, squareVerticesBufferRef.current);\n    const vertices = [\n      1.0, 1.0, 0.0, -1.0, 1.0, 0.0, 1.0, -1.0, 0.0, -1.0, -1.0, 0.0,\n    ];\n    gl?.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);\n  };\n\n  const onDeviceOrientationChange = ({\n    alpha,\n    beta,\n    gamma,\n  }: DeviceOrientationEvent) => {\n    uniformsRef.current.iDeviceOrientation!.value = [\n      alpha ?? 0,\n      beta ?? 0,\n      gamma ?? 0,\n      window.orientation ?? 0,\n    ];\n  };\n\n  const mouseDown = (e: MouseEvent | TouchEvent) => {\n    const [clientX = 0, clientY = 0] = latestPointerClientCoords(e);\n    const mouseX =\n      clientX - (canvasPositionRef.current?.left ?? 0) - window.pageXOffset;\n    const mouseY =\n      (canvasPositionRef.current?.height ?? 0) -\n      clientY -\n      (canvasPositionRef.current?.top ?? 0) -\n      window.pageYOffset;\n    mousedownRef.current = true;\n    const mouseValue = Array.isArray(uniformsRef.current.iMouse?.value)\n      ? uniformsRef.current.iMouse.value\n      : undefined;\n    if (mouseValue) {\n      mouseValue[2] = mouseX;\n      mouseValue[3] = mouseY;\n    }\n    lastMouseArrRef.current[0] = mouseX;\n    lastMouseArrRef.current[1] = mouseY;\n  };\n\n  const mouseMove = (e: MouseEvent | TouchEvent) => {\n    canvasPositionRef.current = canvasRef.current?.getBoundingClientRect();\n    const [clientX = 0, clientY = 0] = latestPointerClientCoords(e);\n    const mouseX = clientX - (canvasPositionRef.current?.left ?? 0);\n    const mouseY =\n      (canvasPositionRef.current?.height ?? 0) -\n      clientY -\n      (canvasPositionRef.current?.top ?? 0);\n    if (lerp !== 1) {\n      lastMouseArrRef.current[0] = mouseX;\n      lastMouseArrRef.current[1] = mouseY;\n    } else {\n      const mouseValue = Array.isArray(uniformsRef.current.iMouse?.value)\n        ? uniformsRef.current.iMouse.value\n        : undefined;\n      if (mouseValue) {\n        mouseValue[0] = mouseX;\n        mouseValue[1] = mouseY;\n      }\n    }\n  };\n\n  const mouseUp = () => {\n    const mouseValue = Array.isArray(uniformsRef.current.iMouse?.value)\n      ? uniformsRef.current.iMouse.value\n      : undefined;\n    if (mouseValue) {\n      mouseValue[2] = 0;\n      mouseValue[3] = 0;\n    }\n  };\n\n  const onResize = () => {\n    const gl = glRef.current;\n    if (!gl) return;\n    canvasPositionRef.current = canvasRef.current?.getBoundingClientRect();\n    const realToCSSPixels = devicePixelRatio;\n    const displayWidth = Math.floor(\n      (canvasPositionRef.current?.width ?? 1) * realToCSSPixels,\n    );\n    const displayHeight = Math.floor(\n      (canvasPositionRef.current?.height ?? 1) * realToCSSPixels,\n    );\n    gl.canvas.width = displayWidth;\n    gl.canvas.height = displayHeight;\n    if (uniformsRef.current.iResolution?.isNeeded && shaderProgramRef.current) {\n      gl.uniform2fv(uniformLocationsRef.current[UNIFORM_RESOLUTION] ?? null, [\n        gl.canvas.width,\n        gl.canvas.height,\n      ]);\n    }\n  };\n\n  const createShader = (type: number, shaderCodeAsText: string) => {\n    const gl = glRef.current;\n    if (!gl) return null;\n    const shader = gl.createShader(type);\n    if (!shader) return null;\n    gl.shaderSource(shader, shaderCodeAsText);\n    gl.compileShader(shader);\n    if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n      onWarning?.(log(`Error compiling the shader:\\n${shaderCodeAsText}`));\n      const compilationLog = gl.getShaderInfoLog(shader);\n      gl.deleteShader(shader);\n      onError?.(log(`Shader compiler log: ${compilationLog}`));\n      return null;\n    }\n    return shader;\n  };\n\n  const initShaders = (fragmentShader: string, vertexShader: string) => {\n    const gl = glRef.current;\n    if (!gl) return false;\n    const fragmentShaderObj = createShader(gl.FRAGMENT_SHADER, fragmentShader);\n    const vertexShaderObj = createShader(gl.VERTEX_SHADER, vertexShader);\n    shaderProgramRef.current = gl.createProgram();\n    if (!shaderProgramRef.current || !vertexShaderObj || !fragmentShaderObj) {\n      gl.deleteShader(fragmentShaderObj);\n      gl.deleteShader(vertexShaderObj);\n      gl.deleteProgram(shaderProgramRef.current);\n      shaderProgramRef.current = null;\n      return false;\n    }\n    gl.attachShader(shaderProgramRef.current, vertexShaderObj);\n    gl.attachShader(shaderProgramRef.current, fragmentShaderObj);\n    gl.linkProgram(shaderProgramRef.current);\n    gl.deleteShader(fragmentShaderObj);\n    gl.deleteShader(vertexShaderObj);\n    if (!gl.getProgramParameter(shaderProgramRef.current, gl.LINK_STATUS)) {\n      onError?.(\n        log(\n          `Unable to initialize the shader program: ${gl.getProgramInfoLog(shaderProgramRef.current)}`,\n        ),\n      );\n      gl.deleteProgram(shaderProgramRef.current);\n      shaderProgramRef.current = null;\n      return false;\n    }\n    gl.useProgram(shaderProgramRef.current);\n    vertexPositionAttributeRef.current = gl.getAttribLocation(\n      shaderProgramRef.current,\n      \"aVertexPosition\",\n    );\n    gl.enableVertexAttribArray(vertexPositionAttributeRef.current);\n    // Null locations are valid for uniforms optimized out by the compiler.\n    uniformLocationsRef.current = {};\n    for (const name of Object.keys(uniformsRef.current)) {\n      if (uniformsRef.current[name]?.isNeeded) {\n        uniformLocationsRef.current[name] = gl.getUniformLocation(\n          shaderProgramRef.current,\n          name,\n        );\n      }\n    }\n    return true;\n  };\n\n  const processCustomUniforms = () => {\n    if (propUniforms) {\n      for (const name of Object.keys(propUniforms)) {\n        const uniform = propUniforms[name];\n        if (!uniform) continue;\n        const { value, type } = uniform;\n        const glslType = uniformTypeToGLSLType(type);\n        if (!glslType) continue;\n        const tempObject: { arraySize?: string } = {};\n        if (isMatrixType(type, value)) {\n          const arrayLength = type.length;\n          const val = Number.parseInt(type.charAt(arrayLength - 3));\n          const numberOfMatrices = Math.floor(value.length / (val * val));\n          if (value.length > val * val)\n            tempObject.arraySize = `[${numberOfMatrices}]`;\n        } else if (isVectorListType(type, value)) {\n          tempObject.arraySize = `[${Math.floor(value.length / Number.parseInt(type.charAt(0)))}]`;\n        }\n        uniformsRef.current[name] = {\n          type: glslType,\n          isNeeded: false,\n          value,\n          ...tempObject,\n        };\n      }\n    }\n  };\n\n  const processTextures = () => {\n    const gl = glRef.current;\n    if (!gl) return;\n    if (textures && textures.length > 0) {\n      uniformsRef.current[`${UNIFORM_CHANNELRESOLUTION}`] = {\n        type: \"vec3\",\n        isNeeded: false,\n        arraySize: `[${textures.length}]`,\n        value: [],\n      };\n      const texturePromisesArr = textures.map(\n        (texture: TextureParams, id: number) => {\n          uniformsRef.current[`${UNIFORM_CHANNEL}${id}`] = {\n            type: \"sampler2D\",\n            isNeeded: false,\n          };\n          setupChannelRes(texture, id);\n          texturesArrRef.current[id] = new Texture(gl);\n          return texturesArrRef.current[id]\n            ?.load(texture)\n            .then((t: Texture) => {\n              setupChannelRes(t, id);\n            });\n        },\n      );\n      Promise.all(texturePromisesArr)\n        .then(() => {\n          if (onDoneLoadingTextures) onDoneLoadingTextures();\n        })\n        .catch((e) => {\n          onError?.(e);\n          if (onDoneLoadingTextures) onDoneLoadingTextures();\n        });\n    } else if (onDoneLoadingTextures) onDoneLoadingTextures();\n  };\n\n  const preProcessFragment = (fragment: string) => {\n    const isValidPrecision = PRECISIONS.includes(precision ?? \"highp\");\n    const precisionString = `precision ${isValidPrecision ? precision : PRECISIONS[1]} float;\\n`;\n    if (!isValidPrecision) {\n      onWarning?.(\n        log(\n          `wrong precision type ${precision}, please make sure to pass one of a valid precision lowp, mediump, highp, by default you shader precision will be set to highp.`,\n        ),\n      );\n    }\n    let fragmentShader = precisionString\n      .concat(`#define DPR ${devicePixelRatio.toFixed(1)}\\n`)\n      .concat(fragment.replace(/texture\\(/g, \"texture2D(\"));\n    for (const uniform of Object.keys(uniformsRef.current)) {\n      if (fragment.includes(uniform)) {\n        const u = uniformsRef.current[uniform];\n        if (!u) continue;\n        fragmentShader = insertStringAtIndex(\n          fragmentShader,\n          `uniform ${u.type} ${uniform}${u.arraySize || \"\"}; \\n`,\n          fragmentShader.lastIndexOf(precisionString) + precisionString.length,\n        );\n        u.isNeeded = true;\n      }\n    }\n    const isShadertoy = fragment.includes(\"mainImage\");\n    if (isShadertoy) fragmentShader = fragmentShader.concat(FS_MAIN_SHADER);\n    return fragmentShader;\n  };\n\n  const setUniforms = (timestamp: number) => {\n    const gl = glRef.current;\n    if (!gl || !shaderProgramRef.current) return;\n    const delta = lastTimeRef.current\n      ? (timestamp - lastTimeRef.current) / 1000\n      : 0;\n    lastTimeRef.current = timestamp;\n    const locations = uniformLocationsRef.current;\n    const propUniforms = propsUniformsRef.current;\n    if (propUniforms) {\n      for (const name of Object.keys(propUniforms)) {\n        const currentUniform = propUniforms[name];\n        if (!currentUniform) continue;\n        if (uniformsRef.current[name]?.isNeeded) {\n          const customUniformLocation = locations[name];\n          if (!customUniformLocation) continue;\n          processUniform(\n            gl,\n            customUniformLocation,\n            currentUniform.type as UniformType,\n            currentUniform.value,\n          );\n        }\n      }\n    }\n    if (uniformsRef.current.iMouse?.isNeeded) {\n      gl.uniform4fv(\n        locations[UNIFORM_MOUSE] ?? null,\n        uniformsRef.current.iMouse.value as number[],\n      );\n    }\n    if (uniformsRef.current.iChannelResolution?.isNeeded) {\n      gl.uniform3fv(\n        locations[UNIFORM_CHANNELRESOLUTION] ?? null,\n        uniformsRef.current.iChannelResolution.value as number[],\n      );\n    }\n    if (uniformsRef.current.iDeviceOrientation?.isNeeded) {\n      gl.uniform4fv(\n        locations[UNIFORM_DEVICEORIENTATION] ?? null,\n        uniformsRef.current.iDeviceOrientation.value as number[],\n      );\n    }\n    if (uniformsRef.current.iTime?.isNeeded) {\n      gl.uniform1f(\n        locations[UNIFORM_TIME] ?? null,\n        (timerRef.current += delta),\n      );\n    }\n    if (uniformsRef.current.iTimeDelta?.isNeeded) {\n      gl.uniform1f(locations[UNIFORM_TIMEDELTA] ?? null, delta);\n    }\n    if (uniformsRef.current.iDate?.isNeeded) {\n      const d = new Date();\n      const month = d.getMonth() + 1;\n      const day = d.getDate();\n      const year = d.getFullYear();\n      const time =\n        d.getHours() * 60 * 60 +\n        d.getMinutes() * 60 +\n        d.getSeconds() +\n        d.getMilliseconds() * 0.001;\n      gl.uniform4fv(locations[UNIFORM_DATE] ?? null, [year, month, day, time]);\n    }\n    if (uniformsRef.current.iFrame?.isNeeded) {\n      const frame = uniformsRef.current.iFrame.value as number;\n      gl.uniform1i(locations[UNIFORM_FRAME] ?? null, frame);\n      uniformsRef.current.iFrame.value = frame + 1;\n    }\n    if (texturesArrRef.current.length > 0) {\n      for (let index = 0; index < texturesArrRef.current.length; index++) {\n        const texture = texturesArrRef.current[index];\n        if (!texture) return;\n        const { isVideo, _webglTexture, source, flipY, isLoaded } = texture;\n        if (!isLoaded || !_webglTexture || !source) return;\n        if (uniformsRef.current[`iChannel${index}`]?.isNeeded) {\n          const iChannel = locations[`${UNIFORM_CHANNEL}${index}`] ?? null;\n          gl.activeTexture(gl.TEXTURE0 + index);\n          gl.bindTexture(gl.TEXTURE_2D, _webglTexture);\n          gl.uniform1i(iChannel, index);\n          if (isVideo) {\n            texture.updateTexture(\n              _webglTexture,\n              source as HTMLVideoElement,\n              flipY,\n            );\n          }\n        }\n      }\n    }\n  };\n\n  const drawScene = (timestamp: number) => {\n    const gl = glRef.current;\n    if (!gl || !shaderProgramRef.current) return;\n    gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);\n    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n    gl.bindBuffer(gl.ARRAY_BUFFER, squareVerticesBufferRef.current);\n    gl.vertexAttribPointer(\n      vertexPositionAttributeRef.current ?? 0,\n      3,\n      gl.FLOAT,\n      false,\n      0,\n      0,\n    );\n    setUniforms(timestamp);\n    gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);\n    const mouseValue = uniformsRef.current.iMouse?.value;\n    if (\n      uniformsRef.current.iMouse?.isNeeded &&\n      lerp !== 1 &&\n      Array.isArray(mouseValue)\n    ) {\n      const currentX = mouseValue[0] ?? 0;\n      const currentY = mouseValue[1] ?? 0;\n      mouseValue[0] = lerpVal(currentX, lastMouseArrRef.current[0] ?? 0, lerp);\n      mouseValue[1] = lerpVal(currentY, lastMouseArrRef.current[1] ?? 0, lerp);\n    }\n    if (animateWhenNotVisibleRef.current || isVisibleRef.current) {\n      animFrameIdRef.current = requestAnimationFrame(drawScene);\n    }\n  };\n\n  const addEventListeners = () => {\n    const options = { passive: true };\n    if (uniformsRef.current.iMouse?.isNeeded && canvasRef.current) {\n      canvasRef.current.addEventListener(\"mousemove\", mouseMove, options);\n      canvasRef.current.addEventListener(\"mouseout\", mouseUp, options);\n      canvasRef.current.addEventListener(\"mouseup\", mouseUp, options);\n      canvasRef.current.addEventListener(\"mousedown\", mouseDown, options);\n      canvasRef.current.addEventListener(\"touchmove\", mouseMove, options);\n      canvasRef.current.addEventListener(\"touchend\", mouseUp, options);\n      canvasRef.current.addEventListener(\"touchstart\", mouseDown, options);\n    }\n    if (uniformsRef.current.iDeviceOrientation?.isNeeded) {\n      window.addEventListener(\n        \"deviceorientation\",\n        onDeviceOrientationChange,\n        options,\n      );\n    }\n    if (canvasRef.current) {\n      resizeObserverRef.current = new ResizeObserver(onResize);\n      resizeObserverRef.current.observe(canvasRef.current);\n      window.addEventListener(\"resize\", onResize, options);\n    }\n  };\n\n  const removeEventListeners = () => {\n    const options = { passive: true } as EventListenerOptions;\n    if (uniformsRef.current.iMouse?.isNeeded && canvasRef.current) {\n      canvasRef.current.removeEventListener(\"mousemove\", mouseMove, options);\n      canvasRef.current.removeEventListener(\"mouseout\", mouseUp, options);\n      canvasRef.current.removeEventListener(\"mouseup\", mouseUp, options);\n      canvasRef.current.removeEventListener(\"mousedown\", mouseDown, options);\n      canvasRef.current.removeEventListener(\"touchmove\", mouseMove, options);\n      canvasRef.current.removeEventListener(\"touchend\", mouseUp, options);\n      canvasRef.current.removeEventListener(\"touchstart\", mouseDown, options);\n    }\n    if (uniformsRef.current.iDeviceOrientation?.isNeeded) {\n      window.removeEventListener(\n        \"deviceorientation\",\n        onDeviceOrientationChange,\n        options,\n      );\n    }\n    if (resizeObserverRef.current) {\n      resizeObserverRef.current.disconnect();\n      window.removeEventListener(\"resize\", onResize, options);\n    }\n  };\n\n  useEffect(() => {\n    propsUniformsRef.current = propUniforms;\n  }, [propUniforms]);\n\n  useEffect(() => {\n    animateWhenNotVisibleRef.current = animateWhenNotVisible;\n    if (animateWhenNotVisible) {\n      isVisibleRef.current = true;\n      if (drawFrameRef.current) {\n        cancelAnimationFrame(animFrameIdRef.current ?? 0);\n        animFrameIdRef.current = requestAnimationFrame(drawFrameRef.current);\n      }\n    }\n  }, [animateWhenNotVisible]);\n\n  // Resume only one frame loop after visibility changes.\n  useEffect(() => {\n    if (animateWhenNotVisible || !canvasRef.current) return;\n    const canvas = canvasRef.current;\n    const observer = new IntersectionObserver(\n      (entries) => {\n        for (const entry of entries) {\n          isVisibleRef.current = entry.isIntersecting;\n          if (entry.isIntersecting && drawFrameRef.current) {\n            cancelAnimationFrame(animFrameIdRef.current ?? 0);\n            animFrameIdRef.current = requestAnimationFrame(\n              drawFrameRef.current,\n            );\n          }\n        }\n      },\n      { threshold: 0 },\n    );\n    observer.observe(canvas);\n    return () => observer.disconnect();\n  }, [animateWhenNotVisible]);\n\n  useEffect(() => {\n    const textures = texturesArrRef.current;\n\n    function init() {\n      initWebGL();\n      const gl = glRef.current;\n      if (gl && canvasRef.current) {\n        gl.clearColor(...clearColor);\n        gl.clearDepth(1.0);\n        gl.enable(gl.DEPTH_TEST);\n        gl.depthFunc(gl.LEQUAL);\n        gl.viewport(0, 0, canvasRef.current.width, canvasRef.current.height);\n        canvasRef.current.height = canvasRef.current.clientHeight;\n        canvasRef.current.width = canvasRef.current.clientWidth;\n        processCustomUniforms();\n        processTextures();\n        if (!initShaders(preProcessFragment(fs || BASIC_FS), vs || BASIC_VS))\n          return;\n        initBuffers();\n        drawFrameRef.current = drawScene;\n        cancelAnimationFrame(animFrameIdRef.current ?? 0);\n        animFrameIdRef.current = requestAnimationFrame(drawScene);\n        addEventListeners();\n        onResize();\n      }\n    }\n\n    initFrameIdRef.current = requestAnimationFrame(init);\n\n    return () => {\n      drawFrameRef.current = null;\n      const gl = glRef.current;\n      if (gl) {\n        gl.getExtension(\"WEBGL_lose_context\")?.loseContext();\n        gl.useProgram(null);\n        gl.deleteProgram(shaderProgramRef.current ?? null);\n        if (textures.length > 0) {\n          for (const texture of textures as Texture[]) {\n            gl.deleteTexture(texture._webglTexture);\n          }\n        }\n        shaderProgramRef.current = null;\n      }\n      removeEventListeners();\n      cancelAnimationFrame(initFrameIdRef.current ?? 0);\n      cancelAnimationFrame(animFrameIdRef.current ?? 0);\n    };\n    // Shader configuration is fixed per mount; uniforms update through refs.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  return (\n    <canvas\n      ref={canvasRef}\n      style={{ height: \"100%\", width: \"100%\", ...style }}\n      {...canvasProps}\n    />\n  );\n}\n",
      "type": "registry:component",
      "target": "components/pipecat/wave-shader.tsx"
    },
    {
      "path": "src/lib/visualizer.ts",
      "content": "/** Track-derived silent/speaking states; connecting/thinking are explicit overrides. */\nexport type VisualizerState = \"connecting\" | \"silent\" | \"speaking\" | \"thinking\";\n\n/** One mel-spaced analyser band: its FFT bin range plus tilt boost. */\nexport interface VisualizerBand {\n  startBin: number;\n  endBin: number;\n  /** dB-space boost countering speech's high-frequency rolloff. */\n  tiltBoost: number;\n}\n\n/** Call dispose to release the AudioContext; smoothing here only reduces FFT jitter. */\nexport function createVisualizerAnalyser(track: MediaStreamTrack): {\n  analyser: AnalyserNode;\n  dispose: () => void;\n} {\n  const audioContext = new AudioContext();\n  const source = audioContext.createMediaStreamSource(new MediaStream([track]));\n  const analyser = audioContext.createAnalyser();\n  analyser.fftSize = 1024;\n  analyser.smoothingTimeConstant = 0.6;\n  source.connect(analyser);\n  return { analyser, dispose: () => void audioContext.close() };\n}\n\n/** Mel bands cover 200 Hz–8 kHz. A per-octave boost compensates speech rolloff so low bands do not dominate. */\nexport function createVoiceBands(\n  bandCount: number,\n  sampleRate: number,\n  frequencyBinCount: number,\n): VisualizerBand[] {\n  const nyquist = sampleRate / 2;\n  const MIN_FREQ = 200;\n  const MAX_FREQ = 8000;\n  const toMel = (hz: number) => 2595 * Math.log10(1 + hz / 700);\n  const toHz = (mel: number) => 700 * (Math.pow(10, mel / 2595) - 1);\n  const melMin = toMel(MIN_FREQ);\n  const melStep = (toMel(MAX_FREQ) - melMin) / bandCount;\n\n  const TILT_DB_PER_OCTAVE = 4;\n  const BYTES_PER_DB = 255 / 70;\n  const refCenter = Math.sqrt(toHz(melMin) * toHz(melMin + melStep));\n\n  return Array.from({ length: bandCount }, (_, i) => {\n    const startFreq = toHz(melMin + i * melStep);\n    const endFreq = toHz(melMin + (i + 1) * melStep);\n    const startBin = Math.round(\n      (startFreq / nyquist) * (frequencyBinCount - 1),\n    );\n    // Every band covers at least one bin, so high band counts can't\n    // round a band into permanent silence.\n    const endBin = Math.max(\n      Math.round((endFreq / nyquist) * (frequencyBinCount - 1)),\n      startBin + 1,\n    );\n    const center = Math.sqrt(startFreq * endFreq);\n    const tiltBoost =\n      TILT_DB_PER_OCTAVE * BYTES_PER_DB * Math.log2(center / refCenter);\n    return { startBin, endBin, tiltBoost };\n  });\n}\n\n/**\n * Averages a band's FFT bins and applies its tilt boost, returning 0–255.\n * The boost fades in with signal strength so the noise floor near\n * minDecibels isn't amplified into standing bars.\n */\nexport function readBand(spectrum: Uint8Array, band: VisualizerBand): number {\n  let sum = 0;\n  for (let j = band.startBin; j < band.endBin; j++) sum += spectrum[j] ?? 0;\n  const value = sum / (band.endBin - band.startBin);\n  return Math.min(255, value + band.tiltBoost * Math.min(1, value / 32));\n}\n\n/**\n * Resolves a visualizer color prop to a concrete canvas color:\n * \"currentColor\" resolves from the given element, \"--css-var\" names from\n * the document root (where the kit's theme tokens live).\n */\nexport function resolveVisualizerColor(\n  color: string,\n  element: Element | null,\n): string {\n  if (!color) return \"black\";\n  if (color === \"currentColor\") {\n    return element ? getComputedStyle(element).color || \"black\" : \"black\";\n  }\n  if (color.startsWith(\"--\")) {\n    return (\n      getComputedStyle(document.documentElement)\n        .getPropertyValue(color)\n        .trim() || \"black\"\n    );\n  }\n  return color;\n}\n",
      "type": "registry:lib"
    }
  ],
  "docs": "Use AudioVisualizerWave inside a PipecatClientProvider, or AudioVisualizerWaveView with any MediaStreamTrack. Silent/speaking derive from the track; isConnecting/isThinking opt into the other shared states. The aura is made of light — bright colors read best, and it defaults to a vivid cyan. Requires WebGL; renders nothing where it is unavailable.",
  "categories": [
    "voice"
  ],
  "type": "registry:component"
}