Xtream-Masters P2P Sharing API

This document is for developers who build their own player app and want it to use P2P Sharing on an Xtream-Masters panel. It describes every request, every message and every rule the app must follow. Protocol version: 1.8.

With P2P Sharing, viewers who watch the same live channel give each other parts of the stream. The server sends less traffic. The picture must never get worse: when anything is unsure, the app takes the segment from the server by normal HTTP, exactly as a player without P2P does.

App ↔ Panel (main server)Asks if P2P is on (/p2p/info). Keeps one WebSocket open to the tracker (/p2p/ws) to find other viewers.
App ↔ BalancerPlays the live HLS playlist and segments as always. Gets a session key from the playlist answer. Reports its state every 10 seconds (/p2p/beat).
App ↔ AppWebRTC data channel between viewers of the same channel. Segments are asked and sent in pieces, then checked.
Three things to remember 1. Playback comes first. P2P may only use spare buffer time.
2. The server decides. The app never decides by itself to share; it obeys mode from the beat answer.
3. Off means off. When the panel says P2P is off, the app sends nothing new at all.

The login, channel lists and stream URLs are the normal player_api.php / playlist API. This document adds only the P2P part on top of it.

Requirements

What must be ready on the panel, and what the app must be able to do.

Panel side (done by the panel owner)

RequirementDetail
Core versionsMain core 3.1.394 or newer and balancer core 1.2.406 or newer. Every balancer of the panel must be updated. A channel on an old balancer gives no session key and never shares.
Switch onPanel → Manage Servers → Servers Tools → P2P Sharing → turn it on. With the switch off, /p2p/info answers {"p2p":0,"live_hls":0} and nothing else exists.
Channels on a balancerSharing works only on live channels that a balancer streams. A channel the main server streams itself plays as normal HTTP and never gives a key.
HLS output for the lineThe line must be allowed to use the m3u8 output format. P2P works only on HLS, never on .ts streams.
Normal HLS segmentsThe playlist must list segments as /hls/<32 hex>/<name>.ts. Other playlist shapes (proxy paths, restream lines) are not capable.
Minimum viewersSetting on the P2P page, default 10, lowest 2. It counts capable devices on one channel on one balancer. Below it the app is told announce with reason min_viewers.
Test groupDefault on, 10% of devices. These devices stay on HTTP on purpose, so the panel can compare freezes. They get group: "control".
Slow startAfter each switch-on, sharing opens in steps: 5%, 25%, 50%, 100% of devices (10 minutes on the first step, then 30 minutes per step). Devices not yet included get reason ramp. Turning the switch off and on starts the steps again.
Mobile dataSetting off (default: no P2P on mobile data) or receive (download from peers allowed, upload never).
WebSocket to the panelThe app opens ws(s)://<panel address>/p2p/ws. Any proxy or CDN in front of the panel must let WebSocket pass. If it does not, playback still works, but nothing is shared.
Proxy in front of a balancerIt must pass the request header X-XM-P2P, the answer header X-XM-P2P-K, and POST /p2p/beat to the same balancer that served the playlist.
STUNThe panel sends the STUN server list in the beat answer (default: two public Google STUN servers; changeable on the panel). No TURN server is used.

App side (done by the app developer)

RequirementDetail
HLS player with a custom segment loaderThe app must be able to give the player segment bytes from its own code (from a peer or from HTTP), and to read the answer headers of the playlist request.
WebRTC data channelsAny WebRTC library with reliable ordered data channels and STUN. No audio or video tracks are used.
WebSocket clientText frames, answers server pings (standard pong).
MD5 and SHA-256MD5 to check segments, SHA-256 for the turn rule.
Device factsRAM size, network type (wifi, ethernet, mobile), battery saver state, buffer length of the player, stall events.
A device idA random id made once per install, 16 hex characters. Not a hardware id.
Monotonic clockAll timers use a monotonic clock. Never the wall clock of the device.

The full flow, step by step

One viewing session from login to channel change.

  1. After login, the app asks GET /p2p/info on the panel address. Answer p2p:0: stop here, behave as an app without P2P.
  2. Open a live channel as m3u8 (when live_hls is 1 and the line allows m3u8). Add the header X-XM-P2P: 1 to every live playlist request. Not to segment requests.
  3. Read the answer header X-XM-P2P-K of the playlist. Present: this is the session key. Missing: no P2P on this channel; do nothing more.
  4. Play normally by HTTP for join_after_sec (30 seconds) without interruption. Nothing of P2P runs during channel start.
  5. Send the first beat: POST /p2p/beat to the same origin that served the playlist. Then one beat every 10 seconds.
  6. Obey the answer. mode: off: stay on HTTP, keep beating. Any other mode: the answer carries a ticket.
  7. Open the tracker socket on the panel address, send join with the ticket. The tracker answers joined with your peer id and a list of other viewers.
  8. Connect to the listed peers by WebRTC. Offer, answer and ICE go through the tracker socket. Open one data channel per peer.
  9. Exchange have lists on each data channel: which checked segments each side holds.
  10. In mode share: when the player wants a segment and the buffer is deep enough, try peers first inside a strict time budget; otherwise HTTP. Check every peer segment before the player gets it.
  11. After every beat answer send the new ticket to the tracker ({"t":"ticket",...}). Without it the tracker closes the socket after 60 seconds.
  12. On channel change, stop, background or any playlist error: everything off at once. Send leave, close peer links, clear the cache. The next channel starts again at step 2.

