Skip to content

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.BuildStreamID lower-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 empty scheduled: [] are always added: the Castis streamer rejects a new pl:// key through PATCH, so the slot the Scheduling domain fills must exist from creation. defaultUrl is pl:///default (scheduled + mediaPlaylistId) or pl:///fallback (live + fallbackPlaylistId), filled by resolvePlaylistFilePaths, which requires the playlist to be ready. Scheduled channels have a dead primary input (udp://0.0.0.0:19999), so the streamer always falls through to defaultUrl.
  • SMIL vs progressive file. Feeding the streamer a multi-rendition ladder.smil on 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). So resolvePlaylistFilePaths uses Media.ProgressiveKey (single top rung MP4) unless the channel is full passthrough, which gets SmilKey.
  • Ingest tuning. chunkDuration, fragmentDuration, netTimeout, forceClean, dropSecondAudio are top-level ingestConfig fields in the streamer's wire format (POST /api/streams/path/:id in the Castis Streamer docs). PlayoutAdmin copies them from the selected transcoding preset (helpers.js buildPayload), or from its standalone "Ingest tuning" fields for passthrough without a preset. The server never expands a preset.
  • transcodeConfig. BuildPayload unmarshals it as an object and sets transcoders only 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 failures with the streamer's body in response. If all fail, the draft row is deleted and 502 is returned. Until 2026-08-03 a streamer 500 counted as success.
  • Scope checks (ingest_guard.go). The client's ingestConfig is forwarded verbatim (no allowlist), and the streamer plays any bucket filePath, so every filePath must match a live media key (storage, SMIL, progressive, optimized or manifest, with or without <bucket>/) of the caller's workspace. ingestUrl must be udp:// or pl:///. Each streamer must be in streamersForWorkspace (org streamer with access_mode = all_workspaces or a streamer_workspace_access row).

Updating and deleting channels

  • UpdateChannel writes 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 or mediaPlaylistId after creation is a planned "Configuration tab" feature.
  • DeleteChannel deletes 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

  • TranscodingPreset is always a ladder; one rung behaves like the old "single" type. It is the source of a channel's ingest tuning (moved from IngestPreset in the 2026-07-31 merge).
  • UpdateTranscodingPreset uses an explicit Select(...) column list, so zero values (forceClean: false, passthroughMode: "") are written. Consequence for clients: PUT is a full replace.
  • PassthroughMode is a string, not a bool, to avoid GORM's zero-value-with-default problem: full force-clears VideoRenditions/FilterChain and PlayoutAdmin omits transcoders (verified against the streamer source); video keeps audio encoding, enforced per track in the streamer's transcoder.
  • FilterChain entries (for example bwdif) are separate objects placed before the encoding objects in the streamer's video[] array (verified against streamer v1.2.23, 2026-08-05).
  • Publishers on TranscodingPreset was 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 by PUT. Channel-level publishers ride in ingestConfig.publishers.
  • IngestPreset is address-only (transport, udpHost, udpPort). LastProbeResult/LastProbedAt cache the last probe, because probe streams are deleted right after each probe; PlayoutAdmin's presetCompatibility.js uses 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).
  • UpdateIngestPreset still uses struct Updates(in), which skips zero values: isDefault can't go back to false and text fields can't be cleared (known issue, same class as the old forceClean bug).

