{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "audio-visualizer-radial",
  "title": "Audio Visualizer Radial",
  "description": "Canvas-2D radial audio visualizer: a ring of spokes growing outward with mel-scale voice bands, sharing the kit visualizer lifecycle states (connecting, silent, speaking, thinking). 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"
  ],
  "files": [
    {
      "path": "src/components/audio-visualizer-radial.tsx",
      "content": "\"use client\";\n\nimport { usePipecatClientMediaTrack } from \"@pipecat-ai/client-react\";\nimport { memo, useEffect, useRef } from \"react\";\n\nimport {\n  createVisualizerAnalyser,\n  createVoiceBands,\n  readBand,\n  resolveVisualizerColor,\n  type VisualizerState,\n} from \"@/lib/visualizer\";\n\nexport type { VisualizerState };\n\ntype ParticipantType = Parameters<typeof usePipecatClientMediaTrack>[1];\n\n// Thinking's breath swells the ring by this fraction of its radius.\nconst BREATH = 0.1;\n\nexport interface AudioVisualizerRadialViewProps {\n  /** Audio track to visualize. Renders the dim resting ring when null. */\n  track?: MediaStreamTrack | null;\n  /** Canvas background. Any CSS color, or \"transparent\". */\n  backgroundColor?: string;\n  /** Dot color. Supports \"currentColor\" (default) and \"--css-var\" names. */\n  barColor?: string;\n  /**\n   * Color of the lit dots in the connecting and thinking animations; same\n   * formats as barColor, which it defaults to.\n   */\n  accentColor?: string;\n  /** Number of dots around the ring. */\n  barCount?: number;\n  /**\n   * Dot diameter / bar thickness in px. Defaults to filling half the\n   * ring's circumference (radius × π / barCount), so dots and gaps stay\n   * balanced at any barCount or radius.\n   */\n  barWidth?: number;\n  /** Max length a dot grows outward from the ring while speaking, in px. */\n  barMaxLength?: number;\n  /** Radius of the resting ring, in px. */\n  radius?: number;\n  /** Dot / bar end style. */\n  barLineCap?: \"round\" | \"square\";\n  /** Spectrum smoothing per frame (0–1, default 0.5); 1 disables smoothing. */\n  barSpeed?: number;\n  /** Opacity of unlit dots (default 0.1). Lit dots render at 1. */\n  restingOpacity?: number;\n  /**\n   * Speed multiplier for both animated overrides (default 1): the\n   * connecting pair and the thinking comet orbit at the same rate, one\n   * lap every two seconds.\n   */\n  rotationSpeed?: 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 — a comet (bright head,\n   * fading tail) orbits the ring while the ring slowly breathes. The\n   * track is ignored while set.\n   */\n  isThinking?: boolean;\n  /**\n   * Breaths per second for the thinking swell (default 0.2 — a\n   * five-second cycle, ±10% of radius). 0 disables breathing.\n   */\n  breathingSpeed?: number;\n  className?: string;\n}\n\n/** Mirrored mel bands avoid a seam around the ring. Connecting and thinking override track-derived state. */\nexport const AudioVisualizerRadialView = memo(\n  function AudioVisualizerRadialView({\n    track = null,\n    backgroundColor = \"transparent\",\n    barColor = \"currentColor\",\n    accentColor,\n    barCount = 24,\n    barWidth,\n    barMaxLength = 24,\n    radius = 32,\n    barLineCap = \"round\",\n    barSpeed = 0.5,\n    restingOpacity = 0.1,\n    rotationSpeed = 1,\n    isConnecting = false,\n    isThinking = false,\n    breathingSpeed = 0.2,\n    className,\n  }: AudioVisualizerRadialViewProps) {\n    const canvasRef = useRef<HTMLCanvasElement>(null);\n    const resolvedBarColorRef = useRef<string>(\"black\");\n    const resolvedAccentColorRef = useRef<string>(\"black\");\n    const analyserRef = useRef<AnalyserNode | null>(null);\n    const frequencyDataRef = useRef<Uint8Array<ArrayBuffer> | null>(null);\n    // Displayed length/alpha/accent-weight per dot, persisted across\n    // renders so state changes ease from wherever the ring currently is.\n    const displayRef = useRef<{ h: number; a: number; c: number }[]>([]);\n    // Eased 0–1 breath weight, persisted the same way so the radius swell\n    // ramps in and out instead of snapping.\n    const breathRef = useRef(0);\n\n    // Resolve CSS-flavored colors to concrete values the canvas can use.\n    // className is a dependency because it can change what currentColor\n    // resolves to.\n    useEffect(() => {\n      resolvedBarColorRef.current = resolveVisualizerColor(\n        barColor,\n        canvasRef.current,\n      );\n      resolvedAccentColorRef.current = resolveVisualizerColor(\n        accentColor ?? barColor,\n        canvasRef.current,\n      );\n    }, [barColor, accentColor, className]);\n\n    // Audio pipeline — only recreated when the track changes. The\n    // overrides are synthetic, so they skip the pipeline entirely.\n    useEffect(() => {\n      if (!track || isConnecting || isThinking) {\n        analyserRef.current = null;\n        frequencyDataRef.current = null;\n        return;\n      }\n\n      const { analyser, dispose } = createVisualizerAnalyser(track);\n      analyserRef.current = analyser;\n      frequencyDataRef.current = new Uint8Array(analyser.frequencyBinCount);\n\n      return () => {\n        analyserRef.current = null;\n        frequencyDataRef.current = null;\n        dispose();\n      };\n    }, [track, isConnecting, isThinking]);\n\n    useEffect(() => {\n      if (!canvasRef.current) return;\n\n      const canvas = canvasRef.current;\n      const dotWidth = barWidth ?? (radius * Math.PI) / barCount;\n      // Line caps extend segments by half the dot width; the canvas fits\n      // whichever reaches further, grown bars or the breath's swell.\n      const capRadius = dotWidth / 2;\n      const growth = Math.max(barMaxLength, BREATH * radius);\n      const side = 2 * (radius + growth + capRadius);\n      const center = side / 2;\n      const scaleFactor = 2;\n\n      canvas.width = side * scaleFactor;\n      canvas.height = side * scaleFactor;\n      canvas.style.width = `${side}px`;\n      canvas.style.height = `${side}px`;\n\n      const canvasCtx = canvas.getContext(\"2d\")!;\n      canvasCtx.lineCap = barLineCap;\n      canvasCtx.scale(scaleFactor, scaleFactor);\n\n      // Half the bands, mirrored: dot i and dot barCount−i share a band,\n      // so both directions around the ring run low→high and the wrap has\n      // no seam. Low frequencies at the top, sibilance at the bottom.\n      const sampleRate = analyserRef.current?.context.sampleRate ?? 48000;\n      const frequencyBinCount = analyserRef.current?.frequencyBinCount ?? 512;\n      const bands = createVoiceBands(\n        Math.floor(barCount / 2) + 1,\n        sampleRate,\n        frequencyBinCount,\n      );\n\n      // Static per-dot geometry, clockwise from the top of the ring.\n      const dots = Array.from({ length: barCount }, (_, i) => {\n        const angle = (i / barCount) * Math.PI * 2;\n        return {\n          angle,\n          ux: Math.cos(angle - Math.PI / 2),\n          uy: Math.sin(angle - Math.PI / 2),\n          band: bands[Math.min(i, barCount - i)]!,\n        };\n      });\n\n      // Displayed values persist across effect restarts (mode/track\n      // changes) so transitions ease from the current picture; a barCount\n      // change (or a hot reload of the entry shape) resets them.\n      const display = displayRef.current;\n      if (display.length !== barCount || display[0]?.c === undefined) {\n        display.length = 0;\n        for (let i = 0; i < barCount; i++) display.push({ h: 0, a: 1, c: 0 });\n      }\n\n      // Displayed values ease toward per-frame targets, so mode changes\n      // blend (~120ms) instead of snapping. Live audio instead chases at\n      // barSpeed — the configurable speaking responsiveness.\n      const EASE = 0.28;\n      const chase = Math.min(1, Math.max(0.05, barSpeed));\n      const rest = Math.min(1, Math.max(0, restingOpacity));\n      // Both overrides orbit at the same angular rate, so switching\n      // states never changes pace. Thinking drags a tail a third of the\n      // ring long, fading quadratically; connecting glows over a tight\n      // window around each of its two opposed dots.\n      const revPerSec = 0.5 * rotationSpeed;\n      const TAIL = (Math.PI * 2) / 3;\n      const glowWindow = 1.5 * ((Math.PI * 2) / barCount);\n      const breathsPerSec = Math.max(0, breathingSpeed);\n      const circDist = (a: number, b: number) => {\n        const d = Math.abs(a - b) % (Math.PI * 2);\n        return d > Math.PI ? Math.PI * 2 - d : d;\n      };\n\n      let rafId: number;\n\n      function drawSpectrum() {\n        const analyser = analyserRef.current;\n        const frequencyData = frequencyDataRef.current;\n        const resolvedBarColor = resolvedBarColorRef.current;\n        const time = performance.now() / 1000;\n\n        canvasCtx.clearRect(0, 0, side, side);\n        canvasCtx.fillStyle = backgroundColor;\n        canvasCtx.fillRect(0, 0, side, side);\n\n        let spectrum: Uint8Array<ArrayBuffer> | null = null;\n        if (!isConnecting && !isThinking && analyser && frequencyData) {\n          analyser.getByteFrequencyData(frequencyData);\n          spectrum = frequencyData;\n        }\n\n        // One shared head position drives both overrides; connecting\n        // mirrors it to the opposite side of the ring.\n        const headAngle =\n          isConnecting || isThinking ? time * revPerSec * Math.PI * 2 : 0;\n\n        let settled = true;\n\n        // Breath: a slow radial sine while thinking, weighted by an\n        // eased ramp so the radius never snaps when the state flips.\n        const breathTarget = isThinking ? 1 : 0;\n        breathRef.current += (breathTarget - breathRef.current) * EASE;\n        if (Math.abs(breathTarget - breathRef.current) > 0.01) settled = false;\n        const ringRadius =\n          radius +\n          breathRef.current *\n            BREATH *\n            radius *\n            Math.sin(time * breathsPerSec * Math.PI * 2);\n\n        for (let i = 0; i < barCount; i++) {\n          const { angle, ux, uy, band } = dots[i]!;\n          let targetLength = 0;\n          // Glow is the accent overlay's strength: 0 rests, 1 is fully\n          // lit, fades in between.\n          let glow = 0;\n\n          if (isConnecting) {\n            const toHead = circDist(angle, headAngle);\n            const nearest = Math.min(toHead, Math.PI - toHead);\n            const w = Math.max(0, 1 - nearest / glowWindow);\n            glow = w * w;\n          } else if (isThinking) {\n            const behind =\n              (((headAngle - angle) % (Math.PI * 2)) + Math.PI * 2) %\n              (Math.PI * 2);\n            const w = behind < TAIL ? 1 - behind / TAIL : 0;\n            glow = w * w;\n          } else if (spectrum) {\n            targetLength = (readBand(spectrum, band) / 255) * barMaxLength;\n          }\n          // Silent (no overrides, no analyser): a dim resting ring.\n          const targetAlpha = spectrum ? 1 : rest;\n\n          const d = display[i]!;\n          d.h += (targetLength - d.h) * (spectrum ? chase : EASE);\n          d.a += (targetAlpha - d.a) * EASE;\n          d.c += (glow - d.c) * EASE;\n          if (\n            Math.abs(targetLength - d.h) > 0.5 ||\n            Math.abs(targetAlpha - d.a) > 0.02 ||\n            Math.abs(glow - d.c) > 0.02\n          ) {\n            settled = false;\n          }\n\n          // One stroked segment covers every length — the line cap\n          // renders the floored, near-zero length as the resting dot.\n          // Base layer in barColor, accent overlaid at the glow's\n          // strength, so accent fades to transparent rather than\n          // blending toward the bar color.\n          const len = Math.max(d.h, 0.1);\n          canvasCtx.beginPath();\n          canvasCtx.moveTo(center + ux * ringRadius, center + uy * ringRadius);\n          canvasCtx.lineTo(\n            center + ux * (ringRadius + len),\n            center + uy * (ringRadius + len),\n          );\n          canvasCtx.lineWidth = dotWidth;\n          canvasCtx.globalAlpha = d.a;\n          canvasCtx.strokeStyle = resolvedBarColor;\n          canvasCtx.stroke();\n          if (d.c > 0.01) {\n            canvasCtx.globalAlpha = d.c;\n            canvasCtx.strokeStyle = resolvedAccentColorRef.current;\n            canvasCtx.stroke();\n          }\n          canvasCtx.globalAlpha = 1;\n        }\n\n        // Animated modes and unfinished transitions keep the loop alive;\n        // a settled silent frame stops it (the effect restarts on\n        // changes).\n        if (isConnecting || isThinking || spectrum || !settled) {\n          rafId = requestAnimationFrame(drawSpectrum);\n        }\n      }\n\n      rafId = requestAnimationFrame(drawSpectrum);\n\n      return () => {\n        cancelAnimationFrame(rafId);\n      };\n    }, [\n      backgroundColor,\n      // Colors are drawn from refs, but a settled silent frame stops the\n      // loop — restart it when they change so it repaints. The resolution\n      // effect above runs first (declaration order), so the refs are\n      // fresh.\n      barColor,\n      accentColor,\n      barCount,\n      barLineCap,\n      barMaxLength,\n      barSpeed,\n      barWidth,\n      radius,\n      restingOpacity,\n      rotationSpeed,\n      breathingSpeed,\n      track,\n      isConnecting,\n      isThinking,\n    ]);\n\n    return (\n      <canvas\n        ref={canvasRef}\n        data-slot=\"audio-visualizer-radial\"\n        data-state={\n          (isConnecting\n            ? \"connecting\"\n            : isThinking\n              ? \"thinking\"\n              : track\n                ? \"speaking\"\n                : \"silent\") satisfies VisualizerState\n        }\n        style={{ display: \"block\" }}\n        className={className}\n      />\n    );\n  },\n);\n\nexport interface AudioVisualizerRadialProps extends Omit<\n  AudioVisualizerRadialViewProps,\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 AudioVisualizerRadial({\n  participantType,\n  ...props\n}: AudioVisualizerRadialProps) {\n  const track = usePipecatClientMediaTrack(\"audio\", participantType);\n  return <AudioVisualizerRadialView track={track} {...props} />;\n}\n",
      "type": "registry:component",
      "target": "components/pipecat/audio-visualizer-radial.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 AudioVisualizerRadial inside a PipecatClientProvider, or AudioVisualizerRadialView with any MediaStreamTrack. Silent/speaking derive from the track; isConnecting/isThinking opt into the other shared states. Spokes default to currentColor.",
  "categories": [
    "voice"
  ],
  "type": "registry:component"
}