PHPackages                             xiaosongshu/rtmp\_server - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. xiaosongshu/rtmp\_server

ActiveProject[Utility &amp; Helpers](/categories/utility)

xiaosongshu/rtmp\_server
========================

Native PHP RTMP live server with FLV/HLS, MP4 slicing, PHP client, relay &amp; gateway.

v2.4.5(2w ago)331↓83.3%MITPHPPHP &gt;=8.1

Since May 15Pushed 1w ago1 watchersCompare

[ Source](https://github.com/2723659854/rtmp-server)[ Packagist](https://packagist.org/packages/xiaosongshu/rtmp_server)[ RSS](/packages/xiaosongshu-rtmp-server/feed)WikiDiscussions master Synced 1w ago

READMEChangelog (10)Dependencies (20)Versions (53)Used By (0)

RTMP Server
===========

[](#rtmp-server)

 [**🇨🇳 中文文档**](./README.cn.md) • [**🇬🇧 English Docs**](./README.md)

> A pure PHP self-developed lightweight RTMP live streaming service, **zero dependence on third-party streaming media tools such as FFmpeg and Nginx**, enabling rapid setup of a private live streaming platform out of the box. On Linux, the `event` extension is automatically enabled for epoll event-driven I/O; on Windows, it automatically falls back to the select I/O model, ensuring full platform compatibility. **Project positioning: underlying infrastructure** – fully self-developed RTMP/HTTP-FLV/WS-FLV protocol stacks and asynchronous networking engine; upper-layer applications such as business management, permissions, and playback management need to be extended and developed by developers themselves.

---

Table of Contents (Revised)
---------------------------

[](#table-of-contents-revised)

- [Environment Dependencies](#environment-dependencies)
- [Quick Start](#quick-start)
- [Push/Pull Stream Address Specification](#pushpull-stream-address-specification)
- [Live &amp; VoD Access URLs](#live--vod-access-urls)
- [Page/Script Usage Instructions](#pagescript-usage-instructions)
- [Project Directory Structure](#project-directory-structure)
- [Overall System Architecture](#overall-system-architecture)
- [Port Constant Configuration](#port-constant-configuration)
- [Recording Task Switch Configuration](#recording-task-switch-configuration)
- [Multi‑Process Worker Configuration (IPC Stream Sync Core)](#multi-process-worker-configuration-ipc-stream-sync-core)
- [Push Stream Authentication Configuration](#push-stream-authentication-configuration)
- [FLV Live Distribution Gateway](#flv-live-distribution-gateway)
- [Static File HTTP Gateway](#static-file-http-gateway)
- [Tutorials for Multiple Push/Pull Methods](#tutorials-for-multiple-pushpull-methods)
- [Live Stream Forwarding Tutorial](#live-stream-forwarding-tutorial)
- [Cluster Deployment Architecture for 100,000+ Concurrent Connections](#cluster-deployment-architecture-for-100000-concurrent-connections)
- [FAQ](#faq)
- [Open Source License](#open-source-license)
- [Affiliated Toolkits](#affiliated-toolkits)
- [Contact](#contact)

---

Environment Dependencies
------------------------

[](#environment-dependencies)

DependencyMandatory RequirementsPHP&gt;= 8.1, CLI mode only, FPM not supportedsockets extension**Strictly required**, foundation for TCP/WS/RTMP communicationevent extensionStrongly recommended on Linux to enable epoll high‑concurrency event model; on Windows, if missing, it automatically falls back to select> Quick environment setup: the project includes a `docker-compose.yml` file. Run `docker-compose up -d` to start a complete runtime environment with one command.

---

Quick Start
-----------

[](#quick-start)

### 1. Project Installation

[](#1-project-installation)

```
composer create-project xiaosongshu/rtmp_server
```

### 2. Start the Origin Main Service

[](#2-start-the-origin-main-service)

```
php server.php
```

Successful startup output example:

```
[INFO] RTMP Server started on 0.0.0.0:1935
[INFO] HTTP-FLV/WS-FLV Server started on 0.0.0.0:8501
[INFO] HTTP Static Server started on 0.0.0.0:80

```

### 3. Quick Push Stream Test

[](#3-quick-push-stream-test)

#### Method 1: Browser‑based push without extra software

[](#method-1-browserbased-push-without-extra-software)

- Screen real‑time push: `http://127.0.0.1/push.html`
- Local MP4/FLV file loop push: `http://127.0.0.1/flv_push.html`

#### Method 2: Standard FFmpeg push

[](#method-2-standard-ffmpeg-push)

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

#### Method 3: OBS Studio push

[](#method-3-obs-studio-push)

- Server: `rtmp://127.0.0.1:1935/live/`
- Stream Key: `stream`

#### Method 4: Built‑in PHP push client

[](#method-4-builtin-php-push-client)

```
php pusher.php test.mp4 http://127.0.0.1:8501/live/stream
```

### 4. Quick Live Viewing

[](#4-quick-live-viewing)

Open in browser: `http://127.0.0.1/index.html`

---

Push/Pull Stream Address Specification
--------------------------------------

[](#pushpull-stream-address-specification)

### Push Addresses (OBS/FFmpeg/PHP/Web unified format)

[](#push-addresses-obsffmpegphpweb-unified-format)

ProtocolStandard FormatExample AddressRTMP`rtmp://host:1935/{app}/{stream}``rtmp://127.0.0.1:1935/live/stream`HTTP-FLV`http://host:8501/{app}/{stream}``http://127.0.0.1:8501/live/stream`WebSocket-FLV`ws://host:8501/{app}/{stream}``ws://127.0.0.1:8501/live/stream`> Field constraints: `{app}` (application name) and `{stream}` (channel name) may only contain English letters, digits, and underscores; special characters and Chinese are prohibited.

### Live &amp; VoD Access URLs

[](#live--vod-access-urls)

#### Live Playback Addresses

[](#live-playback-addresses)

ProtocolAccess URLUse CaseRTMP`rtmp://127.0.0.1:1935/live/stream`ffplay, desktop professional playersHTTP-FLV`http://127.0.0.1:8501/live/stream.flv`Low‑latency PC browser playbackWebSocket-FLV`ws://127.0.0.1:8501/live/stream.flv`Browser native WebSocket MSE playbackHLS-TS`http://127.0.0.1:80/hls/live/stream/index.m3u8`Mobile devices, WeChat built‑in browserHLS-FMP4 (muxed audio/video)`http://127.0.0.1:80/mp4/live/stream/output_merge/index.m3u8`Mainstream desktop browsers, mobile devices, WeChat built‑in browser, ffplay, VLC, etc.HLS-FMP4 (demuxed audio/video)`http://127.0.0.1:80/mp4/live/stream/output_separate/index.m3u8`Mainstream desktop browsers, mobile devices, WeChat built‑in browser, ffplay, VLC, etc.#### Recorded VoD Playback Addresses

[](#recorded-vod-playback-addresses)

Recorded files are persistently stored in the project root. After the live stream ends, the complete file is automatically generated:

File TypeStorage PathAccess ExampleStandard transcoded MP4`mp4/live/stream/index.mp4``http://127.0.0.1/mp4/live/stream/index.mp4`Raw FLV recording`flv/live/stream/index.flv``http://127.0.0.1/flv/live/stream/index.flv`HLS TS segments directory`hls/live/stream/index.m3u8``http://127.0.0.1:80/hls/live/stream/index.m3u8`HLS-FMP4 muxed audio/video segments`mp4/live/stream/output_merge/index.m3u8``http://127.0.0.1:80/mp4/live/stream/output_merge/index.m3u8`HLS-FMP4 demuxed audio/video segments`mp4/live/stream/output_separate/index.m3u8``http://127.0.0.1:80/mp4/live/stream/output_separate/index.m3u8`Note: Standard MP4 files are generated only when multi‑process FLV recording is enabled and the FLV file is automatically transcoded to standard MP4 after recording. Alternatively, you can use the toolkit `xiaosongshu/flv2mp4` to manually transcode FLV to MP4.

---

Page/Script Usage Instructions
------------------------------

[](#pagescript-usage-instructions)

### Live/VoD Playback Pages

[](#livevod-playback-pages)

Page FileDescriptionAccess URLindex.htmlHTTP‑FLV low‑latency live playerplay.htmlHLS mobile‑optimized playermp4.htmlMP4 VoD dedicated pagevideo.htmlFLV VoD playerplay\_merge.htmlfMP4 segmented live/VoD page (native JS)[http://127.0.0.1/play\_merge.html](http://127.0.0.1/play_merge.html)mse.htmlfMP4 segmented live/VoD page (hls.js)### Web‑Based Push Pages

[](#webbased-push-pages)

Page FileDescriptionAccess URLpush.htmlBrowser screen capture push (WS‑FLV)flv\_push.htmlLocal MP4/FLV file loop push[http://127.0.0.1/flv\_push.html](http://127.0.0.1/flv_push.html)push\_merge.htmlMulti‑stream composition push[http://127.0.0.1/push\_merge.html](http://127.0.0.1/push_merge.html)push\_transcode.htmlFront‑end multi‑bitrate transcoding push for weak networks[http://127.0.0.1/push\_transcode.html](http://127.0.0.1/push_transcode.html)### PHP Built‑in Push/Pull Client Scripts

[](#php-builtin-pushpull-client-scripts)

ScriptFunctionCommand Examplepusher.phpCommand‑line file push client`php pusher.php video.mp4 http://127.0.0.1:8501/live/stream`puller.phpCommand‑line pull and record client`php puller.php http://127.0.0.1:8501/live/stream.flv output.flv`### PHP Built‑in Relay Client Script

[](#php-builtin-relay-client-script)

ScriptFunctionCommand Exampleforward.phpCommand‑line live stream relay client`php forward.php ws://127.0.0.1:8501/a/b.flv rtmp://127.0.0.1:1935/c/d`### PHP Built‑in Gateway Client Scripts

[](#php-builtin-gateway-client-scripts)

ScriptFunctionCommand ExamplefileGateway.phpCommand‑line file gateway client`php fileGateway.php 0.0.0.0 8100`flvGateway.phpCommand‑line FLV gateway client`php flvGateway.php 8080 http://127.0.0.1:8501`### PHP Live Startup Script

[](#php-live-startup-script)

ScriptFunctionCommand Exampleserver.phpStart live service from command line`php server.php`---

Project Directory Structure
---------------------------

[](#project-directory-structure)

```
rtmp_server/
├── config/                     # Global configuration: ports, multi‑process, recording, push authentication
├── flv/                        # Real‑time raw FLV recording storage
├── mp4/                        # fMP4 segments & complete MP4 merged after stream ends
├── hls/                        # HLS TS segments, m3u8 index files
├── MediaServer/                # Core RTMP/FLV/WS‑FLV protocol stacks, session management
├── Root/                       # Low‑level async I/O, socket event‑driven engine
├── record/                     # Client‑side static page resources
├── server.php                  # RTMP origin main service entry
├── flvGateway.php              # FLV live distribution gateway startup script
├── fileGateway.php             # HLS/MP4/static resource HTTP gateway
├── forward.php                 # Live stream relay client
├── pusher.php                  # PHP push client
├── puller.php                  # PHP pull client
├── auth_config.php             # Push authentication standalone config
├── *.html                      # All Web push/pull/playback pages
├── docker-compose.yml          # Docker one‑click deployment config
└── LICENSE                     # Apache 2.0 open source license

```

---

Overall System Architecture
---------------------------

[](#overall-system-architecture)

```
                                         【External Pushers】OBS / FFmpeg / Web
                                                         │
                                   RTMP(1935) / HTTP‑FLV/WS‑FLV(8501) push access
                                                         │
                                                         ▼
╔══════════════════════════════════════════════════════════════════════════════════════╗
║                         RTMP Origin Main Service (Stream Production Core)            ║
║                                                                                      ║
║  📥 Push/Pull Access: RTMP / HTTP‑FLV / WS‑FLV triple‑protocol compatible, with     ║
║     built‑in push authentication                                                    ║
║  🔄 Protocol Transmuxing: Raw stream output to HTTP‑FLV / WS‑FLV / HLS / fMP4 / MP4 ║
║  💾 Parallel recording tasks (completely non‑blocking, individually toggleable)     ║
║        ┌──────────┬──────────┬──────────┐                                          ║
║        │ FLV raw  │ fMP4 real‑│ HLS TS  │                                          ║
║        │ recording│ time     │ segments│                                          ║
║        │          │ segments │          │                                          ║
║        └──────────┴──────────┴──────────┘                                          ║
║  📤 Real‑time stream output: distributes HTTP‑FLV, WS‑FLV, HLS live streams        ║
║  📦 VoD artifacts: fMP4 segment cache, auto‑merge to complete MP4 after stream ends║
║  📁 Built‑in static HTTP service (port 80): provides direct page and VoD file      ║
║     access without additional gateway in low‑concurrency scenarios                 ║
╚══════════════════════════════════════════════════════════════════════════════════════╝
│
┌───────────────────┼───────────────────┐
│                   │                   │
▼                   ▼                   ▼
HTTP‑FLV real‑time  HLS static          fMP4 static
stream              segment files       segment files
│                   │                   │
▼                   ▼                   ▼
┌─────────────┐    ┌──────────────────────────────────────────┐
│ FLV Live    │    │        Static File Gateway Cluster       │
│ Gateway     │    │          (fileGateway)                   │
│ Cluster     │    │     Hosted resources: HLS/fMP4/MP4/FLV/  │
│             │    │     web static assets                    │
│ ┌─────────┐ │    │                                          │
│ │Primary   │ │    │ ┌───────┐ ┌───────┐ ┌───────┐         │
│ │Gateway   │ │    │ │GW 1   │ │GW 2   │ │GW 3   │         │
│ │(port8080)│ │    │ │(8100) │ │(8101) │ │(8102) │         │
│ └───┬─────┘ │    │ └──┬────┘ └──┬────┘ └──┬────┘         │
│     │       │    │    │        │        │                 │
│ ┌───┴───┐   │    │    ▼        ▼        ▼                 │
│ ▼   ▼   ▼   │    │ ┌──────────────────────────────────┐   │
│ ┌─┐ ┌─┐ ┌─┐ │    │ │End‑user player clients           │   │
│ │S│ │S│ │S│ │    │ │MSE/HLS players/ffplay/browsers   │   │
│ │u│ │u│ │u│ │    │ └──────────────────────────────────┘   │
│ │b│ │b│ │b│ │    │                                          │
│ └┬─┘ └┬─┘ └┬─┘ │    └──────────────────────────────────────────┘
│  │    │    │   │
│  ▼    ▼    ▼   │
│ ┌────────────┐ │
│ │Live viewer │ │
│ │FLV players │ │
│ └────────────┘ │
└─────────────────┘

```

### Architecture Detailed Description

[](#architecture-detailed-description)

1. **Origin Main Service (the sole stream producer)**All external pushes are ingested by the origin, where protocol parsing, authentication, multi‑format transmuxing, and parallel recording are performed. The three recording tasks – FLV recording, fMP4 slicing, and HLS slicing – run in completely isolated threads without blocking each other. In low‑concurrency scenarios, the built‑in port‑80 static service can be used directly without deploying extra gateways.
2. **FLV Live Distribution Gateway**No transcoding logic; it only forwards traffic and caches GOP key frames for instant player start‑up. Supports horizontal scaling and multi‑level cascading (production environment recommended max 2 levels, more levels increase latency). Linux uses epoll for high concurrency; Windows is for testing only. In high‑concurrency scenarios, all player pull requests should go through the gateway to relieve connection pressure on the origin main process.
3. **Static File Gateway Cluster**Dedicated to hosting HLS, MP4, FLV, front‑end pages and other static resources, achieving read‑write separation. Must be deployed for large‑scale VoD scenarios to prevent the origin from being overwhelmed by file I/O requests.
4. **Integrated Live Tooling**This project provides pure PHP client push, pull, and live relay capabilities, as well as web‑based front‑end push, playback, transcoding, and stream mixing. It supports single‑process/multi‑process switching and includes a personalized media toolkit `xiaosongshu/flv2mp4`.

### Deployment Recommendations by Concurrency Level

[](#deployment-recommendations-by-concurrency-level)

Concurrency LevelRecommended DeploymentLow (online viewers &lt; 1000)Run only `server.php` (origin), using built‑in ports 80 and 8501; no gateway neededMedium (1000 ~ 5000 online)Origin + single‑layer FLV gateway cluster + single‑layer static file gateway cluster, with Nginx load balancingHigh / Large‑event live (&gt;5000 online)Origin + multi‑layer FLV and static gateway clusters, front‑end load balancing; for 10,000+ events, must incorporate commercial CDN edge distribution – do not rely on a single server for all traffic---

Port Constant Configuration
---------------------------

[](#port-constant-configuration)

Modify `config/app.php` to adjust global service ports. Built‑in constant definitions:

```
/** HTTP‑FLV / WebSocket‑FLV main service port */
define('BASE_FLV_PORT', 8501);
/** RTMP standard 1935 port */
define('BASE_RTMP_PORT', 1935);
/** Built‑in static web page and VoD file HTTP port */
define('BASE_WEB_PORT', 80);
```

Recording Task Switch Configuration
-----------------------------------

[](#recording-task-switch-configuration)

In `config/app.php`, three recording tasks are independently controlled without interference:

```
define('FLV_TO_RECORD', true);   // Enable real‑time raw FLV recording
define('FLV_TO_MP4', true);      // Enable fMP4 segmentation
define('FLV_TO_HLS', true);      // Enable HLS TS segment generation
```

Multi Process Worker Configuration Ipc Stream Sync Core
-------------------------------------------------------

[](#multi-process-worker-configuration-ipc-stream-sync-core)

### Principle

[](#principle)

In the PHP CLI multi‑process model, each worker process has isolated memory. When a single process receives a push stream, other workers cannot read that stream data. Therefore, **IPC (Inter‑Process Communication) is mandatory** to synchronise live streams across processes. Instead of using traditional system IPC such as shared memory or pipes, this project implements a custom local TCP Socket IPC solution: it allocates a set of internal communication ports. The worker that receives the stream actively replicates the full stream data via a built‑in TCP client and forwards it to all other workers, achieving full stream data sharing among all processes.

### Configuration in `config/app.php`

[](#configuration-in-configappphp)

```
/** Master switch: enable multi‑process worker mode */
define('ENABLE_MULTI_PROCESS', true);
/** Number of worker processes, recommended not to exceed CPU physical cores */
define('WORKER_COUNT', 3);
/** Starting port for inter‑process TCP communication, automatically assigns 8502, 8503... */
define('COPY_PORT_START', 8502);
```

> When multi‑process is disabled (`ENABLE_MULTI_PROCESS=false`), the number of processes and internal communication ports are ignored, and the service runs in single‑process mode without IPC stream sync.

### Load Balancing Rules for Multi‑Process Ports

[](#load-balancing-rules-for-multiprocess-ports)

1. Linux: the system supports port reuse; multiple workers can simultaneously listen on the main FLV port 8501, and the kernel automatically distributes player connections evenly among workers.
2. Windows: although `SO_REUSEADDR` port reuse is supported, new TCP connections will only be assigned to the first process that bound port 8501, so native load balancing is not possible. You can use Nginx to reverse‑proxy the internal communication ports (8502+) for traffic distribution.
3. Internal IPC ports are externally accessible for pull requests and can be used for manual load balancing on Windows.

### Platform Performance Limitations

[](#platform-performance-limitations)

- Linux: epoll I/O model supports thousands of concurrent long‑connections per process; multi‑process can fully utilise multi‑core CPUs – the preferred production environment.
- Windows: the underlying select model has a very low concurrency limit (~256 connections per process) – only for local development and debugging, never for production deployment.

Push Stream Authentication Configuration
----------------------------------------

[](#push-stream-authentication-configuration)

### Overview

[](#overview)

Prevents unauthorised streams from overriding a live room. Only push requests carrying a valid stream key are allowed. Playback pull currently has no built‑in authentication; developers can implement referer/token validation at the gateway or reverse‑proxy layer. Configuration file `config/auth.php`

```
