Introducing a new way to review your PRs.

Read the announcement

capsoftware / cap

Open source Loom alternative. Beautiful, shareable screen recordings.

View on GitHub

31 documents · Updated Nov 23, 2026

docs / media-server-and-web-cluster

Media-server runtime service

The media server is a request-driven worker that moves costly media work away from the web application. It reads media from approved URLs or storage, checks and transforms audio and video, creates delivery-ready HLS renditions, supports live transcription, and stores results through caller-provided upload targets. This page extends Media delivery services with the runtime role, container model, source layout, and operating contracts. The related Recording and media verification page covers the wider recording acceptance flow.

Runtime role

The media server provides controlled compute, temporary disk, and media-tool capacity for media work. Trusted callers provide source access and output destinations so large payloads do not pass through the main web application.

Media server role

The service accepts source URLs and processing instructions from trusted callers. It inspects, converts, edits, packages, or prepares streaming media, then reports progress and completion through direct responses, status events, or webhooks. Short work can return a response. Long work uses a local job and writes output through signed upload targets.

Its main responsibilities are:

  • Audio checks, extraction, and MP3 conversion. Audio-only sources are valid for these operations.
  • Video probing, conversion, editing, thumbnails, segment muxing, and HLS ladder creation.
  • Standard-range output from HDR input for browser playback.
  • Optional NVENC or Capcodec encoding.
  • Recovery checks for damaged raw recordings while keeping the original input.
  • Recording verification, packet proof, object identity checks, and upload digests.
  • Optional preverification of recording fragments.
  • Live transcription from growing recording audio.
  • Cancellation, capacity control, isolated media probing, and cleanup during work and shutdown.

The web application owns durable media and transcript records. The media server owns only the local job state needed to run work and send updates.

References: apps/…/app.ts• L3-25 apps/…/index.ts• L9-50 apps/…/audio.ts• L38-45 apps/…/video.ts• L981-1057 apps/…/media-probe-pool.ts• L23-27 apps/…/hls-ladder-encode.ts• L81-297 apps/…/live-transcribe.ts• L404-512 apps/…/job-manager.ts• L66-98

Recording verification

Recording verification is the acceptance step for local and remote MP4 recordings. It decodes the media and checks that video exists, required audio covers the video, timestamps are valid, and the stream has expected content and timeline evidence.

Source-preserving remuxes also use packet proof. This compares stream settings, packet data, packet order, timestamps, and terminal timing. The files must not change during the check. A smaller decoded frame count is accepted only when packet proof is sound and source reference-frame gaps explain the exact shortfall.

Remote verification treats a recording as a versioned object. It checks identity and size before reading, uses conditional range reads, and checks identity again after the read. A changed object, incomplete read, timeout, cancellation, or decoder stall prevents acceptance. Upload digests provide SHA-256 and provider object identities for this check. The probe also measures timestamp span when a container header is short or missing, so an accepted recording is not cut to a false duration.

References: apps/…/recording-verification.ts• L47-67 apps/…/recording-verification.ts• L1333-1543 apps/…/recording-verification.ts• L2248-2509 apps/…/recording-packet-proof.ts• L583-690 apps/…/recording-timing.ts• L314-391 apps/…/upload-digest.ts• L4-43 apps/…/media-probe-read.ts• L321-407 apps/…/recording-verification.integration.test.ts• L578-721

Segment preverification

Segment preverification is an optional speed path for recordings that arrive as ordered fragments. The server decodes fragment runs during capture and stores signed frame evidence bound to source identities and sizes. Final verification reuses only matching evidence.

The signed result is a cache, not an acceptance decision. Missing, altered, misaligned, or stale evidence is discarded and the final path decodes the fragments itself.

References: apps/…/recording-preverify.ts• L5-121 apps/…/recording-verification.ts• L966-1048 apps/…/video.ts• L2734-2885 apps/…/recording-preverify.test.ts• L23-135

HLS delivery ladder

The HLS delivery ladder turns one source into adaptive video renditions. It produces a master playlist, one video playlist and fragmented MP4 file for each selected tier, and one shared AAC audio rendition when audio exists.