General rules

  • All JSON is UTF-8. Unknown fields must be ignored by both sides. New fields may be added at any time.
  • Times are seconds, unless the field name ends in _ms (milliseconds).
  • The app never reads, cuts or rebuilds the stream URL. After redirects the final URL can have several shapes; treat it as opaque.
  • Playlist origin = scheme + host + port of the final URL that returned the playlist body (after redirects), taken from the newest successful playlist answer. The beat goes to this origin.
  • Panel address = the base URL the app logged in with. /p2p/info and the tracker use this address.
  • The values in the beat answer (timers, sizes, caps) come from the server. The app uses them as given and does not tune them.
  • The session key, the ticket and peer ids are opaque strings. Do not parse them.
  • The beat never carries the username, password or the playlist URL.

Panel state

GET<panel address>/p2p/infoon the main server

Tells the app if P2P Sharing is on for this panel. No parameters, no login. HEAD is also accepted.

{"p2p":1,"live_hls":1}
FieldValueMeaning
p2p0 | 11 = P2P Sharing is on. 0 = off (also during an emergency stop).
live_hls0 | 11 = the app should open live channels as m3u8 by itself, whatever format the viewer chose, but only when the line's allowed formats include m3u8. 0 = choose the format as usual.

Rules

  • Ask once after login. Timeout 5 seconds. While the answer is p2p:1, ask again every 10 minutes.
  • Any failure (timeout, not HTTP 200, missing field) counts as both 0.
  • With p2p:0 the app must stay fully asleep: no X-XM-P2P header, no beat, no socket, no change of format, and no more /p2p/info requests until the next login or app start.
  • A changed answer takes effect at the next channel start, never in the middle of playback.

Playlist and session key

GETlive playlist (.m3u8) and segmentson the balancer

The app plays the live m3u8 URL the panel API gave it, as always. Two headers are added around it.

HeaderDirectionMeaning
X-XM-P2P: 1app → server"I can do P2P, give me a key." Send on every live playlist request (first one and every refresh), only while /p2p/info says p2p:1. Never on segment requests.
X-XM-P2P-K: <key>server → appThe session key for this viewing session. An opaque string of at most 64 characters. Missing = P2P is not available here: no beat, no socket.
# request
GET /live/.../12345.m3u8 HTTP/1.1
X-XM-P2P: 1

# answer
HTTP/1.1 200 OK
X-XM-P2P-K: 3qXv0b7m...43 characters...
Content-Type: application/vnd.apple.mpegurl

#EXTM3U
#EXT-X-TARGETDURATION:10
#EXT-X-MEDIA-SEQUENCE:48210
#EXTINF:10.0,
/hls/9c1f0e6ab1d24c7f8e2a5b3c4d6e7f80/12345_48210.ts
...

Rules for the key

  • Always use the key from the newest playlist answer. It can change (for example after a balancer restart, or when the player opens the playlist again).
  • A new key is a new beat session: seq starts again at 1 and all counters in c start again at 0. If the app carried old totals into a new key, the panel would count them twice.
  • The key lives as long as the playlist keeps being requested. 30 seconds after the last served playlist it ends; a beat with an ended key is answered 406.
  • The server gives no key when: P2P is off or stopped, the line has P2P switched off, the line is a restreamer line, the channel is not served as normal HLS by a balancer.

Rules for segments

  • Segment URLs in the playlist are root-relative: /hls/<token>/<name>. <token> is 32 lowercase hex characters. It is the content hash of the segment (see Checking a segment).
  • The identity of a segment is its token, never its file name. File names are used again after the channel's encoder restarts (numbers start again from 0, with no discontinuity tag).
  • If any segment URL of the playlist does not match ^/hls/[0-9a-f]{32}/, the channel is not capable: stay on HTTP and do not beat.
  • The balancer does not support Range on segments. A segment is always fetched whole by HTTP.
  • If the playlist origin changes during a session, go OFF, clear the cache and start again as on a new channel.

The beat (state report)

POST<playlist origin>/p2p/beaton the balancer

The beat is how the app tells the server its state and counters, and how the server tells the app what to do. It is the heart of the feature: connection, monitoring and stop all pass through it.

  • Header Content-Type: application/json. Body at most 8 KiB. Timeout 5 seconds.
  • First beat join_after_sec (30 s) after stable playback began on this channel. Then every beat_sec (10 s), each interval with a random change of ±25%.
  • A device that cannot share (low memory, mobile data, battery saver) still beats, with capable: false, so the panel can count it and show the reason.
  • Do not beat faster than once per 3 seconds: a faster beat gets the previous answer again and is not recorded.

Request body

