fix(tools): tell a caption-less video from a throttled route; AAC audio in 9:16 MP4s

- Transcript: a finished live stream answers with a duration and no formats,
  and was being reported as "YouTube is blocking us". The degraded-route test
  now keys on the missing duration (watch page served without its player
  response, seen anonymously on two of the three statics), so real
  no-caption videos get the honest no-captions answer. Global daily cap
  1,500.
- 9:16 converter: request AAC for MP4 output when the browser can encode it
  (Opus-in-MP4 does not play in Safari) and only trim when the video is over
  the 5 minute cap; show a frame in the preview instead of a black box.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
victorcavero14 2026-09-23 01:19:19 +02:00
parent 8a8db96ec3
commit 56484dac02
3 changed files with 41 additions and 10 deletions

View file

@ -9,7 +9,7 @@
import { import {
Input, Output, Conversion, BlobSource, BufferTarget, ALL_FORMATS, Input, Output, Conversion, BlobSource, BufferTarget, ALL_FORMATS,
Mp4OutputFormat, WebMOutputFormat, QUALITY_HIGH, Mp4OutputFormat, WebMOutputFormat, QUALITY_HIGH,
getFirstEncodableVideoCodec, getFirstEncodableVideoCodec, getFirstEncodableAudioCodec,
} from 'mediabunny' } from 'mediabunny'
import { $, track, setStatus, downloadBlob, safeFilename } from './common.js' import { $, track, setStatus, downloadBlob, safeFilename } from './common.js'
@ -138,12 +138,24 @@ async function convert() {
} }
if (!codec) throw new Error('This browser cannot encode video on the page. Try a recent Chrome or Edge.') if (!codec) throw new Error('This browser cannot encode video on the page. Try a recent Chrome or Edge.')
// Audio: AAC in MP4 is what every platform and Safari accept. An AAC
// source is copied untouched (no trim below the cap, same codec); anything
// else is encoded to AAC when this browser can, and left to mediabunny's
// default (Opus) only when it cannot.
let audioCodec
if (format instanceof Mp4OutputFormat) {
audioCodec = (await getFirstEncodableAudioCodec(['aac'])) || undefined
}
const output = new Output({ format, target: new BufferTarget() }) const output = new Output({ format, target: new BufferTarget() })
const compose = makeComposer(W, H, fit, pos, vt.displayWidth, vt.displayHeight) const compose = makeComposer(W, H, fit, pos, vt.displayWidth, vt.displayHeight)
const conversion = await Conversion.init({ const conversion = await Conversion.init({
input, input,
output, output,
trim: { start: 0, end }, // Trimming forces the audio through a re-encode, so only trim when the
// video is actually over the cap.
...(duration > MAX_SECONDS ? { trim: { start: 0, end } } : {}),
...(audioCodec ? { audio: { codec: audioCodec } } : {}),
video: { video: {
codec, codec,
bitrate: QUALITY_HIGH, bitrate: QUALITY_HIGH,

View file

@ -48,7 +48,7 @@ router = APIRouter()
# --------------------------------------------------------------------------- # # --------------------------------------------------------------------------- #
# (window seconds, max hits) per IP, plus one global cap per UTC day. # (window seconds, max hits) per IP, plus one global cap per UTC day.
LIMITS = { LIMITS = {
"transcript": {"per_ip": [(600, 10), (86400, 60)], "global_day": 3000}, "transcript": {"per_ip": [(600, 10), (86400, 60)], "global_day": 1500},
"metadata": {"per_ip": [(600, 12), (86400, 50)], "global_day": 2000}, "metadata": {"per_ip": [(600, 12), (86400, 50)], "global_day": 2000},
} }
@ -254,6 +254,16 @@ def parse_json3(data) -> list:
return out return out
def is_degraded(info: dict) -> bool:
"""True for a watch page YouTube served without its player response.
Keyed on the duration, not on the formats: a finished live stream answers
with a duration and zero formats, and it genuinely has no captions (that
one used to be reported as "YouTube is blocking us").
"""
return not info.get("formats") and not info.get("duration")
class TranscriptError(Exception): class TranscriptError(Exception):
def __init__(self, code: str, message: str, status: int): def __init__(self, code: str, message: str, status: int):
super().__init__(message) super().__init__(message)
@ -357,13 +367,14 @@ def fetch_transcript(video_id: str, lang: Optional[str] = None) -> dict:
"duration": info.get("duration") or 0, "duration": info.get("duration") or 0,
"languages": languages, "languages": languages,
} }
if not kind and not info.get("formats"): if not kind and is_degraded(info):
# A degraded answer: one of the statics returned # A degraded answer: anonymous requests from two
# a player response with no formats and no # of the three statics got the watch page without
# captions at all for a TED talk that has 49 # its player response (title, but no duration, no
# human tracks (23-sep-2026, twice in a row on # formats, no captions) for a TED talk with 49
# the same IP, the other two fine). That is the # human tracks (23-sep-2026); the same routes with
# route, not the video: try the next one. # the cookies answered in full. That is the route,
# not the video: try the next attempt.
errors.append("empty player response") errors.append("empty player response")
continue continue
if not kind: if not kind:

View file

@ -176,3 +176,11 @@ def test_metadata_endpoint_validates_input(monkeypatch):
monkeypatch.setattr(ft, "_generate", lambda prompt: {"tags": ["a b", "c"]}) monkeypatch.setattr(ft, "_generate", lambda prompt: {"tags": ["a b", "c"]})
r = c.post("/api/tools/youtube-metadata", json={"mode": "tags", "topic": "A video about sourdough bread at home"}) r = c.post("/api/tools/youtube-metadata", json={"mode": "tags", "topic": "A video about sourdough bread at home"})
assert r.status_code == 200 and r.json()["tags"] == ["a b", "c"] assert r.status_code == 200 and r.json()["tags"] == ["a b", "c"]
def test_degraded_response_is_the_route_not_the_video():
# anonymous answer from a throttled static: title only
assert ft.is_degraded({"title": "Inside the Mind", "formats": [], "duration": None})
# a finished 24/7 stream: no formats, but a real player response
assert not ft.is_degraded({"title": "lofi", "formats": [], "duration": 121601512})
assert not ft.is_degraded({"formats": [{"id": 1}], "duration": 844})