The planner chooses tiers without upscaling, keeps the source aspect ratio, caps very wide output at the encoder size limit, and removes duplicate sizes. Renditions use one frame grid and aligned segment boundaries so a player can switch quality without a time jump. HDR input is converted to standard range before scaling and encoding.

The ladder route is asynchronous. The caller supplies upload targets for every generated file. The server downloads and probes the source, encodes the ladder, uploads the files, optionally creates a poster from the largest rendition, and reports the result through the job and webhook contract. A whole recording or a bounded range can be encoded. Range slices can be stitched by playlist without rewriting their media.

OutputPurpose
Master playlistAdvertises video tiers and shared audio.
Video playlists and fragmented MP4 filesProvide switchable video quality.
Audio playlist and fragmented MP4 fileProvide shared audio when present.
Poster imageProvides a still from the largest encoded rendition.

Infra jobs use a larger poster target, up to 1920 pixels on the long side. The normal poster size remains unchanged for other jobs.

References: apps/…/video.ts• L229-250 apps/…/video.ts• L981-1057 apps/…/video.ts• L1459-1604 apps/…/hls-ladder.ts• L103-147 apps/…/hls-ladder.ts• L661-741 apps/…/hls-ladder-encode.ts• L81-315 apps/…/infra-poster.ts• L3-15 apps/…/media-video.ts• L2396-2485 apps/…/hls-ladder-route.integration.test.ts• L149-255 apps/…/infra-poster.integration.test.ts• L177-231

Runtime flow

The web application sends an authenticated job with source access and upload targets. The media server prepares the source, performs the requested work, uploads accepted output, and sends progress or completion back to the web application. A cluster keeps job state on the instance that owns the job and forwards status or cancel requests to configured peers when a request reaches another instance.

This diagram shows the common asynchronous video path.

flowchart LR
    A[Web application] -->|authenticated job| B[Media server instance]
    B -->|read approved source| C[Storage or media URL]
    C --> D[Prepare and inspect]
    D --> E[Validate when required]
    E --> F[Process, edit, or encode ladder]
    F --> G[Verify output]
    G -->|upload accepted media and previews| C
    B -->|progress and completion webhook| A
    A -->|status or cancel| B
    B -.->|owner lookup| P[Peer media-server instances]

Direct file downloads can use bounded byte ranges. The first response establishes size and identity. Later ranges must match, and unsupported ranges fall back to one stream. Segmented recordings use a shared bounded pool with retries. One fatal fragment failure cancels the remaining work. Streaming manifests are first turned into safe local playlists or materialized segments before media tools consume them. Their inherited query data stays on resolved resources, and the service rejects unsupported resource forms.

Live transcription is a separate session flow. The server reads new audio segments from a signed manifest, submits chunks to an AssemblyAI-compatible service, and reports accepted words and a cursor to the web application.

sequenceDiagram
    participant W as Web application
    participant M as Media server
    participant S as Recording storage
    participant A as Speech service
    W->>M: Start session
    loop While recording grows
        M->>S: Read new audio segments
        M->>A: Submit audio chunk
        A-->>M: Transcript words
        M->>W: Report words and cursor
    end
    W-->>M: Stop or release session

Long video jobs move through download, probe, processing, upload, preview, and verification phases. Job state is local to the media-server process. Recording jobs add generation, attempt, worker ownership, and a short lease so two runtimes cannot publish one attempt. Probe work can run in separate bounded workers so a parser fault affects one request instead of the server.

The Loom importer uses a separate queue for large imports. It gives customer work priority over bulk work, restricts source hosts, selects usable HLS or DASH tracks, bounds downloads and previews, and sends terminal updates.

References: apps/…/video.ts• L637-712 apps/…/video.ts• L981-1057 apps/…/video.ts• L1459-1604 apps/…/hls-ladder-encode.ts• L81-297 apps/…/live-transcribe.ts• L104-180 apps/…/live-transcribe.ts• L404-651 apps/…/media-video.ts• L793-1015 apps/…/media-video.ts• L1271-1437 apps/…/parallel-download.ts• L107-218 apps/…/job-manager.ts• L720-935 apps/…/media-probe-pool.ts• L100-199 apps/…/peer-jobs.ts• L6-103 apps/…/job.ts• L185-254 apps/…/job.ts• L319-499

