Skip to content

pplayer Player Integration Guide

pplayer is PPCDN's Web player SDK, built on WHEP / WebRTC, with simulcast/ABR, HEVC/H264 multitrack support, P2P direct connect with Edge fallback, a current-frame timestamp API, end-to-end latency display, playback buffer tuning, screenshots and recording.

This page is for developers integrating playback into their own pages. To just try it, open the demo above and paste a WHEP URL into the webrtc: field.

1. Capabilities

Component Role
MediaMTXWebRTCReader WHEP protocol, WebRTC connection, RTP receive and SDP negotiation
ABREngine Tracks which quality layers exist, which is playing, and whether the server auto-selects
MMXControlClient WebSocket signaling channel for layer switching with the server
TimeSync Application-layer clock calibration against ppcenter, for end-to-end latency (optional)
codec-capability Detects HEVC decode support and chooses h264/whep vs hevc/whep (optional)
buffer-config Playback buffer (jitter buffer) length (optional)

Adaptive bitrate (ABR) decisions are made server-side; the SDK only records state and applies the server's suggested switch.

pplayer accepts the WHEP pull format only. The pull address must be a WHEP URL (https://<edge>/{appId}/{streamName}[/{h264|hevc}]/whep), or appId/streamName in the Stream box so ppcenter supplies the address; HLS, FLV, RTMP, SRT, RTSP and any other pull format is not supported and is refused with "pplayer only plays WHEP streams". WebRTC carries Opus-class audio only, so viewers hear audio only when the publisher's audio is Opus (see the ppobs guide: WHIP / SRT / ERTMP publishes accept Opus only).

2. Quick integration

2.1 Import

The SDK uses ES modules. Drop the files into your static assets and load the entry point with a plain <script type="module"> — no bundler needed:

<script type="module" src="main.js"></script>

ES modules must be served over HTTP(S); opening via file:// is blocked by the browser's CORS policy.

To use a single component instead of the whole page, import it directly:

import { MediaMTXWebRTCReader, MMXControlClient } from './ppplayer.mjs';
import { ABREngine } from './abr-engine.mjs';

2.2 Minimal example

import { MediaMTXWebRTCReader, MMXControlClient } from './ppplayer.mjs';
import { ABREngine } from './abr-engine.mjs';

const abrEngine = new ABREngine();
const whepUrl = 'https://edge-1.edge.pp-cdn.org/{appId}/{stream}/whep';

const reader = new MediaMTXWebRTCReader({
  url: whepUrl,
  maxBitrate: 2500, // optional: initial bandwidth cap (kbps)

  onTrack: (evt) => {
    const videoEl = document.getElementById('video');
    if (videoEl.srcObject !== evt.streams[0]) {
      videoEl.srcObject = evt.streams[0];
    }
  },
  onConnected: () => initControlClient(whepUrl, reader.sessionId),
  onError: (err) => console.error('playback error:', err),
});

function initControlClient(whepUrl, sessionId) {
  const controlClient = new MMXControlClient(whepUrl, sessionId, {
    onTracksInfo: (tracks, activeId) => abrEngine.setTracks(tracks, activeId),
    onLayerSwitched: (id) => abrEngine.notifyLayerSwitched(id),
    onABRMode: (auto) => abrEngine.notifyAutoMode(auto),
    onBandwidthEstimate: (bps) => abrEngine.notifyBandwidthEstimate(bps),
  });
}

You don't need to feed getStats() fps / bitrate into ABR — layer selection is decided server-side from link loss and RTT.

3. Build a play (WHEP) URL from a publish URL

Playback needs the WHEP play URL, not the WHIP publish URL. They differ by one letter; rewrite as follows:

Example
Publish URL (WHIP) https://origin.pp-cdn.org/{appId}/{stream}/whip
Play URL (WHEP) https://edge-1.edge.pp-cdn.org/{appId}/{stream}/whep

Two changes:

  1. host: origin.pp-cdn.org → any Edge domain (from the console or the play-decision API);
  2. suffix: /whip → /whep.

To pin a codec, insert /h264 or /hevc before /whep:

https://edge-1.edge.pp-cdn.org/{appId}/{stream}/hevc/whep

If you paste a whip publish URL into pplayer, it detects it and suggests the whep URL instead.

4. From a stream identity to playback: auth, path selection and codec choice

This section follows pplayer's real execution order: how an appId/streamName or signed link becomes a playable address, how pull authentication works, how P2P vs Edge is selected, and how HEVC/H264 is chosen.

4.1 Input forms

pplayer accepts three forms with different behavior:

Input Behavior
Signed link: ?ppcenter=&appId=&streamName=&txTime=&txSecret= Full ppcenter routing flow; P2P may be used
Stream box: appId/streamName or appId/streamName/h264|hevc First mints a short-lived viewer token from ppcenter, then runs the full flow
Complete WHEP URL: ?url=https://edge/.../h264/whep?txTime=...&txSecret=... Plays that URL directly and skips routing; intended for previews with a known Edge URL

A signed link requires all five parameters; a partial link is reported as malformed instead of silently downgraded. An explicit /h264 or /hevc in the Stream box overrides browser capability detection.

4.2 Pull authentication

txTime / txSecret are derived from appSecret on your backend. Never ship appSecret to the browser.

  • Signed link: your page passes the five parameters to pplayer.
  • Stream box: pplayer calls POST /v1/play/link with appId + streamName to obtain short-lived txTime / txSecret.
  • Play-decision request: POST /v1/play/requests with:
Authorization: Bearer <appId>:<txTime>:<txSecret>
  • The NAT probe submission uses the same token.
  • ppcenter's edgeStreamUrl already carries txTime / txSecret. The WHEP signature is bound to the appId/streamName/codec path, so do not change the codec segment or path after the final WHEP URL is built.
  • On an Edge 401/403, pplayer refreshes the token once, requests a new decision and reconnects once; a second rejection is surfaced as an error.

4.3 NAT probe: whether P2P is worth trying

The viewer NAT probe runs only when:

  • P2P is enabled by the viewer; and
  • the selected codec is not HEVC (P2P carries H264 + Opus only).

Flow:

  1. Gather local ICE candidates over STUN, preferring IPv4 server-reflexive;
  2. Submit POST /v1/nat/probe with kind=player, streamName, clientId and the candidate;
  3. ppcenter returns a probeId, which is sent as natProbeId in the play-decision request.

The probe is given 800ms. If it is still running, pplayer requests a decision without it and lets the probe finish in the background, so a slow STUN server never blocks Edge startup. The publisher-side probe comes from ppobs; when it is missing, ppcenter returns missing_publisher_probe and selects Edge.

4.4 Request the play decision

Key fields of POST /v1/play/requests:

{
  "streamName": "<streamName>",
  "clientId": "<uuid>",
  "requestRegion": "<optional>",
  "codec": "<optional: h264|hevc>",
  "natProbeId": "<optional>",
  "capabilities": ["whep", "p2p-h264-opus"]
}
  • With P2P allowed and a non-HEVC codec, capabilities includes p2p-h264-opus;
  • With P2P off or HEVC selected, only whep is sent and ppcenter answers edge-only;
  • While ppcenter cannot see the stream it may return 503 no_edge_available / no_healthy_edge; pplayer retries up to 6 times, every 2 seconds. Authentication/validation errors (401/403/400) are not retried.

Response fields:

Field Meaning
mode edge-only or p2p-connect
edgeStreamUrl Edge stream base URL, already signed, usually without a codec segment or /whep
p2p Signaling URL, token, sessionId and STUN list for p2p-connect
p2pAvailable ppcenter's explicit "P2P is usable now" flag; when false, go straight to Edge even if mode is p2p-connect
reason Why this path was chosen, e.g. missing_publisher_probe, p2p_not_requested

4.5 P2P / Edge selection

Edge-only

mode=edge-only or p2pAvailable=false
    -> connect Edge WHEP directly with edgeStreamUrl

P2P-connect

mode=p2p-connect and p2pAvailable != false
    -> connect P2P first; Edge is only a sequential fallback

P2P steps:

  1. Open the ppcdn-p2p-v1 WebSocket at decision.p2p.signalUrl, with the token as a subprotocol;
  2. Wait for the publisher's ready, then create a recvonly offer preferring H264;
  3. Exchange offer/answer/ICE; use decision.p2p.stunServers for ICE;
  4. On ontrack, attach the media stream to <video>;
  5. A first frame must be decoded within the grace window: 5s for the handshake and roughly max(4s, connectTimeoutMs + 2s) for the first frame;
  6. Any signaling/ICE failure, missing answer, missing first frame or blocked SEI transform stops P2P and falls back sequentially to edgeStreamUrl;
  7. P2P carries one H264 layer + Opus only and has no ABR layer switching.

After Edge connects, pplayer opens MMXControlClient over /ws/control to receive the track/layer list and ABR mode. Layer switching is available on the Edge path only.

4.6 HEVC / H264 choice

The codec is fixed before the WHEP handshake and cannot be switched mid-play like ABR layers:

  1. An explicit /h264, /hevc or ?codec= in the Stream box / signed link wins;
  2. Otherwise codec-capability probes support:
  3. navigator.mediaCapabilities.decodingInfo();
  4. fallback to RTCRtpReceiver.getCapabilities('video');
  5. HEVC is chosen only when one probe affirmatively supports it, otherwise H264;
  6. A forced HEVC request falls back to H264 when local decode capability is absent;
  7. P2P is always H264; selecting HEVC omits the p2p-h264-opus capability and goes Edge-only;
  8. The final URL is built by buildEdgeWhepUrl(edgeStreamUrl, codec):
.../{appId}/{streamName}/h264/whep?txTime=...&txSecret=...
.../{appId}/{streamName}/hevc/whep?txTime=...&txSecret=...

The query from edgeStreamUrl is preserved; only the codec and /whep segments are inserted into the path.

4.7 End-to-end timeline

appId/streamName / signed link
        |
        +-- Stream box: POST /v1/play/link -> txTime/txSecret
        |
        +-- (optional) STUN gather + POST /v1/nat/probe -> probeId
        |        (800ms grace; continue without it on timeout)
        |
        +-- POST /v1/play/requests
        |        capabilities=[whep(,p2p-h264-opus)]
        |        -> mode / edgeStreamUrl / p2p / p2pAvailable
        |
        +-- mode=p2p-connect && p2pAvailable != false
        |        -> P2P signaling / ICE / first frame
        |        -> sequential Edge fallback on failure
        |
        +-- otherwise Edge WHEP
                 -> codec capability detection
                 -> buildEdgeWhepUrl
                 -> WHEP authentication and playback
                 -> MMXControlClient manages ABR

5. Optional: browser auto-selects HEVC / H264

With multitrack enabled, the server exposes separate h264 and hevc paths. The codec must be chosen once before connecting — it cannot be switched mid-play the way ABR switches layers.

codec-capability detects HEVC decode support (preferring mediaCapabilities.decodingInfo(), falling back to RTCRtpReceiver.getCapabilities('video')) and inserts the chosen codec segment into the WHEP URL:

.../{stream}/whep  →  .../{stream}/hevc/whep   (HEVC supported)
.../{stream}/whep  →  .../{stream}/h264/whep   (unsupported or module not imported)
  • If the URL already contains /h264/whep or /hevc/whep, detection is skipped.
  • You can force it with the URL param ?codecType=hevc.
  • If HEVC is chosen but the connection fails with a codec/SDP-looking reason, it automatically downgrades to H264 and reconnects once within the same playback.

6. Optional: playback buffer (latency vs jitter tolerance)

The buffer decides how many milliseconds of media to cache before rendering: larger tolerates more jitter but adds latency; smaller lowers latency but stutters more easily. It is purely local, not negotiated with the server.

  • Default 50 ms, usable range 50–1000 ms;
  • URL param ?bufferMs=300 presets it; the UI slider overrides live;
  • Prefers RTCRtpReceiver.jitterBufferTarget, falling back to Chrome's playoutDelayHint.
import { applyPlayoutBuffer } from './buffer-config.mjs';
const applied = applyPlayoutBuffer(pc, 300); // returns the API actually applied, or null

7. Optional: end-to-end latency (TimeSync)

ppobs embeds UTC-calibrated timestamps in the bitstream. To compute "end-to-end latency = calibrated local now − in-frame timestamp", the player must first align its clock to UTC — using an uncalibrated Date.now() gives wrong results.

TimeSync performs one application-layer clock-offset estimate against ppcenter (NTP's four-timestamp algorithm, several rounds, keeping the one with the lowest RTT; re-calibrates every 10 minutes by default):

import { TimeSync } from './time-sync.mjs';

const timeSync = new TimeSync({ ppcenter: 'https://api.pp-cdn.org' });
timeSync.start().catch((e) => console.warn('calibration unavailable:', e.message));

const now = timeSync.now(); // null until calibration completes
if (now !== null) {
  const delayMs = now - embeddedTimestamp;
}

Key convention: now() returns null before calibration completes; treat that as "latency not computable yet" and do not fall back to a raw Date.now(). Without the module or when ppcenter is unreachable, playback is unaffected and the latency display falls back to an estimate.

TimeSync can also report latency via reportLatency({ path, delayMs }), where path is 'edge' or 'p2p'.

8. P2P direct connect and Edge fallback

The current version does not race both connections in the client. ppcenter's play decision determines whether P2P is used; the player executes that decision and falls back to Edge sequentially if P2P fails:

  • mode=p2p-connect with p2pAvailable != false: connect P2P first; if it fails or produces no first frame within the timeout, fall back to the edgeStreamUrl WHEP;
  • mode=edge-only or p2pAvailable=false: connect Edge WHEP directly.

p2pAvailable is ppcenter's explicit availability flag (traversable pair AND a free publisher P2P slot); an older ppcenter without the field is handled by mode. P2P carries a single H264 video layer; ABR layer selection is available on Edge only.

To enable, the URL must carry all five parameters (missing any is a clear error, not a silent downgrade):

index.html?ppcenter=https://api.pp-cdn.org&appId=<appId>&streamName=<stream>&txTime=<hex>&txSecret=<hmac>

Flow: NAT probe and report → request a play decision from ppcenter → it returns edge-only (WHEP only) or p2p-connect (plus P2P session params). Whether P2P is used is decided entirely by the server.

Without these parameters, the player uses the WHEP URL in the input box and the P2P code never runs — this is edge-only integration.

txTime / txSecret are derived from appSecret; never put appSecret into a play page or share link. To issue short-lived tokens to players, have your own server call ppcenter's open API.

9. Screenshot & recording

The control bar offers 📷 screenshot and ⏺ record buttons; the logic lives in main.js:

  • Screenshot: captures the current frame with <canvas> and downloads a PNG;
  • Record: records the picture to WebM with MediaRecorder, up to 60 s, stoppable early;
  • Both are disabled in ABR Auto mode: resolution/bitrate switching on the fly would make captures jump, so pick a quality layer manually first.

10. File list

File Role
main.js Entry: UI binding, playback orchestration
ppplayer.mjs MediaMTXWebRTCReader + MMXControlClient
abr-engine.mjs Layer state tracking
time-sync.mjs Clock calibration
obs-timestamp.mjs End-to-end latency computation
sei-timestamp.mjs In-bitstream SEI timestamp parsing (Chromium)
codec-capability.mjs HEVC/H264 capability detection
buffer-config.mjs Playback buffer length
play-request.mjs Requests a play decision from ppcenter
nat-probe.mjs NAT type probe
playback-paths.mjs The Edge / P2P playback paths
playback-race-controller.mjs Legacy rollback only; the normal playback flow no longer uses it
play-decision-runner.mjs Starts Edge or direct P2P from the ppcenter decision

11. Interface reference

pplayer exposes two layers of interfaces:

  • Page API: window.pplayer, created when the standalone entry point main.js is loaded;
  • SDK module API: ES modules imported on demand. Importing the modules alone does not create window.pplayer.

11.1 Page API: window.pplayer

API Description
getCurrentFrameTimestamp() Returns the latest publisher frame timestamp, or null when no frame is available or none arrived in the last 5 s
onFrameTimestamp Optional per-frame callback: (frame) => void

getCurrentFrameTimestamp() returns:

{
  timestampMs: 1793347200123,  // absolute UTC ms stamped by ppobs in the bitstream
  source: 'sei',               // 'sei' | 'relay'
  path: 'edge',                // 'edge' | 'p2p'
  receivedAtMs: 1793347200198, // local Date.now() when the player read it
  ageMs: 75                    // milliseconds since it was read
}

Usage:

// Per-frame callback
window.pplayer.onFrameTimestamp = (frame) => {
  console.log('frame timestamp', frame.timestampMs, frame.source, frame.path);
};

// Or read the latest frame whenever needed; null when unavailable
const frame = window.pplayer.getCurrentFrameTimestamp();
if (frame) {
  const now = timeSync.now(); // calibrated clock, null before calibration
  const delayMs = now === null ? null : now - frame.timestampMs;
}

Notes:

  • timestampMs is the publisher-side encode time, not the local browser render time. Chromium reads it directly from the in-band SEI; other browsers fall back to the OBS_TIMESTAMP relayed by mmx over the control channel.
  • It returns null before the first frame, while paused, after switching streams, or after 5 s without a new media frame. Do not cache stale values.
  • To get the local display time, use requestVideoFrameCallback instead of treating timestampMs as the render time:
const videoEl = document.getElementById('video');
videoEl.requestVideoFrameCallback((now, meta) => {
  const displayWallMs = performance.timeOrigin + meta.presentationTime;
});

11.2 MediaMTXWebRTCReader(config)

Param Type Required Notes
url String yes Full WHEP URL
videoCodec String no 'h264' or 'hevc', pins the receive codec
maxBitrate Number no Initial max bandwidth (kbps) for SDP b=AS
user / pass String no Basic Auth
token String no Bearer token
insertableStreams Boolean no Enables encoded-stream transforms; set to true to read SEI
onTrack Function no (RTCTrackEvent) => void, fired when a media track arrives
onConnected Function no Fired when the WHEP handshake completes
onError Function no (message, httpStatus) => void
onUnauthorized Function no Fired on 401/403

Properties sessionId (read-only), pc (the underlying RTCPeerConnection); method close().

11.3 MMXControlClient(whepUrl, sessionId, callbacks)

Callbacks:

  • onConnected / onDisconnected
  • onTracksInfo(tracks, activeId)
  • onLayerSwitched(id)
  • onABRMode(auto)
  • onBandwidthEstimate(bps)
  • onAbrRecommend(targetTrackId)
  • onObsTimestamp(data): the relayed OBS_TIMESTAMP; data.timestamp is the publisher's absolute ms

Methods:

  • selectLayer(trackId, reason): request a layer switch. Use the exported constant ABR_REASON_AUTO_BANDWIDTH for reason to mean "apply the server suggestion" (stays in Auto); any other value means the user picked manually.
  • setABRMode(auto): hand layer selection back to the server (true) or take it (false).
  • close(): close the connection.

11.4 ABREngine

Properties isAutoMode, currentTrackId, lastBandwidthEstimate; methods setTracks, notifyLayerSwitched, notifyManualSwitch, notifyAutoMode, setAutoMode, selectedTrackId().

11.5 Low-level frame timestamp: attachSeiTimestampReader

When you import the SDK without the standalone page, read each frame's SEI timestamp directly:

import { MediaMTXWebRTCReader } from './ppplayer.mjs';
import { attachSeiTimestampReader, attachPassthroughTransform } from './sei-timestamp.mjs';

const reader = new MediaMTXWebRTCReader({
  url: whepUrl,
  videoCodec: 'h264',
  insertableStreams: true,
  onTrack: (evt) => {
    if (evt.track.kind === 'video' && evt.receiver) {
      attachSeiTimestampReader(evt.receiver, (timestampMs) => {
        console.log('frame timestamp', timestampMs);
      }, 'h264'); // 'h264' | 'hevc'
    }
    if (evt.track.kind === 'audio' && evt.receiver) {
      attachPassthroughTransform(evt.receiver);
    }
  },
});
  • false means the browser does not support createEncodedStreams() (mostly non-Chromium).
  • With insertableStreams enabled, the audio receiver must also consume its encoded stream, otherwise packets arrive but produce no sound; attachPassthroughTransform handles that.
  • On non-Chromium browsers or when SEI is unavailable, use MMXControlClient's onObsTimestamp fallback.
  • findObsAbsTimestamp(data, codec) parses the timestamp from a single Annex-B access unit for custom pipelines.

11.6 TimeSync

Method/property Description
new TimeSync({ ppcenter, resyncIntervalMs, sampleCount, onStateChange }) ppcenter is the base URL; defaults to a 10-minute resync and 6 samples
start() Connects and runs the first calibration; returns Promise<Boolean>
now() Calibrated UTC ms; null until calibration completes
isReady() Whether at least one calibration has completed
reportLatency({ path, delayMs }) Reports latency; path is 'edge' or 'p2p'
stop() Stops calibration and closes the connection
offsetMs / lastSyncRttMs Current offset and RTT of the sample used

Key convention: now() returns null before calibration completes; do not fall back to raw Date.now() to compute latency.

12. FAQ

Q: Blank page / CORS error? ES modules must be loaded over HTTP(S); file:// won't work.

Q: Safari / iOS doesn't autoplay? Autoplay policy requires one user gesture to start playback.

Q: The latency display is empty? The clock is not calibrated yet (TimeSync.now() returns null); wait for calibration to complete.

Q: P2P didn't connect? Under symmetric NAT / CGNAT, no direct P2P is normal; the player falls back to Edge automatically and viewing is unaffected.