Skip to content

[codex] fix ASS subtitle font loading - #28

Merged
Quick104 merged 3 commits into
mainfrom
codex/ass-subtitle-fonts
May 30, 2026
Merged

Quick104 merged 3 commits into
mainfrom
codex/ass-subtitle-fonts

Conversation

@Quick104

@Quick104 Quick104 commented May 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes ASS/SSA subtitle rendering for non-Latin scripts in the web player by making fonts explicit instead of relying on browser/local font probing.

  • Advertise a font_bundle_url for embedded ASS/SSA tracks and add an authenticated stream endpoint that extracts font attachments from the source container.
  • Preload embedded font attachment bytes and deterministic Noto Arabic/Thai fallback font bytes before constructing JASSUB.
  • Detect Arabic/Thai by language metadata or subtitle script content, rewrite ASS style font names and inline \fn overrides to the selected fallback, and disable JASSUB local font probing to reduce fontselect console noise.
  • Add web unit coverage for Arabic fallback, Thai fallback/style rewrite, embedded font bundles, ASS content loading, and disabled local probing.
  • Install Noto core/CJK fonts in server images for server-side subtitle paths.

Root Cause

JASSUB/libass only renders missing glyphs through its configured default font and logs fontselect misses while trying to resolve style fonts such as Trebuchet MS. Loading random extra fonts is not enough unless libass can actually select them. Thai tracks rendered as boxes because the default font did not cover Thai, and Arabic could still box for glyphs outside the available fallback set.

Validation

  • pnpm exec vitest run src/player/hooks/useASSSubtitles.test.tsx
  • pnpm exec eslint src/player/hooks/useASSSubtitles.ts src/player/hooks/useASSSubtitles.test.tsx src/player/utils/subtitleFonts.ts src/player/types.ts src/player/hooks/usePlaybackSession.ts
  • pnpm exec tsc -b
  • pnpm exec vite build
  • go test ./...
  • git diff --check

Notes

Real-media playback should still be checked against the Arabic/Thai samples that exposed the issue, especially embedded fonts in MKV releases.

Summary by CodeRabbit

  • New Features

    • Serve downloadable font bundles for embedded ASS/SSA subtitle tracks.
    • Player can load bundled fonts and apply forced fallback fonts for ASS rendering.
  • Enhancements

    • Automatic fallback selection for Arabic and Thai; local font probing disabled for safer behavior.
    • Runtime images include additional Noto font packages.
  • Tests

    • Added tests covering font extraction and player font handling.

Review Change Stack

@coderabbitai

coderabbitai Bot commented May 30, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds backend extraction and API endpoints for embedded ASS/SSA subtitle fonts, advertises per-track font_bundle_url, provides frontend fallback/font-loading utilities, integrates font delivery into useASSSubtitles, and adds tests and runtime font packages.

Changes

Embedded ASS/SSA Subtitle Font Bundle Support

Layer / File(s) Summary
Backend font extraction infrastructure
internal/playback/subtitle_fonts.go
ffprobe/ffmpeg probe-and-extract pipeline for embedded font attachments with heuristics, per-attachment and total size limits, safe display names, and JSON/base64 helpers.
API font endpoint and subtitle metadata
internal/api/handlers/stream.go, internal/api/handlers/playback.go, internal/api/router.go, internal/proxy/server.go
New authenticated stream endpoint /stream/{session_id}/subtitles/{track}/fonts that extracts and returns base64 font bundles; playback responses include font_bundle_url for ASS/SSA tracks and proxy rewrites it when needed.
Frontend subtitle types and session enrichment
web/src/player/types.ts, web/src/player/hooks/usePlaybackSession.ts
Adds optional font_bundle_url to PlayerSubtitleInfo and computes client stream URLs for advertised font bundle endpoints.
Frontend font fallback & loaders
web/src/player/utils/subtitleFonts.ts
Defines Noto Arabic/Thai fallback fonts, language/script selection, cached loaders for fallback font files and bundled-manifest endpoints with size-aware eviction, base64 decoding, and ASS rewriting to force font families.
Frontend subtitle rendering with fonts
web/src/player/hooks/useASSSubtitles.ts
Fetches ASS content and attached font bundles concurrently with abort support, computes fallback fonts, loads font bytes, rewrites ASS, and initializes JASSUB with explicit fonts, defaultFont, and queryFonts: false.
Frontend tests
web/src/player/hooks/useASSSubtitles.test.tsx
Tests validate fallback selection (Arabic/Thai vs Latin), fetched ASS content usage, attached font bundle preloading, and disabled local font probing.
Backend tests and helpers
internal/playback/subtitle_fonts_test.go
Unix-only tests for extraction and over-limit rejection, plus test helper to write executable scripts.
System dependencies
Dockerfile, Dockerfile.dev, web/package.json
Runtime images install fonts-noto-core and fonts-noto-cjk; frontend deps add @fontsource/noto-sans-arabic and @fontsource/noto-sans-thai.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant PlaybackHandler
  participant StreamHandler
  participant ExtractAttachedSubtitleFonts
  participant ffprobe
  participant ffmpeg
  Client->>PlaybackHandler: GET /playback/start
  PlaybackHandler-->>Client: subtitle_urls (font_bundle_url)
  Client->>StreamHandler: GET /stream/{session}/subtitles/{track}/fonts
  StreamHandler->>ExtractAttachedSubtitleFonts: inputPath, ffmpegPath
  ExtractAttachedSubtitleFonts->>ffprobe: probe attachment streams
  ffprobe-->>ExtractAttachedSubtitleFonts: stream JSON
  ExtractAttachedSubtitleFonts->>ffmpeg: extract attachment (stdout)
  ffmpeg-->>ExtractAttachedSubtitleFonts: font bytes
  ExtractAttachedSubtitleFonts-->>StreamHandler: []SubtitleFontAttachment
  StreamHandler-->>Client: JSON [{name, data}]
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Poem