Container model

The media server runs in a standalone Bun container with FFmpeg. Deployment files provide the network path, port, and readiness check.

Media server image

The production image installs Bun and FFmpeg, applies the pinned Mediabunny parser patch, copies the media-server source, exposes port 3456, and checks /health. The repository-root image runs the media test groups during the build. The standalone image supports local Compose and self-hosted use. Both start src/index.ts, and neither includes the optional Capcodec executable.

apps/media-server/Dockerfile builds from the repository root. apps/media-server/Dockerfile.standalone builds from apps/media-server. The package manifest ties Mediabunny 1.45.2 to the patch and lockfile. Capcodec is an external binary. Operators must mount it and set CAPCODEC_BIN before selecting that encoder.

References: apps/…/Dockerfile• L1-54 apps/…/Dockerfile.standalone• L1-27 apps/…/package.json• L1-27 apps/…/bunfig.toml• L1-2 apps/…/mediabunny@1.45.2.patch• L1-118 apps/…/capcodec-encoder.ts• L81-120 apps/…/railway.toml• L1-9 docker-compose.yml• L46-62

Deployment topology

The local Compose setup places the web application and media server on one private service network. The web application addresses the media server by service name. The media server calls back to the web application through the configured webhook URL. In a multi-instance deployment, MEDIA_SERVER_PEERS lets an instance find the owner of an in-memory job. Storage and the database remain the durable systems around this worker.

References: docker-compose.yml• L4-62 docker-compose.coolify.yml• L3-61 apps/…/Dockerfile.standalone• L19-27 apps/…/peer-jobs.ts• L6-103

Source layout

The source layout follows the media workflow. Routes define service contracts. Libraries provide probing, delivery ladder creation, media work, job state, source safety, recording proof, storage transfer, live sessions, and process control. Probe parsing has its own worker boundary because media files are untrusted input.

Media server source

The main service starts at src/index.ts and assembles routes in src/app.ts. Startup installs rejection protection, hides the server from child-process inspection where supported, warms probe workers, and begins temporary-file and transfer-cache maintenance. Shutdown releases sessions, aborts jobs, cancels media operations, stops probe workers, clears transfer state, removes temporary files, and exits cleanly.

Remote inputs pass through address checks and a loopback relay before FFmpeg or FFprobe reads them. Child processes receive a filtered environment. Tool protocol, demuxer, decoder, frame-size, playlist, and content limits prevent input-controlled access to unrelated files or networks.

The important conceptual areas are:

  • routes: health, audio, video, and live transcription contracts.
  • lib/hls-ladder and lib/hls-ladder-encode: adaptive HLS planning, encoding, validation, and slice stitching.
  • lib/media-probe, lib/media-probe-read, and lib/media-probe-pool: source inspection, timestamp measurement, and bounded parser workers.
  • lib/media-video: streaming preparation, processing, upload, and previews. It also turns supported DASH manifests into local HLS views for import and download work.
  • lib/media-address-guard, lib/media-relay, and lib/media-input-policy: checked remote reads and input limits.
  • lib/media-transfer and lib/parallel-download: authorized storage reads, caching, and bounded source transfer.
  • lib/nvenc-encoder, lib/capcodec-encoder, and lib/encode-stall: encoder choice, acceleration, fallback, and stuck-process detection.
  • lib/recording-verification, lib/recording-packet-proof, lib/recording-timing, and lib/upload-digest: recording acceptance evidence.
  • lib/recording-preverify and lib/live-transcribe: fragment evidence and live sessions.
  • lib/job-manager, lib/media-spawn, lib/subprocess, and lib/temp-files: job ownership, child processes, cancellation, and cleanup.
  • lib/isolated-worker-pool and lib/process-hardening: worker limits and protection of server state from media child processes.
  • lib/peer-jobs and lib/runtime-report: cross-instance job lookup and protected runtime status.