{
  "v": 1,
  "k": "<key from X-XM-P2P-K>",
  "dev": "a3f9c2e17b604d58",
  "app_ver": "2.7.1",
  "mod_ver": 2,
  "seq": 17,
  "state": "share",
  "capable": true,
  "why": "",
  "net": "wifi",
  "device": "tv",
  "api": 31,
  "ram_mb": 2048,
  "buffer_ms": 24500,
  "peers": 6,
  "c": {
    "bytes_http": 48211200, "bytes_p2p_used": 20736000, "bytes_p2p_shadow": 0,
    "bytes_p2p_wasted": 524288, "bytes_p2p_out": 18432000,
    "seg_http": 26, "seg_p2p": 11, "seg_mixed": 1,
    "seg_p2p_timeout": 0, "seg_p2p_bad": 0, "seg_hedged": 1,
    "conn_try": 7, "conn_ok": 6,
    "stall_count": 0, "stall_ms": 0, "stall_p2p_count": 0,
    "watch_ms": 372000, "dropped_frames": 3, "zap_ms_last": 1240
  },
  "conn": [ {"p": "p0a1b2c3d4e5f", "ok": true, "ms": 840} ]
}
FieldTypeMeaning
vintrequiredAlways 1.
kstringrequiredThe session key from the newest playlist answer.
devstringrequiredDevice id: random, made once per install, 16 hex characters. Only letters, digits, _ and -; 8 to 64 characters. The server uses it to put the device in the test group or the slow-start steps, and the panel shows it.
seqintrequiredBeat counter of this session. Starts at 1, +1 for every beat sent.
mod_verintrequiredProtocol level of the app. Send 2 for this document. The panel can set a minimum; a lower value is answered off, reason version.
app_verstringoptionalApp version text, at most 24 characters. Shown on the panel.
statestringrequiredWhat the app is doing now: off, connecting, announce, share or shadow.
capableboolrequiredtrue when this device could share right now. Only capable devices count for the minimum viewers of a channel.
whystringoptionalThe device's own reason while its state is off. One short word, at most 24 characters. The panel shows it. Known words: memory, metered, power_save, background, api, breaker, bandwidth, settling, error.
netstringrequiredwifi, eth, mobile or other.
devicestringoptionaltv, phone, tablet, stick or other.
apiintoptionalOS API level (Android), or 0.
ram_mbintoptionalTotal memory of the device in MB. Shown on the panel next to the reason memory.
buffer_msintoptionalBuffered time ahead of the playback position.
peersintoptionalNumber of open peer links now.
cobjectrequiredCounters, see below.
connarrayoptionalResults of peer connection attempts since the last beat, at most 16 entries: peer id, success, time in ms.
diagarrayoptionalOnly when the previous answer had "diag": true. See Diagnostics.

Counters c

All counters are cumulative since the first beat of this session and are never reset. The server works out the differences itself using seq, so a lost beat loses nothing.

CounterMeaning
bytes_httpSegment bytes fetched from the balancer by HTTP.
bytes_p2p_usedBytes from peers that were checked and given to the player. This is the saving.
bytes_p2p_shadowBytes from peers checked in shadow mode (the player was fed by HTTP).
bytes_p2p_wastedBytes from peers received and then not used (attempt cancelled, timed out, or bad).
bytes_p2p_outBytes this device sent to peers.
seg_httpSegments fetched by HTTP in the normal way.
seg_p2pSegments where all bytes came from peers.
seg_mixedHTTP fetches that replaced a failed, cancelled or bad peer attempt.
seg_p2p_timeoutPeer attempts that reached their deadline.
seg_p2p_badPeer segments that failed the check.
seg_hedgedPeer attempts cancelled early because they would be late.
conn_try, conn_okPeer connections tried, and opened.
stall_count, stall_msFreezes of the player and their total length.
stall_p2p_countFreezes that began within stall_window_sec (30 s) after any peer attempt (running, cancelled, timed out or failed) for the frozen segment or the one before. Do not make this narrower.
watch_msTime played in this session.
dropped_frames, zap_ms_lastDropped video frames; start time of the last channel change.
What counts as a stallThe player goes from playing to buffering while play is requested. Channel start, channel change and seek are not stalls. A segment served from the app's cache counts by where its bytes first came from, never automatically as seg_p2p.

Answer (HTTP 200)

{
  "ok": true,
  "p2p": {
    "mode": "share",
    "group": "p2p",
    "tracker": "/p2p/ws",
    "ticket": "eyJ2IjoxLC...",
    "ticket_ttl": 60,
    "stun": ["stun:stun.l.google.com:19302", "stun:stun1.l.google.com:19302"],
    "beat_sec": 10,
    "join_after_sec": 30,
    "floor_ms": 10000,
    "attempt_ms_max": 8000,
    "wait_have_ms": 3000,
    "cooldown_segments": 1,
    "stall_window_sec": 30,
    "neighbours": 6,
    "max_peers": 8,
    "piece_kib": 256,
    "upload_kbps_max": 8000,
    "upload_kbps_start": 2000,
    "cache_segments": 3,
    "cache_mb": 24,
    "min_ram_mb": 1500,
    "mobile": "off",
    "diag": false,
    "reason": "ok"
  }
}
FieldMeaning
modeWhat the app must do. See the mode table below.
groupp2p or control. control = test group: stay on HTTP, treat as mode off, but keep beating.
trackerWhere the tracker is. Starts with /: a path on the panel address (change http to ws, https to wss, same host and port, then the path). Starts with ws:// or wss://: use as it is. Anything else or empty: treat the answer as mode off.
ticketA signed pass for the tracker, at most 512 characters. Sent with every mode other than off. No ticket = treat as mode off.
ticket_ttlLife of the ticket in seconds (60), counted from when the app received it.
stunSTUN servers for WebRTC (up to 4).
beat_sec, join_after_secBeat interval; wait before the first beat and before P2P arms on a new channel.
floor_msProtected buffer. P2P may only use buffer above this. Per channel: 1000 × segment seconds, between 6000 and 15000.
attempt_ms_maxLongest time one peer attempt may hold a segment. Per channel: 800 × segment seconds, between 2000 and 10000.
wait_have_msLongest wait for another viewer to announce a new segment. Per channel: 300 × segment seconds, between 1000 and 4000. 0 or missing = do not wait.
cooldown_segmentsNumber of segments that go by HTTP at once after any failed peer attempt.
stall_window_secWindow for stall_p2p_count.
neighboursPeer links the app should keep open.
max_peersThe app never holds more peer links than this.
piece_kibPiece size for peer transfers, in KiB.
upload_kbps_maxHighest upload speed to peers. Per channel: about 2 × the channel bitrate, between 2000 and 10000 (or a fixed value set on the panel).
upload_kbps_startWhere the upload speed limit starts (a quarter of the maximum, between 500 and 2500). Missing = 500.
cache_segments, cache_mbHow many checked segments the app keeps for others, and the byte ceiling of that cache.
min_ram_mbA device with less memory is not capable: capable:false, state off, why: "memory".
mobileoff: on mobile data the device is not capable (why: "metered"). receive: on mobile data it may download from peers but never upload.
diagtrue = send diagnostics in the next beat.
reasonWhy the server chose this mode. See the reason table below.

