MPEG-TS Delivery¶
How a live MPEG-TS viewer is served, from the player's first request to the
end of its session, and which parts PHP and xc_fanout (Go) each own. HLS
is covered in Streaming Subsystem and its segment
gateway in ADR 0005.
Overview¶
A TS session takes two HTTP requests. Only the first is a PHP decision:
- MAIN (
/live/<user>/<pass>/<id>.tsand the other forms,auth.php) authenticates the line, picks the server and mints a token. - The serving node (
/auth/<token>,live.php) admits the viewer, records the connection and hands the byte path to the daemon. With fanout on, the PHP-FPM worker is free once it has answered. xc_fanout(/live/<id>on its client socket) streams the TS from its in-memory ring for the whole session.
sequenceDiagram
participant P as Player
participant M as MAIN nginx + auth.php
participant N as Node nginx
participant L as live.php (FPM)
participant F as xc_fanout
P->>M: GET /live/u/p/12.ts
M-->>P: 302 /auth/<token>
P->>N: GET /auth/<token>
N->>L: /stream/live?token=…
L->>F: register + probe (proxy channel) / is fed? (other channels)
L-->>N: X-Accel-Redirect /xc_fanout/12?c=<uuid>&prebuffer=<s>&vc=<codec>
N->>F: GET /live/12?c=…
F-->>P: MPEG-TS for the whole session
1. MAIN: auth.php¶
nginx turns every live URL form (/live/u/p/12.ts, /u/p/12, /play/<token>, …) into /stream/auth?…&type=live.
- Checks: the cache is complete, the node lease accepts new sessions, the credentials or HMAC, auth flood, the line's state (expired, banned, disabled), user agent, allowed IPs and countries, ISP and ASN, the device, restream detection, the allowed extension and the bouquet.
- Server choice:
StreamRedirector::redirectStream()picks the server (redirect_id, andoriginator_idbehind a proxy server);getStreamingURL()gives its base URL. case 'ts':disable_ts(withdisable_ts_allow_restream) refuses TS. The token holds the stream, the line (username and password) or HMAC identity,extension: ts,channel_info(redirect_id,originator_id,pid,on_demand,llod,monitor_pid,proxy= the stream'sdirect_proxy),user_info(id,max_connections,pair_id,con_isp_name,is_restreamer),prebuffer,country_code,activity_start,external_device,video_codecanduuid.ConnectionAdmission::admitToken()reserves the viewer's place (the token'suuid);ViewerKey::mint()seals the token for the serving node.- The answer is
302 <server>/auth/<token>(/auth/<id>.ts?token=<token>withallow_cdn_access).
2. The node: live.php¶
nginx rewrites /auth/<token> to /stream/live?token=<token>. StreamingRequestBootstrap runs first (flood block, verify_host), then live.php. Each step below refuses with generateError() or the not-on-air video (OffAirHandler::showNotOnAir()).
2.1 The token¶
StreamAuthMiddleware::decryptToken()opens it. Avideo_pathoroff_airtoken gets that video file and stops.- An extension other than
tsorm3u8becomesapi_container. A proxy channel accepts onlyts(USER_DISALLOW_EXT). use_buffer = 0sendsX-Accel-Buffering: no.- The serving server is
originator_id(withredirect_idas the proxy in front of it) orredirect_id, else this server.
2.2 The producer¶
- Proxy channel, fanout on (
FanoutMode::legacyDelivery()false andLicenseGate::fanoutUsable()): the stream's source is read from the database (StreamSource::sourceRow(),arguments()),FanoutClient::buildSource()turns it into the daemon's form, andFanoutClient::register()sends it to the daemon. This is the only place a proxy channel's source reaches the daemon, so an edited source takes effect at the next viewer's request.FanoutClient::probe()then waits up toon_demand_wait_timefor data; none means not-on-air. - The
_.pidand_.monitorfiles updatechannel_info.on_demand_instant_offqueues this worker for the on-demand channel (ConnectionTracker::addToQueue(); the shutdown handler removes it). - No live producer (and not a registered proxy channel):
FanoutMode::startFor()decides.START_PROXY(fanout off): oneProxyCommandper stream, started underStreamProcess::lockOnDemandStart().START_MONITOR(on-demand): starts the monitor (or the fanout supervisor), then waitson_demand_wait_timefor_.pid.- Otherwise: not-on-air.
- Non-proxy channel: for TS it waits for
_.m3u8, or_0.ts/_0.m4s(up toon_demand_wait_time,WAIT_TIME_EXPIRED), and checks that the stream is still watched and alive.
2.3 Admission and the connection¶
disallow_2nd_ip_con(not a restreamer, andmax_connectionswithindisallow_2nd_ip_max, or the maximum at 0): the line's other address (ConnectionTracker::acceptedIP()) gets the connected video.- The uuid: TS keeps the token's
uuid. HLS replaces it withhlsConnectionKey()(one record per player). - The delivery (
FanoutMode::tsDelivery()): the daemon for a proxy channel that registered and probed, or a non-proxy channel the daemon is fed with (FanoutClient::isStreamFed(),has_data); the legacy feed when fanout is off. The connection'spidis 0 for the daemon (no worker serves it) and this worker's pid for the legacy feed. ConnectionTracker::lookupLive($ctx, 'ts', withPid, openOnly = false), in the node's agent (CONNECTIONS), else Redis orlines_live:- none: the token's
activity_start + create_expirationmust not have passed (TOKEN_EXPIRED), thencreateLive(); - found, ended or not (TS re-opens an ended connection):
restrict_same_ip(IP_MISMATCH); a php-fpm worker still feeding it is killed;updateLive()writes thepidandhls_last_readand re-opens it.
- none: the token's
- A failed write:
StreamAuth::refuseAdmission(),LINE_CREATE_FAIL. StreamAuth::validateConnections(): on a CONNECTIONS node,conn.limitspooled for MAIN (lanep0); else the line's limit enforced here (ConnectionLimiter).- The database or Redis is closed. For the legacy feed only,
$rCloseConis set (the shutdown handler closes the connection) and the viewer's markerCONS_TMP_PATH/<uuid>touched. A daemon viewer gets neither: its record outlives the worker (section 4), and nothing reads a TS viewer's marker.
2.4 The bytes¶
| Channel | Fanout | What answers |
|---|---|---|
| proxy | on | X-Accel-Redirect: /xc_fanout/<id>?c=<uuid>&prebuffer=<s>&vc=<codec>; the worker returns |
| proxy | off | the worker relays ProxyCommand's datagrams from CONS_TMP_PATH/<id>/<uuid> to the viewer, for the whole session |
| non-proxy | on, fed | the same X-Accel-Redirect |
| non-proxy | on, not fed | not-on-air |
| non-proxy | off | the worker chase-reads the on-disk segments (SegmentReader), with the send-message signal (SIGNALS_PATH/<uuid>) and the divergence file, for the whole session |
prebuffer is the seconds of history the daemon sends on join: client_prebuffer; for a restreamer restreamer_prebuffer, or max(1, seg_time) when its link asks for a prebuffer.
nginx's location ^~ /xc_fanout/ (internal) rewrites the target to /live/<id> on the daemon's client socket bin/xc_fanout/sockets/http.sock, with buffering off and a one-hour read timeout.
2.5 After the answer: ShutdownHandler::handle('live')¶
$rCloseConset (the legacy feed): it closes the connection whosepidis this worker's (hls_end = 1) in the agent, Redis orlines_live, and deletes the markerCONS_TMP_PATH/<uuid>and the legacy relay's socket file. A daemon viewer skips this step: it had nothing to close (itspidis 0) and cost an agent round-trip, or a database reconnect and an UPDATE matching no row, per session.- Instant off: the worker leaves the on-demand queue.
3. The daemon: xc_fanout's /live/<id>¶
Manager.serveLive (internal/server/server.go):
- attaches the viewer to the stream (starting a stopped puller), joins the ring
prebufferseconds back on a keyframe; - counts the viewer under
c(the uuid), which/connectionslists for the panel; - writes with a per-write deadline (
write_timeout_sec), drops a viewer that got nothing forviewer_idle_timeout_sec, and sends a pending send-message overlay (vcis the codec it is drawn with).
4. The session's end¶
The viewer's record stays open after PHP has answered (pid 0). The record is closed by whichever holds the node's viewers:
- The agent (CONNECTIONS): it reconciles its registry against the daemon's
/connectionsitself. - Otherwise
fanout_sync(FanoutSyncCommand): it closes the openpid = 0rows the daemon no longer lists (after a short grace for the connect race), ends daemon viewers with no open row (dropOrphans()), and writes the per-viewer rates and divergence.
A kick, a connection limit or an expired line closes a record whoever holds it. A viewer who simply disconnects is noticed by this reconciliation alone: in the legacy store (no agent) cron:users leaves pid = 0 records to fanout_sync, so while that daemon is not running they stay open and count against their lines' limits.
servicestartsfanout_syncat boot, with fanout on or off. Acron:serversrun that gets as far as its daemon checks (it booted, nginx is running, the server's row was found) starts it again when it is not running (ServersCronJob::reviveFanoutSync()); the daemon's lock keeps a second one from running beside it.- A
fanout_syncthat is running when the database becomes unreachable stays up: it keeps the settings it holds, skips each pass whose records it cannot read (never taking them for "no records"), and asks for the connection again at the next pass. The first pass after the database is back closes the records of the viewers who left meanwhile and keeps those the daemon still lists. - A
fanout_syncstarted while the database is unreachable ends in its bootstrap where that bootstrap connects to the database (MAIN, and a node that does not boot from its replica), like any command there; the next eligiblecron:serversrun after the database is back starts it. A node that boots from a ready replica starts without MAIN's database: itsfanout_synccomes up during the outage and skips its passes as above.
5. The segment gateway¶
With gateway_mode = segments+playlist, nginx sends /auth/<token> to the gateway in xc_fanout first. It answers a TS viewer there, without PHP, as section 2 would answer it:
- A first request (no record under the token's
uuidyet): the gateway creates the connection ascreateLive()does, from the token MAIN sealed. It registers the record in the agent (containerts,pid0, the token's start, country, ISP and device, MAIN's proof of the mint), with the admission request for a line with a limit (X-XCVM-Admission), spoolsconn.limit(no marker, as above), and streams from the daemon's/live/<id>in-process. - A reconnect (the same token again): it checks the connection, re-opens the record with
pid0, spoolsconn.limitand streams the same way.
live.php still answers, before anything is written: a token older than create_expiration (its TOKEN_EXPIRED), a stream that is not running or not fed (it starts an on-demand one), every proxy channel (whose source only live.php registers), a line under the second-address rule, and a panel or daemon that predates this. After the register, it also answers a viewer the agent refuses (it asks the agent again and shows the refusal) and one the agent did not answer for. See ADR 0005, "MPEG-TS reconnects" and "MPEG-TS first requests".