References: apps/…/index.ts• L1-70 apps/…/app.ts• L1-53 apps/…/video.ts• L1-53 apps/…/media-video.ts• L793-1015 apps/…/media-video.ts• L1271-1437 apps/…/media-probe-pool.ts• L23-27 apps/…/isolated-worker-pool.ts• L4-8 apps/…/process-hardening.ts• L1-6 apps/…/media-address-guard.ts• L217-402 apps/…/media-input-policy.ts• L17-215 apps/…/media-spawn.ts• L9-135 apps/…/peer-jobs.ts• L6-103 apps/…/runtime-report.ts• L21-62 apps/…/job-manager.ts• L354-418

Loom importer source

The loom-importer source is a separate HTTP application for queued Loom imports. It has its own entry point and drain sequence. Its areas cover approved source fetching, HLS or DASH materialization, track selection and segment prefetch, remuxing, queue and webhook state, and bounded preview creation.

The importer chooses the best usable HLS video variant and its audio rendition. It can tolerate a small amount of missing media while preserving the gap in the result. It also supports audio-only sources by creating a still video track. Compatible H.264/AAC sources become MP4. VP8, VP9, or AV1-compatible sources can remain WebM when the caller provides an original upload target. An AAC copy failure can fall back to audio encoding. Preview failure does not prevent a valid media import from completing.

References: apps/…/app.ts• L84-325 apps/…/index.ts• L1-30 apps/…/fetch.ts• L11-83 apps/…/job.ts• L185-254 apps/…/job.ts• L319-499 apps/…/media.ts• L82-304 apps/…/streaming.ts• L51-161 apps/…/streaming.ts• L231-438 apps/…/preview.ts• L18-38

Operational contracts

Operations depend on contracts for authentication, health, source access, output files, jobs, recording acceptance, transcription, and capacity.

Health surface

The health endpoint reports media-engine availability, effective capacity, system pressure, encoder status, probe-worker status, and drain state. Deployment systems should use it before routing work. Unauthenticated callers receive only the service state. Trusted callers receive runtime and resource detail.

SurfacePurpose
Media server 3456Media HTTP API and /health
/health statusok, degraded, or draining
Protected health detailEngine, encoder, worker, resource, job, and cleanup state

References: apps/…/health.ts• L10-57 apps/…/auth.ts• L26-38 apps/…/runtime-report.ts• L21-62 apps/…/Dockerfile• L48-52 apps/…/health.test.ts• L21-65

Remote input safety

Remote reads are allowed only after checks of URL scheme, resolved address class, and redirect path. Public addresses are allowed. Private hosts must be named by the operator. Reserved addresses remain blocked. Checked DNS results are pinned for the request.

FFmpeg and FFprobe do not enforce this policy themselves. The loopback relay makes every child-process request pass through the guard and does not expose signed source URLs. Streaming playlists use same-host checks and trusted streaming-host rules. Input policy also bounds decoded frame size, allowed containers and codecs, playlist size, and nested resources.

References: apps/…/media-address-guard.ts• L217-263 apps/…/media-address-guard.ts• L273-402 apps/…/media-relay.ts• L8-120 apps/…/media-input-policy.ts• L17-25 apps/…/media-input-policy.ts• L51-77 apps/…/media-input-policy.ts• L212-323 apps/…/media-probe-read.ts• L210-260 apps/…/media-spawn.ts• L32-124 apps/…/media-address-guard.test.ts• L95-176 apps/…/media-probe-hardening.test.ts• L170-235

Media probing

Probing supplies metadata for later work and classifies input failures. It accepts ordinary video, audio-only sources for audio routes, legacy codecs that the configured decoder allowlist can read, and unfinished Matroska or WebM recordings when their tail provides a usable timestamp.

Parser work normally runs in a small worker pool with memory and time limits. A worker that crashes or exceeds a limit is replaced. If workers cannot start, the service falls back to in-process reading so it can still return an answer. Missing source data remains retryable. Unsupported content returns an input error.

References: apps/…/media-probe.ts• L245-328 apps/…/media-probe-read.ts• L276-304 apps/…/media-probe-read.ts• L378-407 apps/…/media-probe-pool.ts• L100-199 apps/…/isolated-worker-pool.ts• L107-205 apps/…/matroska-tail.ts• L251-290 apps/…/media-probe-hardening.test.ts• L170-256 apps/…/matroska-length.test.ts• L236-325 apps/…/isolated-worker-pool.test.ts• L49-129

Live transcription contract

