← Commit history
adom-audio: audio player with spectrum analyzer + Premiere-style waveform; tools/audio-viz.py
3 files changed
+650
README.md+1@@ -68,4 +68,5 @@ Five load from adom/component-widgets and take a JSON `src`; adom-stock and adom | `::adom-verified{src="..."}` | the "verified by" trust mark: big green check, who verified the page and when, per-variant coverage, and the full verification log with evidence; turns amber when a verified file changes; takes the page's `verification.json`; loads from adom/component-widgets | | `::adom-models{src="..."}` | every 3D file on a component page as a card: thumbnail, STEP or GLB, etched or unmarked and where the part number sits, what makes it different from its siblings, what it was derived from, a download, and whether the page still serves the file that was described (checked against the file listing, nothing downloaded); previous versions fold away; takes the page's `models.json` (adom/models@1); loads from adom/component-widgets | | `::adom-video{video="..."}` | a YouTube-style video player: every YouTube shortcut (Space/K, J/L, arrows, 0 to 9, `,` `.` frame step at the video's real frame rate with a frame-number overlay, `<` `>` speed 0.25x to 4x, hold the mouse on the video for 2x, C captions, + / - size, O / W caption opacity, Ctrl+arrows chapters, F, I, M, Shift+N/P, media keys, ?), Clean frame (H: hides the title, controls and captions for a screenshot; the mouse does not bring them back), Copy / Save this frame as a full-resolution PNG, a Share button (copies a link to the page that opens on this video, optionally at the current time: `#video=<file-name>&t=90`, plus the file's own link), a 24px timeline grab zone with drag-to-scrub and a hover frame preview, chapters as bar segments, captions, speed and loop; `title` `poster` `chapters` (JSON `[{"t":12,"title":"..."}]` or WebVTT) `captions` (.vtt or .srt) `start` (`90` or `1m30s`) `loop` `muted` `autoplay`; F opens the player full-window in a new tab (widget frames cannot go fullscreen); a narrated video gets captions and chapters free: gang-takes (adom/adom-video-post) writes the `.vtt` from the adom-tts narration text, the `.chapters.json` from its segment labels, and the embed line; on a private page pass `src=` a manifest with them inlined; a private page's VIDEO plays only where the browser sends third-party cookies until adom/wiki#228 (signed media URLs) ships, elsewhere the widget offers Play it in a new tab; loads from this page |+| `::adom-audio{audio="..." viz="..."}` | an audio player with a live spectrum analyzer (64 log-spaced bands, falling peak caps, glow, 50 Hz to 14 kHz) and a Premiere-style waveform (min/max envelope with an RMS body, played part lit, timecode ruler, glowing playhead): click or drag the waveform to jump anywhere (byte ranges through the files API, so a jump into a long WAV plays at once); the same shortcuts as adom-video (Space/K, J/L, arrows, 0 to 9, Home/End, `,` `.` 0.1 s nudge while paused, `<` `>` speed 0.25x to 4x, hold the mouse on the analyzer for 2x, click it to play/pause, M, R loop, Shift+N/P, media keys, ?); format chips (WAV / MP3, sample rate, 32-bit float, mono/stereo) and a download button (`download="off"` hides it); plays WAV (16/24-bit and 32-bit float), MP3, M4A/AAC, FLAC, OGG/Opus; `viz` is the precomputed `.viz.json` from [tools/audio-viz.py](tools/audio-viz.py) (`python3 tools/audio-viz.py voice.wav` writes `voice.viz.json`, about 310 KB for 2 minutes); without it the widget decodes the file in the browser for the waveform and analyses live for the spectrum; on a private page pass `src=` a manifest `{"audio": "...", "title": "...", "viz": {...}}` with the viz inlined (`tools/audio-viz.py voice.wav --manifest /OWNER/SLUG/render/voice.wav`); `title` `start` `loop`; loads from this page | | `::adom-3d{src="..."}` | any GLB in the canonical Adom 3D Viewer, click to load (nothing loads until the reader asks; it unloads offscreen and releases the WebGL context); `poster` `heading` `caption`; publish the GLB without Draco, the frame cannot reach the decoder CDN; loads from adom/component-widgets |
tools/audio-viz.pyadded+113@@ -0,0 +1,113 @@+#!/usr/bin/env python3+"""Precompute the waveform and spectrum data that <adom-audio> draws.++ audio-viz.py voice.wav # writes voice.viz.json next to it+ audio-viz.py voice.mp3 -o out.viz.json --fps 30 --bands 64++Reads any format ffmpeg reads (WAV 16/24/32-bit float, MP3, M4A, FLAC, OGG). Output, all compact:+ peaks: "min/max per column" over the whole clip (int8 pairs, base64), for the Premiere-style waveform+ rms: loudness per column (uint8, base64), drawn as the inner, brighter body of the waveform+ spectrum: one row of `bands` log-spaced levels (uint8, base64) per frame at `fps`, for the analyzer+ meta: duration, sample rate, channels, integrated loudness estimate+Point the widget at it with viz="/OWNER/SLUG/render/voice.viz.json". On a private page use --manifest to write+a voice.audio.json manifest with the viz inlined, and embed it as src="/OWNER/SLUG/render/voice.audio.json".+"""+import argparse, base64, json, math, os, subprocess, sys++import numpy as np+++def decode(path, sr):+ cmd = ['ffmpeg', '-v', 'error', '-i', path, '-ac', '1', '-ar', str(sr), '-f', 'f32le', '-']+ raw = subprocess.run(cmd, capture_output=True, check=True).stdout+ return np.frombuffer(raw, dtype=np.float32)+++def probe(path):+ out = subprocess.run(['ffprobe', '-v', 'error', '-select_streams', 'a:0', '-show_entries',+ 'stream=sample_rate,channels,codec_name,bits_per_raw_sample,sample_fmt:format=duration',+ '-of', 'json', path], capture_output=True, text=True).stdout+ j = json.loads(out or '{}')+ s = (j.get('streams') or [{}])[0]+ return {'duration': float(j.get('format', {}).get('duration', 0) or 0), 'sampleRate': int(s.get('sample_rate', 0) or 0),+ 'channels': int(s.get('channels', 0) or 0), 'codec': s.get('codec_name', ''), 'sampleFormat': s.get('sample_fmt', '')}+++def b64(a):+ return base64.b64encode(a.tobytes()).decode()+++def main():+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ ap.add_argument('audio')+ ap.add_argument('-o', '--out')+ ap.add_argument('--cols', type=int, default=2400, help='waveform columns (default 2400)')+ ap.add_argument('--fps', type=int, default=30, help='spectrum frames per second (default 30)')+ ap.add_argument('--bands', type=int, default=64, help='spectrum bands, log-spaced (default 64)')+ ap.add_argument('--fmin', type=float, default=50)+ ap.add_argument('--fmax', type=float, default=14000)+ ap.add_argument('--manifest', metavar='AUDIO_URL', help='write a widget manifest {audio, title, viz} instead (for src=, which the wiki inlines: works on private pages)')+ ap.add_argument('--title', help='title for the manifest')+ a = ap.parse_args()++ sr = 32000+ x = decode(a.audio, sr)+ if not len(x):+ sys.exit('no audio decoded')+ meta = probe(a.audio)+ meta['duration'] = meta['duration'] or len(x) / sr++ # waveform: min/max and RMS per column, scaled to the clip's own peak so quiet takes still read+ n = a.cols+ edges = np.linspace(0, len(x), n + 1).astype(int)+ mn = np.zeros(n, np.float32); mx = np.zeros(n, np.float32); rms = np.zeros(n, np.float32)+ for i in range(n):+ seg = x[edges[i]:max(edges[i + 1], edges[i] + 1)]+ mn[i] = seg.min(); mx[i] = seg.max(); rms[i] = math.sqrt(float(np.mean(seg * seg)))+ peak = max(float(np.max(np.abs(x))), 1e-6)+ pk = np.empty(2 * n, np.int8)+ pk[0::2] = np.clip(np.round(mn / peak * 127), -127, 127)+ pk[1::2] = np.clip(np.round(mx / peak * 127), -127, 127)+ rmsq = np.clip(np.round(rms / peak * 255), 0, 255).astype(np.uint8)++ # spectrum: Hann FFT at fps, log-spaced bands, dB mapped to 0..255 against the clip's own range+ hop = sr // a.fps+ win = 2048+ w = np.hanning(win).astype(np.float32)+ pad = np.concatenate([np.zeros(win // 2, np.float32), x, np.zeros(win, np.float32)])+ frames = int(math.ceil(len(x) / hop))+ freqs = np.fft.rfftfreq(win, 1 / sr)+ be = np.geomspace(a.fmin, a.fmax, a.bands + 1)+ idx = [np.where((freqs >= be[b]) & (freqs < be[b + 1]))[0] for b in range(a.bands)]+ idx = [ix if len(ix) else np.array([np.argmin(np.abs(freqs - be[b]))]) for b, ix in enumerate(idx)]+ spec = np.zeros((frames, a.bands), np.float32)+ for f in range(frames):+ s = pad[f * hop:f * hop + win]+ if len(s) < win:+ s = np.pad(s, (0, win - len(s)))+ mag = np.abs(np.fft.rfft(s * w))+ spec[f] = [mag[ix].max() for ix in idx]+ db = 20 * np.log10(spec + 1e-9)+ # tilt so speech highs show (voice energy falls ~4.5 dB/octave)+ db += 4.5 * np.log2(np.sqrt(be[:-1] * be[1:]) / 200.0)[None, :].clip(0)+ # scale against loud speech frames only (silence would drag the range down), 45 dB of range+ loud = db[db.max(axis=1) > np.percentile(db.max(axis=1), 40)]+ top = np.percentile(loud, 99.5); floor = top - 45+ sq = np.clip((db - floor) / (top - floor), 0, 1)+ sq = np.round(sq ** 1.15 * 255).astype(np.uint8)++ out = {+ 'v': 1, 'meta': meta, 'peak': round(peak, 6),+ 'waveform': {'cols': n, 'peaks': b64(pk), 'rms': b64(rmsq)},+ 'spectrum': {'fps': a.fps, 'bands': a.bands, 'fmin': a.fmin, 'fmax': a.fmax, 'frames': frames, 'data': b64(sq)},+ }+ if a.manifest:+ out = {'audio': a.manifest, 'title': a.title or os.path.basename(a.audio), 'viz': out}+ dst = a.out or os.path.splitext(a.audio)[0] + ('.audio.json' if a.manifest else '.viz.json')+ with open(dst, 'w') as fh:+ json.dump(out, fh, separators=(',', ':'))+ print(f'OK: {dst} {os.path.getsize(dst) // 1024} KB ({meta["duration"]:.1f} s, {frames} spectrum frames x {a.bands} bands, {n} waveform columns)')+++if __name__ == '__main__':+ main()
widgets/audio-widget.jsadded+536@@ -0,0 +1,536 @@+// <adom-audio>: an audio player for wiki pages with a live spectrum analyzer and a Premiere-style waveform.+//+// ::adom-audio{audio="/OWNER/SLUG/render/voice.wav" viz="/OWNER/SLUG/render/voice.viz.json" title="Voiceover"}+//+// Plays anything the browser plays: WAV (16/24-bit PCM and 32-bit float), MP3, M4A/AAC, FLAC, OGG/Opus.+// The waveform and the analyzer draw from precomputed data (tools/audio-viz.py on adom/widgets writes the+// .viz.json), so they are exact, cost nothing at play time and show the whole clip before it loads.+// Without a viz file the player analyses the audio in the browser instead.+//+// Click or drag anywhere on the waveform to jump; the files API serves byte ranges, so a jump into a long+// WAV starts playing at once. Keys (once the player is clicked, as on YouTube): Space/K play, J/L 10 s,+// arrows 5 s and volume, 0-9 jump to 0-90 %, Home/End, M mute, < > speed, R loop.+//+// Attributes: audio (required; never pass the audio as `src`: the wiki inlines a registered tag's `src`+// file), viz (the .viz.json), src (optional JSON manifest {audio, title, viz}, inlined by the wiki),+// title, start (seconds or 1m30s), loop, download (show a download button; on by default, "off" hides it).+(() => {+ if (customElements.get('adom-audio')) return;++ const ICON = {+ play: '<path d="M8 5.14v13.72a1 1 0 0 0 1.5.86l11-6.86a1 1 0 0 0 0-1.72l-11-6.86A1 1 0 0 0 8 5.14z"/>',+ pause: '<path d="M7 5h3.5v14H7zM13.5 5H17v14h-3.5z"/>',+ vol: '<path d="M4 9v6h4l5 4V5L8 9H4zm12.5 3a4.5 4.5 0 0 0-2.5-4v8a4.5 4.5 0 0 0 2.5-4zM14 3.2v2.1a7 7 0 0 1 0 13.4v2.1a9 9 0 0 0 0-17.6z"/>',+ mute: '<path d="M4 9v6h4l5 4V5L8 9H4zm12.6 3 2.7-2.7-1.4-1.4-2.7 2.7-2.7-2.7-1.4 1.4 2.7 2.7-2.7 2.7 1.4 1.4 2.7-2.7 2.7 2.7 1.4-1.4z"/>',+ loop: '<path d="M7 7h10v3l4-4-4-4v3H5v6h2V7zm10 10H7v-3l-4 4 4 4v-3h12v-6h-2v4z"/>',+ dl: '<path d="M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z"/>',+ back: '<path d="M11.5 12 20 18V6zM3 12l8.5 6V6z"/>',+ fwd: '<path d="M12.5 12 4 6v12zM21 12l-8.5-6v12z"/>',+ };+ const svg = (n, s = 22) => `<svg viewBox="0 0 24 24" width="${s}" height="${s}" aria-hidden="true">${ICON[n]}</svg>`;+ const SPEEDS = [0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2, 2.5, 3, 3.5, 4];+ const SHORTCUTS = [+ ['Play / pause', 'Space or K'], ['Back 10 s / forward 10 s', 'J / L'], ['Back 5 s / forward 5 s', '← / →'],+ ['Volume up / down', '↑ / ↓'], ['Mute', 'M'], ['Jump to 0% to 90%', '0 to 9'], ['Start / end', 'Home / End'],+ ['Nudge 0.1 s (while paused)', ', / .'], ['Slower / faster (0.25x to 4x)', '< / >'], ['2x while held', 'Hold the mouse on the analyzer'],+ ['Play / pause', 'Click the analyzer'], ['Jump anywhere', 'Click or drag the waveform'], ['Previous / next player on the page', 'Shift + P / Shift + N'],+ ['Loop', 'R'], ['Media keys', 'Play/Pause, Stop, Next'], ['Close this list', 'Esc'], ['This list', '?'],+ ];+ const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));+ const clamp = (x, a, b) => Math.min(b, Math.max(a, x));+ const fmt = (t) => { if (!isFinite(t) || t < 0) t = 0; t = Math.floor(t); const m = Math.floor(t / 60), s = String(t % 60).padStart(2, '0'); return `${m}:${s}`; };+ // Premiere-style timecode, 30 fps+ const tc = (t) => { if (!isFinite(t) || t < 0) t = 0; const f = Math.floor((t % 1) * 30), s = Math.floor(t) % 60, m = Math.floor(t / 60) % 60, h = Math.floor(t / 3600); const p = (n) => String(n).padStart(2, '0'); return `${p(h)}:${p(m)}:${p(s)}:${p(f)}`; };+ const parseT = (v) => {+ if (v == null || v === '') return 0; v = String(v).trim();+ if (/^\d+(\.\d+)?$/.test(v)) return Number(v);+ if (v.includes(':')) return v.split(':').reduce((a, x) => a * 60 + Number(x || 0), 0);+ const m = v.match(/^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?$/);+ return m ? (Number(m[1] || 0) * 3600 + Number(m[2] || 0) * 60 + Number(m[3] || 0)) : 0;+ };+ const unb64 = (s, T) => { const b = atob(s), u = new Uint8Array(b.length); for (let i = 0; i < b.length; i++) u[i] = b.charCodeAt(i); return T === Int8Array ? new Int8Array(u.buffer) : u; };++ const CSS = `+@font-face{font-family:'Satoshi';src:url('https://adom.inc/fonts/satoshi/satoshi-400-normal.woff2') format('woff2');font-weight:400;font-display:swap}+@font-face{font-family:'Satoshi';src:url('https://adom.inc/fonts/satoshi/satoshi-500-normal.woff2') format('woff2');font-weight:500;font-display:swap}+@font-face{font-family:'Satoshi';src:url('https://adom.inc/fonts/satoshi/satoshi-700-normal.woff2') format('woff2');font-weight:700;font-display:swap}+:host{display:block;max-width:100%;color:#e6edf3;font:13px/1.35 'Satoshi',system-ui,sans-serif;--teal:#00e6dc;--teal2:#00b8b0;--violet:#8b7bff;--muted:#8b949e;--line:#263040}+*{box-sizing:border-box}+.p{position:relative;border-radius:14px;overflow:hidden;background:radial-gradient(120% 140% at 50% -20%,#11303a 0%,#0b1118 55%,#080c11 100%);border:1px solid #1f2a36;box-shadow:0 10px 30px rgba(0,0,0,.35),inset 0 1px 0 rgba(255,255,255,.04);outline:none;user-select:none;-webkit-user-select:none}+.p:focus-visible{box-shadow:0 0 0 2px var(--teal2),0 10px 30px rgba(0,0,0,.35)}+.head{display:flex;align-items:center;gap:10px;padding:12px 16px 4px}+.title{font-weight:700;font-size:14.5px;letter-spacing:.01em;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;min-width:0}+.chips{display:flex;gap:6px;margin-left:auto;flex-shrink:0}+.chip{font-size:10.5px;letter-spacing:.06em;text-transform:uppercase;color:#9fb3c4;border:1px solid #243243;border-radius:999px;padding:2px 8px;background:rgba(10,18,26,.6);white-space:nowrap}+.chip.hot{color:var(--teal);border-color:#0f4d4d}+.spec{display:block;width:100%;height:170px}+.ruler{display:block;width:100%;height:20px;cursor:pointer}+.wavewrap{position:relative;cursor:pointer;touch-action:none}+.wave{display:block;width:100%;height:92px}+.tip{position:absolute;top:-26px;transform:translateX(-50%);padding:3px 7px;border-radius:6px;background:#0d1117;border:1px solid #2b3a4c;color:#e6edf3;font:11px/1 'Satoshi',system-ui,sans-serif;font-variant-numeric:tabular-nums;pointer-events:none;opacity:0;transition:opacity .12s;white-space:nowrap}+.wavewrap:hover .tip,.wavewrap.drag .tip{opacity:1}+.row{display:flex;align-items:center;gap:6px;padding:8px 12px 12px}+button{all:unset;display:inline-grid;place-items:center;width:36px;height:36px;border-radius:10px;color:#c9d6e2;cursor:pointer;transition:background .12s,color .12s}+button:hover{background:rgba(255,255,255,.06);color:#fff}+button svg{fill:currentColor}+button.on{color:var(--teal)}+.play{width:46px;height:46px;border-radius:50%;background:linear-gradient(145deg,var(--teal),var(--teal2));color:#06201f;box-shadow:0 0 0 1px rgba(0,230,220,.35),0 6px 22px rgba(0,230,220,.28)}+.play:hover{background:linear-gradient(145deg,#4ff6ee,var(--teal));color:#041615}+.time{font-variant-numeric:tabular-nums;font-size:12.5px;color:#c9d6e2;margin-left:6px;white-space:nowrap}+.time .tc{font:500 12.5px/1 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;color:var(--teal);letter-spacing:.02em}+.time .dur{color:var(--muted)}+.sp{flex:1}+.speed{width:auto;padding:0 10px;font:600 12px/1 'Satoshi',system-ui,sans-serif;font-variant-numeric:tabular-nums}+.vol{display:flex;align-items:center}+.vslide{width:0;overflow:hidden;transition:width .18s;height:36px;display:flex;align-items:center;cursor:pointer}+.vol:hover .vslide,.vol:focus-within .vslide{width:72px;padding:0 8px 0 2px}+.rail{position:relative;width:100%;height:4px;border-radius:2px;background:#2a3644}+.lvl{position:absolute;inset:0 auto 0 0;border-radius:2px;background:var(--teal)}+a.dlb{display:inline-grid;place-items:center;width:36px;height:36px;border-radius:10px;color:#c9d6e2}+a.dlb:hover{background:rgba(255,255,255,.06);color:#fff}+a.dlb svg{fill:currentColor}+.err{display:none;padding:14px 16px;color:#f5a3a3}.err.on{display:block}+.err code{color:#e6edf3}+.stage{position:relative;cursor:pointer}+.hold{position:absolute;left:50%;top:10px;transform:translateX(-50%);display:none;align-items:center;gap:6px;padding:5px 12px;background:rgba(0,0,0,.55);border:1px solid rgba(0,230,220,.35);border-radius:16px;font-size:13px;font-weight:700;pointer-events:none}+.hold.on{display:flex}.hold svg{fill:var(--teal)}+.bezel{position:absolute;top:50%;transform:translate(-50%,-50%) scale(.9);padding:8px 14px;border-radius:999px;background:rgba(0,0,0,.55);border:1px solid rgba(0,230,220,.3);font-weight:700;font-size:14px;color:#e6fffd;opacity:0;pointer-events:none;transition:opacity .35s,transform .35s;font-variant-numeric:tabular-nums;white-space:nowrap}+.bezel.on{opacity:1;transform:translate(-50%,-50%) scale(1);transition:none}+.help{position:absolute;inset:8px;display:none;flex-direction:column;background:rgba(6,10,15,.94);border:1px solid #243243;border-radius:12px;padding:12px 16px;overflow:auto;z-index:5}+.help.on{display:flex}.help h3{margin:0 0 8px;font-size:13px;letter-spacing:.06em;text-transform:uppercase;color:var(--teal)}+.help table{border-collapse:collapse;font-size:12.5px}.help td{padding:3px 10px 3px 0;color:#c9d6e2}.help td:last-child{color:#fff;font-weight:600;white-space:nowrap}+.help .x{position:absolute;right:8px;top:6px;width:30px;height:30px}+@media (max-width:520px){.chips .chip:not(.hot){display:none}.spec{height:130px}.speed{display:none}}+`;++ let playing = null; // one player at a time+ let active = null; // which player owns the keyboard++ class AdomAudio extends HTMLElement {+ static get observedAttributes() { return ['audio', 'src', 'viz', 'title']; }+ constructor() {+ super();+ const r = this.attachShadow({ mode: 'open' });+ r.innerHTML = `<style>${CSS}</style>+ <div class="p" tabindex="0" role="region" aria-label="Audio player">+ <div class="head"><div class="title"></div><div class="chips"></div></div>+ <div class="stage" title="Click to play or pause; hold for 2x"><canvas class="spec" aria-hidden="true"></canvas><div class="hold">2x ${svg('fwd', 16)}</div><div class="bezel"></div></div>+ <canvas class="ruler" aria-hidden="true"></canvas>+ <div class="wavewrap" role="slider" tabindex="-1" aria-label="Seek"><canvas class="wave"></canvas><div class="tip"></div></div>+ <div class="row">+ <button class="play" data-k="play" title="Play (k)">${svg('play', 24)}</button>+ <button data-k="back" title="Back 10 s (j)">${svg('back', 18)}</button>+ <button data-k="fwd" title="Forward 10 s (l)">${svg('fwd', 18)}</button>+ <div class="time"><span class="tc">00:00:00:00</span> <span class="dur">/ 0:00</span></div>+ <div class="sp"></div>+ <button class="speed" data-k="speed" title="Speed (< >)">1x</button>+ <button data-k="loop" title="Loop (r)">${svg('loop', 20)}</button>+ <div class="vol"><button data-k="mute" title="Mute (m)">${svg('vol', 20)}</button><div class="vslide"><div class="rail"><div class="lvl"></div></div></div></div>+ <a class="dlb" download title="Download the original file">${svg('dl', 20)}</a>+ </div>+ <div class="err"></div>+ <div class="help" role="dialog" aria-label="Keyboard shortcuts"></div>+ <audio preload="metadata"></audio>+ </div>`;+ this.$ = (s) => r.querySelector(s);+ this.p = this.$('.p'); this.a = this.$('audio');+ this.cs = this.$('.spec'); this.cr = this.$('.ruler'); this.cw = this.$('.wave'); this.ww = this.$('.wavewrap');+ this.viz = null; this.disp = null; this.caps = null; this.capV = null; this.capHold = null;+ this.hoverX = -1; this.lastT = 0; this._raf = 0;+ this._wire();+ }++ connectedCallback() {+ if (!active) active = this;+ if (location.pathname.includes('/widget/') && window.top !== window) document.documentElement.style.overflow = 'hidden';+ this._ro = new ResizeObserver(() => this._size()); this._ro.observe(this.p);+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => this._load(), { once: true });+ else this._load();+ }+ disconnectedCallback() { this._ro && this._ro.disconnect(); cancelAnimationFrame(this._raf); this.a.pause(); if (active === this) active = null; }+ attributeChangedCallback(n, a, b) { if (a !== b && this._loaded) this._load(); }++ _abs(u) { try { return new URL(u, location.href).href; } catch { return u; } }+ // the render route answers Range with the whole file (200) = unseekable; the files API answers 206+ _media(u) {+ const a = this._abs(u);+ try {+ const url = new URL(a);+ if (url.hostname !== 'wiki.adom.inc' && url.origin !== location.origin) return a;+ const m = url.pathname.match(/^\/([^/]+)\/([^/]+)\/render\/(.+)$/);+ if (m) url.pathname = `/api/pages/${m[1]}/${m[2]}/files/${m[3]}`;+ return url.href;+ } catch { return a; }+ }+ _manifest() {+ if (this._man !== undefined) return this._man;+ this._man = null;+ const el = this.querySelector('script[type="application/json"]');+ if (el) { try { const j = JSON.parse(el.textContent); if (j && typeof j === 'object' && !Array.isArray(j)) this._man = j; } catch {} }+ return this._man;+ }+ _opt(n) { const a = this.getAttribute(n); if (a != null && a !== '') return a; const m = this._manifest(); return m && m[n] != null ? m[n] : null; }++ async _load() {+ this._loaded = true; this._man = undefined;+ const m = this._manifest();+ const src = this.getAttribute('audio') || (m && m.audio) || (m ? null : this.getAttribute('src'));+ if (!src) return this._error('No audio: add <code>audio="/OWNER/SLUG/render/voice.wav"</code> to the tag.');+ this.$('.err').classList.remove('on');+ const name = decodeURIComponent(String(src).split('/').pop().split('?')[0]);+ this.$('.title').textContent = this._opt('title') || name;+ this._ext = (name.split('.').pop() || '').toLowerCase();+ const dl = this.$('.dlb');+ if ((this._opt('download') || '').toLowerCase() === 'off') dl.style.display = 'none';+ else { dl.href = this._media(src); dl.setAttribute('download', name); }+ this.a.loop = this.hasAttribute('loop'); this._loopUI();+ this.a.src = this._media(src);+ this._start = parseT(this.getAttribute('start'));+ this.a.addEventListener('loadedmetadata', () => { if (this._start > 0 && this._start < this.a.duration) this.a.currentTime = this._start; this._chips(); this._draw(); }, { once: true });+ this._chips(); this._size();+ const v = this._opt('viz');+ if (v) {+ try {+ const j = typeof v === 'object' ? v : await (await fetch(this._media(v))).json();+ this._setViz(j);+ } catch { this.viz = null; }+ }+ if (!this.viz) this._liveWave(this.a.src);+ this._draw();+ }++ _setViz(j) {+ const w = j.waveform, s = j.spectrum;+ this.viz = {+ meta: j.meta || {}, cols: w.cols, peaks: unb64(w.peaks, Int8Array), rms: w.rms ? unb64(w.rms) : null,+ fps: s ? s.fps : 0, bands: s ? s.bands : 0, frames: s ? s.frames : 0, spec: s ? unb64(s.data) : null, fmin: s && s.fmin, fmax: s && s.fmax,+ };+ this._chips();+ }++ // no viz file: decode in the browser for the waveform, and analyse live for the spectrum+ async _liveWave(url) {+ try {+ const buf = await (await fetch(url)).arrayBuffer();+ if (buf.byteLength > 120e6) return;+ const ac = new (window.OfflineAudioContext || window.webkitOfflineAudioContext)(1, 2, 44100);+ const ab = await ac.decodeAudioData(buf);+ const x = ab.getChannelData(0), n = 2400, pk = new Int8Array(2 * n), rm = new Uint8Array(n);+ let peak = 1e-6; for (let i = 0; i < x.length; i += 7) peak = Math.max(peak, Math.abs(x[i]));+ for (let c = 0; c < n; c++) {+ const a0 = Math.floor(c * x.length / n), a1 = Math.max(a0 + 1, Math.floor((c + 1) * x.length / n));+ let lo = 0, hi = 0, ss = 0; for (let i = a0; i < a1; i++) { const v = x[i]; if (v < lo) lo = v; if (v > hi) hi = v; ss += v * v; }+ pk[2 * c] = clamp(Math.round(lo / peak * 127), -127, 127); pk[2 * c + 1] = clamp(Math.round(hi / peak * 127), -127, 127);+ rm[c] = clamp(Math.round(Math.sqrt(ss / (a1 - a0)) / peak * 255), 0, 255);+ }+ this.viz = { meta: { duration: ab.duration, sampleRate: ab.sampleRate, channels: ab.numberOfChannels }, cols: n, peaks: pk, rms: rm, fps: 0, bands: 0, spec: null, live: true };+ this._chips(); this._draw();+ } catch {}+ }+ _liveAnalyser() {+ if (this._an || (this.viz && this.viz.spec)) return;+ try {+ const AC = window.AudioContext || window.webkitAudioContext; this._ac = new AC();+ const srcNode = this._ac.createMediaElementSource(this.a); this._an = this._ac.createAnalyser();+ this._an.fftSize = 2048; this._an.smoothingTimeConstant = 0.6; srcNode.connect(this._an); this._an.connect(this._ac.destination);+ this._fbuf = new Float32Array(this._an.frequencyBinCount);+ } catch {}+ }++ _chips() {+ const m = (this.viz && this.viz.meta) || {}, c = [];+ const ext = this._ext ? this._ext.toUpperCase() : '';+ if (ext) c.push(`<span class="chip hot">${ext}</span>`);+ if (m.sampleFormat === 'flt' || m.sampleFormat === 'fltp') c.push('<span class="chip">32-bit float</span>');+ if (m.sampleRate) c.push(`<span class="chip">${(m.sampleRate / 1000).toFixed(m.sampleRate % 1000 ? 1 : 0)} kHz</span>`);+ if (m.channels) c.push(`<span class="chip">${m.channels === 1 ? 'Mono' : m.channels === 2 ? 'Stereo' : m.channels + ' ch'}</span>`);+ this.$('.chips').innerHTML = c.join('');+ }++ _error(html) { const e = this.$('.err'); e.innerHTML = html; e.classList.add('on'); }++ _wire() {+ const a = this.a;+ this.p.addEventListener('pointerdown', () => { active = this; });+ this.p.addEventListener('focus', () => { active = this; });+ this.p.addEventListener('click', (e) => {+ const b = e.target.closest('button'); if (!b) return;+ const k = b.dataset.k;+ if (k === 'play') this.toggle();+ else if (k === 'back') this.seekBy(-10);+ else if (k === 'fwd') this.seekBy(10);+ else if (k === 'loop') { a.loop = !a.loop; this._loopUI(); }+ else if (k === 'mute') { a.muted = !a.muted; this._volUI(); }+ else if (k === 'speed') { const q = [0.5, 0.75, 1, 1.25, 1.5, 2]; a.playbackRate = q[(q.indexOf(a.playbackRate) + 1) % q.length] || 1; this._speedUI(); }+ else if (k === 'helpx') this._help(false);+ });+ a.addEventListener('play', () => { if (playing && playing !== this) playing.a.pause(); playing = this; this._playUI(); this._loop(); });+ a.addEventListener('pause', () => { this._playUI(); this._draw(); });+ a.addEventListener('ended', () => { this._playUI(); this._draw(); });+ a.addEventListener('timeupdate', () => { if (a.paused) this._draw(); });+ a.addEventListener('seeked', () => this._draw());+ a.addEventListener('durationchange', () => this._draw());+ a.addEventListener('volumechange', () => this._volUI());+ a.addEventListener('error', () => { if (a.error) this._error(`This browser could not play <code>${this._ext || 'this file'}</code> audio. Try the download button.`); });++ // waveform + ruler: click, drag, hover time+ const pos = (e) => { const r = this.cw.getBoundingClientRect(); return clamp((e.clientX - r.left) / r.width, 0, 1); };+ const dur = () => (isFinite(a.duration) && a.duration) || (this.viz && this.viz.meta.duration) || 0;+ const onDown = (e) => {+ e.preventDefault(); active = this; this.p.focus({ preventScroll: true });+ const el = e.currentTarget; el.setPointerCapture(e.pointerId); this.ww.classList.add('drag'); this._drag = true;+ this.seek(pos(e) * dur());+ const mv = (ev) => { this.hoverX = pos(ev); this.seek(this.hoverX * dur()); this._tip(); };+ const up = () => { this._drag = false; this.ww.classList.remove('drag'); el.removeEventListener('pointermove', mv); el.removeEventListener('pointerup', up); el.removeEventListener('pointercancel', up); };+ el.addEventListener('pointermove', mv); el.addEventListener('pointerup', up); el.addEventListener('pointercancel', up);+ };+ [this.ww, this.cr].forEach((el) => {+ el.addEventListener('pointerdown', onDown);+ el.addEventListener('pointermove', (e) => { this.hoverX = pos(e); this._tip(); if (a.paused) this._draw(); });+ el.addEventListener('pointerleave', () => { if (!this._drag) { this.hoverX = -1; if (a.paused) this._draw(); } });+ });++ // volume slider+ const vs = this.$('.vslide');+ const setVol = (e) => { const r = vs.querySelector('.rail').getBoundingClientRect(); a.volume = clamp((e.clientX - r.left) / r.width, 0, 1); a.muted = a.volume === 0; };+ vs.addEventListener('pointerdown', (e) => { e.preventDefault(); vs.setPointerCapture(e.pointerId); setVol(e); const mv = (ev) => setVol(ev), up = () => { vs.removeEventListener('pointermove', mv); vs.removeEventListener('pointerup', up); }; vs.addEventListener('pointermove', mv); vs.addEventListener('pointerup', up); });++ // the analyzer is the "picture": click to play or pause, press and hold for 2x (like YouTube)+ const st = this.$('.stage'); let holdTimer = 0, downAt = 0;+ st.addEventListener('pointerdown', (e) => { if (e.button) return; active = this; this._engaged = true; this.p.focus({ preventScroll: true }); downAt = performance.now(); clearTimeout(holdTimer); holdTimer = setTimeout(() => this._holdStart(), 450); });+ const endHold = () => { clearTimeout(holdTimer); return this._holdEnd(); };+ st.addEventListener('pointerup', () => { if (endHold()) return; if (performance.now() - downAt < 450) this.toggle(); });+ st.addEventListener('pointerleave', endHold); st.addEventListener('pointercancel', endHold);+ st.addEventListener('contextmenu', (e) => { if (this._hold) e.preventDefault(); });+ this.p.addEventListener('pointerdown', () => { this._engaged = true; });++ // the same shortcuts as ::adom-video (YouTube's), for whichever player owns the keyboard+ document.addEventListener('keydown', (e) => {+ if (active !== this) return;+ const tgt = e.composedPath()[0];+ if (tgt && (/^(INPUT|TEXTAREA|SELECT)$/.test(tgt.tagName || '') || tgt.isContentEditable)) return;+ if (e.metaKey || e.altKey || e.ctrlKey) return;+ const inFrame = location.pathname.includes('/widget/');+ const focusIn = !!this.shadowRoot.activeElement || document.activeElement === this;+ const nothingElse = !document.activeElement || document.activeElement === document.body || document.activeElement === document.documentElement;+ if (!inFrame && !focusIn && !(this._engaged && nothingElse)) return;+ const k = e.key, d = this._dur(); let hit = true;+ const helpOn = this.$('.help').classList.contains('on');+ if (helpOn && k !== '?' && k !== 'Escape') return;+ if (k === ' ' || k === 'k' || k === 'K') this.toggle();+ else if (k === 'j' || k === 'J') this.seekBy(-10);+ else if (k === 'l' || k === 'L') this.seekBy(10);+ else if (k === 'ArrowLeft') this.seekBy(-5);+ else if (k === 'ArrowRight') this.seekBy(5);+ else if (k === 'ArrowUp') this.volBy(0.05);+ else if (k === 'ArrowDown') this.volBy(-0.05);+ else if (k === '<' || (k === ',' && e.shiftKey)) this.speedStep(-1);+ else if (k === '>' || (k === '.' && e.shiftKey)) this.speedStep(1);+ else if (k === ',' && a.paused) this.seekBy(-0.1);+ else if (k === '.' && a.paused) this.seekBy(0.1);+ else if (k === 'Home') this.seek(0);+ else if (k === 'End') this.seek(d);+ else if (/^[0-9]$/.test(k)) { this.seek(d * Number(k) / 10); this._bezel(`${Number(k) * 10}%`); }+ else if (k === 'm' || k === 'M') { a.muted = !a.muted; this._bezel(a.muted ? 'Muted' : `${Math.round(a.volume * 100)}%`); }+ else if (k === 'r' || k === 'R') { a.loop = !a.loop; this._loopUI(); this._bezel(a.loop ? 'Loop on' : 'Loop off'); }+ else if (k === 'N' && e.shiftKey) this.sibling(1);+ else if (k === 'P' && e.shiftKey) this.sibling(-1);+ else if (k === 'MediaPlayPause') this.toggle();+ else if (k === 'MediaStop') { a.pause(); this.seek(0); }+ else if (k === 'MediaTrackNext') this.sibling(1);+ else if (k === 'MediaTrackPrevious') this.sibling(-1);+ else if (k === '?') this._help();+ else if (k === 'Escape' && helpOn) this._help(false);+ else hit = false;+ if (hit) { e.preventDefault(); e.stopPropagation(); }+ }, true);+ }++ _dur() { const a = this.a; return (isFinite(a.duration) && a.duration) || (this.viz && this.viz.meta.duration) || 0; }+ seekBy(s) { this.seek(this.a.currentTime + s); this._bezel(`${s > 0 ? '+' : '−'}${Math.abs(s) < 1 ? Math.abs(s).toFixed(1) : Math.abs(s)} s`, s > 0 ? 0.82 : 0.18); }+ volBy(x) { const a = this.a; a.volume = clamp(Math.round((a.volume + x) * 100) / 100, 0, 1); a.muted = a.volume === 0; this._bezel(`Volume ${Math.round(a.volume * 100)}%`); }+ speedStep(dir) { const a = this.a; let i = SPEEDS.indexOf(a.playbackRate); if (i < 0) i = SPEEDS.indexOf(1); a.playbackRate = SPEEDS[clamp(i + dir, 0, SPEEDS.length - 1)]; this._speedUI(); this._bezel(`${a.playbackRate}x`); }+ sibling(dir) { const all = [...document.querySelectorAll('adom-audio')], i = all.indexOf(this), n = all[i + dir]; if (!n) return; this.a.pause(); active = n; n._engaged = true; n.scrollIntoView({ block: 'center', behavior: 'smooth' }); n.p.focus({ preventScroll: true }); n.toggle(); }+ _holdStart() { const a = this.a; if (a.paused || this._hold) return; this._hold = { rate: a.playbackRate }; a.playbackRate = Math.max(2, a.playbackRate); this.$('.hold').classList.add('on'); }+ _holdEnd() { if (!this._hold) return false; this.a.playbackRate = this._hold.rate; this._hold = null; this.$('.hold').classList.remove('on'); this._speedUI(); return true; }+ _bezel(text, x = 0.5) { const b = this.$('.bezel'); b.textContent = text; b.style.left = `${x * 100}%`; b.classList.add('on'); clearTimeout(this._bz); this._bz = setTimeout(() => b.classList.remove('on'), 500); }+ _help(on) {+ const h = this.$('.help'); on = on == null ? !h.classList.contains('on') : on;+ if (on && !h.innerHTML) { h.innerHTML = `<h3>Keyboard shortcuts</h3><button class="x" data-k="helpx" aria-label="Close">✕</button><table>${SHORTCUTS.map(([a, b]) => `<tr><td>${esc(a)}</td><td>${esc(b)}</td></tr>`).join('')}</table>`; }+ h.classList.toggle('on', on);+ }++ toggle() {+ const a = this.a;+ if (a.paused) { if (!this.viz || !this.viz.spec) this._liveAnalyser(); if (this._ac && this._ac.state === 'suspended') this._ac.resume(); a.play().catch(() => {}); }+ else a.pause();+ }+ seek(t) { const a = this.a, d = (isFinite(a.duration) && a.duration) || (this.viz && this.viz.meta.duration) || 0; a.currentTime = clamp(t, 0, d || 0); this._draw(); }++ _playUI() { const b = this.$('.play'); b.innerHTML = svg(this.a.paused ? 'play' : 'pause', 24); b.title = this.a.paused ? 'Play (k)' : 'Pause (k)'; }+ _loopUI() { this.$('[data-k="loop"]').classList.toggle('on', this.a.loop); }+ _speedUI() { this.$('.speed').textContent = `${this.a.playbackRate}x`; }+ _volUI() { const a = this.a; this.$('[data-k="mute"]').innerHTML = svg(a.muted || a.volume === 0 ? 'mute' : 'vol', 20); this.$('.lvl').style.width = `${(a.muted ? 0 : a.volume) * 100}%`; }+ _tip() {+ const d = (isFinite(this.a.duration) && this.a.duration) || (this.viz && this.viz.meta.duration) || 0, tp = this.$('.tip');+ if (this.hoverX < 0) return;+ tp.textContent = tc(this.hoverX * d); tp.style.left = `${clamp(this.hoverX * 100, 4, 96)}%`;+ }++ _size() {+ const dpr = Math.min(window.devicePixelRatio || 1, 2);+ [this.cs, this.cr, this.cw].forEach((c) => { const r = c.getBoundingClientRect(); const w = Math.max(1, Math.round(r.width * dpr)), h = Math.max(1, Math.round(r.height * dpr)); if (c.width !== w || c.height !== h) { c.width = w; c.height = h; } });+ this._bg = null; this._draw();+ }++ _loop() {+ cancelAnimationFrame(this._raf);+ const step = (now) => { this._draw(now); if (!this.a.paused || this._settling) this._raf = requestAnimationFrame(step); };+ this._raf = requestAnimationFrame(step);+ }++ // ---- drawing ----+ _draw(now) {+ if (!this.cs.width) return;+ const a = this.a, d = (isFinite(a.duration) && a.duration) || (this.viz && this.viz.meta.duration) || 0, t = a.currentTime || 0;+ const fr = d ? t / d : 0;+ this.$('.tc').textContent = tc(t); this.$('.dur').textContent = `/ ${fmt(d)}`;+ this._drawSpec(t, now);+ this._drawRuler(d);+ this._drawWave(fr);+ }++ _bands(t) {+ const v = this.viz;+ if (v && v.spec) {+ const nb = v.bands, f = clamp(t * v.fps, 0, v.frames - 1), i0 = Math.floor(f), i1 = Math.min(v.frames - 1, i0 + 1), k = f - i0, out = new Float32Array(nb);+ for (let b = 0; b < nb; b++) out[b] = (v.spec[i0 * nb + b] * (1 - k) + v.spec[i1 * nb + b] * k) / 255;+ return out;+ }+ if (this._an && !this.a.paused) {+ const an = this._an, buf = this._fbuf, nb = 64, sr = this._ac.sampleRate, out = new Float32Array(nb);+ an.getFloatFrequencyData(buf);+ for (let b = 0; b < nb; b++) {+ const f0 = 50 * Math.pow(14000 / 50, b / nb), f1 = 50 * Math.pow(14000 / 50, (b + 1) / nb);+ let mx = -140; for (let i = Math.floor(f0 / sr * 2 * buf.length); i <= Math.ceil(f1 / sr * 2 * buf.length) && i < buf.length; i++) mx = Math.max(mx, buf[i]);+ const tilt = 4.5 * Math.log2(Math.max(1, Math.sqrt(f0 * f1) / 200));+ out[b] = clamp((mx + tilt + 85) / 60, 0, 1) ** 1.4;+ }+ return out;+ }+ return null;+ }++ _drawSpec(t, now) {+ const c = this.cs, g = c.getContext('2d'), W = c.width, H = c.height, dpr = W / c.getBoundingClientRect().width || 1;+ g.clearRect(0, 0, W, H);+ const base = Math.round(H * 0.74);+ // grid+ g.strokeStyle = 'rgba(120,160,190,0.07)'; g.lineWidth = 1;+ for (let i = 1; i <= 4; i++) { const y = Math.round(base - (base - 10 * dpr) * i / 4) + 0.5; g.beginPath(); g.moveTo(0, y); g.lineTo(W, y); g.stroke(); }+ const target = this._bands(t);+ const nb = target ? target.length : 64;+ if (!this.disp || this.disp.length !== nb) { this.disp = new Float32Array(nb); this.caps = new Float32Array(nb); this.capV = new Float32Array(nb); this.capHold = new Float32Array(nb); }+ const dt = now && this.lastT ? clamp((now - this.lastT) / 1000, 0, 0.1) : 0.016; this.lastT = now || 0;+ const playingNow = !this.a.paused;+ let settling = false;+ for (let b = 0; b < nb; b++) {+ const tv = target ? Math.min(1, target[b] * 1.08) * (playingNow ? 1 : 0.8) : 0;+ // fast attack, smooth release+ const cur = this.disp[b];+ this.disp[b] = tv > cur ? cur + (tv - cur) * Math.min(1, dt * 28) : cur + (tv - cur) * Math.min(1, dt * 7);+ if (Math.abs(this.disp[b] - tv) > 0.002) settling = true;+ // falling peak caps with a short hold+ if (this.disp[b] >= this.caps[b]) { this.caps[b] = this.disp[b]; this.capV[b] = 0; this.capHold[b] = 0.35; }+ else if (this.capHold[b] > 0) this.capHold[b] -= dt;+ else { this.capV[b] += dt * 1.6; this.caps[b] = Math.max(this.disp[b], this.caps[b] - this.capV[b] * dt); settling = true; }+ }+ this._settling = settling && this.a.paused;+ if (this._settling && !this._raf) this._loop();++ const pad = 14 * dpr, span = W - pad * 2, slot = span / nb, bw = Math.max(1, slot * 0.64), top = 12 * dpr, hMax = base - top;+ const grad = g.createLinearGradient(0, base, 0, top);+ grad.addColorStop(0, '#009e98'); grad.addColorStop(0.35, '#00e6dc'); grad.addColorStop(0.7, '#62c8ff'); grad.addColorStop(1, '#9b7bff');+ const H_ = (b) => Math.max(2 * dpr, Math.pow(this.disp[b], 0.8) * hMax);+ // soft glow underneath, then crisp gradient bars on top+ g.save(); g.filter = `blur(${10 * dpr}px)`; g.globalAlpha = 0.55; g.fillStyle = grad;+ for (let b = 0; b < nb; b++) { const h = H_(b), x = pad + b * slot + (slot - bw) / 2; g.fillRect(x - bw * 0.2, base - h, bw * 1.4, h); }+ g.restore();+ g.fillStyle = grad;+ for (let b = 0; b < nb; b++) { const h = H_(b), x = pad + b * slot + (slot - bw) / 2, r = Math.min(bw / 2, 3 * dpr); this._rr(g, x, base - h, bw, h, r); g.fill(); }+ // glossy highlight on each bar+ g.fillStyle = 'rgba(255,255,255,0.10)';+ for (let b = 0; b < nb; b++) { const h = H_(b), x = pad + b * slot + (slot - bw) / 2; g.fillRect(x, base - h, Math.max(1, bw * 0.35), h); }+ // reflection+ g.save(); g.globalAlpha = 0.22;+ const rg = g.createLinearGradient(0, base, 0, H); rg.addColorStop(0, '#00e6dc'); rg.addColorStop(1, 'rgba(0,230,220,0)');+ g.fillStyle = rg;+ for (let b = 0; b < nb; b++) { const h = Math.min(H - base - 2 * dpr, Math.pow(this.disp[b], 0.8) * hMax * 0.32), x = pad + b * slot + (slot - bw) / 2; if (h > 0) g.fillRect(x, base + 2 * dpr, bw, h); }+ g.restore();+ // peak caps+ g.fillStyle = 'rgba(230,252,255,0.92)';+ for (let b = 0; b < nb; b++) { if (this.caps[b] < 0.02) continue; const x = pad + b * slot + (slot - bw) / 2, y = base - Math.pow(this.caps[b], 0.8) * hMax - 4 * dpr; g.fillRect(x, y, bw, 2 * dpr); }+ // baseline + frequency labels+ g.fillStyle = 'rgba(0,230,220,0.35)'; g.fillRect(pad, base, span, Math.max(1, dpr));+ const v = this.viz, fmin = (v && v.fmin) || 50, fmax = (v && v.fmax) || 14000;+ g.font = `${10 * dpr}px Satoshi, system-ui, sans-serif`; g.fillStyle = 'rgba(140,165,185,0.75)'; g.textAlign = 'center';+ [100, 250, 500, 1000, 2000, 4000, 8000].forEach((f) => { const x = pad + Math.log(f / fmin) / Math.log(fmax / fmin) * span; if (x > pad && x < W - pad) g.fillText(f >= 1000 ? `${f / 1000}k` : `${f}`, x, H - 5 * dpr); });+ }++ _rr(g, x, y, w, h, r) { g.beginPath(); g.moveTo(x + r, y); g.lineTo(x + w - r, y); g.quadraticCurveTo(x + w, y, x + w, y + r); g.lineTo(x + w, y + h); g.lineTo(x, y + h); g.lineTo(x, y + r); g.quadraticCurveTo(x, y, x + r, y); g.closePath(); }++ _drawRuler(d) {+ const c = this.cr, g = c.getContext('2d'), W = c.width, H = c.height, dpr = W / c.getBoundingClientRect().width || 1;+ g.clearRect(0, 0, W, H);+ g.fillStyle = '#0c131b'; g.fillRect(0, 0, W, H);+ g.fillStyle = '#1d2733'; g.fillRect(0, H - dpr, W, dpr);+ if (!d) return;+ const pxPerSec = W / d, steps = [1, 2, 5, 10, 15, 30, 60, 120, 300, 600];+ const major = steps.find((s) => s * pxPerSec >= 90 * dpr) || 600, minor = major / 5;+ g.fillStyle = 'rgba(140,165,185,0.55)';+ for (let s = 0; s <= d + 0.001; s += minor) { const x = Math.round(s * pxPerSec) + 0.5; g.fillRect(x, H - 5 * dpr, 1, 4 * dpr); }+ g.font = `${10 * dpr}px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace`; g.fillStyle = 'rgba(170,190,205,0.85)'; g.textAlign = 'left';+ for (let s = 0; s <= d + 0.001; s += major) { const x = Math.round(s * pxPerSec) + 0.5; g.fillRect(x, H - 10 * dpr, 1, 9 * dpr); if (x < W - 60 * dpr) g.fillText(tc(s).slice(3, 8), x + 4 * dpr, H - 7 * dpr); }+ }++ _drawWave(fr) {+ const c = this.cw, g = c.getContext('2d'), W = c.width, H = c.height, dpr = W / c.getBoundingClientRect().width || 1;+ g.clearRect(0, 0, W, H);+ const bg = g.createLinearGradient(0, 0, 0, H); bg.addColorStop(0, '#0e1620'); bg.addColorStop(1, '#0a1017'); g.fillStyle = bg; g.fillRect(0, 0, W, H);+ const mid = H / 2, amp = H / 2 - 6 * dpr, px = fr * W;+ g.fillStyle = 'rgba(0,230,220,0.12)'; g.fillRect(0, mid, W, Math.max(1, dpr));+ const v = this.viz;+ if (v) {+ const n = v.cols;+ // outer envelope (min/max), then the RMS body, split at the playhead+ const env = (from, to, cOut, cIn) => {+ g.beginPath();+ for (let x = from; x <= to; x++) { const i = Math.min(n - 1, Math.floor(x / W * n)); g.lineTo(x, mid - (v.peaks[2 * i + 1] / 127) * amp); }+ for (let x = to; x >= from; x--) { const i = Math.min(n - 1, Math.floor(x / W * n)); g.lineTo(x, mid - (v.peaks[2 * i] / 127) * amp); }+ g.closePath(); g.fillStyle = cOut; g.fill();+ if (v.rms) {+ g.beginPath();+ for (let x = from; x <= to; x++) { const i = Math.min(n - 1, Math.floor(x / W * n)); g.lineTo(x, mid - (v.rms[i] / 255) * amp * 1.15); }+ for (let x = to; x >= from; x--) { const i = Math.min(n - 1, Math.floor(x / W * n)); g.lineTo(x, mid + (v.rms[i] / 255) * amp * 1.15); }+ g.closePath(); g.fillStyle = cIn; g.fill();+ }+ };+ const played = g.createLinearGradient(0, mid - amp, 0, mid + amp);+ played.addColorStop(0, '#5fe9ff'); played.addColorStop(0.5, '#00e6dc'); played.addColorStop(1, '#5fe9ff');+ if (px > 0) { g.save(); g.shadowColor = 'rgba(0,230,220,0.45)'; g.shadowBlur = 8 * dpr; env(0, Math.floor(px), 'rgba(0,200,192,0.55)', played); g.restore(); }+ if (px < W) env(Math.floor(px), W, 'rgba(96,122,145,0.42)', 'rgba(150,175,195,0.55)');+ }+ // hover ghost line+ if (this.hoverX >= 0) { g.fillStyle = 'rgba(255,255,255,0.35)'; g.fillRect(Math.round(this.hoverX * W), 0, Math.max(1, dpr), H); }+ // playhead (Premiere style: a bright line with a cap)+ const x = Math.round(px);+ g.save(); g.shadowColor = 'rgba(120,200,255,0.9)'; g.shadowBlur = 8 * dpr;+ g.fillStyle = '#7cc4ff'; g.fillRect(x - dpr, 0, 2 * dpr, H);+ g.beginPath(); g.moveTo(x - 6 * dpr, 0); g.lineTo(x + 6 * dpr, 0); g.lineTo(x + 6 * dpr, 5 * dpr); g.lineTo(x, 10 * dpr); g.lineTo(x - 6 * dpr, 5 * dpr); g.closePath(); g.fill();+ g.restore();+ this.ww.setAttribute('aria-valuenow', String(Math.round(fr * 100)));+ }+ }++ customElements.define('adom-audio', AdomAudio);+})();