Skip to content
Projetos

wy3/media-server

Ver no GitHub

Sobre

Pure PHP live streaming server on Workerman: RTMP / HTTP-FLV / WS-FLV ingest and playback, fMP4 recording with time-range playback, built-in admin console.

Design e mídia

Como estes números são medidos

Crescimento medido de estrelas

em 24 h
0
em 7 dias
0
em 15 dias
0
em 1 mês
Coletando histórico

Variações líquidas em períodos sobrepostos, não totais diários. Medições ausentes ficam em branco. Estrelas indicam interesse, não qualidade.

README.md

Original

PHP Media Server

简体中文 | English

CI PHP License: MIT Latest Release Website

A media server built on Workerman, implemented in PHP: RTMP/HTTP-FLV ingest, RTMP / HTTP-FLV / WS-FLV playback, fMP4 recording and time-range playback, plus a built-in admin console.

📺 Project site (screenshots and benchmark data): https://wy3.github.io/media-server/ · 简体中文

Table of Contents

Features

Live streaming

  • Ingest
    • RTMP push to the ingest listener (rtmp://<host>:1935/<app>/<stream> by default)
    • HTTP-FLV push via POST with chunked FLV body to the ingest HTTP listener (:18081 by default)
  • Playback
    • RTMP: the play listener (rtmp://<host>:1936/<app>/<stream> by default)
    • HTTP-FLV: the play HTTP listener (http://<host>:18080/<app>/<stream>.flv by default)
    • WS-FLV: ws://<host>:18080/<app>/<stream>.flv
    • Playback filters via query string: disableAudio, disableVideo, disableGop
  • Supported codecs: H.264 / H.265 (HEVC) video, AAC audio
  • H.265 accepts both Enhanced RTMP (codecId=0 + hvc1 FourCC) and legacy codecId=12; the legacy format works with FFmpeg 6.x.
    • FourCC: a four-character code that identifies the video codec in Enhanced RTMP.

Recording

  • Real-time muxing of H.264/AAC and H.265/AAC into fragmented MP4 (ftyp + moov + moof/mdat)
  • Fragments are cut on keyframe boundaries (fragmentDurationMs, default 2000 ms)
  • Segment rotation on keyframe boundaries (segmentDurationMs, default 60000 ms), one .mp4 per segment
  • Video-only, audio-only and audio+video streams are all supported
  • Each segment carries a complete moov, so it plays standalone and is readable by ffprobe / browsers
  • Segment index stored in SQLite (recordings.db, WAL mode), queryable per publish path

Time-range playback

  • GET /playback/{publishPath}?start={ms}&end={ms}
  • start / end are wall-clock timestamps in milliseconds; omitting end plays through to the end
  • The server slices across segments, re-muxes into a new fMP4 and streams it back as video/mp4
  • Video starts at the nearest keyframe at or before start; audio start follows the video keyframe so both tracks stay aligned in duration
  • Segment boundaries are stitched on a continuous decode timeline
  • mdat payloads are streamed in chunks from the source files, so memory usage is independent of playback length

Admin console

  • Served at http://<host>:18099/admin/
  • Token-based login (in-process token, default TTL 24 hours, invalidated on restart)
  • Panels: dashboard, live streams (bitrate and detailed stream info), recordings (with time-range playback), settings
  • Chinese / English UI, switchable from the top-right selector and remembered in browser localStorage

E2E tests

  • Data-driven suite covering push → record → playback → decode verification

Requirements

  • PHP >= 8.2 (tested on PHP 8.3 / 8.4 with Workerman 5.2), extension: json
  • Composer
  • Required for multi-process: shmop extension
    • Linux / WSL deployment is supported; event is optional and improves throughput
  • Running the E2E tests requires ffmpeg / ffprobe

Quick Start

composer install
php start.php

All services run in multi-process mode. Listen addresses/ports and process counts are configured in start.php via MediaServer\ServerConfig:

Service Config fields Default
Ingest RTMP $ingestRtmpHost / $ingestRtmpPort 0.0.0.0:1935
Ingest HTTP-FLV $ingestHttpHost / $ingestHttpPort 0.0.0.0:18081
Play RTMP $playRtmpHost / $playRtmpPort 0.0.0.0:1936
Play HTTP-FLV / WS-FLV $playHttpHost / $playHttpPort 0.0.0.0:18080
Admin $adminHttpHost / $adminHttpPort 0.0.0.0:18099
Registry $registryHost / $registryPort 0.0.0.0:18090

Publish and playback have independent listeners. $ingestCount / $playCount / $recordCount control worker counts; MP_INGEST_*_PORT / MP_PLAY_*_PORT override the listen ports.

Publish

ffmpeg -re -stream_loop 1 -i file.mp4 -c:v libx264 -c:a aac -f flv rtmp://127.0.0.1/live/stream

Play

Protocol URL
RTMP rtmp://127.0.0.1/live/stream
HTTP-FLV http://127.0.0.1:18080/live/stream.flv
WS-FLV ws://127.0.0.1:18080/live/stream.flv

For web playback use mpegts.js or Aliplayer; on desktop vlc / ffplay work out of the box.

Admin console

Open http://127.0.0.1:18099/admin/ in a browser. The default account is configured in start.php.

Screenshots

The console ships with Simplified Chinese and English. Use the language selector in the top-right corner to switch; the choice is stored in browser localStorage.

Login Dashboard
Login Dashboard
Live streams Recordings
Live preview Recordings
Playback Settings
Playback Settings

Simplified Chinese UI:

登录 仪表盘
登录 仪表盘
直播预览 录像列表
直播预览 录像管理

Configuration

Edit start.php:

// Recording
\MediaServer\Recorder\RecorderManager::$enabled = true;                     // enable recording
\MediaServer\Recorder\RecorderManager::$recordPath = __DIR__ . '/record';   // recording root
\MediaServer\Recorder\RecorderManager::$fragmentDurationMs = 2000;          // fMP4 fragment duration
\MediaServer\Recorder\RecorderManager::$segmentDurationMs = 60000;          // segment file duration

// Admin console
\MediaServer\Admin\AdminAuth::$username = 'admin';
\MediaServer\Admin\AdminAuth::$password = 'admin123';
\MediaServer\Admin\AdminAuth::$tokenTtl = 86400;                            // token TTL in seconds

In production, always change the default credentials and put the admin console plus the playback endpoint behind a reverse proxy with access control.

Recording and Playback

Recording layout:

record/
├── recordings.db           # SQLite index (streams + segments)
└── live_stream/            # one directory per publish path ("/" becomes "_")
    ├── xxx.mp4
    └── yyy.mp4
  • Publish paths are sanitized into directory names, e.g. /live/stream → live_stream
  • recordings.db keeps per-segment wall-clock start/end times, duration and codec metadata
  • Playback requests are sliced and re-muxed server-side:
GET /playback/live/stream?start=1788165249473&end=1788165554005

The response is video/mp4 with a Content-Length header, so it can be assigned directly to a <video src>.

Admin API

All management calls go through one endpoint:

POST /api
Content-Type: application/json
X-Auth-Token: <token>

{"name": "listPushStream", "args": []}

Every call except login requires a valid token, supplied via X-Auth-Token, Authorization: Bearer <token>, or a token query parameter (401 otherwise).

name Description args
login Log in, returns {token, expires} [username, password]
logout Invalidate the current token [token]
getServerStats Uptime, publish/play counts, memory usage []
listPushStream Live stream list, optionally filtered by path [path?]
listRecordFiles Recording segment list, optionally filtered by path [path?]
getPlayStreamCount Playback connection count per path [path?]
getSettings Current configuration (no secrets) []

GET /api?name=...&args=[...] is also supported for read-only calls.

Performance Benchmarks

The server runs as a set of single-purpose processes (control / ingest / play / admin, recording optional) and scales horizontally by adding play or ingest workers. Benchmarks use automatic ramping: submit a batch, wait until the streams are actually registered, sample CPU over a fixed window, mark saturated when average worker CPU stays ≥80% for 30 s, then hold 40 s for stability.

Test conditions: AMD Ryzen 9 9900X (12C/24T), WSL2 (Ubuntu 24.04 / PHP 8.3.6 / event 3.2.0), 1080p30 4096 kb/s, Linux ffmpeg -c copy push (-f tee -use_fifo 1), srs-bench sb_rtmp_load pull, recording disabled.

Benchmark data (WSL2)

The server runs as native Workerman multi-process (php start.php start with $worker->count + reusePort). On Linux, workers can be pinned to physical cores (MP_CPU_AFFINITY=1; control→core 0, ingest→core 2,4,..., clients→remaining cores).

Test stream: H.264 1920×1080 @ 30fps, 4096 kbps video + AAC 128 kbps audio (4.151 Mbps per stream, 30 s sample, -c copy push).

Direction Workers Streams CPU/worker Measured throughput Result
Push ingest=8 6400 60.9% 26.99 Gbps 0 drops / 0 errors
Pull play=8 6000 21–22% 25.69 Gbps 100% held

Throughput is measured from loopback interface byte counters.

Streams share SysV segments in groups: each segment holds 64 streams by default (MP_SHM_SLOTS_PER_ARENA), so 6400 streams use about 100 segments. The number of streams per segment is adjustable.

Standard push baseline: 150 streams per ffmpeg process.

Push command uses -f tee -use_fifo 1.

See tests/bench/RESULTS.md for full benchmark data. Reproduce with tests/bench/ramp_push_linux.sh and tests/bench/hold_pull.sh.

Further reading

Document Contents
docs/rtmp-parsing-performance.md RTMP parsing hot-path analysis
docs/performance-improvements.md Performance analysis and improvement plan
tests/bench/PROCEDURE.md Full test procedure, setup, metric definitions, FAQ
tests/bench/RESULTS.md Multi-process benchmark data
tests/bench/RESULTS_EN.md Full data and analysis (English)
tests/bench/README.md Benchmark suite usage

Reproduce with:

php tests/smoke.php

# Push benchmark (WSL): 8 ingest workers, 150 streams per Linux ffmpeg
MP_CPU_AFFINITY=1 bash tests/bench/ramp_push_linux.sh 8 150 6400 400

# Pull benchmark (WSL): 8 play workers, fixed 6000 concurrent streams
bash tests/bench/hold_pull.sh 8 6000 60 2

Tests

Two suites are provided.

Smoke tests — no running server, no ffmpeg required (this is what CI runs):

php tests/smoke.php

Covers autoloading, MP4 box byte layout, RTMP handshake echo behaviour, AVC SPS parsing, recording path sanitization, SQLite index read/write, and HTTP chunked streaming (split chunks, pipelined bytes after the terminal chunk, chunk-size overflow, cleanup on disconnect).

Ingest/playback E2E verification — requires a running server plus ffmpeg / ffprobe:

# HTTP-FLV chunked publish + HTTP-FLV playback
ffmpeg -re -f lavfi -i testsrc=size=320x180:rate=15 -c:v libx264 -preset ultrafast -pix_fmt yuv420p -f flv \
  http://127.0.0.1:18081/live/test.flv
curl -N http://127.0.0.1:18080/live/test.flv

# RTMP publish + RTMP playback
ffmpeg -re -f lavfi -i testsrc=size=320x180:rate=15 -c:v libx264 -preset ultrafast -pix_fmt yuv420p -f flv \
  rtmp://127.0.0.1:1935/live/test2
ffprobe rtmp://127.0.0.1:1936/live/test2

Playback E2E tests — requires a running server plus ffmpeg / ffprobe:

php tests/playback_e2e.php            # run all cases
php tests/playback_e2e.php aonly      # run cases whose name matches

Cases are data-driven — add an entry to $CASES in tests/playback_e2e.php. Each case cleans old recordings, pushes with ffmpeg, waits for segments to land, issues playback requests, then validates tracks and duration with ffprobe and performs a full decode pass with ffmpeg.

CI runs syntax checks and the smoke suite on PHP 8.2 / 8.3 / 8.4 via GitHub Actions.

Project Layout

src/
├── Admin/        Admin console auth (token based)
├── Flv/          FLV publish/play streams
├── Http/         HTTP server (live, playback, admin, static routing)
├── MediaReader/  FLV tag parsing (AVC/AAC packets)
├── PushServer/   Publish/play stream interfaces
├── Recorder/     fMP4 muxer/recorder, playback slicer, MP4 parser, SQLite index
├── Rtmp/         RTMP protocol handling
└── Utils/        Binary/HTTP/WS stream helpers
public/admin/     Admin console SPA (vanilla JS, i18n.js holds the zh/en dictionaries)
packages/         Vendored SabreAMF
tests/            Playback E2E tests
tests/bench/      Performance benchmark suite (procedure + scripts + results)
docs/screenshots/ Admin console screenshots used by the READMEs
docs/multiprocess/ Multiprocess architecture design (split by topic)
record/           Recording output (git-ignored)

Known Limitations

  • Only H.264 / H.265 (HEVC) + AAC streams are supported; other codecs may not work
  • Browser playback of H.265 depends on OS-level HEVC decoding: on Windows the "HEVC Video Extensions" package must be installed, macOS / iOS Safari support it natively, and Chrome / Edge use the system decoder. Without it the video silently renders black (no error), so pre-flight with video.canPlayType('video/mp4; codecs="hvc1.1.6.L93.B0"')
  • H.265 push works with FFmpeg 6.x via legacy FLV codecId=12; FFmpeg 7.x is only needed for the Enhanced RTMP hvc1 variant
  • Multi-process deployment: control / ingest / play / admin / record run as separate single-purpose workers; add play workers to scale playback and ingest workers to scale publishing
  • The latency measurement method is only accurate to ±30 ms — it can detect order-of-magnitude degradation but not fine differences
  • Streams that add or drop a track mid-flight are not handled (a mid-stream track switch can corrupt the active segment)
  • The sample table for a playback request is built in memory, so very long ranges are best avoided; always bound end for long recordings
  • Fast start / slow loading may be noticeable for some players
  • Memory exhaustion is possible in specific environments — supervise the process in production

Acknowledgements

License

MIT

Explore projetos relacionados

Carregando…