Modes

modeTrackerPeer linksUpload to peersDownload from peers
offclosednonenono
announceconnectedkeep neighbours openyesno
shadowconnectedopenyesyes, but only checked and counted (bytes_p2p_shadow); the player is always fed by HTTP started at once
shareconnectedopenyesyes, given to the player after the check

Reasons

reasonmodeMeaning
okshareSharing is allowed.
min_viewersannounceNot enough capable viewers on this channel on this balancer yet. Sharing starts when the count reaches the minimum and stops when it falls under 80% of it.
rampannounceSlow start: this device is not yet in the allowed share of devices.
breakerannounceThe server saw problems on this channel (bad segments, freezes, many failed attempts) and paused peer downloads for 10 to 30 minutes.
controloffThis device is in the test group. A ticket is still sent, but the tracker refuses the join; do not join.
line_offoffP2P is switched off for this line on the panel.
versionoffmod_ver is lower than the panel's minimum.
disabledoffP2P is switched off or stopped (emergency stop).

What to do with the answer

  • HTTP 200 with ok:true and a p2p object: apply it.
  • Anything else (timeout, bad JSON, ok:false, no p2p, other HTTP codes not listed below) is one failed beat: keep the current mode, try again at the next interval.
  • Two failed beats in a row: mode OFF until a beat succeeds.
  • HTTP 401, 403, 404 or 406: mode OFF at once. The session is not live on this balancer any more. Use the key of the next playlist answer.
  • If the playlist request itself fails (any non-200), go OFF at once and send leave. The app never keeps playing from peers after the playlist stopped.
  • The beat answer sets the mode. A mode message from the tracker can only make it stricter (see tracker).

The tracker (finding peers)

WS<panel address>/p2p/wson the main server

A WebSocket for signaling only. It introduces viewers of the same channel on the same balancer to each other and passes their WebRTC offer, answer and ICE messages. It does not know who holds which segment; peers tell each other directly. Text frames, one JSON object per frame.

Connection rules

  • Connect only while the mode is announce, shadow or share. No sub-protocol and no special headers are needed.
  • Send join within 10 seconds of opening, or the socket is closed.
  • If the socket cannot be opened (a proxy refuses WebSocket, HTTP 503 busy, anything), the app stays on HTTP. Playback is never affected.
  • The server sends a WebSocket ping every 20 seconds. No traffic for 60 seconds = dead: reconnect.
  • Reconnect waits: 1, 2, 4, 8, 16, 30 seconds (then 30 each time), each with a random change of ±50%.
  • If the tracker socket has been down for 60 seconds, the app must close every peer link. Without the tracker it cannot hear that a peer was removed.
  • One socket per viewing session. A second join for the same session closes the first one with error replaced.

App → tracker

{"t":"join","v":1,"ticket":"<ticket>","dev":"a3f9c2e17b604d58"}
{"t":"ticket","ticket":"<newer ticket>"}
{"t":"offer","to":"<peer id>","sdp":"..."}
{"t":"answer","to":"<peer id>","sdp":"..."}
{"t":"ice","to":"<peer id>","cand":{"candidate":"...","sdpMid":"0","sdpMLineIndex":0}}
{"t":"leave"}
MessageWhen
joinFirst message. Carries the newest ticket from the beat answer.
ticketAfter every beat answer that carries a ticket. This keeps the socket alive. No renewal before the last ticket runs out = the tracker closes the socket.
offer / answer / iceWebRTC signaling to one peer. The tracker replaces to with from and passes the rest unchanged.
leaveChannel change, stop, background, mode off. The socket is closed.

Tracker → app

{"t":"joined","you":"p0a1b2c3d4e5f","peers":[{"id":"p9f8e7d6c5b4a","rank":1},{"id":"p112233445566","rank":3}]}
{"t":"peer_join","id":"p77aa88bb99cc","rank":2}
{"t":"offer","from":"p9f8e7d6c5b4a","sdp":"..."}
{"t":"answer","from":"p9f8e7d6c5b4a","sdp":"..."}
{"t":"ice","from":"p9f8e7d6c5b4a","cand":{...}}
{"t":"peer_gone","id":"p9f8e7d6c5b4a"}
{"t":"mode","mode":"off"}
{"t":"error","code":"ticket_expired","msg":"no renewal"}
{"t":"bye","reason":"ticket expired"}
MessageMeaning and what the app does
joinedyou = this app's peer id for this socket. peers = other viewers to connect to, best first, at most 2 × neighbours. rank: 1 = same internet provider, 2 = same country, 3 = other. Prefer the lower rank.
peer_joinA new viewer the app may connect to.
offer / answer / iceSignaling from a peer. Accept an offer only from an id known from joined or peer_join.
peer_goneThat viewer left or was removed. Close the data channel to it at once and throw away any unfinished transfer from it. Also the answer when the app signals to an id the tracker did not introduce.
modeThe tracker can only make the mode stricter. off must be obeyed at once and holds until the next successful beat answer says otherwise. The tracker never raises the mode.
errorSee the code table below.
byeThe server closes the socket; reason is a short text.

Error codes

codeSocketWhat the app does
ticket_invalidclosedWait for the next beat answer, then join again with its ticket.
ticket_expiredclosedSame. If the session ended on the server, no new ticket will come and the app stays on HTTP.
replacedclosedA newer socket joined for the same session. Do not reconnect from the old one.
bad_requeststays open, except: message too large, too many messages, or a test-group ticketFix the message. Sent for: not JSON, unknown t, to missing, a message before join, a second join.

Who connects to whom

  • Start connecting right after joined and keep neighbours links open. Connection setup takes seconds; it cannot start when a segment is already needed.
  • The peer with the smaller id (plain string compare) sends the offer. If both sent one, the offer from the smaller id wins and the other is dropped.
  • Never open more than max_peers links. The tracker also never lists a viewer that already has max_peers links, and spreads new viewers so nobody becomes a hub.
  • The ticket ties the socket to the viewing session, the channel and the balancer. A renewed ticket for a different channel is refused (ticket_invalid). A renewed ticket after the player re-opened the same channel is accepted and the socket keeps its peer id and links.

Peer link (WebRTC data channel)

How two apps talk to each other once the tracker has introduced them.

ItemValue
ConnectionOne RTCPeerConnection per peer. ICE uses only the stun list from the beat answer. No TURN.
CandidatesUDP only. ICE over TCP is switched off.
Data channelOne channel, label xm-seg, ordered, reliable.
Binary frame sizeAt most 16 KiB (16,384 bytes) including the 12-byte header.
Flow controlSend only while the channel's bufferedAmount is under 256 KiB.

Control messages (text frames, JSON)

{"t":"hello","v":2,"have":[{"k":"9c1f0e6ab1d24c7f8e2a5b3c4d6e7f80","size":1843200}]}
{"t":"have","add":[{"k":"<32 hex>","size":1843200}],"del":["<32 hex>"]}
{"t":"req","id":7,"k":"<32 hex>","piece":3,"deadline_ms":2500}
{"t":"ok","id":7,"len":262144}
{"t":"nak","id":7,"why":"missing"}
{"t":"cancel","id":7}
{"t":"done","id":7}
MessageMeaning
helloFirst message on a new channel, from both sides. v is 2. have = the checked segments the sender holds (token k and size in bytes).
haveChange of the list: add for new checked segments, del for segments dropped from the cache. List only complete, checked segments that are in the sender's current playlist.
reqAsk for one piece. id is chosen by the asker and names this request. piece is the piece number. deadline_ms is how long the asker can wait.
okThe sender will send it; len = bytes of this piece. Binary frames follow, then done.
nakRefused. missing = not held any more. busy = cannot finish inside the deadline at the current upload speed. limit = over a cap.
cancelThe asker does not need it any more. The sender stops.
doneAll bytes of this request were sent.

Pieces

A segment is cut into pieces of piece_kib KiB (256 KiB). Piece n covers the bytes from n × piece to min((n+1) × piece, size). Different pieces of one segment may be asked from different peers at the same time.

Binary frame

offset  size  field (big-endian)
0       4     id    uint32   the "id" of the req
4       4     off   uint32   byte offset inside the piece
8       4     len   uint32   number of payload bytes in this frame
12      len   payload

Frames of one id are sent in rising off order with no gaps.

Checking a segment (mandatory)

A segment is complete when every piece is there. Then the app computes:

token = md5hex( md5hex(all bytes of the segment) + decimal(size in bytes) )

The result must be equal to the token in the segment URL (/hls/<token>/...).

  • Equal: the segment is checked. It may go to the player (not in shadow) and into the have list.
  • Not equal: nothing reaches the player. Fetch the whole segment by HTTP. Compare each peer piece with the HTTP bytes: every peer that sent a wrong piece is dropped for the rest of the session and counted in seg_p2p_bad. Peers whose pieces were right are kept.
  • Segments fetched by HTTP are checked the same way before they are announced to others.
  • No unchecked byte ever reaches the player. The player gets a peer segment only when the whole segment is checked.
Test vectorBytes: the ASCII text xm-peer-assist-test-vector followed by one line feed (27 bytes).
Inner MD5: 55da0f3f5a7ecbba79cb7d2645f5eb8d
Token = md5hex("55da0f3f5a7ecbba79cb7d2645f5eb8d27") = 1ca9aaa8b8351c2b582f3ce3a7ff90cb

