Playback
Internals of the Playback domain. For the public API, see Playback API.
The domain lives in CoreAPI under domain/playback/. It owns channels and their origins on Castis Streamer
nodes, transcoding and ingest presets, channel groups and channel artwork. Every route is mounted at
/api/v1/playback/:workspaceId/… behind ProtectedRS256 + RequireWorkspacePermission; the background of that
migration is in Playout workspace auth.
Code layout¶
domain/playback/
├── config.go Config + ConfigFromEnv(): MEDIA_ORIGIN_BASE_URL, MINIO_BUCKET
├── models.go Channel, ChannelOrigin, ChannelGroup, ChannelGroupMembership,
│ TranscodingPreset(+History), IngestPreset(+History), PlaybackGroup (unrouted)
├── brand.go brand slots, ChannelBrand, AssetURL, Channel.AfterFind (fills Brand)
├── helper.go ComputeGroupStatus (unrouted playback groups), RewritePublicPlaybackURL
├── validation.go CreateChannelRequest + ValidateCreateChannel, group/membership validators, ParseID
├── handlers/
│ ├── scope.go workspaceID/workspaceOrgID from locals, scoped query helpers
│ ├── handler_channels.go list/get/create/update/delete, star, status, memberships,
│ │ resolvePlaylistFilePaths
│ ├── handler_channels_helpers.go computeChannelQuality (FHD/HD/SD)
│ ├── handler_channels_sync.go syncChannelPlaylist (not called from any route today)
│ ├── ingest_guard.go filePath ownership check, udp:// | pl:/// check
│ ├── handler_channel_relay.go external relay create, delete cleanup, relay health
│ ├── relay_inspect.go relay-probe: link-style inspection
│ ├── relay_playlist.go HLS/DASH classification helpers
│ ├── handler_channel_health.go GET /channels/:id/health, probeChannelHealth
│ ├── handler_stats.go POST /stats/dashboard
│ ├── handler_brand.go brand upload (ffmpeg resize) and delete
│ ├── handler_streamers.go GET /streamers (workspace picker)
│ ├── handler_channel_groups.go group CRUD, memberships, publish rules, push, payload preview, facets
│ ├── device_access.go device-token read of GET /channel-groups
│ ├── handler_transcoding_presets.go, handler_ingest_presets.go
│ └── handler_playback.go Playback Groups CRUD + device assignment (NOT routed)
├── livethumb/ background worker: one still frame per channel
└── routes/ wire.go (Setup, the only entry main calls) + routes.go
Routes are registered in routes_platform.go with playbackroutes.Setup(v1, db.GetDB(), rs256Validator); the
live-thumbnail worker starts from infra.go.
Data model¶
erDiagram
Channel ||--o{ ChannelOrigin : "has"
ChannelOrigin }o--o| Streamer : "runs on (distribution)"
Channel }o--o| TranscodingPreset : "created from"
ChannelGroup ||--o{ ChannelGroupMembership : "has"
ChannelGroupMembership }o--|| Channel : "references"
TranscodingPreset ||--o{ TranscodingPresetHistory : "snapshots"
IngestPreset ||--o{ IngestPresetHistory : "snapshots"
| Table | Notes |
|---|---|
channels |
organization_id, workspace_id set from the authorized workspace, never from the body. sid has a partial unique index idx_channels_sid_active (WHERE deleted_at IS NULL), global across all workspaces, managed by a self-heal step in pkg/db/migrate.go; don't add uniqueIndex to the struct tag. Artwork keys logo_light_key, logo_dark_key, poster_key, epg_thumb_key (migration 2026-10-01_channel_brand_assets.sql) and live_thumb_key/live_thumb_at are never in JSON. |
channel_origins |
No tenancy columns; reached only through a scoped channel. streamer_id is NULL for a relay. ingest_extra = {"cacheId","relayKeyId"} for a relay. |
channel_groups |
Tenancy columns as channels. status draft/published, version counter, no snapshot history. |
channel_group_memberships |
Unique (channel_group_id, channel_id) (idx_group_channel) and (channel_group_id, lcn) (idx_group_lcn). Always hard-deleted, because a soft-deleted row would still hold the unique slot. |
transcoding_presets, ingest_presets |
Empty workspace_id = shared system preset (seeded in pkg/seed/, found by code). code has a global, non-partial unique index, so a soft-deleted preset still reserves its code. |
*_preset_history |
Write-only snapshot log, one row per replaced version. Nothing at runtime reads it. Safe because a channel copies its config at creation and never reads the preset again. |
Channel.Type (live/scheduled) is an explicit choice at creation. DeriveChannelType (from origin URLs) is kept
only for optional UI warnings. A virtual channel type is not modelled.
Channel creation¶
sequenceDiagram
participant Client
participant CoreAPI
participant PostgreSQL
participant Streamer
Client->>CoreAPI: POST /api/v1/playback/:workspaceId/channels
CoreAPI->>CoreAPI: ValidateCreateChannel; relay? → createRelayChannel
CoreAPI->>PostgreSQL: scope checks: preset, playlists, streamers, filePaths
CoreAPI->>CoreAPI: BuildStreamID(name); reserve timedAlternativeUrl + scheduled
CoreAPI->>CoreAPI: defaultUrl from mediaPlaylistId / fallbackPlaylistId
CoreAPI->>PostgreSQL: save Channel (status draft)
loop each origin
CoreAPI->>CoreAPI: streamer.Role must be "ingest" for udp
CoreAPI->>CoreAPI: BuildPayload(ingestUrl, ingestConfig, transcodeConfig)
CoreAPI->>Streamer: POST /api/streams/:streamId
Streamer-->>CoreAPI: 200/201/204 = success, anything else = failure
CoreAPI->>PostgreSQL: save ChannelOrigin (success only)
end
CoreAPI-->>Client: 201 {success, data, failures[]} or 502 if all failed
- Stream ID.
streamerclient.BuildStreamIDlower-cases the name and replaces spaces with_, then adds.stream("BBC World"→bbc_world.stream). It is shared by all origins and never changes, even when the channel is renamed. Two channels whose names slug to the same ID would collide on the same streamer. - Reserved keys.
timedAlternativeUrl: "pl:///scheduled"plus an emptyscheduled: []are always added: the Castis streamer rejects a newpl://key throughPATCH, so the slot the Scheduling domain fills must exist from creation.defaultUrlispl:///default(scheduled +mediaPlaylistId) orpl:///fallback(live +fallbackPlaylistId), filled byresolvePlaylistFilePaths, which requires the playlist to beready. Scheduled channels have a dead primary input (udp://0.0.0.0:19999), so the streamer always falls through todefaultUrl. - SMIL vs progressive file. Feeding the streamer a multi-rendition
ladder.smilon a channel that re-encodes makes it decode every source rendition and re-encode each into the full ladder (a 2-rendition SMIL into a 4-rung config gave 8 outputs, confirmed live). SoresolvePlaylistFilePathsusesMedia.ProgressiveKey(single top rung MP4) unless the channel is full passthrough, which getsSmilKey. - Ingest tuning.
chunkDuration,fragmentDuration,netTimeout,forceClean,dropSecondAudioare top-levelingestConfigfields in the streamer's wire format (POST /api/streams/path/:idin the Castis Streamer docs). PlayoutAdmin copies them from the selected transcoding preset (helpers.jsbuildPayload), or from its standalone "Ingest tuning" fields for passthrough without a preset. The server never expands a preset. transcodeConfig.BuildPayloadunmarshals it as an object and setstranscodersonly when it has keys;{}means a real no-transcode pipeline (no decoder is built). PlayoutAdmin builds{"*": {…}}and, for live fallback media with its own preset,"pl:///fallback": {…}.- Partial success. Failed origins go to
failureswith the streamer's body inresponse. If all fail, the draft row is deleted and502is returned. Until 2026-08-03 a streamer500counted as success. - Scope checks (
ingest_guard.go). The client'singestConfigis forwarded verbatim (no allowlist), and the streamer plays any bucketfilePath, so everyfilePathmust match a live media key (storage, SMIL, progressive, optimized or manifest, with or without<bucket>/) of the caller's workspace.ingestUrlmust beudp://orpl:///. Each streamer must be instreamersForWorkspace(org streamer withaccess_mode = all_workspacesor astreamer_workspace_accessrow).
Updating and deleting channels¶
UpdateChannelwrites metadata only (name,synopsis→description, G1 discovery fields). Pointer fields mean""clears and an absent key keeps; lists:[]clears. Nothing is pushed to the running stream; changing ingest, transcode ormediaPlaylistIdafter creation is a planned "Configuration tab" feature.DeleteChanneldeletes each origin's stream on its streamer (errors ignored), drops relay rows, soft-deletes the channel, removes its memberships (bumping published groups'version), deletes its brand and live-thumbnail objects, then reconciles affected relay nodes.
Presets¶
TranscodingPresetis always a ladder; one rung behaves like the old "single" type. It is the source of a channel's ingest tuning (moved fromIngestPresetin the 2026-07-31 merge).UpdateTranscodingPresetuses an explicitSelect(...)column list, so zero values (forceClean: false,passthroughMode: "") are written. Consequence for clients:PUTis a full replace.PassthroughModeis a string, not a bool, to avoid GORM's zero-value-with-defaultproblem:fullforce-clearsVideoRenditions/FilterChainand PlayoutAdmin omitstranscoders(verified against the streamer source);videokeeps audio encoding, enforced per track in the streamer's transcoder.FilterChainentries (for examplebwdif) are separate objects placed before the encoding objects in the streamer'svideo[]array (verified against streamer v1.2.23, 2026-08-05).PublishersonTranscodingPresetwas added and dropped from the UI on 2026-08-18: a preset is shared by many channels, so a publish address on it would collide. The column still exists and is still written byPUT. Channel-level publishers ride iningestConfig.publishers.IngestPresetis address-only (transport,udpHost,udpPort).LastProbeResult/LastProbedAtcache the last probe, because probe streams are deleted right after each probe; PlayoutAdmin'spresetCompatibility.jsuses it for a dismissible warning.- Update writes a history snapshot of the current row before parsing and validating the body, so a rejected update still leaves a history row (known issue).
UpdateIngestPresetstill uses structUpdates(in), which skips zero values:isDefaultcan't go back tofalseand text fields can't be cleared (known issue, same class as the oldforceCleanbug).
Channel groups¶
SetChannelGroupMembershipsis a full replace in a transaction: hard-delete all rows, then insert. Onlyreadychannels of the workspace may be members.publishBlocker: a group needs at least one membership and every member must be a non-deleted,readychannel of the workspace. Checked ondraft → publishedand on push.GetChannelGroupByIDandSetChannelGroupMembershipspreloadChannels.Channel.Origins.Streamerand callRewritePublicPlaybackURL, so the response carriespublicPlaybackUrlbuilt fromstreamer.publicHost(alwayshttp://…/manifest.mpd) instead of the stored, possibly Docker-internal,PlaybackURL.- Facets (
facetsForGroups) come from one raw query over memberships and channels and use the sameprovisioning.CategoriesFor+PayloadFacetsas the device payload. - Push calls
provisioning.PushChannelGroup(org, workspace, groupID, spaceIDs), which sendsSET_CHANNEL_GROUPSover MQTT to playout devices of the org in those spaces that are workspace-unbound or bound to this workspace; a device's assignment is recorded only on broker ack. A device endpoint with a blankorganization_idis not eligible (total: 0; the log linechannel group push: no eligible devicessays which condition failed). Push logschannel-group push: requested/rejected/resultwith group, user, org and spaces. - Device read (
device_access.go): registered before the staff group on the same path. A bearer token that parses as a device JWT is checked againstdevices.workspace_id; anything else falls through toProtectedRS256.PLAYOUT_ALLOW_DRAFT=1also serves draft groups (staging only). - The "Genres" view in PlayoutAdmin is a client-side aggregation of channels'
genres; genre is not an entity.
Health and dashboard stats¶
probeChannelHealthchecks the channel's own stream (GET /api/streams/<id>must beRunningwith representations →outputRunning) and, for a real UDP source, creates a throwaway probe streamdashprobe_<host>_<port>.stream, polls it for up to 4 s and deletes it.udp://0.0.0.0(file-loop scheduled channels) is not probed.GET /channels/:id/healthprobes one channel (6 s timeout) and pings only its origins' streamers. Use it from single-channel views; the dashboard is about 4 s per unhealthy channel.POST /stats/dashboardpings every streamer of the organization (not only the workspace's), and on success writesstatus = onlineon the streamer row. It probes the first origin of each channel. ItsscheduledChannelsis the old heuristic (ingestConfighasdefaultUrl), which predatesChannel.Type(2026-06-30 vs 2026-07-14) and was never revisited.
Brand assets¶
Uploads are written to a temp dir, sniffed (PNG/JPEG/WebP only, by content; SVG and GIF are refused), measured,
checked against the slot's minimum size and aspect ratio (3% tolerance), resized with ffmpeg and stored in the media
bucket under channels/<workspaceId>/<channelId>/brand/ with a timestamp in the key (cache-busting). The poster
also yields the 400x225 EPG thumbnail. URLs are <MEDIA_ORIGIN_BASE_URL>/<bucket>/<key>; without
MEDIA_ORIGIN_BASE_URL they come back empty.
External relay channels¶
A live channel whose source is someone else's HLS or DASH stream. Nothing of ours ingests or transcodes it: one of
the org's cproxy nodes pulls and serves it under its own address. Code: handler_channel_relay.go,
relay_inspect.go, relay_playlist.go, the domain/distribution/relay package (naming, origin expansion,
reconciler, warmer, address checks) and pkg/cdn/cproxy/relay_origin.go. Partner how-to:
Relay an external HLS or DASH stream.
How it is stored¶
| Table | Values for a relay channel |
|---|---|
channels |
source_type=external_relay, type=live, ingest_config={}, transcode_config={}, created as draft |
channel_origins |
one origin: ingest_mode=external_relay, ingest_url = the source URL, streamer_id NULL, ingest_extra={"cacheId","relayKeyId"}; the relay address in playback_url_hls (HLS) or playback_url (DASH) |
cache_origin_keys |
the relay row: source_kind=external, origin_key=relay-<slug>, path_prefix=/<slug>, external_url (scheme + host), upstream_base_path, playlist_file, TTLs, disabled, disable_warm, last_sync_* |
Creation¶
- URL check:
http(s),.m3u8or.mpd, no query, fragment or credentials. - Address policy on the host (
relay.ValidateExternalURL, see below). - Node:
relay.DefaultCache= the org's cproxy marked Use for external relays, else the org's only node, else400. A clientcacheIdis ignored. - Source inspection once (
inspectRelaySource);error→400,warn→ created withwarnings. - Per-node cap
relay.MaxPerNode= 50. - Naming (
relay.Names): keyrelay-<slug>, path/<slug>; the channel ID is appended when the slug is empty, reserved or taken on that node (deleted rows and paths other origins claim count).RELAY_INSTANCEprefixes every name when two environments share a node. Renaming the channel doesn't change the path. - Channel, origin and relay row are created in one transaction, then
reconcileRelayCacheapplies it to the node. On failure the three rows are hard-deleted and the call returns502.
The viewer address is <node public base URL>/<slug>/<playlist file>, or built from public host (or host) and
HTTP port when the node has no public base URL. Saving a node's public base URL rewrites the stored address of every
relay channel it serves. An HLS master playlist is pinned for 120 s; media playlists and DASH manifests are not.
Source check¶
relay-probe fetches the source once (no redirects, 6 s timeout, 1 MB limit) and, for an HLS master, its first
variant when it is on the same host. It reads every URI a player would request (segments, variants, #EXT-X-MAP,
#EXT-X-MEDIA, key URI=; DASH media, initialization, BaseURL). The least relayable link decides the level:
relative → ok, absolute → warn, root-relative → error. Anything not a playlist or manifest is error.
How the relay is served¶
Each relay becomes up to three cproxy origins (relay.Expand), in priority order:
| Origin key | Matches | Cached for |
|---|---|---|
relay-<slug>-master |
the entry playlist, HLS master only | 120 s, so viewers share one upstream session |
relay-<slug>-seg |
segment files (.ts .aac .m4s .mp4 .m4a .mp3 .cmfa .cmfv .m4v .webm) |
60 s by default (segmentTtl; "off" disables) |
relay-<slug> |
everything else under /<slug>/ |
2 s for no-cache responses |
Additive writes. A cproxy's API replaces the whole origin list on write. CoreAPI reads the live list, changes
only relay- keys, inserts new ones before the first catch-all, writes, reads back and restores the original if
anything outside relay- moved. Catch-all patterns are refused; the older origin and key routes refuse relay-
keys (409); a full key sync is refused while the node carries relays.
Reconciler and warmer¶
- Reconciler (
relay.Start, at boot, on by default): everyRELAY_RECONCILE_INTERVAL_SECONDS(default 60, minimum 10) it visits every node that has or had a relay row, writes only when the node differs from the database, removes only keys of its own database's disabled/refused/deleted rows, takes off rows whose host now fails the address policy (a DNS failure alone keeps a working relay), recordslast_sync_*, and holds a Postgres advisory lock per node.RELAY_RECONCILER_ENABLED=falseis an emergency switch. - Warmer (
relay.StartWarmer, off unlessRELAY_WARM_ENABLED=true): everyRELAY_WARM_INTERVAL_SECONDS(default 1) it fetches through the cproxy each relay's entry playlist, first variant and newest 4 segments. Only relays whose last sync wasokand withoutdisableWarm. DASH: manifest only. Costs about one viewer of upstream traffic per relay, on every replica.
Address checks and health¶
- Every address the host resolves to must be public (no loopback, private, link-local, CGNAT, multicast or metadata
ranges), at creation, on every reconcile pass and, for CoreAPI's own fetches, at connect time. No redirects, no
HTTP proxy.
RELAY_ALLOWED_HOSTS(comma-separated suffixes) restricts sources;RELAY_ALLOW_PRIVATE=trueturns the check off (local testing only). - Health (
probeRelayHealth) fetches the entry playlist through the cproxy and, for an HLS master, the first variant; thenhealthywithoutputRunning: true. The live-thumbnail worker skips relay channels.
Relays API and UI¶
Org admins have lower-level access to a node's relay rows under
/api/v1/distribution/{orgId}/caches/{cacheId}/relays (org:distribution:view / org:distribution:manage): list,
add a row not tied to a channel, change or remove one (409 for a channel's row), and POST /relays/sync[?dryRun=true].
See the Distribution API. In PlayoutAdmin: Shields set Public base URL and
Use for external relays; the New channel wizard has External Stream Relay (HLS / DASH) with a live source
check (red blocks Next); the status panel shows "Relayed through cproxy: serving / not serving".
Live thumbnails¶
domain/playback/livethumb keeps one still frame per channel in channels/<ws>/<id>/live/thumb.jpg, written only
by the worker (live_thumb_key + live_thumb_at together). The device payload serves it as thumbnail only while
fresh (livethumb.MaxAge), else the EPG thumbnail. One loop per cluster (advisory lock 8_420_101).
cmd/livethumb grabs one frame from a URL for testing.
Configuration¶
| Variable | Default | Effect |
|---|---|---|
MEDIA_ORIGIN_BASE_URL |
empty | Public origin for artwork URLs; empty means artwork URLs are empty |
MINIO_BUCKET |
playtelly |
Bucket for artwork and live frames |
PLAYOUT_ALLOW_DRAFT |
unset | 1 serves draft groups to devices (staging only) |
LIVE_THUMBS_ENABLED |
false |
Turns the live-thumbnail worker on |
LIVE_THUMBS_INTERVAL_SEC |
30 (min 5) |
Time between rounds |
LIVE_THUMBS_CONCURRENCY |
3 (1–16) |
ffmpeg processes at once |
LIVE_THUMBS_GRAB_TIMEOUT_SEC |
15 (3–60) |
Per-channel grab timeout |
LIVE_THUMBS_CHANNEL_TYPES |
live,scheduled |
Channel types to grab |
LIVE_THUMBS_MAX_AGE_SEC |
max(10 min, 3 intervals) | How long a frame counts as fresh |
RELAY_RECONCILER_ENABLED |
true |
Relay reconciler |
RELAY_RECONCILE_INTERVAL_SECONDS |
60 (min 10) |
Reconcile interval |
RELAY_WARM_ENABLED |
false |
Relay cache warmer |
RELAY_WARM_INTERVAL_SECONDS |
1 |
Warm interval |
RELAY_ALLOWED_HOSTS |
empty | Allow-list of source host suffixes |
RELAY_ALLOW_PRIVATE |
false |
Disable the public-address check |
RELAY_INSTANCE |
empty | Prefix for relay names on shared nodes |
Device tokens (the device read of GET /channel-groups) are verified with the provisioning domain's device JWT
secret, DEVICE_JWT_SECRET, kept in the deployment's secret store. If it is unset, CoreAPI falls back to a built-in
debug value: make sure every deployed environment sets it.
Known issues and gaps¶
- Passthrough detection in
CreateChannel.isPassthrough := len(req.TranscodeConfig) == 0is always false, because validation rejects an emptytranscodeConfigand{}is two bytes. So playlist content always resolves toProgressiveKey, also for full-passthrough channels that should get the SMIL ladder. Not verified live. - Playback Groups (
handler_playback.go,PlaybackGroupmodel) are implemented but not wired intoroutes.go; pending review. syncChannelPlaylistis not called by any route (scheduled channels get their schedule through the Scheduling domain's sync).- Streamer exposure. Channel detail preloads
Origins.Streamerin full, so workspace users seeapiPort,accessModeand install fields thatGET /streamersdeliberately hides. The dashboard also returns every org streamer'shost. - Not implemented: ingest modes
srt,rtmp,hls_pull,dash_pull,ll_cmaf_pull(constants only);SourceCDN; live proxy routesGET /channels/:id/streamsand/traffic(commented out); config push to running streams; preset-group snapshot/rollback. - A rejected preset update still writes a history row, and
UpdateIngestPresetcan't write zero values (see Presets).
Change history¶
Internal changes that are not part of the partner changelog.
2026-08-21¶
- PlayoutAdmin:
contentProviderfield added to the channel General tab; Additional Genres became a toggle-chip grid and Keywords/Tags/Languages/Custom Groups addable comboboxes, all aggregated client-side from existing channels (no vocabulary table). - PlayoutAdmin: Service List Membership on the channel General tab now calls
GET /channels/:id/groups. - PlayoutAdmin:
/channels/:id/watch(ChannelPreview.jsx) removed; its pieces moved to theChannelStatusPanelOrigin Playback tab. The On-Air Status tab is real (backed by dashboard stats; only the first origin is probed). Source Status and Activities tabs remain placeholders. - PlayoutAdmin: channel group creation became three steps (Basic Info, Selection, LCN) with live-aggregated
filters; a "Templates" chip is shown disabled.
ChannelGroupList.jsxgained a Genres tab. - Channel and channel-group delete buttons added to the UI (the routes existed since 2026-07-14).
DeletePlaylistadded in the media domain, with an in-use guard that querieschannelsdirectly.- Publish UDP output moved from
TranscodingPreset.Publishersto a channel-level setting inuseChannelForm.js. - PlayoutAdmin: preset detail pages (
TranscodingPresetDetail.jsx,IngestPresetDetail.jsx) and sidebar summaries; several preview-only mock sections are banner-flagged.
2026-08-03¶
forceCleancould never be saved asfalse: the gormdefault:truetag made GORM omit it on insert, and structUpdates()skipped zero values on update. Fixed by dropping the tag and usingSelect(...).CreateChannelexcluded500from its failure check, so a rejected stream was saved as a working origin.
2026-07-31¶
- Ingest/transcode preset merge; history tables added for both preset types.
2026-06-25 and earlier¶
- Extracted from the flat
domain/service/package intodomain/playback/(handlers/,routes/,models.go,validation.go,helper.go,config.go), following thedistributionpattern.Channel/ChannelOriginreferencedistribution.Streamerdirectly. Core CRUD, multi-origin fan-out (streamerclient.CreateStream/DeleteStream) andpkg/responsepagination date from 2026-05-18.