Skip to content

The open-source AI receptionist for businesses. Answers every call, books the appointment and hands over to a person when needed. You own the code and the data.

Waveform in the call recording player (PR 2026)

Tim Gutberletec44023a81a2
diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts
index c20c3555..c8cf0532 100644
--- a/apps/api/src/app.ts
+++ b/apps/api/src/app.ts
@@ -1170,7 +1170,7 @@ app.get('/v1/voices/preview/:voiceId', c => {
app.get('/v1/calls/:id/recording', c => {
const signature = c.req.query('signature')
return signature === undefined
- ? serveRecording(c.get('actor'), c.req.param('id'), c.req.header('range'))
+ ? serveRecording(c.get('actor'), c.req.param('id'), c.req.header('range'), c.req.query('through') === '1')
: serveSignedRecording(c.req.param('id'), c.req.query('expires'), signature, c.req.header('range'))
})
diff --git a/apps/api/src/recording-route.ts b/apps/api/src/recording-route.ts
index 7b7434bf..3f060f75 100644
--- a/apps/api/src/recording-route.ts
+++ b/apps/api/src/recording-route.ts
@@ -2,7 +2,8 @@
// keys), or for anyone with a signed link (recordingLink: the after-call webhook's, valid RECORDING_LINK_HOURS,
// bound to the call's workspace and refused while that workspace is disabled).
// A file store is streamed from here, with Range support so players can seek; an S3 store gets
-// a redirect to a short-lived signed link. The store is the one the call's recording went to
+// a redirect to a short-lived signed link, or with `?through=1` the bytes through the API (same origin: the call
+// page reads them to draw the waveform, and a bucket does not allow that page to read its answers). The store is the one the call's recording went to
// (calls.recording_store), resolved on each request: settings changed in the admin area apply at once.
import { timingSafeEqual } from 'node:crypto'
import { createReadStream } from 'node:fs'
@@ -52,7 +53,11 @@ function fileResponse(path: string, size: number, type: string, rangeHeader: str
}
/** The stored key, if it is the one this call can have. Anything else in the column is not served. */
-export function ownRecordingKey(call: { id: string; workspace_id: string; recording_key: string | null }): string | null {
+export function ownRecordingKey(call: {
+ id: string
+ workspace_id: string
+ recording_key: string | null
+}): string | null {
const key = call.recording_key
const own =
key &&
@@ -61,19 +66,50 @@ export function ownRecordingKey(call: { id: string; workspace_id: string; record
return own ? key : null
}
-export async function serveRecording(actor: Actor, callId: string, rangeHeader: string | undefined): Promise<Response> {
+export async function serveRecording(
+ actor: Actor,
+ callId: string,
+ rangeHeader: string | undefined,
+ through = false,
+): Promise<Response> {
if (!actor.workspaceId || !actor.permissions.includes('call:read')) return error(403, 'missing permission call:read')
- return serveCallRecording(and(eq(calls.id, callId), eq(calls.workspace_id, actor.workspaceId)), rangeHeader)
+ return serveCallRecording(and(eq(calls.id, callId), eq(calls.workspace_id, actor.workspaceId)), rangeHeader, through)
+}
+
+/** The bucket's answer for a signed link, passed on as the API's own (status, body and the headers a player needs). */
+export async function passThrough(
+ url: string,
+ rangeHeader: string | undefined,
+ doFetch: typeof fetch = fetch,
+): Promise<Response> {
+ const answer = await doFetch(url, { headers: rangeHeader ? { range: rangeHeader } : {}, redirect: 'error' })
+ if (!answer.ok) {
+ void answer.body?.cancel()
+ // Only the status: the page draws no waveform then, and the bucket's words stay out of it.
+ return new Response(null, { status: answer.status === 416 ? 416 : 502 })
+ }
+ const headers = new Headers({ 'cache-control': 'private, no-store' })
+ for (const name of ['content-type', 'content-length', 'content-range', 'accept-ranges']) {
+ const value = answer.headers.get(name)
+ if (value) headers.set(name, value)
+ }
+ return new Response(answer.body, { status: answer.status, headers })
}
// --- Signed links ------------------------------------------------------------------------------
const LINK_PURPOSE = 'recording-link'
// The workspace is in the signed text: a link only opens a call of the workspace it was made for.
-const linkText = (workspaceId: string, callId: string, expires: number) => JSON.stringify([workspaceId, callId, expires])
+const linkText = (workspaceId: string, callId: string, expires: number) =>
+ JSON.stringify([workspaceId, callId, expires])
/** A link that opens the call's audio without signing in until `expires_at`; `base` is where the API is reached. */
-export function recordingLink(callId: string, workspaceId: string, base: string, now = new Date()): { url: string; expires_at: string } {
+export function recordingLink(
+ callId: string,
+ workspaceId: string,
+ base: string,
+ now = new Date(),
+): { url: string; expires_at: string } {
const expires = Math.floor(now.getTime() / 1000) + RECORDING_LINK_HOURS * 3_600
const url = new URL(`/v1/calls/${encodeURIComponent(callId)}/recording`, base)
url.searchParams.set('expires', String(expires))
@@ -92,7 +128,13 @@ export const isSignedRecordingRequest = (path: string, query: { signature?: stri
* for this call and its workspace, or when that workspace is disabled. An unknown call is refused like a bad
* signature; a deleted call answers "no recording" only after the signature checked out.
*/
-export async function serveSignedRecording(callId: string, expires: string | undefined, signature: string | undefined, rangeHeader: string | undefined, now = Date.now()) {
+export async function serveSignedRecording(
+ callId: string,
+ expires: string | undefined,
+ signature: string | undefined,
+ rangeHeader: string | undefined,
+ now = Date.now(),
+) {
const until = Number(expires)
if (!Number.isInteger(until) || !signature || !/^[0-9a-f]{64}$/.test(signature)) return notValid()
if (until * 1000 < now) return error(403, 'this recording link has expired; fetch the recording with an API key')
@@ -114,7 +156,11 @@ export async function serveSignedRecording(callId: string, expires: string | und
return serveCallRecording(and(eq(calls.id, callId), eq(calls.workspace_id, call.workspace_id)), rangeHeader)
}
-async function serveCallRecording(which: SQL | undefined, rangeHeader: string | undefined): Promise<Response> {
+async function serveCallRecording(
+ which: SQL | undefined,
+ rangeHeader: string | undefined,
+ through = false,
+): Promise<Response> {
const [call] = await db
.select({
id: calls.id,
@@ -131,6 +177,7 @@ async function serveCallRecording(which: SQL | undefined, rangeHeader: string |
const location = await store.locate(key, SIGNED_URL_TTL_SEC)
if (!location) return error(404, 'no recording for this call')
if (call.recording_store === 's3') void noteProviderOk('s3')
+ if ('url' in location && through) return await passThrough(location.url, rangeHeader)
if ('url' in location)
return new Response(null, {
status: 302,
diff --git a/apps/api/src/recording-through.test.ts b/apps/api/src/recording-through.test.ts
new file mode 100644
index 00000000..0378539c
--- /dev/null
+++ b/apps/api/src/recording-through.test.ts
@@ -0,0 +1,38 @@
+// `?through=1`: a bucket recording passed on by the API (same origin), for the call page's waveform.
+import { expect, test, vi } from 'vitest'
+
+// The module loads db.ts, which needs a URL; this test never queries the database.
+process.env.DATABASE_URL ||= 'postgres://unused@localhost:1/unused'
+const { passThrough } = await import('./recording-route.ts')
+
+const bucket = (status: number, headers: Record<string, string>, body = 'OggS') =>
+ vi.fn(async () => new Response(body, { status, headers })) as unknown as typeof fetch
+
+test('passes the bucket answer on with the headers a player needs, and the range asked for', async () => {
+ const doFetch = bucket(206, {
+ 'content-type': 'audio/ogg',
+ 'content-range': 'bytes 0-3/10',
+ 'x-amz-id': 'secret-ish',
+ })
+ const answer = await passThrough('https://bucket.example/rec.ogg?sig=1', 'bytes=0-3', doFetch)
+ expect(doFetch).toHaveBeenCalledWith('https://bucket.example/rec.ogg?sig=1', {
+ headers: { range: 'bytes=0-3' },
+ redirect: 'error',
+ })
+ expect(answer.status).toBe(206)
+ expect(answer.headers.get('content-type')).toBe('audio/ogg')
+ expect(answer.headers.get('content-range')).toBe('bytes 0-3/10')
+ expect(answer.headers.get('x-amz-id')).toBeNull()
+ expect(answer.headers.get('cache-control')).toBe('private, no-store')
+ expect(await answer.text()).toBe('OggS')
+})
+
+test('a refusal of the bucket is a 502, never its body', async () => {
+ const answer = await passThrough(
+ 'https://bucket.example/rec.ogg',
+ undefined,
+ bucket(403, {}, '<Error>AccessDenied</Error>'),
+ )
+ expect(answer.status).toBe(502)
+ expect(await answer.text()).not.toContain('AccessDenied')
+})
diff --git a/apps/web/src/app.css b/apps/web/src/app.css
index 3012ba60..e37addcf 100644
--- a/apps/web/src/app.css
+++ b/apps/web/src/app.css
@@ -465,6 +465,27 @@ a.auth-switch {
height: 100%;
background: var(--ink);
}
+/* The waveform (reference UI: thin, tight bars), in place of the line once the recording's levels are in. */
+.vn-bars {
+ flex: 1;
+ height: 100%;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 1px;
+}
+.vn-bars i {
+ flex: 1 1 0;
+ min-width: 0;
+ max-width: 3px;
+ border-radius: 1.5px;
+ background: var(--ink-muted);
+ opacity: 0.38;
+}
+.vn-bars i.p {
+ background: var(--ink);
+ opacity: 0.9;
+}
.vn-track:hover .vn-knob {
transform: scale(1.35);
}
diff --git a/apps/web/src/call/RecordingPlayer.tsx b/apps/web/src/call/RecordingPlayer.tsx
index e2600ab8..3a536e03 100644
--- a/apps/web/src/call/RecordingPlayer.tsx
+++ b/apps/web/src/call/RecordingPlayer.tsx
@@ -1,4 +1,12 @@
-import { useEffect, useRef, useState, type KeyboardEvent, type PointerEvent, type SyntheticEvent } from 'react'
+import {
+ useCallback,
+ useEffect,
+ useRef,
+ useState,
+ type KeyboardEvent,
+ type PointerEvent,
+ type SyntheticEvent,
+} from 'react'
import { clock } from '../time.ts'
import { RECORDINGS_NOT_KEPT } from '@linedesk/actions'
import { useWorkspaceSettings } from '../settings/settings-api.ts'
@@ -13,6 +21,7 @@ import {
seekSeconds,
} from './playback.ts'
import { useT } from '@linedesk/i18n/react'
+import { fitLevels, recordingLevels } from './waveform.ts'
type Props = { callId: string; callDurationSec: number | null }
@@ -51,6 +60,7 @@ export function RecordingPlayer({ callId, callDurationSec }: Props) {
// No file: Space keeps its normal meaning, as on a call without a player.
const missing = failedAs === 'missing'
useEffect(() => (missing ? undefined : registerPlayer(() => toggleRef.current())), [missing])
+ const waveform = useWaveform(src, missing || failed)
const clamp = (seconds: number) => Math.max(0, Math.min(length, seconds))
function seek(seconds: number) {
@@ -162,6 +172,7 @@ export function RecordingPlayer({ callId, callDurationSec }: Props) {
) : (
<div
className="vn-track"
+ ref={waveform.measure}
role="slider"
tabIndex={0}
aria-label={t('call.recording.position')}
@@ -178,9 +189,22 @@ export function RecordingPlayer({ callId, callDurationSec }: Props) {
onLostPointerCapture={() => setDragging(false)}
onKeyDown={onTrackKey}
>
- <span className="vn-line">
- <span className="vn-played" style={{ width: `${played * 100}%` }} />
- </span>
+ {waveform.bars.length ? (
+ <span className="vn-bars" aria-hidden="true">
+ {waveform.bars.map((level, i) => (
+ <i
+ // biome-ignore lint/suspicious/noArrayIndexKey: a bar is its place in the track
+ key={i}
+ className={(i + 0.5) / waveform.bars.length <= played ? 'p' : undefined}
+ style={{ height: `${Math.max(8, Math.round(level * 100))}%` }}
+ />
+ ))}
+ </span>
+ ) : (
+ <span className="vn-line">
+ <span className="vn-played" style={{ width: `${played * 100}%` }} />
+ </span>
+ )}
<span className="vn-knob" style={{ left: `${played * 100}%` }} />
</div>
)}
@@ -211,3 +235,37 @@ export function RecordingNotKept() {
</p>
)
}
+
+/** One bar and its gap, in pixels: thin bars, as in the reference UI. */
+const BAR_PITCH = 4
+
+/**
+ * The waveform's bars for the track: the recording's levels (decoded once per call) fitted to the track's width,
+ * none until they are in or when the recording has none to show (then the plain line stays).
+ */
+function useWaveform(src: string, off: boolean) {
+ const [levels, setLevels] = useState<number[] | null>(null)
+ const [width, setWidth] = useState(0)
+ const observer = useRef<ResizeObserver | null>(null)
+ useEffect(() => {
+ if (off) return
+ let current = true
+ void recordingLevels(src).then(result => {
+ if (current) setLevels(result)
+ })
+ return () => {
+ current = false
+ }
+ }, [src, off])
+ // The track's width decides how many bars fit.
+ const measure = useCallback((el: HTMLElement | null) => {
+ observer.current?.disconnect()
+ observer.current = null
+ if (!el) return
+ setWidth(el.getBoundingClientRect().width)
+ observer.current = new ResizeObserver(([entry]) => entry && setWidth(entry.contentRect.width))
+ observer.current.observe(el)
+ }, [])
+ const bars = levels && width > 0 ? fitLevels(levels, Math.floor(width / BAR_PITCH)) : []
+ return { bars, measure }
+}
diff --git a/apps/web/src/call/waveform.test.ts b/apps/web/src/call/waveform.test.ts
new file mode 100644
index 00000000..b1f1410e
--- /dev/null
+++ b/apps/web/src/call/waveform.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from 'vitest'
+import { fitLevels, measureLevels } from './waveform.ts'
+
+describe('recording waveform', () => {
+ it('measures loudness per part, silence as 0 and the loudest parts as 1', () => {
+ const samples = new Float32Array(400)
+ samples.fill(0.5, 100, 200) // speech in the second quarter
+ samples.fill(0.25, 300, 400) // quieter speech at the end
+ const levels = measureLevels([samples], 4)
+ expect(levels[0]).toBe(0)
+ expect(levels[1]).toBe(1)
+ expect(levels[2]).toBe(0)
+ expect(levels[3]).toBeCloseTo(0.5)
+ })
+ it('mixes the channels and gives nothing for no audio', () => {
+ expect(measureLevels([new Float32Array([0.5, 0.5]), new Float32Array([0.5, 0.5])], 1)).toEqual([1])
+ expect(measureLevels([], 10)).toEqual([])
+ expect(measureLevels([new Float32Array(10)], 2)).toEqual([0, 0])
+ })
+ it('fits the levels to the bars, each bar the loudest of its part', () => {
+ expect(fitLevels([0, 0.2, 1, 0.1, 0, 0], 3)).toEqual([0.2, 1, 0])
+ expect(fitLevels([0.3], 3)).toEqual([0.3, 0.3, 0.3])
+ expect(fitLevels([], 3)).toEqual([])
+ })
+})
diff --git a/apps/web/src/call/waveform.ts b/apps/web/src/call/waveform.ts
new file mode 100644
index 00000000..e920e70d
--- /dev/null
+++ b/apps/web/src/call/waveform.ts
@@ -0,0 +1,83 @@
+// The recording's waveform: how loud it is along the call, drawn as thin bars in the player's track. The browser
+// decodes the file once per call (through the API, `?through=1`: same origin) and keeps the levels in memory.
+
+/** Levels measured per recording, before they are fitted to the track's width. */
+export const LEVEL_COUNT = 600
+/** A larger file is not decoded for its waveform (about 40 minutes of call audio); the plain track stays. */
+export const WAVEFORM_MAX_BYTES = 40 * 1024 * 1024
+const DECODE_RATE = 8000
+
+/**
+ * Loudness in `count` equal parts of the audio (all channels mixed), 0 to 1. The loudest parts (the top 2 %) are 1,
+ * so one cough does not flatten the rest; silence stays 0.
+ */
+export function measureLevels(channels: Float32Array[], count = LEVEL_COUNT): number[] {
+ const length = channels[0]?.length ?? 0
+ if (!length || count <= 0) return []
+ const rms: number[] = []
+ for (let i = 0; i < count; i++) {
+ const from = Math.floor((i * length) / count)
+ const to = Math.max(from + 1, Math.floor(((i + 1) * length) / count))
+ let sum = 0
+ for (let s = from; s < to && s < length; s++) {
+ let v = 0
+ for (const channel of channels) v += channel[s] ?? 0
+ v /= channels.length
+ sum += v * v
+ }
+ rms.push(Math.sqrt(sum / (to - from)))
+ }
+ const sorted = [...rms].sort((a, b) => a - b)
+ const top = sorted[Math.floor(sorted.length * 0.98)] ?? 0
+ if (top <= 0) return rms.map(() => 0)
+ return rms.map(v => Math.min(1, v / top))
+}
+
+/** The levels fitted to `bars` bars: each bar shows the loudest level of its part. */
+export function fitLevels(levels: number[], bars: number): number[] {
+ if (!levels.length || bars <= 0) return []
+ const out: number[] = []
+ for (let b = 0; b < bars; b++) {
+ const from = Math.floor((b * levels.length) / bars)
+ const to = Math.max(from + 1, Math.floor(((b + 1) * levels.length) / bars))
+ let max = 0
+ for (let i = from; i < to && i < levels.length; i++) max = Math.max(max, levels[i] ?? 0)
+ out.push(max)
+ }
+ return out
+}
+
+const cache = new Map<string, Promise<number[] | null>>()
+
+/** The levels of the recording at `src`, or null when there are none to show (too large, not decodable, offline). */
+export function recordingLevels(src: string): Promise<number[] | null> {
+ let levels = cache.get(src)
+ if (!levels) {
+ levels = decodeLevels(src)
+ cache.set(src, levels)
+ // A failure is not kept: the next visit of the call tries again.
+ void levels.then(result => {
+ if (!result) cache.delete(src)
+ })
+ }
+ return levels
+}
+
+async function decodeLevels(src: string): Promise<number[] | null> {
+ try {
+ const response = await fetch(`${src}?through=1`, { credentials: 'same-origin' })
+ const size = Number(response.headers.get('content-length'))
+ if (!response.ok || size > WAVEFORM_MAX_BYTES) {
+ void response.body?.cancel()
+ return null
+ }
+ const bytes = await response.arrayBuffer()
+ if (bytes.byteLength > WAVEFORM_MAX_BYTES) return null
+ const context = new OfflineAudioContext(1, 1, DECODE_RATE)
+ const audio = await context.decodeAudioData(bytes)
+ const channels = Array.from({ length: audio.numberOfChannels }, (_, i) => audio.getChannelData(i))
+ return measureLevels(channels)
+ } catch {
+ return null
+ }
+}