An authenticated start request gives the server a recording ID, callback, signed manifest and segment URLs, and speech-service credentials. The media server keeps session state in memory. It sends accepted words and a cursor to the web application, which owns transcript storage.

Only contiguous available segments advance the cursor. Gaps, stale URLs, speech errors, idle capture, budget limits, stop requests, and shutdown produce bounded retry or terminal states. Capacity and drain return retryable busy responses.

References: apps/…/live-transcribe.ts• L13-49 apps/…/live-transcribe.ts• L104-180 apps/…/live-transcribe.ts• L404-512 apps/…/live-transcribe.ts• L609-689 apps/…/live-transcribe.test.ts• L65-104 apps/…/live-transcribe.test.ts• L293-421

Video encoder selection

Libx264 is the default video path. Capcodec is used only when selected and its executable is present. NVENC is used only when selected. Supported sources can use GPU decoding. HDR and rotated sources stay on the CPU path when GPU decoding cannot preserve the required result.

Non-cancelled NVENC failures fall back to libx264. Stalls and deadlines do not trigger encoder fallback. Encoder attempts and fallback causes appear in protected runtime status and redacted logs. The Capcodec media codec page describes the optional setup.

References: apps/…/nvenc-encoder.ts• L23-33 apps/…/nvenc-encoder.ts• L175-259 apps/…/capcodec-encoder.ts• L293-382 apps/…/encode-stall.ts• L27-84 apps/…/media-video.ts• L1866-2050 apps/…/hls-ladder-encode.ts• L167-217 apps/…/nvenc-encoder.test.ts• L250-315

Input validation

Raw recording validation checks media that may be damaged. Raw WebM work keeps the original input available for recovery. Clean input continues. Damaged input can use recovery. Unreadable input, missing video, unsupported content, or incomplete recovery ends the job before output upload.

The probe and decoder enforce a source frame-size limit. The service measures missing Matroska or WebM lengths from bounded head and tail reads. Encodes use the measured timestamp span plus a small margin, while recovery work has no probe-derived length cap.

References: apps/…/video-input-validation.ts• L7-115 apps/…/media-input-policy.ts• L17-32 apps/…/media-spawn.ts• L98-124 apps/…/media-common.ts• L44-80 apps/…/media-probe-read.ts• L378-407 apps/…/video.ts• L1216-1399 apps/…/encode-length-limit.test.ts• L116-171 apps/…/source-frame-limit.integration.test.ts• L112-217

HLS delivery contract

The authenticated /video/ladder route starts an asynchronous ladder job. The caller supplies a source, optional tier or range, upload targets for every expected playlist and media file, and optional poster and webhook targets. The server reports job phases and publishes completion only after required uploads finish.

The output must have consistent rendition names, media types, and segment boundaries. Missing upload targets or unaligned renditions fail the job rather than publishing a partial ladder. Audio-only input is handled by the audio routes instead of this video ladder contract.

References: apps/…/video.ts• L229-250 apps/…/video.ts• L1027-1106 apps/…/video.ts• L1530-1652 apps/…/hls-ladder.ts• L464-537 apps/…/hls-ladder.ts• L661-758 apps/…/hls-ladder-encode.ts• L253-314 apps/…/hls-ladder-encode.integration.test.ts• L139-180 apps/…/hls-ladder-route.integration.test.ts• L149-255

Recording worker contract

Recording verification and segment muxing can be retried by more than one runtime, but one attempt has one owner. The server derives a stable job identity from recording generation and attempt, claims through the webhook, sends ordered progress, and works only while the web application grants a live lease.

An acknowledgement can accept the worker, point to another owner, supersede the attempt, or mark it stale. A changed request context conflicts. A lost lease cancels local work. Terminal webhook delivery remains retried until acknowledged or cleaned up. Status and cancel calls can locate the owning instance through the peer lookup contract.

References: apps/…/video.ts• L2508-2521 apps/…/video.ts• L2566-2793 apps/…/job-manager.ts• L66-100 apps/…/job-manager.ts• L398-458 apps/…/job-manager.ts• L895-1049 apps/…/peer-jobs.ts• L38-103

Loom import contract

The Loom importer accepts authenticated imports with source and storage details. Customer and bulk lanes share bounded capacity. Source hosts are restricted, downloads use retries and timeouts, and imports have size and disk limits.