🐰 I nibble bytes and fonted threads,
Extracting glyphs for subtitle heads.
Arabic curves and Thai lines bloom,
From ffmpeg’s pipe to the web-room.
JASSUB sings with fonts in place—hooray! 🎶

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.81% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title '[codex] fix ASS subtitle font loading' directly describes the main change: fixing ASS/SSA subtitle font loading for non-Latin scripts by adding explicit font handling instead of relying on browser/local font probing.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/ass-subtitle-fonts

Comment @coderabbitai help to get the list of available commands and usage tips.

@Quick104
Quick104 marked this pull request as ready for review May 30, 2026 17:08

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/api/handlers/stream.go`:
- Around line 299-334: The handler currently calls
playback.ExtractAttachedSubtitleFonts directly and returns a 500 when the file
is missing; call playback.Preflight (or the project's equivalent preflight
function) on file.FilePath (using r.Context() and h.FFmpegPath) before calling
playback.ExtractAttachedSubtitleFonts so missing/unavailable-file errors follow
the same abort flow as other stream handlers; if the preflight returns an error,
map it to the existing not-found/missing-file response (use writeError the same
way as the earlier file-not-found handling) and only proceed to
ExtractAttachedSubtitleFonts when preflight succeeds.

In `@internal/playback/subtitle_fonts.go`:
- Around line 199-206: ffprobePathFromFFmpeg rewrites the last "ffmpeg"
occurrence in the entire path which breaks when a parent directory contains
"ffmpeg"; instead make the replacement against the basename only: use
filepath.Base(ffmpegPath) and filepath.Dir(ffmpegPath), find/replace "ffmpeg" in
the base (preserving any suffix like ".exe"), then join dir and the new base
with filepath.Join; keep the existing fallbacks (empty input -> "ffprobe" and
default "ffprobe" when replacement not possible).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: f4a46fde-1323-41a4-bfd0-e326a553f707

📥 Commits

Reviewing files that changed from the base of the PR and between 09c1f23 and afc7763.

⛔ Files ignored due to path filters (1)
  • web/pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (12)
  • Dockerfile
  • Dockerfile.dev
  • internal/api/handlers/playback.go
  • internal/api/handlers/stream.go
  • internal/api/router.go
  • internal/playback/subtitle_fonts.go
  • web/package.json
  • web/src/player/hooks/useASSSubtitles.test.tsx
  • web/src/player/hooks/useASSSubtitles.ts
  • web/src/player/hooks/usePlaybackSession.ts
  • web/src/player/types.ts
  • web/src/player/utils/subtitleFonts.ts

Comment thread internal/api/handlers/stream.go Resolved
Comment thread internal/playback/subtitle_fonts.go Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
internal/proxy/server.go (1)

207-225: 💤 Low value

Missing ASS/SSA track validation in proxy handler.

The authenticated handler in stream.go validates that the requested track is ASS/SSA before extracting fonts (lines 315-318), but this proxy handler extracts fonts for any track type without validation. This inconsistency allows unnecessary font extraction for non-ASS tracks (e.g., VTT/SRT) where fonts are irrelevant.

Consider adding track codec validation. The claims struct would need to carry subtitle track metadata, or the handler could accept this as a known limitation since invalid requests waste resources but don't cause incorrect behavior.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/proxy/server.go` around lines 207 - 225, handleSubtitleFonts
currently parses the subtitle track but does not validate the track codec before
calling playback.ExtractAttachedSubtitleFonts; update this handler to only
attempt font extraction for ASS/SSA tracks by reusing the same validation logic
used in the authenticated handler in stream.go (i.e., after parsing track via
playback.ParseSubtitleTrackParam, check the track codec/type and return 400 (or
skip extraction) if it is not ASS/SSA), and if necessary extend the claims
struct to carry subtitle track metadata used for validation or fetch the track
codec from the same source stream.go uses so that ExtractAttachedSubtitleFonts
is only called for ASS/SSA tracks.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@internal/proxy/server.go`:
- Around line 207-225: handleSubtitleFonts currently parses the subtitle track
but does not validate the track codec before calling
playback.ExtractAttachedSubtitleFonts; update this handler to only attempt font
extraction for ASS/SSA tracks by reusing the same validation logic used in the
authenticated handler in stream.go (i.e., after parsing track via
playback.ParseSubtitleTrackParam, check the track codec/type and return 400 (or
skip extraction) if it is not ASS/SSA), and if necessary extend the claims
struct to carry subtitle track metadata used for validation or fetch the track
codec from the same source stream.go uses so that ExtractAttachedSubtitleFonts
is only called for ASS/SSA tracks.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: d25dfbbe-a4b1-49e4-936f-c8922498f5fa

📥 Commits

Reviewing files that changed from the base of the PR and between afc7763 and 6c6195b.

📒 Files selected for processing (6)
  • internal/api/handlers/playback.go
  • internal/api/handlers/stream.go
  • internal/playback/subtitle_fonts.go
  • internal/playback/subtitle_fonts_test.go
  • internal/proxy/server.go
  • web/src/player/utils/subtitleFonts.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/api/handlers/playback.go
  • web/src/player/utils/subtitleFonts.ts

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
internal/playback/subtitle_fonts_test.go (1)

70-81: ⚡ Quick win

Consider testing edge cases for ffprobePathFromFFmpeg.

The test currently covers the main scenarios (basename replacement and fallback), but could be more comprehensive by adding cases for:

  • Just "ffmpeg" with no directory component
  • Absolute paths (e.g., "/usr/bin/ffmpeg")
  • Empty string input
  • Path already ending in "ffprobe"

These edge cases would help ensure the function handles all inputs correctly and prevent potential bugs.

🧪 Example additional test cases
 	got = ffprobePathFromFFmpeg(filepath.Join("tmp", "ffmpeg-tools", "custom"))
 	if got != "ffprobe" {
 		t.Fatalf("ffprobePathFromFFmpeg custom basename = %q, want ffprobe", got)
 	}
+
+	// Edge case: just the basename
+	got = ffprobePathFromFFmpeg("ffmpeg")
+	if got != "ffprobe" {
+		t.Fatalf("ffprobePathFromFFmpeg bare ffmpeg = %q, want ffprobe", got)
+	}
+
+	// Edge case: absolute path
+	got = ffprobePathFromFFmpeg(filepath.Join(string(filepath.Separator), "usr", "bin", "ffmpeg"))
+	want = filepath.Join(string(filepath.Separator), "usr", "bin", "ffprobe")
+	if got != want {
+		t.Fatalf("ffprobePathFromFFmpeg absolute path = %q, want %q", got, want)
+	}
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/playback/subtitle_fonts_test.go` around lines 70 - 81, Add unit
tests for ffprobePathFromFFmpeg to cover edge cases: call ffprobePathFromFFmpeg
with just "ffmpeg" (expect "ffprobe"), with an absolute path like
"/usr/bin/ffmpeg" (expect "/usr/bin/ffprobe"), with an empty string (decide and
assert expected behavior, e.g., ""), and with a path already ending in "ffprobe"
(expect the same input back). Update TestFFprobePathFromFFmpeg or add a new
table-driven test that includes these cases and asserts the returned value for
each input using the existing test helper pattern.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@internal/playback/subtitle_fonts_test.go`:
- Around line 70-81: Add unit tests for ffprobePathFromFFmpeg to cover edge
cases: call ffprobePathFromFFmpeg with just "ffmpeg" (expect "ffprobe"), with an
absolute path like "/usr/bin/ffmpeg" (expect "/usr/bin/ffprobe"), with an empty
string (decide and assert expected behavior, e.g., ""), and with a path already
ending in "ffprobe" (expect the same input back). Update
TestFFprobePathFromFFmpeg or add a new table-driven test that includes these
cases and asserts the returned value for each input using the existing test
helper pattern.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: d302c8a6-8ea9-48bc-a437-9fc370fa4402

📥 Commits

Reviewing files that changed from the base of the PR and between 6c6195b and eddaea6.

📒 Files selected for processing (3)
  • internal/api/handlers/stream.go
  • internal/playback/subtitle_fonts.go
  • internal/playback/subtitle_fonts_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/api/handlers/stream.go
  • internal/playback/subtitle_fonts.go

@Quick104
Quick104 merged commit 50d5ffe into main May 30, 2026
2 checks passed
@Quick104
Quick104 deleted the codex/ass-subtitle-fonts branch May 30, 2026 18:26
Quick104 added a commit to thezak48/silo-server that referenced this pull request Jun 7, 2026
Quick104 added a commit that referenced this pull request Jun 11, 2026
Quick104 added a commit that referenced this pull request Jun 17, 2026
Quick104 added a commit that referenced this pull request Jun 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant