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-delivery-services

Media delivery services

Media delivery services provide separate runtime capacity for media work that should not run in the main web application. The media server accepts protected requests, processes media through temporary work and storage, imports hosted recordings, and reports results for playback, recovery, editing, and transcription. See Media server and web cluster for the relationship between this service and the web cluster.

Service boundary

The media server keeps costly media work away from normal web traffic. The web application remains the owner of durable media records and user-facing state. The media server owns the work needed to create or inspect media and returns direct results or tracked job updates.

Media server runtime

The media server is a protected service for video and audio delivery, conversion, editing, preview creation, segment assembly, recording checks, live transcription, and hosted recording import. Callers provide time-limited source and storage links so large media payloads do not pass through the main web tier. The service exposes health, audio, video, and live-transcription areas through apps/…/app.ts.

Its broad workload groups are:

  • Direct media inspection, conversion, thumbnail creation, audio extraction, and streaming.
  • Tracked video processing, editing, preview generation, and storage delivery.
  • HLS rendition ladders for playback at several sizes and bit rates.
  • Segment assembly and recording verification before a result becomes publishable.
  • Live transcription of growing recordings through an external speech service.
  • Loom recording import from signed media files and HLS or DASH sources.

References: apps/…/app.ts• L23-51 apps/…/audio.ts• L150-214 apps/…/video.ts• L912-1105 apps/…/live-transcribe.ts• L13-49 apps/…/job.ts• L319-499

Media job ownership

Short work can return a media response to the caller. Long work returns a job identifier and moves through states such as download, probe, processing, upload, complete, error, or cancelled. The media server sends progress and terminal updates to the web application, but the web application decides how those updates affect durable records.

Jobs live in the memory of the instance that runs them. When a status or cancel request reaches another instance behind a load balancer, the media server asks configured peers before it reports that the job is missing. An unavailable peer is not treated as proof that the job does not exist.

Job ownership also supports recording workers that can lose a lease or be replaced. The service must not let a late update revive a cancelled or superseded attempt. This keeps retries safe when a worker or network link fails during a long operation.

References: apps/…/job-manager.ts• L17-35 apps/…/job-manager.ts• L119-190 apps/…/job-manager.ts• L895-1049 apps/…/peer-jobs.ts• L6-103

Media processing flow

Media work moves between a caller, the media server, temporary local work, and object storage. The caller supplies protected access links and receives either a direct media response or a job state that points to the stored result.

This diagram shows the shared boundary for direct work, long-running work, and hosted recording import.

flowchart LR
    A[Web application] -->|authenticated request| B[Media server]
    S[Source media or stream] -->|time-limited link| B
    B -->|download and inspect| T[Temporary media work]
    T -->|convert, edit, assemble, or encode| O[Output media]
    O -->|signed upload| D[Object storage]
    B -->|direct response or job state| A
    B -->|progress and terminal webhook| A

Direct media delivery

Direct operations inspect or transform media for an immediate caller response. They use bounded downloads, media-engine time limits, and cleanup so a slow source or stalled encoder does not hold service capacity forever. Streaming responses have their own idle protection because media may take time to produce its first bytes.

References: apps/…/audio.ts• L150-347 apps/…/video.ts• L650-910 apps/…/media-common.ts• L36-123 apps/…/encode-stall.ts• L27-84

Asynchronous media jobs

Asynchronous processing starts with a source download and media probe. The service then converts or edits the source, creates optional preview assets, uploads the main result, and reports the final state. Temporary files and unfinished transfers are removed when work completes, fails, or is cancelled.

The same job model supports segment assembly. It combines ordered video and optional audio segments into an MP4, then verifies the result before the service reports success. A multipart storage target can be used for large outputs and must be completed or aborted as one attempt.

Ordinary source files can use bounded parallel range downloads when the source supports them. The service falls back to one stream when range metadata is unavailable, and it rejects a response whose byte ranges do not describe the expected object.

References: apps/…/video.ts• L912-1024 apps/…/video.ts• L1452-1604 apps/…/media-transfer.ts• L135-179 apps/…/media-transfer.ts• L369-512 apps/…/media-video.ts• L1271-1437 apps/…/parallel-download.ts• L1-20

Hosted recording import

Hosted recording import brings a signed recording into the media system as a durable video result. It accepts a media file or a trusted HLS or DASH presentation, selects a usable video and audio combination, downloads the source within byte and concurrency limits, and packages it in a browser-friendly format.

The import keeps compatible WebM recordings as original media when the web application supplies a separate original-upload target. Compatible H.264 and AAC media becomes MP4. Audio-only recordings receive a still video track so downstream video records keep one common shape. Small missing segment gaps can be removed with their time accounted for. Larger loss, unsupported stream features, or missing storage targets fail the import instead of producing an incomplete result.

After packaging, the service probes metadata, uploads the result and optional thumbnail or preview GIF, updates the job, and sends a terminal webhook. It removes temporary files and unused upload attempts in both success and failure paths.

This diagram shows how a hosted recording becomes a stored media result.

flowchart TD
    A[Signed recording source] --> B[Source and manifest checks]
    B --> C[File or HLS/DASH download]
    C --> D[Codec and timing inspection]
    D --> E[MP4 or original WebM packaging]
    E --> F[Metadata and preview assets]
    F --> G[Storage upload]
    G --> H[Job state and terminal webhook]

References: apps/…/job.ts• L66-112 apps/…/job.ts• L185-255 apps/…/job.ts• L319-499 apps/…/media.ts• L82-304 apps/…/streaming.ts• L51-181 apps/…/streaming.ts• L258-438

HLS rendition delivery

An HLS rendition ladder is a set of playback versions at different sizes and bit rates. The service selects versions that fit the source without upscaling, keeps their segment boundaries aligned, and publishes a master playlist with optional shared audio. This lets a player change quality during playback while keeping one timeline.

Long recordings can be encoded as time-aligned slices. The service joins the slice playlists in order without rewriting the media data, then uploads the master playlist, variant playlists, media files, and an optional poster. A missing upload target or misaligned slice prevents the job from becoming complete.

The same ladder path supports Cap Infra video delivery. Infra jobs use a larger poster when the player needs a full-size image, while the shared ladder still provides the playback renditions.

References: apps/…/hls-ladder.ts• L105-149 apps/…/hls-ladder.ts• L159-203 apps/…/hls-ladder.ts• L591-619 apps/…/hls-ladder.ts• L671-758 apps/…/hls-ladder-encode.ts• L83-129 apps/…/hls-ladder-encode.ts• L253-309 apps/…/infra-poster.ts• L3-15 apps/…/video.ts• L1027-1105

Recording publication

Recording publication is a proof step rather than a simple upload check. The service compares decoded content, timing, tracks, and source evidence when required. It also checks the identity and size of the remote object so verification refers to the same bytes that were uploaded. Only a verified result receives a completion state.

The service can reuse bounded evidence from earlier fragment checks. Invalid, incomplete, or mismatched evidence causes the affected media to be checked again instead of allowing a partial result to pass.

References: apps/…/recording-verification.ts• L1017-1128 apps/…/recording-verification.ts• L1936-2246 apps/…/recording-timing.ts• L330-390 apps/…/recording-packet-proof.ts• L583-691

Live transcription

Live transcription follows a growing recording while audio becomes available. The media server reads new audio segments, sends bounded chunks to a speech service, and reports words and a cursor to the web application. The web application owns the transcript and accepted cursor, so a lost session can restart without making the media server the source of truth.

References: apps/…/live-transcribe.ts• L3-42 apps/…/live-transcribe.ts• L404-689 apps/…/live-transcribe.ts• L13-49

Input trust boundary

The media server treats source links and media files as untrusted inputs. It validates where a source may be read, limits what a playlist may name, and constrains the media tools that can open nested resources.

Remote media inputs

Remote media uses HTTP or HTTPS and must pass an address check before the service reads it. Public hosts are allowed. Private hosts require an explicit operator allow-list, while reserved addresses remain blocked. Every redirect is checked again. The service pins name-based requests to the addresses that passed the check.

Media tools read remote files through a local relay because tools such as FFmpeg can resolve names and redirects without using the application's fetch rules. The relay forwards only active media requests and releases its source mapping when the child process ends.

References: apps/…/media-address-guard.ts• L236-345 apps/…/media-address-guard.ts• L367-421 apps/…/media-relay.ts• L38-121 apps/…/media-spawn.ts• L127-187

Streaming input policy

HLS and DASH sources are accepted only from configured trusted streaming hosts. The service checks manifests and their nested resources before media processing. It permits supported HTTP(S) resources on the source host and rejects local-file links, off-host references, unsafe protocols, and ordinary files that are actually playlists.

Hosted recording imports apply an additional source rule: Loom sources must use approved Loom hosts or an exact configured local host. The importer selects supported HLS tracks, rejects encrypted or byte-range playlists it cannot prefetch, and limits tolerated missing segments so a damaged recording does not become a false complete result.

This policy keeps a stream manifest from turning a media request into access to local files or unrelated network resources. A trusted manifest created by the service is treated differently from an arbitrary local playlist because it has already crossed the controlled boundary.

References: apps/…/media-input-policy.ts• L267-341 apps/…/media-probe-read.ts• L173-260 apps/…/media-probe-read.ts• L276-303 apps/…/media-video.ts• L958-1000 apps/…/fetch.ts• L1-120 apps/…/streaming.ts• L130-181 apps/…/streaming.ts• L214-243

Media format protection

The service limits source frame size and constrains parser work so a small file cannot claim an unsafe amount of media data. It also checks supported formats before a long job starts. The media engine receives safe demuxer, decoder, protocol, and frame-size boundaries when it opens an untrusted source.

Parser reads run in separate probe workers by default. A worker can be stopped for excess memory, time, or a parser fault, which keeps a damaged file from taking down the server. If a worker cannot start, the service falls back to an in-process read so it can still answer the request.

References: apps/…/media-input-policy.ts• L17-25 apps/…/media-spawn.ts• L32-124 apps/…/media-probe-pool.ts• L23-27 apps/…/media-probe-pool.ts• L100-199 apps/…/isolated-worker-pool.ts• L1-18 apps/…/mediabunny@1.45.2.patch• L9-15

Output and encoding model

The service aims to produce media that downstream players and storage systems can use without knowing which encoder or source type was selected. Encoding choices change the work path, not the caller-facing result contract.

Colour and playback compatibility

HDR means a source uses a wider brightness and colour range than standard video. The service converts supported HDR sources to standard range before it creates MP4 or HLS output, and it keeps the source orientation and playback geometry. Unsupported HDR forms fail instead of producing output with misleading colours.

The HLS ladder uses one shared frame grid and aligned segment cuts across renditions. This makes quality switching and separately encoded slices produce the same playback timeline.

References: apps/…/hdr.ts• L6-15 apps/…/hdr.ts• L63-107 apps/…/hls-ladder.ts• L157-201 apps/…/hls-ladder.ts• L227-305 apps/…/hls-ladder-encode.ts• L115-165

Encoding acceleration

Video encoding can use the standard CPU path or an optional accelerated path. A deployment can select NVENC or capcodec when the needed runtime support exists. If an NVENC attempt fails for a normal encoder error, the service retries with the CPU encoder and reports the fallback in status. Cancellation and deadline failures do not start a second attempt.

Capcodec is an external executable supplied by the deployment rather than by the standard image. The service checks that it is executable before use and keeps the same size, frame-rate, progress, cancellation, and timeout contract as the other encoder paths.

References: apps/…/nvenc-encoder.ts• L23-33 apps/…/nvenc-encoder.ts• L175-225 apps/…/hls-ladder-encode.ts• L167-217 apps/…/capcodec-encoder.ts• L81-120 apps/…/capcodec-encoder.ts• L293-382 apps/…/capcodec.md• L1-16

Resource and deployment model

Media operations use separate capacity signals because probing, downloading, encoding, uploads, and transcription can compete for CPU, memory, storage, and network time. The service rejects new work when it cannot start safely and lets callers retry instead of hiding overload inside a long request.

Capacity and lifecycle

Capacity limits cover direct video work, probes, transfers, HLS jobs, live sessions, and hosted imports. CPU and memory pressure can lower effective capacity. Probe workers also have their own pool and per-worker memory and time limits. Cap Infra work keeps reserved capacity for recordings and limits heavy ladder work so one class of workload does not consume all shared resources.

Hosted imports also bound per-job and global segment downloads. They wait for a minimum free-space level before using temporary storage, because a source can require both downloaded segments and a packaged output at the same time.

A stalled process, expired job, cancelled request, or failed verification stops its work and releases its resources. The service enters a draining state during shutdown. It rejects new work while active requests and jobs finish within the deployment grace period. Health reports distinguish normal, degraded, and draining states so the deployment system can stop sending work before termination.

References: apps/…/job-manager.ts• L192-360 apps/…/job-manager.ts• L363-458 apps/…/media-probe-pool.ts• L57-127 apps/…/isolated-worker-pool.ts• L287-358 apps/…/runtime-report.ts• L21-62 apps/…/health.ts• L12-57 apps/…/index.ts• L31-64 apps/…/job.ts• L101-112 apps/…/streaming.ts• L198-205

Deployment image

The media server is a separate deployable image with Bun, FFmpeg, the media engine, health checks, and build-time media tests. The standard image is built from the repository workspace. apps/media-server/Dockerfile.standalone supports a self-contained deployment with an explicit private-media host setting for a nearby storage service.

The container entrypoint prepares temporary and GPU cache volumes, then runs the server and its media tools as an unprivileged user when the required permissions are available. It keeps root only when the selected user cannot write its work areas or use the encoder devices. The server hides its own process details from child processes where the platform supports it, and child processes receive a reduced environment.

The media engine dependency is patched and checked during image installation to bound parser work. The image must therefore keep its lockfile, patch, Bun settings, FFmpeg runtime, entrypoint, and health probe aligned. The build does not make capcodec a default executable; accelerated codec support remains a deployment choice.

References: apps/…/Dockerfile• L1-64 apps/…/Dockerfile.standalone• L1-38 apps/…/docker-entrypoint.sh• L4-92 apps/…/process-hardening.ts• L1-48 apps/…/media-spawn.ts• L12-23 apps/…/package.json• L1-27 apps/…/mediabunny@1.45.2.patch• L1-133

Change checklist

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

  • Keep the web application request schema, job phases, progress payloads, webhook acknowledgements, peer lookup results, and retry states aligned.
  • Keep HLS tier planning, playlist names, segment boundaries, shared audio, slice stitching, upload targets, and poster selection aligned.
  • Keep hosted import source-host rules aligned with manifest rewriting, HLS track selection, segment prefetch, and local playlist trust.
  • Keep parallel range download validation aligned with byte caps, fallback-to-stream behavior, cancellation, and source object identity.
  • Keep import codec decisions aligned with MP4 or original WebM targets, audio-only handling, metadata, deferred processing, and upload cleanup.
  • Keep remote URL checks aligned with the media relay, FFmpeg protocol limits, playlist rewriting, and private-host deployment settings.
  • Keep source frame limits aligned between probing, spawned media tools, parser protection, and source download caps.
  • Keep probe worker limits and fallback behavior aligned with probe capacity, parser error mapping, health data, and shutdown.
  • Keep HDR traits aligned between probing, MP4 processing, HLS encoding, thumbnails, and the supported colour conversion path.
  • Keep NVENC and capcodec selection aligned with available runtime support, encoder status, fallback time, progress, and capacity reserved for a CPU retry.
  • Keep recording proof bound to source identities, object size, output identity, timing evidence, and immutable upload attempts.
  • Keep direct and multipart storage contracts aligned with completion, abort, retry, and remote verification behavior.
  • Keep shutdown grace time aligned with jobs, probe workers, subprocesses, live sessions, and background transfer work.
  • Keep the Bun and FFmpeg versions aligned with parser limits, stream handling, HLS features, and recording verification.

Important failure modes

TriggerConsequenceGuard
A source resolves to a private or reserved address without an allowed host nameThe source is rejected before the media tool reads itCheck every resolved address and every redirect. Allow only named private hosts.
FFmpeg receives a remote input outside the relayTool-level redirects or name resolution can bypass the URL policyRoute remote FFmpeg and ffprobe inputs through the guarded relay.
A playlist names an off-host, local-file, or unsupported resourceThe stream is rejected before nested resources are readWalk trusted manifests and allow only the approved host and protocols.
A hosted import uses an unapproved host, encrypted playlist, or unsupported byte rangeThe import fails before it can publish a misleading recordingRequire approved source hosts and prefetchable HLS resources.
A ranged response changes object identity or has mismatched byte-range metadataThe assembled file is rejected rather than silently corruptedValidate each range and fall back to one stream only when ranges are unsupported.
A parser worker exceeds its memory or time limit or hits a faultThe worker stops and the media operation fails without taking down the serverRun parser reads in isolated workers with bounded resources and map worker loss to an unreadable input.
A probe worker cannot startThe server may lose parser isolation for that operationFall back to an in-process probe and report the condition in runtime data.
A hosted recording loses more segments than its gap budget allowsThe import ends in error instead of hiding a large gapAllow only bounded missing segment time and count.
A ladder slice has different renditions or segment cutsThe combined playlist can switch incorrectly or lose framesRequire matching rendition sets and aligned segment durations before upload.
A required ladder upload target is missing or an upload failsThe job ends in error without publishing an incomplete ladderValidate every produced file and stop sibling uploads on failure.
A WebM import has no original upload targetThe job cannot preserve the source required for deferred processingRequire the original-media target before accepting that codec set.
AAC stream copy fails during hosted importThe first packaging attempt fails even though the recording may be usableRetry by encoding only the audio when the failure matches a known AAC copy error.
NVENC fails on a supported jobThe accelerated attempt fails and the job needs more CPU timeRetry with the CPU encoder only for normal encoder errors. Reserve the retry budget.
Capcodec is selected without an executable binaryThe encode cannot startCheck the binary before work begins and provide it through the deployment.
A recording source or uploaded output changes during verificationThe service cannot prove that the published object matches the checked mediaPin source and output reads with object identity, size, and hash checks.
CPU, memory, transfer, or process capacity is exhaustedNew work returns busy or active work stops before a complete result existsHonor busy responses, deadlines, cancellation, and retryable job states.
A status or cancel request reaches a peer that is unavailableThe request cannot prove that the job is missingDistinguish unavailable peers from peers that answered with a definite miss.
Shutdown starts before active work drainsNew work is rejected and in-flight work can be cut off at terminationGive the service a grace period that covers its active work.

Key files

FileWhy to read it
apps/…/app.tsShows the service boundary for health, audio, video, and transcription.
apps/…/video.tsShows how direct requests and tracked video jobs reach processing, storage, ladders, and webhooks.
apps/…/job-manager.tsShows job ownership, progress, leases, capacity signals, and terminal delivery.
apps/…/peer-jobs.tsShows how status and cancel requests find jobs on other media-server instances.
apps/…/media-video.tsShows the shared media capabilities used by conversion, previews, streaming, downloads, and output delivery.
apps/…/parallel-download.tsShows bounded range downloads and the single-stream fallback used for large source files.
apps/…/job.tsShows the hosted recording import lifecycle from source preparation to storage and webhooks.
apps/…/media.tsShows codec inspection, container choice, audio-only packaging, and output metadata.
apps/…/streaming.tsShows HLS track selection, segment prefetch, gap limits, and local playlist assembly.
apps/…/hls-ladder.tsShows rendition planning, aligned playback timelines, and slice stitching.
apps/…/hls-ladder-encode.tsShows the ladder lifecycle from source traits to local files and upload-ready results.
apps/…/media-probe-pool.tsShows the isolated parser-worker boundary and its in-process fallback.
apps/…/isolated-worker-pool.tsShows resource limits and lifecycle rules for child workers.
apps/…/media-address-guard.tsShows the allowed network boundary for source and storage reads.
apps/…/media-relay.tsShows how media tools read remote files without bypassing the network policy.
apps/…/recording-verification.tsShows the proof required before recording publication.
apps/…/live-transcribe.tsShows the growing-recording transcription and cursor handoff.
apps/…/nvenc-encoder.tsShows optional accelerated encoding and its CPU fallback contract.
apps/…/capcodec-encoder.tsShows the optional external encoder contract.
apps/media-server/DockerfileShows the standard deployable runtime, health check, and build-time media checks.
apps/media-server/Dockerfile.standaloneShows the self-contained deployment relationship with private storage.
apps/…/docker-entrypoint.shShows the runtime user, volume, and GPU permission setup.
docs/media-server-and-web-cluster.mdExplains how this service relates to the web cluster and its runtime peers.