{"version":3,"file":"useAudioLevel.mjs","names":[],"sources":["../../../../../src/plugins/AIComponents/VoiceVisualization/useAudioLevel.ts"],"sourcesContent":["import { useCallback, useEffect, useRef } from 'react';\n\n/** Below this RMS the signal is treated as room noise. */\nconst NOISE_FLOOR = 0.01;\n/** Maps the RMS of speech at a normal distance (about 0.05 to 0.2) across most of 0 to 1. */\nconst GAIN = 5;\n\ntype AudioContextConstructor = new () => AudioContext;\n\nconst getAudioContext = (): AudioContextConstructor | undefined => {\n  if (typeof window === 'undefined') return undefined;\n  return (\n    window.AudioContext ??\n    (window as Window & { webkitAudioContext?: AudioContextConstructor })\n      .webkitAudioContext\n  );\n};\n\n/** The RMS of a block of 8-bit time-domain samples centred on 128, from 0 to 1. */\nexport const rootMeanSquare = (samples: Uint8Array) => {\n  if (!samples.length) return 0;\n  let sum = 0;\n  for (let i = 0; i < samples.length; i++) {\n    const value = (samples[i] - 128) / 128;\n    sum += value * value;\n  }\n  return Math.sqrt(sum / samples.length);\n};\n\n/** An RMS as a level from 0 to 1, with room noise cut and speech spread across the range. */\nexport const levelFromRms = (rms: number) =>\n  Math.min(Math.max((rms - NOISE_FLOOR) * GAIN, 0), 1);\n\n/**\n * Reads the live level of a `MediaStream`'s audio, such as a microphone from\n * `getUserMedia({ audio: true })` or a remote participant's track, for `VoiceWave` and\n * `VoiceGlow`'s `audioLevel`.\n *\n * Returns a stable getter that measures the level when called, from 0 to 1, so a visualization\n * reading it once a frame re-renders nothing. It returns `null` while there is no stream or the\n * browser has no Web Audio, which lets the visualization animate speech on its own.\n *\n * The audio graph is torn down when the stream changes and on unmount; the stream's tracks are\n * left running, since they belong to the caller.\n */\nexport const useAudioLevel = (stream: MediaStream | null | undefined) => {\n  const analyserRef = useRef<{\n    analyser: AnalyserNode;\n    samples: Uint8Array<ArrayBuffer>;\n  } | null>(null);\n\n  useEffect(() => {\n    const AudioContextClass = getAudioContext();\n    if (!stream || !AudioContextClass || !stream.getAudioTracks().length) return;\n\n    const context = new AudioContextClass();\n    const source = context.createMediaStreamSource(stream);\n    const analyser = context.createAnalyser();\n    // About 43 ms at 48 kHz: a few pitch periods of a voice, so the level holds steady on a vowel\n    // instead of jittering with each period, as a shorter window would.\n    analyser.fftSize = 2048;\n    source.connect(analyser);\n    analyserRef.current = { analyser, samples: new Uint8Array(analyser.fftSize) };\n    // A context made outside a user gesture can start suspended.\n    if (context.state === 'suspended') context.resume?.().catch(() => undefined);\n\n    return () => {\n      analyserRef.current = null;\n      source.disconnect();\n      analyser.disconnect();\n      if (context.state !== 'closed') context.close().catch(() => undefined);\n    };\n  }, [stream]);\n\n  return useCallback((): number | null => {\n    const current = analyserRef.current;\n    if (!current) return null;\n    current.analyser.getByteTimeDomainData(current.samples);\n    return levelFromRms(rootMeanSquare(current.samples));\n  }, []);\n};\n"],"mappings":";;;AAGA,IAAM,cAAc;;AAEpB,IAAM,OAAO;AAIb,IAAM,wBAA6D;CACjE,IAAI,OAAO,WAAW,aAAa,OAAO,KAAA;CAC1C,OACE,OAAO,gBACN,OACE;AAEP;;AAGA,IAAa,kBAAkB,YAAwB;CACrD,IAAI,CAAC,QAAQ,QAAQ,OAAO;CAC5B,IAAI,MAAM;CACV,KAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;EACvC,MAAM,SAAS,QAAQ,KAAK,OAAO;EACnC,OAAO,QAAQ;CACjB;CACA,OAAO,KAAK,KAAK,MAAM,QAAQ,MAAM;AACvC;;AAGA,IAAa,gBAAgB,QAC3B,KAAK,IAAI,KAAK,KAAK,MAAM,eAAe,MAAM,CAAC,GAAG,CAAC;;;;;;;;;;;;;AAcrD,IAAa,iBAAiB,WAA2C;CACvE,MAAM,cAAc,OAGV,IAAI;CAEd,gBAAgB;EACd,MAAM,oBAAoB,gBAAgB;EAC1C,IAAI,CAAC,UAAU,CAAC,qBAAqB,CAAC,OAAO,eAAe,CAAC,CAAC,QAAQ;EAEtE,MAAM,UAAU,IAAI,kBAAkB;EACtC,MAAM,SAAS,QA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