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.
/p2p/info). Keeps one WebSocket open to the tracker (/p2p/ws) to find other viewers./p2p/beat).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)
| Requirement | Detail |
|---|---|
| Core versions | Main 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 on | Panel → 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 balancer | Sharing 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 line | The line must be allowed to use the m3u8 output format. P2P works only on HLS, never on .ts streams. |
| Normal HLS segments | The playlist must list segments as /hls/<32 hex>/<name>.ts. Other playlist shapes (proxy paths, restream lines) are not capable. |
| Minimum viewers | Setting 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 group | Default on, 10% of devices. These devices stay on HTTP on purpose, so the panel can compare freezes. They get group: "control". |
| Slow start | After 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 data | Setting off (default: no P2P on mobile data) or receive (download from peers allowed, upload never). |
| WebSocket to the panel | The 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 balancer | It 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. |
| STUN | The 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)
| Requirement | Detail |
|---|---|
| HLS player with a custom segment loader | The 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 channels | Any WebRTC library with reliable ordered data channels and STUN. No audio or video tracks are used. |
| WebSocket client | Text frames, answers server pings (standard pong). |
| MD5 and SHA-256 | MD5 to check segments, SHA-256 for the turn rule. |
| Device facts | RAM size, network type (wifi, ethernet, mobile), battery saver state, buffer length of the player, stall events. |
| A device id | A random id made once per install, 16 hex characters. Not a hardware id. |
| Monotonic clock | All 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.
- After login, the app asks
GET /p2p/infoon the panel address. Answerp2p:0: stop here, behave as an app without P2P. - Open a live channel as m3u8 (when
live_hlsis 1 and the line allows m3u8). Add the headerX-XM-P2P: 1to every live playlist request. Not to segment requests. - Read the answer header
X-XM-P2P-Kof the playlist. Present: this is the session key. Missing: no P2P on this channel; do nothing more. - Play normally by HTTP for
join_after_sec(30 seconds) without interruption. Nothing of P2P runs during channel start. - Send the first beat:
POST /p2p/beatto the same origin that served the playlist. Then one beat every 10 seconds. - Obey the answer.
mode: off: stay on HTTP, keep beating. Any other mode: the answer carries aticket. - Open the tracker socket on the panel address, send
joinwith the ticket. The tracker answersjoinedwith your peer id and a list of other viewers. - Connect to the listed peers by WebRTC. Offer, answer and ICE go through the tracker socket. Open one data channel per peer.
- Exchange
havelists on each data channel: which checked segments each side holds. - 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. - After every beat answer send the new ticket to the tracker (
{"t":"ticket",...}). Without it the tracker closes the socket after 60 seconds. - 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/infoand 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
Tells the app if P2P Sharing is on for this panel. No parameters, no login. HEAD is also accepted.
{"p2p":1,"live_hls":1}
| Field | Value | Meaning |
|---|---|---|
p2p | 0 | 1 | 1 = P2P Sharing is on. 0 = off (also during an emergency stop). |
live_hls | 0 | 1 | 1 = 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:0the app must stay fully asleep: noX-XM-P2Pheader, no beat, no socket, no change of format, and no more/p2p/inforequests 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
The app plays the live m3u8 URL the panel API gave it, as always. Two headers are added around it.
| Header | Direction | Meaning |
|---|---|---|
X-XM-P2P: 1 | app → 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 → app | The 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:
seqstarts again at 1 and all counters incstart 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
Rangeon 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)
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 everybeat_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} ]
}
| Field | Type | Meaning | |
|---|---|---|---|
v | int | required | Always 1. |
k | string | required | The session key from the newest playlist answer. |
dev | string | required | Device 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. |
seq | int | required | Beat counter of this session. Starts at 1, +1 for every beat sent. |
mod_ver | int | required | Protocol level of the app. Send 2 for this document. The panel can set a minimum; a lower value is answered off, reason version. |
app_ver | string | optional | App version text, at most 24 characters. Shown on the panel. |
state | string | required | What the app is doing now: off, connecting, announce, share or shadow. |
capable | bool | required | true when this device could share right now. Only capable devices count for the minimum viewers of a channel. |
why | string | optional | The 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. |
net | string | required | wifi, eth, mobile or other. |
device | string | optional | tv, phone, tablet, stick or other. |
api | int | optional | OS API level (Android), or 0. |
ram_mb | int | optional | Total memory of the device in MB. Shown on the panel next to the reason memory. |
buffer_ms | int | optional | Buffered time ahead of the playback position. |
peers | int | optional | Number of open peer links now. |
c | object | required | Counters, see below. |
conn | array | optional | Results of peer connection attempts since the last beat, at most 16 entries: peer id, success, time in ms. |
diag | array | optional | Only 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.
| Counter | Meaning |
|---|---|
bytes_http | Segment bytes fetched from the balancer by HTTP. |
bytes_p2p_used | Bytes from peers that were checked and given to the player. This is the saving. |
bytes_p2p_shadow | Bytes from peers checked in shadow mode (the player was fed by HTTP). |
bytes_p2p_wasted | Bytes from peers received and then not used (attempt cancelled, timed out, or bad). |
bytes_p2p_out | Bytes this device sent to peers. |
seg_http | Segments fetched by HTTP in the normal way. |
seg_p2p | Segments where all bytes came from peers. |
seg_mixed | HTTP fetches that replaced a failed, cancelled or bad peer attempt. |
seg_p2p_timeout | Peer attempts that reached their deadline. |
seg_p2p_bad | Peer segments that failed the check. |
seg_hedged | Peer attempts cancelled early because they would be late. |
conn_try, conn_ok | Peer connections tried, and opened. |
stall_count, stall_ms | Freezes of the player and their total length. |
stall_p2p_count | Freezes 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_ms | Time played in this session. |
dropped_frames, zap_ms_last | Dropped video frames; start time of the last channel change. |
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"
}
}
| Field | Meaning |
|---|---|
mode | What the app must do. See the mode table below. |
group | p2p or control. control = test group: stay on HTTP, treat as mode off, but keep beating. |
tracker | Where 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. |
ticket | A signed pass for the tracker, at most 512 characters. Sent with every mode other than off. No ticket = treat as mode off. |
ticket_ttl | Life of the ticket in seconds (60), counted from when the app received it. |
stun | STUN servers for WebRTC (up to 4). |
beat_sec, join_after_sec | Beat interval; wait before the first beat and before P2P arms on a new channel. |
floor_ms | Protected buffer. P2P may only use buffer above this. Per channel: 1000 × segment seconds, between 6000 and 15000. |
attempt_ms_max | Longest time one peer attempt may hold a segment. Per channel: 800 × segment seconds, between 2000 and 10000. |
wait_have_ms | Longest 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_segments | Number of segments that go by HTTP at once after any failed peer attempt. |
stall_window_sec | Window for stall_p2p_count. |
neighbours | Peer links the app should keep open. |
max_peers | The app never holds more peer links than this. |
piece_kib | Piece size for peer transfers, in KiB. |
upload_kbps_max | Highest 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_start | Where the upload speed limit starts (a quarter of the maximum, between 500 and 2500). Missing = 500. |
cache_segments, cache_mb | How many checked segments the app keeps for others, and the byte ceiling of that cache. |
min_ram_mb | A device with less memory is not capable: capable:false, state off, why: "memory". |
mobile | off: on mobile data the device is not capable (why: "metered"). receive: on mobile data it may download from peers but never upload. |
diag | true = send diagnostics in the next beat. |
reason | Why the server chose this mode. See the reason table below. |
Modes
| mode | Tracker | Peer links | Upload to peers | Download from peers |
|---|---|---|---|---|
off | closed | none | no | no |
announce | connected | keep neighbours open | yes | no |
shadow | connected | open | yes | yes, but only checked and counted (bytes_p2p_shadow); the player is always fed by HTTP started at once |
share | connected | open | yes | yes, given to the player after the check |
Reasons
| reason | mode | Meaning |
|---|---|---|
ok | share | Sharing is allowed. |
min_viewers | announce | Not 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. |
ramp | announce | Slow start: this device is not yet in the allowed share of devices. |
breaker | announce | The server saw problems on this channel (bad segments, freezes, many failed attempts) and paused peer downloads for 10 to 30 minutes. |
control | off | This device is in the test group. A ticket is still sent, but the tracker refuses the join; do not join. |
line_off | off | P2P is switched off for this line on the panel. |
version | off | mod_ver is lower than the panel's minimum. |
disabled | off | P2P is switched off or stopped (emergency stop). |
What to do with the answer
- HTTP 200 with
ok:trueand ap2pobject: apply it. - Anything else (timeout, bad JSON,
ok:false, nop2p, 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
modemessage from the tracker can only make it stricter (see tracker).
The tracker (finding peers)
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,shadoworshare. No sub-protocol and no special headers are needed. - Send
joinwithin 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
joinfor the same session closes the first one with errorreplaced.
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"}
| Message | When |
|---|---|
join | First message. Carries the newest ticket from the beat answer. |
ticket | After 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 / ice | WebRTC signaling to one peer. The tracker replaces to with from and passes the rest unchanged. |
leave | Channel 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"}
| Message | Meaning and what the app does |
|---|---|
joined | you = 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_join | A new viewer the app may connect to. |
offer / answer / ice | Signaling from a peer. Accept an offer only from an id known from joined or peer_join. |
peer_gone | That 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. |
mode | The 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. |
error | See the code table below. |
bye | The server closes the socket; reason is a short text. |
Error codes
| code | Socket | What the app does |
|---|---|---|
ticket_invalid | closed | Wait for the next beat answer, then join again with its ticket. |
ticket_expired | closed | Same. If the session ended on the server, no new ticket will come and the app stays on HTTP. |
replaced | closed | A newer socket joined for the same session. Do not reconnect from the old one. |
bad_request | stays open, except: message too large, too many messages, or a test-group ticket | Fix 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
joinedand keepneighbourslinks 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_peerslinks. The tracker also never lists a viewer that already hasmax_peerslinks, 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.
| Item | Value |
|---|---|
| Connection | One RTCPeerConnection per peer. ICE uses only the stun list from the beat answer. No TURN. |
| Candidates | UDP only. ICE over TCP is switched off. |
| Data channel | One channel, label xm-seg, ordered, reliable. |
| Binary frame size | At most 16 KiB (16,384 bytes) including the 12-byte header. |
| Flow control | Send 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}
| Message | Meaning |
|---|---|
hello | First message on a new channel, from both sides. v is 2. have = the checked segments the sender holds (token k and size in bytes). |
have | Change 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. |
req | Ask 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. |
ok | The sender will send it; len = bytes of this piece. Binary frames follow, then done. |
nak | Refused. missing = not held any more. busy = cannot finish inside the deadline at the current upload speed. limit = over a cap. |
cancel | The asker does not need it any more. The sender stops. |
done | All 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 thehavelist. - 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.
xm-peer-assist-test-vector followed by one line feed (27 bytes).Inner MD5:
55da0f3f5a7ecbba79cb7d2645f5eb8dToken = md5hex("55da0f3f5a7ecbba79cb7d2645f5eb8d27") =
1ca9aaa8b8351c2b582f3ce3a7ff90cbUpload rules
Who is served
- Serve a
reqonly to a peer known from the tracker, and only for a checked segment that is in the app's own current playlist. - Answer
okonly if the piece can be finished insidedeadline_msat the current upload speed; otherwisenak busyat 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.
- In the cache and checked? Serve it.
- 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 notshare; group iscontrol;A' < 2000; a cooldown is running; no peer link is open. - Nobody has
Tyet (normal at the live edge, all viewers ask at the same moment): the devices take turns without any message. See "The turn rule" below. - Can the holders deliver in time? HTTP at once when the peers that have
Ttogether 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 ofupload_kbps_max. - Peer attempt: ask the pieces from the peers that have
T, several peers at once, eachreqwith the time left asdeadline_ms. The attempt ends at the latestA'after the player asked. - 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:
cancelall, fetch the whole segment by HTTP, count it asseg_hedged(orseg_p2p_timeout) andseg_mixed, count the peer bytes asbytes_p2p_wasted, start a cooldown. - Cooldown: after any failed, cancelled or bad attempt, the next
cooldown_segmentssegments go by HTTP at once. - Device breaker: one freeze counted in
stall_p2p_count= the app goes to stateofffor 15 minutes withwhy: "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 ofT(EXT-X-MEDIA-SEQUENCEplus the position ofTin the list), as a decimal string.- For a peer id
P(your ownyou, and theidof each neighbour):h(P)= the first 8 bytes of SHA-256 over the ASCII textP + ":" + n, read as an unsigned big-endian number. - The device is the seed for
Twhen its ownhis smaller than thehof 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
haveofT, at mostmin(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 announceT. - With
W= 0 or missing: HTTP at once.
48213.p0a1b2c3d4e5f → first 8 bytes 31c2df4079bb851c = 3585673721353569564p112233445566 → 9680159a28cd46a4 = 10844691654561842852p9f8e7d6c5b4a → eeb7139268475759 = 17201238821300557657The seed among these three is
p0a1b2c3d4e5f.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 beat | Meaning |
|---|---|
off | Not taking part. Give the reason in why when it is the device's own decision. |
connecting | Allowed by the server, opening the tracker socket and peer links. |
announce | Connected, serving uploads, not downloading from peers. |
share | Full sharing. |
shadow | Downloading from peers for checking only. |
- Nothing of P2P runs on the channel-start path. The module arms only after
join_after_secof uninterrupted playback on the current channel (before that: stateoff,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, stateoff): memory undermin_ram_mb(memory); mobile data withmobile: "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 panel | What the app sees | What the app must do |
|---|---|---|
| Emergency stop (kill button) or P2P switched off | Tracker: {"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 restart | The 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 update | Tracker: 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 removed | Tracker: peer_gone. | Close the data channel to that peer at once; drop unfinished transfers from it. |
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 panel | Shown reason | Comes from |
|---|---|---|
| Sharing | ok | Answer mode share and beat state: "share". |
| Waiting | connecting | Answer mode share, but the beat's state is not yet share. |
| Waiting | min_viewers, ramp, breaker | The reason of the answer. |
| Off | memory, metered, power_save, ... or device | Beat state: "off": the panel shows the beat's why word. No why = "device". |
| Off | line_off, version, disabled | The reason of the answer. |
| Test | control | The device is in the test group. |
| No report | no_report | The session has a key but has not sent a beat yet. |
Which beat fields the panel uses
| Panel figure | Beat fields |
|---|---|
| Traffic saved, "from viewers %" | c.bytes_p2p_used against c.bytes_http |
| Sent to others | c.bytes_p2p_out |
| Freezes | c.stall_count, c.stall_ms, c.stall_p2p_count, c.watch_ms |
| Device, network, app version, memory | device, net, app_ver, mod_ver, ram_mb |
| Peers, buffer | peers, buffer_ms |
| Minimum viewers of a channel | Devices 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.
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
| Limit | Value | If exceeded |
|---|---|---|
| Beat body | 8 KiB | HTTP 413 |
| Beat rate per session key | 1 per 3 seconds | The previous answer is sent again; nothing is recorded |
| Beat rate per IP address | 50 per second (burst 100) | HTTP 429, Retry-After: 10 |
| Session key life | 30 seconds after the last served playlist | Beat answers 406 |
Device id dev | at most 64 characters | HTTP 400 |
| Ticket life | 60 seconds | Tracker closes the socket |
Tracker: time to join | 10 seconds | Socket closed |
| Tracker: message size | 16 KiB | bad_request, socket closed |
| Tracker: message rate | 20 per second (burst 200) | bad_request, socket closed |
| Tracker: sockets per IP address | 200 | HTTP 503, Retry-After: 30 |
| Tracker: slow reader | 64 waiting messages | Socket closed |
| Peer links per device | max_peers (8) | Not listed to new viewers |
| Data channel frame | 16,384 bytes | - |
HTTP answers
POST /p2p/beat
| Code | Body | Meaning | App action |
|---|---|---|---|
| 200 | {"ok":true,"p2p":{...}} | Normal answer | Apply it |
| 400 | {"ok":false,"error":"..."} | Bad JSON; v, k, dev or seq missing; dev too long; diag not an array | Failed beat. Fix the app. |
| 404 | error page | P2P is off on this server | OFF at once |
| 405 | {"ok":false,...} | Not a POST | Fix the app |
| 406 | {"ok":false,"error":"unknown key: session not live here"} | The key is unknown or ended | OFF at once; use the key of the next playlist answer |
| 413 | {"ok":false,...} | Body over 8 KiB | Failed beat. Send less. |
| 429 | {"ok":false,...} | Too many beats from this address | Failed beat. Wait. |
GET /p2p/ws (before the WebSocket opens)
| Code | Meaning | App action |
|---|---|---|
| 101 | WebSocket open | Send join |
| 400 | Not a WebSocket request | Fix the app |
| 404 | P2P is off or stopped | Stay on HTTP; wait for a beat answer with a mode other than off |
| 503 | Tracker full, or too many sockets from this address | Retry 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 see | Usual cause |
|---|---|
/p2p/info says p2p:0 | The switch is off on the panel, or the emergency stop is active. |
No X-XM-P2P-K header in the playlist answer | The 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 m3u8 | P2P needs HLS. Open live as m3u8 when live_hls is 1. Check that the line allows m3u8. |
| Beat answers 406 | Old 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_viewers | Too 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 ramp | Slow 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 control | The 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 open | A 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 opens | UDP blocked, or both devices behind strict NAT (no TURN is used). Check conn_try against conn_ok. |
| Links open, but few bytes from peers | Player 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
- Off means off. With
p2p:0the app sends exactly one new request (/p2p/info) and nothing else changes. - Check. The two test vectors in this document give the same results in your code.
- Two devices, one channel (minimum viewers 2, test group off): both reach state
share,bytes_p2p_usedgrows on both, no stall. - Bad data. A peer that sends a wrong byte is dropped, the segment comes by HTTP, the player shows no error.
- Slow peer. A peer that stops sending in the middle: the attempt is cancelled in time, no stall,
seg_hedgedgrows. - Emergency stop on the panel: all peer links closed within a few seconds, playback goes on.
- Connection killed on the panel: the app gets no more bytes from peers after the playlist request fails.
- Line expired / over the connection limit: same behaviour as an app without P2P.
- Channel change: not slower than without P2P; old links closed within 2 seconds.
- Tracker blocked (firewall): playback normal, state stays
connecting/off, no crash. - Long run: 2 hours on one channel with 2 or more devices: memory stable, counters keep growing, no stall counted in
stall_p2p_count. - Encoder restart (file names start again from 0): no old segment is served for a new name, because the cache is keyed by token.
- Mobile data and battery saver: the device reports
capable:falsewith the rightwhy. - 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.