Channel groups

  • SetChannelGroupMemberships is a full replace in a transaction: hard-delete all rows, then insert. Only ready channels of the workspace may be members.
  • publishBlocker: a group needs at least one membership and every member must be a non-deleted, ready channel of the workspace. Checked on draft → published and on push.
  • GetChannelGroupByID and SetChannelGroupMemberships preload Channels.Channel.Origins.Streamer and call RewritePublicPlaybackURL, so the response carries publicPlaybackUrl built from streamer.publicHost (always http://…/manifest.mpd) instead of the stored, possibly Docker-internal, PlaybackURL.
  • Facets (facetsForGroups) come from one raw query over memberships and channels and use the same provisioning.CategoriesFor + PayloadFacets as the device payload.
  • Push calls provisioning.PushChannelGroup(org, workspace, groupID, spaceIDs), which sends SET_CHANNEL_GROUPS over 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 blank organization_id is not eligible (total: 0; the log line channel group push: no eligible devices says which condition failed). Push logs channel-group push: requested/rejected/result with 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 against devices.workspace_id; anything else falls through to ProtectedRS256. PLAYOUT_ALLOW_DRAFT=1 also 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

  • probeChannelHealth checks the channel's own stream (GET /api/streams/<id> must be Running with representations → outputRunning) and, for a real UDP source, creates a throwaway probe stream dashprobe_<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/health probes 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/dashboard pings every streamer of the organization (not only the workspace's), and on success writes status = online on the streamer row. It probes the first origin of each channel. Its scheduledChannels is the old heuristic (ingestConfig has defaultUrl), which predates Channel.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

  1. URL check: http(s), .m3u8 or .mpd, no query, fragment or credentials.
  2. Address policy on the host (relay.ValidateExternalURL, see below).
  3. Node: relay.DefaultCache = the org's cproxy marked Use for external relays, else the org's only node, else 400. A client cacheId is ignored.
  4. Source inspection once (inspectRelaySource); error → 400, warn → created with warnings.
  5. Per-node cap relay.MaxPerNode = 50.
  6. Naming (relay.Names): key relay-<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_INSTANCE prefixes every name when two environments share a node. Renaming the channel doesn't change the path.
  7. Channel, origin and relay row are created in one transaction, then reconcileRelayCache applies it to the node. On failure the three rows are hard-deleted and the call returns 502.

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): every RELAY_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), records last_sync_*, and holds a Postgres advisory lock per node. RELAY_RECONCILER_ENABLED=false is an emergency switch.
  • Warmer (relay.StartWarmer, off unless RELAY_WARM_ENABLED=true): every RELAY_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 was ok and without disableWarm. 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=true turns the check off (local testing only).
  • Health (probeRelayHealth) fetches the entry playlist through the cproxy and, for an HLS master, the first variant; then healthy with outputRunning: 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) == 0 is always false, because validation rejects an empty transcodeConfig and {} is two bytes. So playlist content always resolves to ProgressiveKey, also for full-passthrough channels that should get the SMIL ladder. Not verified live.
  • Playback Groups (handler_playback.go, PlaybackGroup model) are implemented but not wired into routes.go; pending review.
  • syncChannelPlaylist is not called by any route (scheduled channels get their schedule through the Scheduling domain's sync).
  • Streamer exposure. Channel detail preloads Origins.Streamer in full, so workspace users see apiPort, accessMode and install fields that GET /streamers deliberately hides. The dashboard also returns every org streamer's host.
  • Not implemented: ingest modes srt, rtmp, hls_pull, dash_pull, ll_cmaf_pull (constants only); SourceCDN; live proxy routes GET /channels/:id/streams and /traffic (commented out); config push to running streams; preset-group snapshot/rollback.
  • A rejected preset update still writes a history row, and UpdateIngestPreset can't write zero values (see Presets).

Change history

Internal changes that are not part of the partner changelog.

2026-08-21

  • PlayoutAdmin: contentProvider field 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 the ChannelStatusPanel Origin 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.jsx gained a Genres tab.
  • Channel and channel-group delete buttons added to the UI (the routes existed since 2026-07-14).
  • DeletePlaylist added in the media domain, with an in-use guard that queries channels directly.
  • Publish UDP output moved from TranscodingPreset.Publishers to a channel-level setting in useChannelForm.js.
  • PlayoutAdmin: preset detail pages (TranscodingPresetDetail.jsx, IngestPresetDetail.jsx) and sidebar summaries; several preview-only mock sections are banner-flagged.

2026-08-03

  • forceClean could never be saved as false: the gorm default:true tag made GORM omit it on insert, and struct Updates() skipped zero values on update. Fixed by dropping the tag and using Select(...).
  • CreateChannel excluded 500 from 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 into domain/playback/ (handlers/, routes/, models.go, validation.go, helper.go, config.go), following the distribution pattern. Channel/ChannelOrigin reference distribution.Streamer directly. Core CRUD, multi-origin fan-out (streamerclient.CreateStream / DeleteStream) and pkg/response pagination date from 2026-05-18.