diff --git a/AGENTS.md b/AGENTS.md index ee67bcda..268e0bcd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -520,14 +520,17 @@ How the page is put together: devices". The two are plain modes: online the server says the lines, offline this computer makes them and the server is not asked (`line()` in `site/voice.js`); the switch says which is on and whether the model is downloaded, and the download's progress and the GPU voice stand inside it. The GPU voice shows only with offline mode on. Server video export is planned, not built. -- **The voice's sound is kept in Cloudflare R2 (Nov 2026, asked for: "the users ones also goes to the - Cloudflare", and what is heard often is served from its cache; this replaces "never on the server" above for - the server voice).** One file a line, named by the voice and a hash of the words (`storeKey()` in - `site/voice.js` and in the function `voiceover`; change the two together), so a line is made and paid for once, - whoever asks. The function looks in the store before it counts a line against the account, and writes what it - makes. The page asks the store's public address first (`STORE` in `site/voice.js`, `fromStore()`; empty until - the bucket has one), which needs no sign-in, and gives up after `STORE_MISSES` misses in a row. Voiceovers for - the built views are to be made into the same store. Without the function's R2 secrets nothing is kept. +- **A voiceover is one file in Cloudflare R2 (Nov 2026, asked for: a wiki view and a published timeline alike, + "for consistency"; per-line files were found "complicated" and were dropped).** A wiki view's file is made by + `tools/voice/` and kept at `views/wiki///.mp3`. A published timeline's is made by the + function `voiceover` (`{ record: { id } }`): every line is said by the server voice as an MP3, side by side, and + the lines are joined frame by frame with `GAP` seconds of silence between them (`joinMp3()` in + `supabase/functions/voiceover/mp3.js`, nothing encoded again), kept at `views////.mp3` + with its words and cues in the same table as the wiki's. The page asks for it when the timeline is published + and when a published timeline's voiceover changes (`voiceFile()` in `site/account.js`), and keeps the answer + on the row as `voice.audio`, so every reader plays from that one file (`STORE`, `fileOf()` in `site/voice.js`). + An unpublished timeline's voice stays on the reader's device: taking a timeline down deletes its file. Lines on + their own are not kept on the server. Without the function's R2 secrets nothing is kept. - **The voice dialog is design A, "Two tabs" (Nov 2026, picked from three after the pill and box were found "too noisy"; this replaces what the points above say about the voice dialogs).** `voiceMenu()` draws one column (`.vo-form.vx`): the title, Online and Offline as two tabs (`.vo-tabs`, hidden on a phone), the voice as one diff --git a/docs/ACCOUNTS.md b/docs/ACCOUNTS.md index b32afeef..d893b4a4 100644 --- a/docs/ACCOUNTS.md +++ b/docs/ACCOUNTS.md @@ -284,8 +284,23 @@ the function `voiceover` (`{ speak }`). There is nothing to download, so it star works on a phone. Nothing is stored on the server: the sound goes to the reader's browser, which keeps each line (`server()` in `site/voice.js`, `speak()` in `site/account.js`). +**A published timeline's voiceover is one file.** When a timeline with a voiceover is published, or its +voiceover changes while it is published, the function `voiceover` (`{ record: { id } }`) has every line said +as an MP3, side by side, joins them into one file with a short silence between lines, and keeps it in the +public store at `views////.mp3`, the same shape as a wiki view's. Where each line +starts goes on the row (`voice.audio`), so every reader plays the one file. The same words in the same voice +are made once; the characters count against the owner's month. Taking the timeline down deletes the file: an +unpublished timeline's voice stays on the reader's device. + +**An account's limits are on its own row**, so each can be changed without new code, for every account by +plan (`stripe-webhook` writes them) or for one account by hand: `ai_daily` (AI requests a day: 20 free, 200 +pro), `publish_max` (timelines published at once: 10 free, 1,000 pro; the database refuses one more, and the +publish dialog says to make one private or delete one first) and `voice_monthly` (characters of the server +voice a month: 5,000 free, 500,000 pro). The real guarantee on the bill is the spending limit on the voice's +own OpenRouter key (`VOICE_API_KEY`): whatever the accounts do, it stops there. + Every signed-in account has a share of it a month, counted in characters by the server: a taste -for a free account (30,000, about half an hour of speech) and far more for pro (500,000, about +for a free account (5,000, about five minutes of speech, half a cent, so even a thousand free accounts cost at most about $5 a month) and far more for pro (500,000, about nine hours). The account menu shows what is left. When the share is used up, and for a reader who is not signed in, the browser's own voice says the lines. diff --git a/site/account.js b/site/account.js index 8b579c39..b3dc1e80 100644 --- a/site/account.js +++ b/site/account.js @@ -67,7 +67,7 @@ const PHONE = '(max-width: 699px)'; const KEY = 'cg-session', FOLD = 'cg-sb', INTENT = 'cg-intent', MODEL = 'cg-model', PROMPT = 'cg-prompt', FAILED = 'cg-ai-failed'; // An account's share of the server voice a month, in characters (the function `voiceover` holds the same // numbers and is the one that counts), and about how many characters make a minute of speech. -export const SPEECH = { free: 30000, pro: 500000 }, CHARS_A_MINUTE = 900; +export const SPEECH = { free: 5000, pro: 500000 }, CHARS_A_MINUTE = 900; const AI_PER_DAY = 20; // the allowance until the account's row is read (`profiles.ai_daily`) /* `app` is what the page lends: $, esc, views() (ids on the road), view(id), @@ -128,7 +128,7 @@ export function createAccount(app) { async function refreshList() { if (!user) return; const [p, l] = await Promise.all([ - api(`/rest/v1/profiles?id=eq.${user.id}&select=username,ai_daily,plan`), + api(`/rest/v1/profiles?id=eq.${user.id}&select=username,ai_daily,plan,voice_monthly`), api(`/rest/v1/timelines?owner=eq.${user.id}&select=id,slug,title,visibility,entries,updated_at&order=updated_at.desc`), ]); profile = p[0] || { username: null }; @@ -259,6 +259,7 @@ export function createAccount(app) { } catch (e) { a.fail(e.message); } } async function patch(row, body) { + const said = (t) => { const v = t && JSON.parse(t).voice; return v ? JSON.stringify([v.voice, v.lines]) : ''; }, before = said(row.text); const got = await api(`/rest/v1/timelines?id=eq.${row.id}&select=id,slug,title,description,visibility,entries,updated_at`, { method: 'PATCH', headers: { Prefer: 'return=representation' }, body }); if (!got[0]) throw new Error('That timeline is no longer there.'); Object.assign(row, got[0]); @@ -266,6 +267,28 @@ export function createAccount(app) { app.replace(payloadOf(row)); if (editor.row() === row) editor.reload(); await refreshList(); + // Published, or taken down, or its voiceover changed while published: the one file on the server follows. + if (body.visibility || (body.data && row.visibility !== 'private' && said(row.text) !== before)) voiceFile(row); + } + // A published timeline's voiceover is one MP3 made on the server, kept under the username like a wiki view's + // (asked for, Nov 2026); a private one keeps its voice on this device only, and the server deletes its file. + // The answer (`audio`: where the file is and where each line starts) goes on the row, so every reader plays + // from that one file. Nothing waits for it: until it is there, the lines are said one by one as before. + const filing = new Map(); + function voiceFile(row) { + if (filing.get(row.id)) return filing.get(row.id).again = true; + const job = { again: false }; + filing.set(row.id, job); + voiceFn({ record: { id: row.id } }).then(async (d) => { + const data = JSON.parse(row.text), v = data.voice, had = JSON.stringify(v?.audio || null); + if (!v || had === JSON.stringify(d.audio || null)) return; + if (d.audio && (d.audio.voice !== v.voice || d.audio.cues.length !== v.lines.length)) return; + if (d.audio) v.audio = d.audio; else delete v.audio; + await api(`/rest/v1/timelines?id=eq.${row.id}`, { method: 'PATCH', body: { data } }); + row.text = JSON.stringify(data); + app.replace(payloadOf(row)); + }).catch((x) => { if (row.visibility !== 'private') toast('The voiceover file could not be made: ' + x.message); }) + .finally(() => { filing.delete(row.id); if (job.again) voiceFile(row); }); } async function ensureRow(uuid) { if (!rows.has(uuid)) await fetchView('t/' + uuid); return rows.get(uuid); } async function rawEntry(id) { @@ -624,7 +647,12 @@ export function createAccount(app) { // other single view, this browser (asked for, Nov 2026: Generate voiceover on the existing views too). function holder() { const cur = current(); - if (cur) return { own: true, title: cur.title, description: cur.description || '', get: () => JSON.parse(cur.text).voice, set: (v) => { const data = JSON.parse(cur.text); if (v) data.voice = v; else delete data.voice; return patch(cur, { data }); } }; + if (cur) return { own: true, title: cur.title, description: cur.description || '', get: () => JSON.parse(cur.text).voice, set: (v) => { + // The file of the voice before is kept only while the voice and its words are the same. + const data = JSON.parse(cur.text), was = data.voice; + if (v) { data.voice = { ...v }; delete data.voice.audio; if (was?.audio && was.voice === v.voice && JSON.stringify(was.lines) === JSON.stringify(v.lines)) data.voice.audio = was.audio; } else delete data.voice; + return patch(cur, { data }); + } }; const o = app.one(); // `fixed`: a built view's default voiceover, which is told as it is (Make it your own to change it). return o ? { own: false, fixed: !!o.voice?.base, title: o.title, description: o.description, get: () => app.one()?.voice, set: async (v) => app.keepVoice(v) } : null; @@ -1366,7 +1394,7 @@ export function createAccount(app) { // the characters said; `SPEECH` here only says how large the share is, to draw it). api(`/rest/v1/speech_use?select=chars&month=eq.${new Date().toISOString().slice(0, 7)}-01`).then((got) => { const box = d.querySelector('#me-say'); if (!box) return; - const most = SPEECH[isPro() ? 'pro' : 'free'], left = Math.max(0, most - (got?.[0]?.chars || 0)); + const most = Number(profile?.voice_monthly) || SPEECH[isPro() ? 'pro' : 'free'], left = Math.max(0, most - (got?.[0]?.chars || 0)); box.querySelector('span').textContent = `${Math.round(left / CHARS_A_MINUTE).toLocaleString('en-US')} of ${Math.round(most / CHARS_A_MINUTE).toLocaleString('en-US')} min left`; box.querySelector('u').style.width = (100 * left / most) + '%'; box.classList.toggle('none', !left); diff --git a/site/app.js b/site/app.js index 65cf6442..ccb24719 100644 --- a/site/app.js +++ b/site/app.js @@ -113,14 +113,14 @@ import { NEAR, GONE, FAR, FINE, calMarks, dayText, sizeAt, warp, focalYears, tra let RANKED = false, AX = null; const axisKey = (v) => (v?.axis === 'scale' ? 'scale:' + v.id : v?.axis === 'rank' ? 'rank' : 'time'); const isRanked = () => state.views.length > 0 && axisKey(viewById.get(state.views[0])) !== 'time'; - function yearText(y) { + function yearText(y, short = false) { if (RANKED) return axisLabel(AX, y); if (y > 0) return y < 1000 ? y + ' CE' : String(y); const a = -y; if (a < 10000) return a + ' BCE'; if (a < 1e5) return group(sig(a)) + ' BCE'; // on a phone the deep-time words are short: 100k, 66M, 13.8B years ago (asked for, Nov 2026) - const ph = matchMedia(PHONE).matches; + const ph = short || matchMedia(PHONE).matches; if (a < 1e6) return (ph ? sig(a / 1e3) + 'k' : group(sig(a))) + ' years ago'; if (a < 1e9) return sig(a / 1e6) + (ph ? 'M' : ' million') + ' years ago'; return sig(a / 1e9) + (ph ? 'B' : ' billion') + ' years ago'; @@ -705,7 +705,10 @@ import { NEAR, GONE, FAR, FINE, calMarks, dayText, sizeAt, warp, focalYears, tra } // A step of a plan with no end that starts after today still stands where it starts. const inSpan = (t) => (t.lead ?? t.born) < tMax && Math.max(t.end ?? NOW, t.born) >= tMin; - return { selected, groupsOf, rowsOf, all, fitMin, fitMax, autoMin, tMin, tMax, inSpan }; + // The first start and the last date of the entries in sight, for the year pill. + const seen = all.filter(inSpan), first = seen.length ? Math.min(...seen.map((t) => t.born)) : null; + const lastIn = seen.length ? Math.max(...seen.map((t) => Math.max(t.end ?? NOW, t.born))) : null; + return { selected, groupsOf, rowsOf, all, fitMin, fitMax, autoMin, tMin, tMax, inSpan, first, lastIn }; } // ---------------------------------------------------------------- render function render() { @@ -802,7 +805,7 @@ import { NEAR, GONE, FAR, FINE, calMarks, dayText, sizeAt, warp, focalYears, tra const camAtEnd = () => { const [lo, hi] = camLimits(); return camDir() > 0 ? road.t >= hi - L.D * 0.01 : road.t <= lo + L.D * 0.01; }; function roadLayout() { - const { selected, groupsOf, rowsOf, all, fitMin, fitMax, autoMin, tMin, tMax, inSpan } = chosen(); + const { selected, groupsOf, rowsOf, all, fitMin, fitMax, autoMin, tMin, tMax, inSpan, first, lastIn } = chosen(); const box = $('road'), G = stageOf(box.clientWidth, box.clientHeight, TOP, ($('axisbar')?.offsetWidth || 0) / 2); $('road-views').style.left = G.vx + 'px'; const lanes = []; @@ -846,7 +849,7 @@ import { NEAR, GONE, FAR, FINE, calMarks, dayText, sizeAt, warp, focalYears, tra const own = state.views.some((id) => viewById.get(id)?.stored) || shown.filter((p) => wallMedia(p.t).length).length >= Math.max(3, 0.15 * shown.length); // The latest start on the road: turned round, the reader opens just before it, even when it stands close to the end. const lastA = shown.reduce((m, p) => (p.a <= tMax && p.a > m ? p.a : m), -Infinity); - L = { eps: Math.min(0.01, (tMax - tMin) / 2000), own, tMin, tMax, lastA, fitMin, fitMax, autoMin, shown, groups, total: groupsOf.size, D, G, lanes, place, when, + L = { eps: Math.min(0.01, (tMax - tMin) / 2000), own, first, last: lastIn, tMin, tMax, lastA, fitMin, fitMax, autoMin, shown, groups, total: groupsOf.size, D, G, lanes, place, when, at: new Map([...shown].reverse().map((p) => [p.t.id, p])), byKey: new Map(shown.map((p) => [p.key, p])), barH: $('axis').clientHeight }; return L; } @@ -989,7 +992,7 @@ import { NEAR, GONE, FAR, FINE, calMarks, dayText, sizeAt, warp, focalYears, tra const t = p.t, P = roadPalette(); return { id: t.id, name: t.name, kind: t.cat.short || t.cat.name, when: spanOf(t), summary: t.summary || '', img: t.image && !t.noImage ? mediaUrl(t.image.src) : '', imgs: t.image && !t.noImage ? [t.image, ...(t.media || []).filter((m) => m && m.src && (!m.type || m.type === 'image'))].map((m) => mediaUrl(m.src)).filter((u, i, a) => a.indexOf(u) === i).slice(0, 4) : [], - mark: shortYear(writtenOf(t.born)), col: colVar(p.lane.col), rgb: `rgb(${colRgb(P, p.lane.col).join(',')})`, place: t.where ? [t.where[0], t.where[1], 'city', ''] : !RANKED && t.born > DEEP ? places[t.id] || null : null }; + mark: RANKED ? shortYear(writtenOf(t.born)) : yearText(writtenOf(t.born), true), col: colVar(p.lane.col), rgb: `rgb(${colRgb(P, p.lane.col).join(',')})`, place: t.where ? [t.where[0], t.where[1], 'city', ''] : !RANKED && t.born > DEEP ? places[t.id] || null : null }; } function globeShow() { if (!globe) { @@ -1981,7 +1984,11 @@ import { NEAR, GONE, FAR, FINE, calMarks, dayText, sizeAt, warp, focalYears, tra if (document.activeElement !== $('y-from')) $('y-from').value = pos(lo); if (document.activeElement !== $('y-to')) $('y-to').value = pos(hi); const last = hi >= NOW - 0.5 ? 'today' : yearText(writtenOf(hi - 1e-9)); - $('years-out').textContent = `${yearText(writtenOf(lo))} – ${last}`; + // The pill names the years of the entries themselves, not the room the road leaves before the first + // (Japan read "801 BCE" for a first entry of 660 BCE); a range the reader narrowed is named as chosen. + const said = (t) => yearText(writtenOf(t)); + const out = !L || state.span ? [said(lo), last] : [said(Math.max(lo, L.first ?? lo)), L.last != null && L.last < hi && L.last < NOW - 0.5 ? said(L.last) : last]; + $('years-out').textContent = `${out[0]} – ${out[1]}`; $('y-from').setAttribute('aria-valuetext', yearText(writtenOf(lo))); $('y-to').setAttribute('aria-valuetext', last); // Reset a narrowed range; or, when the timeline opened on its busy part, reach back to the first entry. diff --git a/site/export.js b/site/export.js index ff4e9f5e..bc07810f 100644 --- a/site/export.js +++ b/site/export.js @@ -231,13 +231,15 @@ export function painter(cv, { title, steps, scenes, fonts, subsOf, globe }) { c.font = font(!s.place && globe); const nm = s.name.length > 36 ? s.name.slice(0, 34) + '…' : s.name, w = px(18) + c.measureText(nm).width; const o = { x, nm, w, yr: s.mark && s.mark !== said ? s.mark : '', it: !s.place && globe }; if (o.yr) said = s.mark; - x += w + gap; return o; + // A year wider than its name keeps the next name clear of it, as on the page. + if (o.yr) { c.font = `500 ${ys}px ${sans}`; o.w = Math.max(o.w, c.measureText(o.yr).width + px(6)); } + x += o.w + gap; return o; }); } // As on the page: the marker stands on the dot of the entry in front, what has passed at its // left, and what is still to come shows only its dot until its turn (asked for, Nov 2026). const pos = posAt(scenes, t), k = Math.min(strip.length - 1, Math.max(0, Math.floor(pos))), nx = strip[k + 1]; - const at = pos < 0 ? strip[0].x + px(40) * pos : nx ? strip[k].x + (nx.x - strip[k].x) * (pos - k) : strip[k].x; + const at = pos < 0 ? strip[0].x : nx ? strip[k].x + (nx.x - strip[k].x) * (pos - k) : strip[k].x; const xm = x1 - px(lay.wide ? 380 : 300), off = xm - px(5) - at, acc = steps[now].rgb || '#e8b04a'; c.save(); c.textBaseline = 'alphabetic'; c.textAlign = 'left'; strip.forEach((o, n) => { diff --git a/site/globe.js b/site/globe.js index 73e2112a..9a1d23eb 100644 --- a/site/globe.js +++ b/site/globe.js @@ -418,7 +418,8 @@ export function createGlobe(host, { open, goTo, seek, credit, esc, calm, pane, c if (shelf.hidden) return; let said = ''; track.innerHTML = S.steps.map((s, i) => { - const yr = s.mark && s.mark !== said ? `${esc(s.mark)}` : ''; + // The year is written under the entry; a hidden copy in the flow keeps the next name clear of it. + const yr = s.mark && s.mark !== said ? `${esc(s.mark)}` : ''; if (yr) said = s.mark; return ``; }).join(''); @@ -427,8 +428,9 @@ export function createGlobe(host, { open, goTo, seek, credit, esc, calm, pane, c // Where each entry stands on the strip. function measure() { // An entry is placed by its left edge, where its dot is: the marker stands just before it, so the reader is seen going to it. - S.xs = Array.from(track.children, (el) => el.offsetLeft); - rows.style.setProperty('--now', Math.round(nowAt()) + 'px'); + // Each entry is placed by the middle of its dot, so the marker stands exactly on it. + S.xs = Array.from(track.children, (el) => { const d = el.firstElementChild; return el.offsetLeft + (d ? d.offsetLeft + d.offsetWidth / 2 : 0); }); + S.nowX = Math.round(nowAt()); rows.style.setProperty('--now', S.nowX + 'px'); } function markShelf() { const els = track.children; @@ -440,16 +442,19 @@ export function createGlobe(host, { open, goTo, seek, credit, esc, calm, pane, c // stays in sight at its left, and what is still to come is not shown until its turn, coming in from the right. // (Before, the marker stood at the left and the strip showed what was to come.) const nowAt = () => Math.max(30, rows.clientWidth - (S.phone ? 160 : 300)); - // At a card the marker stands right on its dot (asked for, Nov 2026: "stopping right on the dot"), the dot being - // 7 px wide at the entry's left edge; between two cards it travels from one dot to the next. The shift is as - // measured on the page (the strip's own inset included), not worked out. - const DOT_SHIFT = 3.4; + // At a card the marker stands right on its dot (asked for, Nov 2026: "stopping right on the dot"): `S.xs` holds the + // middle of each dot, measured on the page. + const DOT_SHIFT = 0; // The place on the strip that belongs under the marker for a reader at `pos`. + // The marker keeps to the camera: it stands on an entry's dot while the camera rests there (`STAY`; play waits + // there for the entry's line) and before play, on the first dot, and moves on to the next dot, easing out and in, + // only while the camera does (asked for, Nov 2026: "exact on that point on the first dot", and on each one after). + const glide = (f) => { const u = clamp01((f - STAY) / (1 - STAY)); return u * u * (3 - 2 * u); }; function xAt(pos) { if (!S.xs.length) return 0; - if (pos < 0) return S.xs[0] + 34 * pos; + if (pos < 0) return S.xs[0]; const i = Math.min(S.xs.length - 1, Math.floor(pos)), a = S.xs[i], b = S.xs[i + 1]; - return b == null ? a : a + (b - a) * (pos - i); + return b == null ? a : a + (b - a) * glide(pos - i); } // ---- space: where a view has no place on the Earth the reader flies on among the stars, as fast as they travel. @@ -549,7 +554,8 @@ export function createGlobe(host, { open, goTo, seek, credit, esc, calm, pane, c if (d) light(o.way && o.way.a, o.way && o.way.b, o.way ? o.way.e : 0, o.way ? o.way.key : '', o.way && o.way.c); else trail(S.pos); } // The entry in front stands just after the marker, its dot first: the marker is on its way to it (asked for, Nov 2026). - if (!shelf.hidden) track.style.transform = `translateX(${(nowAt() + DOT_SHIFT - xAt(S.pos)).toFixed(1)}px)`; + // The marker is moved with the strip: the strip's width changes when the bar on the left steps away for play. + if (!shelf.hidden) { const n = Math.round(nowAt()); if (n !== S.nowX) { S.nowX = n; rows.style.setProperty('--now', n + 'px'); } track.style.transform = `translateX(${(n + DOT_SHIFT - xAt(S.pos)).toFixed(1)}px)`; } if (sp > 0.005) { S.warp = still ? 0 : d ? d.warp : toward(S.warp, Math.max(-1.2, Math.min(1.2, speed * 0.34)), dt * 4); stars(dt); @@ -600,7 +606,14 @@ export function createGlobe(host, { open, goTo, seek, credit, esc, calm, pane, c const xs = S.xs; if (!xs.length) return 0; if (x <= xs[0]) return Math.max(-1, (x - xs[0]) / 34); - for (let i = 0; i < xs.length - 1; i++) if (x < xs[i + 1]) return i + (x - xs[i]) / (xs[i + 1] - xs[i]); + for (let i = 0; i < xs.length - 1; i++) if (x < xs[i + 1]) { + // The way back from a place on the strip to the reader: glide() turned round (by halving; it only rises). + const want = (x - xs[i]) / (xs[i + 1] - xs[i]); + if (want <= 0) return i; + let lo = STAY, hi = 1; + for (let k = 0; k < 24; k++) { const m = (lo + hi) / 2; if (glide(m) < want) lo = m; else hi = m; } + return i + (lo + hi) / 2; + } return xs.length - 1; } rows.addEventListener('pointerdown', (e) => { diff --git a/site/styles.css b/site/styles.css index ae3ff30b..472c2e14 100644 --- a/site/styles.css +++ b/site/styles.css @@ -705,6 +705,7 @@ body.globe:has(#globe.close) #wall .w-scene { opacity: 0; } #globe .g-track { position: absolute; left: 0; bottom: 0; height: 100%; display: flex; align-items: flex-end; gap: 30px; white-space: nowrap; will-change: transform; } #globe .g-track u { position: absolute; left: 50%; top: calc(100% + 8px); transform: translateX(-50%); text-decoration: none; font-size: 10.5px; line-height: 12px; letter-spacing: .02em; font-variant-numeric: tabular-nums; color: #8f97a8; pointer-events: none; } #globe .g-track .on u { color: #ece7dc; } +#globe .g-track .yw { display: block; height: 0; overflow: hidden; visibility: hidden; font-size: 10.5px; font-style: normal; line-height: 0; letter-spacing: .02em; font-variant-numeric: tabular-nums; } #globe .g-note { position: absolute; left: 50%; top: 45%; transform: translateX(-50%); margin: 0; font-size: 13px; color: var(--muted); } #globe .g-note[hidden] { display: none; } @media (max-width: 699px) { diff --git a/site/voice.js b/site/voice.js index b93de9eb..70810e27 100644 --- a/site/voice.js +++ b/site/voice.js @@ -82,20 +82,10 @@ export function lineKey(voice, text) { return `https://voice.codegrave.invalid/${voice}/${(h >>> 0).toString(36)}-${text.length}`; } -// Where a line's sound is kept for everyone (asked for, Nov 2026: the voice files go to Cloudflare, and what is -// heard often is served from its cache): one file a line in a public store, named by the voice and a hash of the -// words, so the same line in the same voice is made once, whoever asks. The function `voiceover` writes it and -// names it the same way (`storeKey()` there; change the two together). `STORE` is the store's public address, -// with no slash at its end; while it is empty the page does not ask the store, and the function still does. +// The public store (Cloudflare R2) where a timeline's voiceover is kept as one file: a wiki view's, and a +// published timeline's (asked for, Nov 2026). Lines on their own are not kept there; this browser keeps them. export const STORE = 'https://pub-f5afdcf4890045a5ab305d4297af0129.r2.dev'; export const sayText = (s) => String(s ?? '').replace(/\s+/g, ' ').trim().slice(0, 700); -export async function storeKey(voice, text) { - const d = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(voice + '\n' + sayText(text))); - return `v1/${voice}/${[...new Uint8Array(d)].map((b) => b.toString(16).padStart(2, '0')).join('')}.pcm`; -} -// After this many lines in a row that the store does not have, it is not asked again for a while: a script -// nobody has heard yet has no files there, and each miss is a wasted request. -export const STORE_MISSES = 3; // The lines in the order they are made: the one asked for now first, then those after it, then the rest. export function madeOrder(ids, from) { @@ -211,7 +201,7 @@ export function createSpeaker(status = () => {}) { // A pro account's line is said by the server (nothing to download); if that cannot be, by this device. // Two plain modes (asked for, Nov 2026: "clearly know whether it is the online active or it is the offline"): // online, the server says the line; offline, this computer makes it and the server is not asked. - const far = offlineOn() ? null : (await fromStore(key, text, voice)) || (await fromServer(key, text, voice, now)); + const far = offlineOn() ? null : await fromServer(key, text, voice, now); if (far) return far; // Not from the server and offline mode is off: nothing is downloaded, and whoever asked says the line // with the browser's own voice. @@ -245,20 +235,6 @@ export function createSpeaker(status = () => {}) { }).catch(() => w.ok(null)).finally(() => { asking--; pump(); }); } } - // The public store first: a line anyone has heard before is there, costs no account anything and comes from - // Cloudflare's cache. It needs no sign-in, so a built timeline's voiceover plays for every reader. - let misses = 0; - async function fromStore(key, text, voice) { - if (!STORE || misses >= STORE_MISSES || !isVoice(voice) || voice === 'device') return null; - try { - const r = await fetch(STORE + '/' + (await storeKey(voice, text))); - if (!r.ok) { misses++; return null; } - const out = { audio: pcmToFloat(await r.arrayBuffer()), rate: 24000 }; - misses = 0; status({ made: true }); - opened().then((c) => c?.put(key, new Response(out.audio.slice(), { headers: { 'x-rate': String(out.rate) } }))).catch(() => {}); - return out; - } catch (e) { misses++; return null; } - } function fromServer(key, text, voice, now) { if (!remote || !has()) return Promise.resolve(null); return new Promise((ok) => { const w = { key, text, voice, ok }; if (now) waiting.unshift(w); else waiting.push(w); pump(); }); diff --git a/supabase/functions/stripe-webhook/index.ts b/supabase/functions/stripe-webhook/index.ts index e396b6fb..dc006395 100644 --- a/supabase/functions/stripe-webhook/index.ts +++ b/supabase/functions/stripe-webhook/index.ts @@ -31,7 +31,10 @@ export const planOf = (status: string) => (status === "active" || status === "tr const rows = (query: string, fields: Record) => fetch(`${URL_}/rest/v1/profiles?${query}`, { method: "PATCH", headers: { apikey: SERVICE, Authorization: "Bearer " + SERVICE, "Content-Type": "application/json", Prefer: "return=representation" }, body: JSON.stringify(fields) }) .then(async (r) => (r.ok ? (await r.json()).length : (console.error("profiles", r.status, await r.text()), -1))); -const fieldsFor = (plan: string) => ({ plan, ai_daily: plan === "pro" ? PRO_DAILY : FREE_DAILY }); +// What a plan allows, written on the account's row (each can then be changed for one account by hand). +const fieldsFor = (plan: string) => plan === "pro" + ? { plan, ai_daily: PRO_DAILY, publish_max: 1000, voice_monthly: 500000 } + : { plan, ai_daily: FREE_DAILY, publish_max: 10, voice_monthly: 5000 }; const uuid = (s: unknown) => (typeof s === "string" && /^[0-9a-f-]{36}$/i.test(s) ? s : ""); Deno.serve(async (req) => { diff --git a/supabase/functions/voiceover/index.ts b/supabase/functions/voiceover/index.ts index 266d3988..83f7aad5 100644 --- a/supabase/functions/voiceover/index.ts +++ b/supabase/functions/voiceover/index.ts @@ -12,21 +12,31 @@ // // Only the words come from here. The page keeps them on the timeline's row, and the reader's own browser // speaks them while play goes (site/voice.js: Kokoro, a free voice model that runs on the device, or the -// device's own voice; asked for, Nov 2026: no sound files on the server, and a cost that does not grow with -// the hours people listen). +// device's own voice, or the server voice below). A published timeline's voice is one file in the store (`record`). // // { speak: { text, voice } } // One line said by a hosted copy of the same voice. Answer: the sound itself, // 16-bit samples at the rate in the header `x-rate`. Nothing is kept here: the reader's browser keeps it. // +// { record: { id } } +// A published timeline of the reader's own gets its voiceover as one MP3, as a wiki view has (asked for, +// Nov 2026): every line is said by the server voice as an MP3, side by side, and the lines are joined +// frame by frame with a short silence between them (mp3.js). The file goes to the public store at +// views////.mp3 (`v` from the voice and the words, as tools/voice/version.mjs +// makes it for the wiki), the older files of that timeline are deleted, and the words and cues are kept +// in the same table as the wiki's. A private timeline, or one with no voiceover, has its file deleted: +// an unpublished timeline's voice stays on the reader's device. Answer: { audio } to keep on the row +// ({ voice, v, secs, cues, src }), or { audio: null }. The characters count against the account's month. +// // Secrets (Supabase → Edge Functions → Secrets): // OPENROUTER_API_KEY required: the same one Create with AI uses // VOICE_API_KEY optional: an OpenRouter key of its own for the server voice, with a spending limit -// SPEECH_FREE optional: the most characters a month a free account may have said (30000) +// SPEECH_FREE optional: the share of a free account whose row says none (5000) // SPEECH_PRO optional: the same for a pro account (500000) // VOICE_SCRIPT_MODEL optional: the OpenRouter model that writes the script import { AwsClient } from "npm:aws4fetch@1.0.20"; +import { joinMp3 } from "./mp3.js"; const WRITER = Deno.env.get("VOICE_SCRIPT_MODEL") ?? "deepseek/deepseek-v4.1-flash"; // A long timeline is written in parts of PART entries, side by side, so the last entries get their lines too @@ -45,47 +55,118 @@ const SERVICE = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!; // the same model costs four times as much at another. const SPEECH_MODEL = Deno.env.get("SPEECH_MODEL") ?? "hexgrad/kokoro-82m"; const SPEECH_HOST = Deno.env.get("SPEECH_HOST") ?? "deepinfra"; -// The most characters a month an account may have said: a taste for a free account (about half an hour of -// speech, three cents), and far more for pro (about nine hours, fifty cents). -const SPEECH_FREE = Number(Deno.env.get("SPEECH_FREE")) || 30_000; +// The most characters a month an account may have said, when its row does not say (`voice_monthly` there is +// what counts): for a free account about five minutes of speech, half a cent, so even a thousand free accounts +// stay within about five dollars a month (asked for, Nov 2026), and far more for pro (about nine hours, fifty cents). +const SPEECH_FREE = Number(Deno.env.get("SPEECH_FREE")) || 5_000; const SPEECH_PRO = Number(Deno.env.get("SPEECH_PRO")) || 500_000; const SPEECH_VOICES = ["af_heart", "am_michael", "af_bella", "af_nicole", "bf_emma", "bm_george"]; const SPEECH_RATE = 24000; // Kokoro's own: the sound comes back as plain 16-bit samples at this rate -// Where the sound is kept (asked for, Nov 2026: Cloudflare R2, "the users ones also goes to the Cloudflare", and -// what is heard often served from its cache). One file a line, named by the voice and a hash of the words -// (`storeKey()`, the same in site/voice.js; change the two together), so a line is paid for once however many -// accounts ask for it, and the page reads it straight from the store's public address without coming here. -// A line found in the store is not counted against the account. Without the secrets nothing is kept. +// Where a published timeline's voiceover is kept (asked for, Nov 2026: Cloudflare R2, the same store and the +// same shape of address as the wiki's, "for consistency"). One file a timeline; the lines on their own are +// not kept anywhere on the server: the reader's browser keeps what it was sent. Without the secrets nothing is kept. // R2_ENDPOINT, R2_BUCKET, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY the bucket, written with the S3 API // VOICE_PUBLIC_URL its public address, no slash at the end const R2 = { at: Deno.env.get("R2_ENDPOINT"), bucket: Deno.env.get("R2_BUCKET"), id: Deno.env.get("R2_ACCESS_KEY_ID"), secret: Deno.env.get("R2_SECRET_ACCESS_KEY"), open: Deno.env.get("VOICE_PUBLIC_URL") }; const r2 = R2.at && R2.bucket && R2.id && R2.secret ? new AwsClient({ accessKeyId: R2.id, secretAccessKey: R2.secret, service: "s3", region: "auto" }) : null; const r2Url = (key: string) => `${R2.at!.replace(/\/+$/, "")}/${R2.bucket}/${key}`; -async function storeKey(voice: string, text: string) { - const d = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(voice + "\n" + text)); - return `v1/${voice}/${[...new Uint8Array(d)].map((b) => b.toString(16).padStart(2, "0")).join("")}.pcm`; -} -const kept = async (key: string) => { - if (!r2) return null; - const r = await r2.fetch(r2Url(key), { signal: AbortSignal.timeout(8000) }).catch(() => null); - return r?.ok ? r.arrayBuffer() : null; -}; -const keep = (key: string, sound: ArrayBuffer) => - r2 ? r2.fetch(r2Url(key), { method: "PUT", body: sound, headers: { "Content-Type": "application/octet-stream", "Cache-Control": "public, max-age=31536000, immutable" } }) - .then((r) => { if (!r.ok) console.error("keep", r.status); }).catch((e) => console.error("keep", String(e))) : Promise.resolve(); const sound = (buf: ArrayBuffer, left: number | null, from: string) => new Response(buf, { headers: { ...cors, "Content-Type": "application/octet-stream", "x-rate": String(SPEECH_RATE), ...(left === null ? {} : { "x-left": String(left) }), "x-from": from, "Access-Control-Expose-Headers": "x-rate, x-left, x-from", "Cache-Control": "no-store" } }); +const sayText = (t: unknown) => String(t ?? "").replace(/\s+/g, " ").trim().slice(0, 700); +// The same as versionOf() in tools/voice/version.mjs: a new file whenever the voice or a word changes. +async function versionOf(voice: string, lines: { id: string; text: string }[]) { + const d = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(voice + "\n" + lines.map((l) => l.id + "\t" + sayText(l.text)).join("\n"))); + return [...new Uint8Array(d)].map((b) => b.toString(16).padStart(2, "0")).join("").slice(0, 12); +} +const GAP = 0.35; // seconds of silence after each line, as in the wiki's files +const AT_ONCE = 12; // lines asked of the server voice side by side + +// The month's share of the server voice, as `speak` counts it: answers the running total, -1 past the share, +// -2 when it could not be counted. +async function share(account: string) { + // The share is on the account's own row (`voice_monthly`), so it can be changed without new code. + const own = await service(`/rest/v1/profiles?id=eq.${account}&select=plan,voice_monthly`).then((r) => (r.ok ? r.json() : [])).catch(() => []); + const most = Number.isFinite(Number(own[0]?.voice_monthly)) ? Number(own[0].voice_monthly) : own[0]?.plan === "pro" ? SPEECH_PRO : SPEECH_FREE; + const count = (n: number): Promise => service("/rest/v1/rpc/speech_add", { method: "POST", body: JSON.stringify({ who: account, n, most }) }).then((r) => (r.ok ? r.json() : -2)).catch(() => -2); + return { most, count }; +} + +// Deletes every file kept for a timeline but `keep`. +async function sweep(dir: string, keep = "") { + const list = await r2!.fetch(`${r2Url("")}?list-type=2&prefix=${encodeURIComponent(dir)}`).catch(() => null); + const old = list?.ok ? [...(await list.text()).matchAll(/([^<]+)<\/Key>/g)].map((m) => m[1]).filter((k) => k !== keep) : []; + await Promise.all(old.map((k) => r2!.fetch(r2Url(k), { method: "DELETE" }).catch(() => null))); + return old.length; +} + +async function record(account: string, ask: any): Promise { + if (!r2) return json({ error: "The store is not set up.", code: "not_configured" }, 503); + const id = String(ask?.id ?? ""); + if (!/^[0-9a-f-]{36}$/.test(id)) return json({ error: "That request could not be read." }, 400); + const rows = await service(`/rest/v1/timelines?id=eq.${id}&owner=eq.${account}&select=slug,visibility,data,profiles(username)`).then((r) => (r.ok ? r.json() : null)).catch(() => null); + if (!rows) return json({ error: "The timeline could not be read. Try again." }, 502); + if (!rows.length) return json({ error: "That timeline is not yours." }, 404); + const t = rows[0], username = String(t.profiles?.username ?? ""), slug = String(t.slug ?? ""); + if (!username || !slug) return json({ audio: null }); + const dir = `views/${username}/${slug}/`, vo = t.data?.voice; + const lines = (Array.isArray(vo?.lines) ? vo.lines : []).map((l: any) => ({ id: String(l?.id ?? ""), text: sayText(l?.text) })).filter((l: any) => l.id && l.text); + // Not published, or nothing to say in a server voice: nothing of it stays on the server. + if (t.visibility === "private" || !lines.length || !SPEECH_VOICES.includes(vo?.voice)) { + await sweep(dir); + await service(`/rest/v1/view_voices?owner=eq.${encodeURIComponent(username)}&view=eq.${encodeURIComponent(slug)}`, { method: "DELETE" }).catch(() => null); + return json({ audio: null }); + } + const voice = vo.voice as string, v = await versionOf(voice, lines), at = `${dir}${voice}/${v}.mp3`; + // Made already: the same words in the same voice are not paid for twice. + const had = await service(`/rest/v1/view_voices?owner=eq.${encodeURIComponent(username)}&view=eq.${encodeURIComponent(slug)}&select=audio`).then((r) => (r.ok ? r.json() : [])).catch(() => []); + const was = had[0]?.audio; + if (was?.v === v && was?.voice === voice && Array.isArray(was?.cues) && was.cues.length === lines.length) return json({ audio: { voice, v, secs: was.secs, cues: was.cues, src: was.path } }); + + const key = Deno.env.get("VOICE_API_KEY") ?? Deno.env.get("OPENROUTER_API_KEY"); + if (!key) return json({ error: "The server voice is not switched on yet.", code: "not_configured" }, 503); + const chars = lines.reduce((n: number, l: any) => n + l.text.length, 0), { most, count } = await share(account); + const total = await count(chars); + if (total === -2) return json({ error: "The server voice could not be reached. Try again." }, 502); + if (total < 0) return json({ error: "That is more than is left of this month's voice.", code: "limit" }, 429); + const say = async (text: string) => { + for (let go = 0; go < 2; go++) { + const r = await fetch("https://openrouter.ai/api/v1/audio/speech", { + method: "POST", + headers: { Authorization: "Bearer " + key, "Content-Type": "application/json", "HTTP-Referer": "https://codegrave.com", "X-Title": "codegrave" }, + body: JSON.stringify({ model: SPEECH_MODEL, input: text, voice, response_format: "mp3", provider: { only: [SPEECH_HOST] } }), + signal: AbortSignal.timeout(60_000), + }).catch(() => null); + if (r?.ok) return new Uint8Array(await r.arrayBuffer()); + console.error("record", r?.status, r ? (await r.text().catch(() => "")).slice(0, 300) : "no answer"); + } + throw new Error("a line was not said"); + }; + try { + const parts: Uint8Array[] = new Array(lines.length); + let next = 0; + await Promise.all(Array.from({ length: Math.min(AT_ONCE, lines.length) }, async () => { + while (next < lines.length) { const k = next++; parts[k] = await say(lines[k].text); } + })); + const { mp3, secs, cues } = joinMp3(parts, GAP); + const put = await r2.fetch(r2Url(at), { method: "PUT", body: mp3, headers: { "Content-Type": "audio/mpeg", "Cache-Control": "public, max-age=31536000, immutable" } }); + if (!put.ok) throw new Error("the store said " + put.status); + await sweep(dir, at); + const audio = { voice, v, secs, cues, path: at }; + const row = await service("/rest/v1/view_voices?on_conflict=owner,view", { method: "POST", headers: { Prefer: "resolution=merge-duplicates" }, body: JSON.stringify({ owner: username, view: slug, script: { style: String(vo.style ?? ""), lines }, audio, updated_at: new Date().toISOString() }) }); + if (!row.ok) console.error("record row", row.status, (await row.text()).slice(0, 300)); + return json({ audio: { voice, v, secs, cues, src: at }, left: Math.max(0, most - total) }); + } catch (e) { + console.error("record", String(e)); await count(-chars); + return json({ error: "The voiceover file could not be made. Try again." }, 502); + } +} async function speak(account: string, ask: any): Promise { const text = String(ask?.text ?? "").replace(/\s+/g, " ").trim().slice(0, 700), voice = String(ask?.voice ?? ""); if (!text || !SPEECH_VOICES.includes(voice)) return json({ error: "That request could not be read." }, 400); const key = Deno.env.get("VOICE_API_KEY") ?? Deno.env.get("OPENROUTER_API_KEY"); if (!key) return json({ error: "The server voice is not switched on yet.", code: "not_configured" }, 503); - const at = await storeKey(voice, text), had = await kept(at); - if (had) return sound(had, null, "store"); - const own = await service(`/rest/v1/profiles?id=eq.${account}&select=plan`).then((r) => (r.ok ? r.json() : [])).catch(() => []); - const SPEECH_MONTHLY = own[0]?.plan === "pro" ? SPEECH_PRO : SPEECH_FREE; - const count = (n: number) => service("/rest/v1/rpc/speech_add", { method: "POST", body: JSON.stringify({ who: account, n, most: SPEECH_MONTHLY }) }).then((r) => (r.ok ? r.json() : -2)).catch(() => -2); + const { most: SPEECH_MONTHLY, count } = await share(account); const total = await count(text.length); if (total === -2) return json({ error: "The server voice could not be reached. Try again." }, 502); if (total < 0) return json({ error: "That is this month's voice used up.", code: "limit" }, 429); @@ -98,7 +179,6 @@ async function speak(account: string, ask: any): Promise { }); if (!r.ok) { console.error("speak", r.status, (await r.text().catch(() => "")).slice(0, 400)); await count(-text.length); return json({ error: "The server voice is busy just now." }, 502); } const buf = await r.arrayBuffer(); - if (buf.byteLength > 2000) await keep(at, buf); return sound(buf, Math.max(0, SPEECH_MONTHLY - total), "made"); } catch (e) { console.error("speak", String(e)); await count(-text.length); @@ -194,6 +274,7 @@ Deno.serve(async (req) => { // ---- a line said by the server, within the account's share of the month if (body.speak) return editor ? json({ error: "Not for the editors' key." }, 400) : speak(user.id, body.speak); + if (body.record) return editor ? json({ error: "Not for the editors' key." }, 400) : record(user.id, body.record); const router = Deno.env.get("OPENROUTER_API_KEY"); if (!router) return json({ error: "Voiceover is not switched on yet.", code: "not_configured" }, 503); diff --git a/supabase/functions/voiceover/mp3.js b/supabase/functions/voiceover/mp3.js new file mode 100644 index 00000000..9f28472f --- /dev/null +++ b/supabase/functions/voiceover/mp3.js @@ -0,0 +1,66 @@ +// One MP3 made of several (asked for, Nov 2026: a published timeline's voiceover is one file, like a wiki +// view's). Each line comes from the server voice as an MP3 of its own; MP3 is a run of frames that stand on +// their own, so the lines are joined frame after frame, with frames of silence between them, and nothing is +// encoded again (an encoder would cost the function more time than it has). Plain JavaScript, so the +// function (Deno) and the tests (Node) share it. + +const KBPS_1 = [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320]; // MPEG-1 Layer III +const KBPS_2 = [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160]; // MPEG-2 and 2.5 Layer III +const RATES = { 3: [44100, 48000, 32000], 2: [22050, 24000, 16000], 0: [11025, 12000, 8000] }; + +// What a frame header says: { len, rate, spf, side } or null when the four bytes at `i` are not one. +function head(b, i) { + if (b[i] !== 0xff || (b[i + 1] & 0xe0) !== 0xe0) return null; + const ver = (b[i + 1] >> 3) & 3, layer = (b[i + 1] >> 1) & 3, bi = b[i + 2] >> 4, sri = (b[i + 2] >> 2) & 3, pad = (b[i + 2] >> 1) & 1; + if (ver === 1 || layer !== 1 || bi === 0 || bi === 15 || sri === 3) return null; + const one = ver === 3, rate = RATES[ver][sri], kbps = (one ? KBPS_1 : KBPS_2)[bi], mono = b[i + 3] >> 6 === 3; + return { len: Math.floor(((one ? 144 : 72) * kbps * 1000) / rate) + pad, rate, spf: one ? 1152 : 576, side: one ? (mono ? 17 : 32) : (mono ? 9 : 17) }; +} + +// The audio frames of one MP3: { frames: [Uint8Array], rate, spf, first } (`first` is a frame to copy the +// header of). The tags before and after, and the frame that only carries the file's length (Xing, Info, +// VBRI), are left out, since the joined file is one new stream. +export function framesOf(bytes) { + const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes), out = []; + let i = 0, rate = 0, spf = 0; + if (b[0] === 0x49 && b[1] === 0x44 && b[2] === 0x33) i = 10 + ((b[6] & 127) << 21 | (b[7] & 127) << 14 | (b[8] & 127) << 7 | (b[9] & 127)) + (b[5] & 0x10 ? 10 : 0); + while (i + 4 <= b.length) { + const h = head(b, i); + if (!h || i + h.len > b.length || (rate && h.rate !== rate)) { i++; continue; } + const f = b.subarray(i, i + h.len), tag = String.fromCharCode(...f.subarray(4 + h.side, 8 + h.side)), vbri = String.fromCharCode(...f.subarray(36, 40)); + if (!out.length && (tag === 'Xing' || tag === 'Info' || vbri === 'VBRI')) { i += h.len; continue; } + rate = h.rate; spf = h.spf; out.push(f); i += h.len; + } + return { frames: out, rate, spf, first: out[0] || null }; +} + +// A frame of silence shaped like `like`: the lowest bit rate, no padding, no checksum, and all its side +// information zero, so a decoder reads no sound in it. +export function silentFrame(like) { + const f = new Uint8Array(4); + f[0] = 0xff; f[1] = like[1] | 1; f[2] = (1 << 4) | (like[2] & 0x0c); f[3] = like[3]; + const h = head(f, 0), out = new Uint8Array(h.len); + out.set(f); + return out; +} + +// Joins the lines' MP3s, `gap` seconds of silence after each. Answers { mp3, secs, cues } with a +// [start, end] in seconds for each line, or throws when the lines are not one kind of MP3. +export function joinMp3(parts, gap = 0.35) { + const got = parts.map(framesOf); + if (!got.length || got.some((g) => !g.frames.length)) throw new Error('a line has no sound'); + const { rate, spf, first } = got[0]; + if (got.some((g) => g.rate !== rate || g.spf !== spf)) throw new Error('the lines are not one kind of MP3'); + const quiet = silentFrame(first), n = Math.max(0, Math.round((gap * rate) / spf)), cues = [], all = []; + let at = 0; + for (const g of got) { + cues.push([+((at * spf) / rate).toFixed(2), +(((at + g.frames.length) * spf) / rate).toFixed(2)]); + all.push(...g.frames); + for (let k = 0; k < n; k++) all.push(quiet); + at += g.frames.length + n; + } + const mp3 = new Uint8Array(all.reduce((s, f) => s + f.length, 0)); + let o = 0; + for (const f of all) { mp3.set(f, o); o += f.length; } + return { mp3, secs: +((at * spf) / rate).toFixed(2), cues }; +} diff --git a/supabase/migrations/20261128030000_publish_cap.sql b/supabase/migrations/20261128030000_publish_cap.sql new file mode 100644 index 00000000..94cbd333 --- /dev/null +++ b/supabase/migrations/20261128030000_publish_cap.sql @@ -0,0 +1,25 @@ +-- The limits of an account, on its own row like `ai_daily`, so each can be changed without new code +-- (asked for, Nov 2026: "in the future, we can make it configurable"; free use must stay within a small, +-- known cost even with many accounts). `stripe-webhook` sets them by plan; one account can be changed by hand. +-- publish_max how many timelines it may have published at once (each with a voiceover keeps one MP3) +-- voice_monthly how many characters a month the server voice may say for it +-- Accounts may still write only their username, so they cannot raise their own limits. +alter table public.profiles add column publish_max integer not null default 10 check (publish_max >= 0); +alter table public.profiles add column voice_monthly integer not null default 5000 check (voice_monthly >= 0); +update public.profiles set publish_max = 1000, voice_monthly = 500000 where plan = 'pro'; + +-- Publishing past the limit is refused here, so no way round the page gets past it. +create function public.publish_cap() returns trigger +language plpgsql security definer set search_path = '' as $$ +declare n integer; most integer; +begin + if new.visibility = 'private' or (tg_op = 'UPDATE' and old.visibility <> 'private') then return new; end if; + select p.publish_max into most from public.profiles p where p.id = new.owner; + select count(*) into n from public.timelines t where t.owner = new.owner and t.visibility <> 'private' and t.id <> new.id; + if n >= coalesce(most, 10) then + raise exception 'You can have % timelines published at once. Make one private or delete one first, or go Pro.', coalesce(most, 10) using errcode = 'P0001'; + end if; + return new; +end $$; +create trigger publish_cap before insert or update of visibility on public.timelines + for each row execute function public.publish_cap(); diff --git a/tests/voice.test.mjs b/tests/voice.test.mjs index 23c19ad6..c0685e57 100644 --- a/tests/voice.test.mjs +++ b/tests/voice.test.mjs @@ -61,11 +61,20 @@ test('the server sends 16-bit samples, low byte first, and the page plays floats assert.deepEqual([...out].map((x) => Math.round(x * 1000) / 1000), [0, 0.5, -1, 1]); }); -test('a line has one name in the store, whoever asks', async () => { - const { storeKey, sayText } = await import('../site/voice.js'); - const a = await storeKey('af_heart', 'Hello there '); - assert.equal(a, await storeKey('af_heart', 'Hello there')); - assert.notEqual(a, await storeKey('bm_george', 'Hello there')); - assert.match(a, /^v1\/af_heart\/[0-9a-f]{64}\.pcm$/); +test('words are said as written, with their spaces made plain', async () => { + const { sayText } = await import('../site/voice.js'); assert.equal(sayText(' a \n b '), 'a b'); }); + +test('a published timeline\'s lines are joined into one MP3, frame by frame, with silence between', async () => { + const { joinMp3, framesOf, silentFrame } = await import('../supabase/functions/voiceover/mp3.js'); + // MPEG-2 Layer III, 24 kHz, one channel: frames of 576 samples, 0.024 s each. + const frame = silentFrame(new Uint8Array([0xff, 0xf3, 0x64, 0xc4])); + assert.equal(frame.length, 24); + const file = (n, tag = false) => { const out = new Uint8Array((tag ? 10 : 0) + n * frame.length); if (tag) out.set([0x49, 0x44, 0x33, 3, 0, 0, 0, 0, 0, 0]); for (let k = 0; k < n; k++) out.set(frame, (tag ? 10 : 0) + k * frame.length); return out; }; + assert.equal(framesOf(file(5, true)).frames.length, 5); + const { mp3, secs, cues } = joinMp3([file(50, true), file(25)], 0.24); + assert.deepEqual(cues, [[0, 1.2], [1.44, 2.04]]); + assert.equal(secs, 2.28); + assert.equal(framesOf(mp3).frames.length, 95); +});