The importer selects a usable HLS or DASH track set before downloading segments. It rejects encrypted or byte-range playlists that it cannot safely materialize. A small number of missing segments can be removed from the local playlist. Larger gaps fail the import. An empty video playlist remains an error, while an empty audio rendition can be dropped. Audio-only input receives a still video track so the result remains a playable MP4.

Compatible sources are remuxed where possible. A damaged AAC copy can trigger audio-only re-encoding. VP9 WebM output is stored as the original when its upload target is present, and the completion state points the web application to that deferred source. Valid video can complete when preview creation fails. Incomplete storage uploads are aborted. A full queue or draining importer returns a retryable busy response.

References: apps/…/app.ts• L32-59 apps/…/app.ts• L108-289 apps/…/fetch.ts• L38-171 apps/…/job.ts• L185-254 apps/…/job.ts• L319-499 apps/…/media.ts• L82-304 apps/…/streaming.ts• L51-161 apps/…/streaming.ts• L231-438

Source transfer contract

Large direct sources can use bounded parallel byte ranges. The service requires exact range responses and a stable identity when supplied. Invalid, short, oversized, or changing responses are rejected. Unsupported ranges use one stream.

Internal storage reads return a pinned object identity, size, SHA-256 value, and authorized download target. The server can resume the read and reuse a bounded local cache only after the object checks pass. Segment downloads use a separate bounded pool with transient retries.

References: apps/…/parallel-download.ts• L3-38 apps/…/parallel-download.ts• L107-218 apps/…/media-transfer.ts• L15-28 apps/…/media-transfer.ts• L181-223 apps/…/media-transfer.ts• L225-334 apps/…/media-transfer.ts• L369-513 apps/…/parallel-download.test.ts• L98-332

Capacity and recovery

The server limits active probes, video work, live sessions, imports, and previews. CPU and memory pressure can reduce effective capacity. Busy responses are retryable. Recovery work receives a lower share of capacity. Shared Infra work reserves slots for recording work and limits heavy ladders and slices.

An encode has a separate progress guard. It allows time before the first frame, then stops work when encoder counters and output writes stop advancing. Worker processes are also stopped when they exceed memory or time limits. Shutdown releases sessions, aborts jobs, cancels media operations, clears transfer and temporary-file state, and exits for a clean restart.

References: apps/…/media-operations.ts• L17-53 apps/…/video-capacity.ts• L5-47 apps/…/job-manager.ts• L354-458 apps/…/isolated-worker-pool.ts• L287-358 apps/…/encode-stall.ts• L27-84 apps/…/index.ts• L15-55 apps/…/infra-capacity.test.ts• L67-130

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the media-server URL, shared secrets, webhook receiver, peer lookup secret, and deployment health contract aligned with the web application.
  • Keep HLS tier names, file names, audio mapping, segment boundaries, range stitching, and upload targets aligned with playback consumers.
  • Keep HDR tags, standard-range conversion, posters, MP4 output, and HLS output aligned.
  • Keep remote address checks, DNS pinning, relay use, redirects, private-host configuration, playlist walking, and child-process filtering aligned.
  • Keep source frame limits applied to both probing and FFmpeg or FFprobe decoding.
  • Keep parser worker limits, fallback behavior, and worker health reporting aligned with probe admission.
  • Keep raw-recording validation connected to probing, recovery, conversion, and original-source preservation.
  • Keep cancellation and timeout signals connected to decoding, stalled encodes, processing, previews, transcription, uploads, and isolated workers. A cancelled upload must not continue a retry or leave multipart work without cleanup.
  • Keep live transcription payloads, cursors, signed URLs, session handoff, limits, and drain behavior aligned with the web application.
  • Keep Capcodec and NVENC selection, binaries, devices, architecture, fallback, and timeout budgets aligned with the image and job settings.
  • Keep multipart upload signing, completion, abort, digest, object identity, and provider metadata rules aligned with storage.
  • Keep recording packet proof, timing evidence, object stability, frame-gap acceptance, and verification fallbacks aligned.
  • Keep recording generation, attempt, lease, webhook acknowledgement, progress sequence, and peer ownership rules aligned with the worker owner.
  • Keep preverification optional and bind cached evidence to the same signing secret, identities, sizes, order, and final-decode fallback.
  • Keep media job phases and progress payloads compatible with status clients and webhook consumers.
  • Keep ranged source downloads and segment pools within source request limits.
  • Keep the rejection guard installed before media work and keep signed URLs out of logs.
  • Keep Loom allowlists, queue lanes, import size, disk limits, retries, uploads, previews, and drain behavior aligned with callers.
  • Keep HLS and DASH manifest rules aligned with query inheritance, supported resource protocols, segment limits, track selection, missing-segment tolerance, and audio-only output.
  • Keep deferred WebM imports tied to an original upload target and keep completion metadata aligned with the web application's later processing path.
  • Keep the default container command distinct from the Loom importer entry point.
  • Keep the parser patch, root-image checks, runtime source, probe worker source, and external encoder expectations aligned in the image.

Important failure modes

TriggerConsequenceGuard
Shared secret or peer lookup secret is missing or differsProtected media operations or cross-instance lookup return unauthorizedConfigure one secret set and test both direct and peer paths
FFmpeg, the parser, or the media engine is unavailableHealth is degraded and jobs cannot runUse /health as a deployment gate and keep parser and engine checks in the image build
A probe worker exceeds memory or time or the parser faultsOne probe fails and the worker is replaced; the server remains availableKeep probe isolation enabled and monitor protected worker stats
Remote media bypasses address, relay, protocol, demuxer, decoder, playlist, or frame limitsA source can reach unintended files or networks or consume excess memoryUse the address guard, relay, hardened spawn boundary, playlist checks, and decoder caps
HLS upload targets are incomplete or renditions are unalignedThe ladder is partial or players cannot switch qualityValidate all file targets and reject unaligned playlists
HDR input is encoded without standard-range conversionDelivered video looks flat or has wrong colorsProbe color traits and convert HDR before scaling and encoding
NVENC lacks a usable device or FFmpeg supportThe job falls back to CPU encoding and takes longerCheck encoder status and keep libx264 available
Capcodec is selected without an executableThe encode fails before output is publishedMount an executable binary and set CAPCODEC_BIN
Encoding stops advancingA worker remains occupied without a resultStop stalled work using encoder and output-write progress
Capacity or memory pressure reaches a limitNew work is busy or active work is stoppedRetry busy work and monitor health and capacity
A job status or cancel request reaches a non-owner instance and peers are unavailableThe caller receives a retryable lookup failure instead of a false not-found resultConfigure reachable peers and preserve the peer lookup secret
Recording lease is absent, expired, or supersededWork is cancelled and cannot publish a competing resultTreat webhook ownership and lease state as authoritative
Source or upload links expireThe job fails before durable output existsUse links that cover the full job and handle terminal webhooks
A source returns invalid ranges, changes identity, or is shortThe server rejects the download instead of building corrupt mediaRequire exact ranges and retain the one-stream fallback
Internal storage identity, size, or hash changesThe server rejects stale or mixed bytesUse pinned identity, conditional reads, and final digest checks
Raw input is unreadable or recovery is incompleteThe job ends without publishing outputKeep the original source and make recovery an explicit acceptance path
Verification finds changed packets, invalid timing, missing tracks, or unexplained frame lossThe recording is rejectedRequire packet proof and full evidence before acceptance
Preverification evidence is stale, invalid, or unavailableFinal verification decodes fragments againTreat preverification as an optional cache
Live transcription has a gap, stale URL, speech error, or full session poolThe cursor waits, retries, reports a gap, or the session is busyPublish only contiguous chunks and honor retry limits and drain state
A handled media error creates an unhandled rejectionBun can terminate the process and active jobsInstall the process guard at startup
Loom source, size, disk, queue, or preview limit is exceededImport is rejected, delayed, or completes without previewEnforce allowlists, bounded queues, byte caps, disk checks, and cleanup
A Loom manifest uses encryption, byte ranges, an empty video playlist, or unsupported DASH structureThe import cannot safely materialize the sourceReject unsupported forms and keep the generic DASH fallback for supported resource layouts
Loom loses more segments than the allowed gapThe import fails rather than publishing a badly damaged recordingBound missing segments by count and duration and cancel the remaining prefetch
The importer starts with the main entry pointLoom routes are not availableDeploy the importer entry point when Loom imports are required