Upload rules

Who is served

  • Serve a req only to a peer known from the tracker, and only for a checked segment that is in the app's own current playlist.
  • Answer ok only if the piece can be finished inside deadline_ms at the current upload speed; otherwise nak busy at once.
  • Run at most one upload at a time per 1,000 kbps of the current speed limit (at least 1).
  • Never upload while the app's own buffer is below floor_ms.
  • With mobile: "receive" on mobile data: never upload.

Upload speed limit (changes by itself)

Start at upload_kbps_start. Every 10 seconds:

  • Raise by 25%, up to upload_kbps_max, when neither rule below fired in that period.
  • Halve when the app's own HTTP segment fetch took both more than 30% longer and more than 500 ms longer than the median of its last 10 HTTP fetches. With fewer than 5 fetches known, this rule does not apply.
  • Halve and pause uploads when the buffer falls below floor_ms, until it is back above.

Both halving rules in one period count as one halving. The limit never goes below half of upload_kbps_start. When the server lowers upload_kbps_max, cut the running limit to it at once.

When to use peers

These rules decide, for every segment the player asks for, whether it comes from a peer or from HTTP. They protect playback.

Names: B = buffered time ahead of the playback position (ms). F = floor_ms. A = attempt_ms_max. W = wait_have_ms. T = the segment the player asks for.

  1. In the cache and checked? Serve it.
  2. Work out the time budget: A' = min(A, B − F), fixed at the moment the player asks. Use HTTP at once when any of these is true: mode is not share; group is control; A' < 2000; a cooldown is running; no peer link is open.
  3. Nobody has T yet (normal at the live edge, all viewers ask at the same moment): the devices take turns without any message. See "The turn rule" below.
  4. Can the holders deliver in time? HTTP at once when the peers that have T together cannot send the rest of the segment in the time left. The speed of a peer is the speed measured on pieces from it in the last 60 seconds; no measurement = assume half of upload_kbps_max.
  5. Peer attempt: ask the pieces from the peers that have T, several peers at once, each req with the time left as deadline_ms. The attempt ends at the latest A' after the player asked.
  6. Watch the attempt every 250 ms: estimate the finish time from the bytes received (average speed since the attempt began). Do not judge during the first fifth of the budget. No byte at all after a quarter of the budget counts as late. As soon as the estimate is later than the deadline, or the deadline is reached without a complete checked segment: cancel all, fetch the whole segment by HTTP, count it as seg_hedged (or seg_p2p_timeout) and seg_mixed, count the peer bytes as bytes_p2p_wasted, start a cooldown.
  7. Cooldown: after any failed, cancelled or bad attempt, the next cooldown_segments segments go by HTTP at once.
  8. Device breaker: one freeze counted in stall_p2p_count = the app goes to state off for 15 minutes with why: "breaker", and keeps beating.

The turn rule

When nobody has announced segment T and W > 0, exactly one device should fetch it by HTTP and the others wait for it. Every device works this out alone:

  • n = the HLS media sequence number of T (EXT-X-MEDIA-SEQUENCE plus the position of T in the list), as a decimal string.
  • For a peer id P (your own you, and the id of each neighbour): h(P) = the first 8 bytes of SHA-256 over the ASCII text P + ":" + n, read as an unsigned big-endian number.
  • The device is the seed for T when its own h is smaller than the h of every neighbour with an open data channel. Equal values: the smaller id string wins.
  • Seed: fetch by HTTP at once (a normal fetch, not counted as an attempt), check it, announce it with have.
  • Not seed: wait for a have of T, at most min(W, A'/2). When one arrives, go on to steps 4 and 5 at once; holders that announce later join the running attempt. The deadline still counts from the moment the player asked. If the wait ends first: HTTP at once, not counted as a failed attempt, no cooldown; then announce T.
  • With W = 0 or missing: HTTP at once.
Test vector for the turn ruleSegment number 48213.
p0a1b2c3d4e5f → first 8 bytes 31c2df4079bb851c = 3585673721353569564
p112233445566 → 9680159a28cd46a4 = 10844691654561842852
p9f8e7d6c5b4a → eeb7139268475759 = 17201238821300557657
The seed among these three is p0a1b2c3d4e5f.
Why the floor mattersA peer attempt can only use buffer above floor_ms. At the end of the worst attempt the player still has at least floor_ms ahead. If the player's normal buffer is smaller than floor_ms + 2 seconds, P2P will never engage on that device; set the player's buffer target above that.

A real HTTP error, or a load the player cancelled, passes through unchanged. The P2P code never hides or retries them.

States and channel change

OFF  →  CONNECTING  →  ANNOUNCE  →  SHARE   (or SHADOW)
 ↑___________any failure, stop or "off"___________|
state in the beatMeaning
offNot taking part. Give the reason in why when it is the device's own decision.
connectingAllowed by the server, opening the tracker socket and peer links.
announceConnected, serving uploads, not downloading from peers.
shareFull sharing.
shadowDownloading from peers for checking only.
  • Nothing of P2P runs on the channel-start path. The module arms only after join_after_sec of uninterrupted playback on the current channel (before that: state off, why: "settling").
  • Channel change, stop, app to background, playlist origin change, playlist error: OFF at once. Send leave, close peer links within 2 seconds, clear the cache. Do this off the main thread, so the next channel is not delayed.
  • When several players run at once (multi-screen), do not use P2P.
  • Reasons for a device to switch itself off (capable:false, state off): memory under min_ram_mb (memory); mobile data with mobile: "off" (metered); battery saver (power_save); app in background (background); connection too slow to upload (bandwidth); device breaker (breaker); internal error (error).

Stop, kill and session end

How the server ends sharing, what the app sees, and what it must do. In every case playback goes on by HTTP if the line is still allowed to watch.

What happens on the panelWhat the app seesWhat the app must do
Emergency stop (kill button) or P2P switched offTracker: {"t":"mode","mode":"off"} then bye, at once. Beat: within about 2 seconds mode: off, reason disabled, or HTTP 404. New playlists carry no key. /p2p/info answers p2p:0.OFF at once: close all peer links, clear the cache, play by HTTP. Do not reconnect the tracker until a beat answer gives a mode other than off.
P2P off for one line (button on the line)Beat: mode: off, reason line_off, within about 2 seconds. New playlist answers carry no key; the old key ends 30 seconds later (406).OFF. Keep playing by HTTP.
The server ends the connection (killed on the panel, line expired, over its connection limit)The playlist request fails (not 200). No key is refreshed, so the beat answers 406 after 30 seconds and no new ticket arrives. The tracker closes the socket when the last ticket runs out (ticket_expired, bye) and tells the others peer_gone.On the first failed playlist request: OFF at once, leave, close peer links. Never keep playing from peers after the playlist stopped. Then behave as your player normally does on that error.
Viewer changes channel or stops(started by the app)leave, close peer links within 2 seconds, clear the cache.
Problems on one channel (server breaker)Beat: mode: announce, reason breaker, for 10 minutes (30 minutes if it happens again within an hour).Keep links, serve uploads, download nothing from peers.
Panel-wide pause (too many freezes compared with the test group, 3 times in an hour)Beat: mode: announce, reason ramp, for 30 minutes; then the slow start begins again.Same as above.
Balancer restartThe key is lost; beats answer 406 (or fail). The next playlist answer carries a new key.OFF on 406. Start again with the new key as a new beat session (see the key rules).
Main server restart or updateTracker: bye, socket closed. Beats keep working.Reconnect the tracker with the normal waits. If it stays down 60 seconds, close all peer links.
A peer is removedTracker: peer_gone.Close the data channel to that peer at once; drop unfinished transfers from it.
Safety rules that are not optional A removed viewer must stop getting the stream from peers. That only works when every app: (1) closes the link on peer_gone at once, (2) closes all links when its own tracker socket was down for 60 seconds, (3) serves only peers the tracker introduced, (4) goes OFF on the first failed playlist request.

Monitoring on the panel

Everything the panel owner sees comes from the beats. If the app reports wrong values, the panel shows wrong values.

Panel → Manage Servers → Servers Tools → P2P Sharing has: an overview (traffic saved, devices, channels), the channels sharing now, a history, and Active clients with one row per viewing session.

How a device's row is worked out

Status on the panelShown reasonComes from
SharingokAnswer mode share and beat state: "share".
WaitingconnectingAnswer mode share, but the beat's state is not yet share.
Waitingmin_viewers, ramp, breakerThe reason of the answer.
Offmemory, metered, power_save, ... or deviceBeat state: "off": the panel shows the beat's why word. No why = "device".
Offline_off, version, disabledThe reason of the answer.
TestcontrolThe device is in the test group.
No reportno_reportThe session has a key but has not sent a beat yet.

Which beat fields the panel uses

Panel figureBeat fields
Traffic saved, "from viewers %"c.bytes_p2p_used against c.bytes_http
Sent to othersc.bytes_p2p_out
Freezesc.stall_count, c.stall_ms, c.stall_p2p_count, c.watch_ms
Device, network, app version, memorydevice, net, app_ver, mod_ver, ram_mb
Peers, bufferpeers, buffer_ms
Minimum viewers of a channelDevices with capable: true that sent a beat in the last 30 seconds, not in the test group, and not on mobile data while the panel's mobile setting is off.

What the server does with the counters

  • Channel breaker (per channel, per balancer, last 5 minutes). Peer downloads on that channel pause when the beats show too many bad segments, freezes after peer attempts on several devices, or too many peer attempts cancelled or timed out. The exact limits are set by the server and can change.
  • Panel breaker (last 15 minutes). Compares freeze time per watched minute of sharing devices with the test group. Clearly worse = one step back in the slow start. Three times in one hour = sharing paused for 30 minutes.
Report honestlyThese protections work only with true counters. Count every stall, every bad segment and every cancelled attempt exactly as described in the beat.

Diagnostics

The panel owner can ask one device for its recent events (button on its row in Active clients). The app then sees "diag": true in a beat answer and adds diag to its next beat, once.

"diag": [
  {"t": 371204, "e": "seg_p2p_ok",   "x": {"k": "9c1f0e6a...", "ms": 2140, "peers": 2}},
  {"t": 381310, "e": "seg_hedged",   "x": {"k": "5b3c4d6e...", "got": 393216}},
  {"t": 381950, "e": "peer_close",   "x": {"p": "p9f8e7d6c5b4a", "why": "peer_gone"}}
]
  • A JSON array of the last events, at most 50. Anything that is not an array is refused with HTTP 400.
  • t = milliseconds since the session started (monotonic). e = event name. x = free details.
  • Events to record at least: mode_change, tracker_connect, tracker_close, peer_connect, peer_close, seg_p2p_ok, seg_p2p_bad, seg_p2p_timeout, seg_hedged, breaker_on, breaker_off, memory, error.
  • The whole beat must still fit in 8 KiB. Shorten the list if needed.

Limits

LimitValueIf exceeded
Beat body8 KiBHTTP 413
Beat rate per session key1 per 3 secondsThe previous answer is sent again; nothing is recorded
Beat rate per IP address50 per second (burst 100)HTTP 429, Retry-After: 10
Session key life30 seconds after the last served playlistBeat answers 406
Device id devat most 64 charactersHTTP 400
Ticket life60 secondsTracker closes the socket
Tracker: time to join10 secondsSocket closed
Tracker: message size16 KiBbad_request, socket closed
Tracker: message rate20 per second (burst 200)bad_request, socket closed
Tracker: sockets per IP address200HTTP 503, Retry-After: 30
Tracker: slow reader64 waiting messagesSocket closed
Peer links per devicemax_peers (8)Not listed to new viewers
Data channel frame16,384 bytes-

HTTP answers

POST /p2p/beat

CodeBodyMeaningApp action
200{"ok":true,"p2p":{...}}Normal answerApply it
400{"ok":false,"error":"..."}Bad JSON; v, k, dev or seq missing; dev too long; diag not an arrayFailed beat. Fix the app.
404error pageP2P is off on this serverOFF at once
405{"ok":false,...}Not a POSTFix the app
406{"ok":false,"error":"unknown key: session not live here"}The key is unknown or endedOFF at once; use the key of the next playlist answer
413{"ok":false,...}Body over 8 KiBFailed beat. Send less.
429{"ok":false,...}Too many beats from this addressFailed beat. Wait.

GET /p2p/ws (before the WebSocket opens)

CodeMeaningApp action
101WebSocket openSend join
400Not a WebSocket requestFix the app
404P2P is off or stoppedStay on HTTP; wait for a beat answer with a mode other than off
503Tracker full, or too many sockets from this addressRetry with the normal waits

GET /p2p/info

Always HTTP 200 with the JSON answer on a panel that has the feature. Any other answer (for example 404 on an old panel) = treat as {"p2p":0,"live_hls":0}.

Not sharing? Check this

What you seeUsual cause
/p2p/info says p2p:0The switch is off on the panel, or the emergency stop is active.
No X-XM-P2P-K header in the playlist answerThe balancer is on an old core; the channel is streamed by the main server; the header X-XM-P2P: 1 was not sent on the playlist request; the line has P2P off; a proxy removes the headers.
The app plays .ts, not m3u8P2P needs HLS. Open live as m3u8 when live_hls is 1. Check that the line allows m3u8.
Beat answers 406Old key (use the newest), the playlist is no longer refreshed, or the beat went to a different server than the one that served the playlist.
Always announce, reason min_viewersToo few capable devices on this channel on this balancer. The same channel on two balancers is two separate groups. For tests, set minimum viewers to 2.
Always announce, reason rampSlow start after switch-on. Wait up to 70 minutes. Do not turn the switch off and on; that starts the steps again.
mode: off, reason controlThe device is in the test group (10% by default). Turn the test group off on the panel for tests with few devices.
Tracker socket does not openA proxy or CDN in front of the panel blocks WebSocket, or the wrong address is used. The tracker is on the panel address, not on the balancer.
Joined, but no peer link opensUDP blocked, or both devices behind strict NAT (no TURN is used). Check conn_try against conn_ok.
Links open, but few bytes from peersPlayer buffer smaller than floor_ms + 2 s; upload limit too low on the holders; every viewer at the live edge at the same moment (check the turn rule).
Panel shows many devices "Off: memory"Devices report less than min_ram_mb.

Test checklist before release

  1. Off means off. With p2p:0 the app sends exactly one new request (/p2p/info) and nothing else changes.
  2. Check. The two test vectors in this document give the same results in your code.
  3. Two devices, one channel (minimum viewers 2, test group off): both reach state share, bytes_p2p_used grows on both, no stall.
  4. Bad data. A peer that sends a wrong byte is dropped, the segment comes by HTTP, the player shows no error.
  5. Slow peer. A peer that stops sending in the middle: the attempt is cancelled in time, no stall, seg_hedged grows.
  6. Emergency stop on the panel: all peer links closed within a few seconds, playback goes on.
  7. Connection killed on the panel: the app gets no more bytes from peers after the playlist request fails.
  8. Line expired / over the connection limit: same behaviour as an app without P2P.
  9. Channel change: not slower than without P2P; old links closed within 2 seconds.
  10. Tracker blocked (firewall): playback normal, state stays connecting/off, no crash.
  11. Long run: 2 hours on one channel with 2 or more devices: memory stable, counters keep growing, no stall counted in stall_p2p_count.
  12. Encoder restart (file names start again from 0): no old segment is served for a new name, because the cache is keyed by token.
  13. Mobile data and battery saver: the device reports capable:false with the right why.
  14. Panel view: every test device shows on Active clients with the right status, reason, network and version.

P2P Sharing protocol 1.8. Needs main core 3.1.394 or newer and balancer core 1.2.406 or newer.