Key files

FileWhy to read it
apps/…/app.tsDefines the media server service boundary.
apps/…/index.tsShows startup, probe-worker warmup, signal handling, cleanup, and process protection.
apps/…/video.tsShows video jobs, HLS ladder work, recording ownership, peer lookup, and storage handoff.
apps/…/audio.tsDefines audio checks, audio-only handling, and streamed MP3 delivery.
apps/…/health.tsDefines public health and protected operational status.
apps/…/hls-ladder.tsDefines rendition planning, timing alignment, playlist checks, and stitching.
apps/…/hls-ladder-encode.tsTurns a source into uploadable ladder files and a poster.
apps/…/media-probe.tsDefines metadata, codec, duration, and input classification.
apps/…/media-probe-pool.tsDefines isolated parser work and fallback behavior.
apps/…/isolated-worker-pool.tsDefines bounded child workers and replacement after faults.
apps/…/media-video.tsDefines streaming materialization, video processing, previews, storage uploads, and encoder use.
apps/…/media-address-guard.tsDefines URL checks, DNS pinning, private-host rules, and redirects.
apps/…/media-spawn.tsDefines child-process filtering, decoder limits, and remote-input relay.
apps/…/media-transfer.tsDefines authorized storage reads, resuming, identity checks, and caching.
apps/…/parallel-download.tsDefines bounded ranged downloads and the one-stream fallback.
apps/…/nvenc-encoder.tsDefines accelerated encoder selection and fallback.
apps/…/capcodec-encoder.tsDefines the optional external encoder contract.
apps/…/encode-stall.tsDefines stalled-encode detection.
apps/…/matroska-tail.tsDefines bounded length reads for unfinished Matroska and WebM inputs.
apps/…/recording-verification.tsDefines decoded recording acceptance and fallback evidence.
apps/…/recording-packet-proof.tsDefines source-preserving packet proof.
apps/…/recording-timing.tsDefines bounded packet-timing reads.
apps/…/recording-preverify.tsDefines signed fragment evidence.
apps/…/live-transcribe.tsDefines manifest polling, chunks, cursors, retries, and release.
apps/…/job-manager.tsDefines jobs, leases, capacity, progress, and cleanup.
apps/…/peer-jobs.tsDefines cross-instance status and cancel lookup.
apps/…/app.tsDefines queued Loom import routes and drain behavior.
apps/…/job.tsDefines the Loom import lifecycle, output choice, upload handoff, and terminal state.
apps/…/media.tsDefines source codec decisions, output metadata, and MP4 or WebM packaging.
apps/…/streaming.tsDefines HLS track selection, segment materialization, and missing-segment policy.
apps/media-server/DockerfileDefines the production image and build-time checks.
apps/media-server/Dockerfile.standaloneDefines local and self-hosted image behavior.
apps/…/package.jsonDefines runtime dependencies and the patched parser package.
apps/…/hls-ladder-route.integration.test.tsShows end-to-end ladder, upload, poster, and failure guarantees.
apps/…/media-video.integration.test.tsShows video processing, streaming manifest handling, preview, upload cancellation, and cleanup guarantees.
apps/…/media-probe-hardening.test.tsShows input classification, duration correction, and probe safety guarantees.
apps/…/isolated-worker-pool.test.tsShows worker reuse, limits, cancellation, and replacement guarantees.
apps/…/peer-jobs.test.tsShows cross-instance status and cancel lookup behavior.
apps/…/recording-verification.integration.test.tsShows recording proof and acceptance guarantees.
apps/…/infra-capacity.test.tsShows shared-worker capacity and heavy-ladder limits.
apps/…/import.integration.test.tsShows end-to-end Loom import, track choice, gaps, audio-only input, deferred WebM storage, previews, and cleanup.
apps/…/parsing.test.tsShows supported playlist forms, source restrictions, packaging decisions, and missing-segment limits.
apps/…/parallel-download.test.tsShows ranged download integrity, caps, fallback, metadata checks, and cancellation guarantees.