## 问题 / Problem
部分摄像机(实测:宇视/Uniview)推流时,在 `@setDataFrame` 之前插入了 **2 个多余的 AMF0 number(共
18 字节)**。抓包结果:
Some publishers (verified with a Uniview camera) insert **two redundant
AMF0 numbers (18 bytes)** before `@setDataFrame`. Captured bytes:
```
44 00 00 28 00 00 a9 12 <- chunk header, type 0x12 (AMF0_DATA), body_size 169
00 0000000000000000 <- AMF0 number 0.0 (多余 / redundant)
00 0000000000000000 <- AMF0 number 0.0 (多余 / redundant)
02 00 0d "@setDataFrame" <- 按标准应从这里开始 / message should start here
02 00 0a "onMetaData" ...
```
`RtmpSession::onRtmpChunk()` 在 `MSG_DATA` 分支中无条件把首个 AMF 元素当作字符串读取,遇到
`0x00`(number)标记时 `amf.cpp` 抛出 `Expected a string`,异常未被捕获,推流连接被断开。
`RtmpSession::onRtmpChunk()` reads the first AMF element as a string
unconditionally in the `MSG_DATA` branch. With a `0x00` (number) marker,
`amf.cpp` throws `Expected a string`; the exception is not caught and
the publisher is dropped.
nginx-rtmp 可以正常接收同一路流,ZLMediaKit 无法接收。
nginx-rtmp accepts the very same stream; ZLMediaKit does not.
### 修复前日志 / Log before the fix
```
RtmpSession.cpp:130 | publish 回复时间:2ms
TcpServer.cpp:210 | on err: 6(Expected a string)
RtmpSession.cpp:28 | RTMP推流器(__defaultVhost__/live/stream)断开:Expected a string,耗时(s):0
```
## 修改内容 / Changes
新增 `amfLoadLeadingString()`,跳过前置的非字符串 AMF 值后再取首个字符串。该写法参考了 `FlvSplitter`
中已有的防御式解析(先 `load<AMFValue>()`
再判断类型),并把它统一成一个公共函数。`AMFDecoder::remain()` 用于限定循环边界,避免缓冲区读完后再次抛异常。
Add `amfLoadLeadingString()`, which skips leading non-string AMF values
before returning the first string. This generalizes the defensive
parsing already present in `FlvSplitter` (`load<AMFValue>()` followed by
a type check) into one shared helper. `AMFDecoder::remain()` bounds the
loop so it does not throw once the buffer is exhausted.
- `amf.h` / `amf.cpp` — 新增 `remain()` 与 `amfLoadLeadingString()` / add
`remain()` and `amfLoadLeadingString()`
- `RtmpSession.cpp` — 推流侧,本 issue 的根因 / publish side, the root cause
here
- `RtmpPlayer.cpp` — 拉流侧存在同样的崩溃风险 / pull side has the identical failure
mode
- `FlvSplitter.cpp` — 原本不会断开,但会静默丢弃 metadata;现在能正确解析 / did not
disconnect before, but silently dropped the metadata; now parses it
## 验证 / Verification
用真实摄像机推流抓取了 17.8 MB 原始 RTMP 字节流,分别回放到修改前后的 MediaServer:
A 17.8 MB raw RTMP capture from the live camera was replayed against
MediaServer before and after the change:
| 场景 / Scenario | 修改前 / Before | 修改后 / After |
|---|---|---|
| 原始流(含多余 AMF 值)/ raw stream with redundant AMF values | `Expected a
string`,推流被断开 / dropped | 全部回放完成,无断开 / replayed fully, no disconnect |
| 去掉那 18 字节的标准流 / same stream with the 18 bytes removed | 正常 / OK | 正常 /
OK(回归测试 / regression) |
对照实验:**仅**从原始抓包中删除那 18 字节,其余字节完全不变,修改前的版本即可正常收流 —— 说明问题确实由这段多余的 AMF 值引起。
Control experiment: removing **only** those 18 bytes from the capture,
leaving every other byte untouched, makes the unpatched build work —
confirming those bytes are the cause.
修复后的日志 / Log after the fix:
```
MultiMediaSourceMuxer.cpp | stream: rtmp://__defaultVhost__/live/stream , codec info: H264[1920/1080/25]
MediaSource.cpp | 媒体注册:rtmp://__defaultVhost__/live/stream
MediaSource.cpp | 媒体注册:rtsp/hls/ts/fmp4://__defaultVhost__/live/stream
```
摄像机实时推流也已验证:拉取 HTTP-FLV 后用 ffmpeg 解码无报错(H264 1920x1080 25fps)。
Also verified end to end with the live camera: pulling HTTP-FLV and
decoding it with ffmpeg produces no errors (H264 1920x1080 25fps).
## 行为变化说明 / Note on behavior change
`RtmpPlayer` 中被修改的分支同时处理
`MSG_CMD`。命令消息的首个元素本来就是字符串,正常情况下行为不变;但如果收到首元素非字符串的畸形命令消息,以前会断开连接,现在会打印
`can not support cmd:` 警告并继续。符合标准的流行为完全不变(已通过上面的回归测试验证)。
The modified branch in `RtmpPlayer` also handles `MSG_CMD`. The first
element of a command message is already a string, so normal behavior is
unchanged; for a malformed command message whose first element is not a
string, the connection used to be dropped and now a `can not support
cmd:` warning is logged instead. Standard-compliant streams are
unaffected, as shown by the regression test above.
### Motivation
- Harden VP9 RTP payload parsing against malformed/truncated packets to
avoid OOB reads and crashes.
- Fix incorrect assembly of extended `pictureID` and incorrect
consumption of reference indices in flexible mode.
- Add focused unit tests to cover descriptor variants and edge cases so
regressions are caught automatically.
### Description
- Change parser signature to `int parse(const unsigned char *data, int
dataLength)` and replace raw pointer arithmetic with
`readByte`/`skipBytes` helpers that track remaining bytes and enforce
bounds.
- Fix `largePictureID` assembly by concatenating bytes correctly instead
of using `ntohs` arithmetic, and ensure `additionalReferenceIdx` is set
from the parsed byte; also limit flexible-mode reference chain to at
most three references.
- Parse scalability-structure fields (`spatialLayers`, `hasResolution`,
`hasGof`) with bounds checks and correctly read resolution entries and
GOF reference indices; return `-1` on truncation.
- Add an extra safety check in `VP9RtpDecoder::decodeRtp` to verify the
parsed header offset is within payload bounds, and add
`tests/test_vp9_rtp.cpp` with many descriptor/edge-case cases exercising
parsing logic.
### Testing
- Added unit test `tests/test_vp9_rtp.cpp` covering L/F/P combinations,
picture ID variants, reference chains, resolution and GOF parsing, and
truncation cases, and executed it as an automated test.
- The new test binary completed all test cases successfully (all
expected pass/fail outcomes matched).
------
[Codex
Task](https://chatgpt.com/codex/cloud/tasks/task_e_6a63e97a4c2c8320aa66d51a746c2e4d)
### Motivation
- Prevent unbounded recursive-descent parsing in the AMF decoder that
allowed deeply nested AMF objects/arrays to exhaust the process stack
and cause a pre-auth remote DoS.
### Description
- Add an RAII depth guard `AMFDecoder::DepthGuard` and a per-decoder
`depth` counter with `kMaxDepth = 64` to `AMFDecoder` in
`src/Rtmp/amf.h`/`src/Rtmp/amf.cpp`.
- Instrument `load_object()`, `load_ecma()`, and `load_arr()` to create
a `DepthGuard` at entry so nesting is incremented and reliably
decremented on return or exception, and throw
`std::runtime_error("Maximum AMF nesting depth exceeded")` when the
limit is exceeded.
- Add `tests/test_amf.cpp` to assert that a 64-level nested AMF
container is accepted and a 65-level nested container is rejected with
the expected error.
- Keep non-nested parsing behavior unchanged; the guard only enforces a
maximum container nesting depth.
### Testing
- Configured the project with tests enabled using `cmake -S . -B build
-DENABLE_TESTS=ON`, which generated the `test_amf` target successfully.
- Built the test target with `cmake --build build --target test_amf` and
performed smoke compiles of modified sources, with `src/Rtmp/amf.cpp`
compiling to object (`/tmp/amf.o`) successfully.
- Compiled the new test source with `c++ -std=gnu++11 -c
tests/test_amf.cpp` successfully and verified `git diff --cached
--check` passed.
------
[Codex
Task](https://chatgpt.com/codex/cloud/tasks/task_e_6a63c9326b9883209c857c0f4fa5d0cc)
Add GitHub Actions workflow to build ZLMediaKit for linux/arm64
(aarch64) using the native ubuntu-24.04-arm runner.
- Build container: debian:11 (glibc 2.31) for broad compatibility
- Compile steps extracted into package/build_linux_arm64.sh for
debugging
- OpenSSL: no-asm/no-dso/-fPIC to fix aarch64 PIC relocation issues
- Artifacts: Linux_ARM64_<branch>_<date>
Successfully tested on my fork; artifact includes MediaServer and
related binaries.
Co-authored-by: yangheng <492238647@qq.com>
- Add maxUploadSize config (default 1GB) for custom HttpBody streaming uploads;
maxReqSize now only controls in-memory buffering threshold
- Reject uploads exceeding maxUploadSize with 413 before writing any data
- Delete incomplete files on HttpFileStorage destruction
- Open HttpFileStorage in "wb" mode instead of "ab" to avoid stale data
- Pass content_size to writeData() for integrity validation
- Use uint64_t for content_len to support large file uploads
- Wrap HttpBody _on_completed callback in try-catch to prevent unhandled exceptions
- Make GET_CONFIG global variables read-only
- Update ZLToolKit submodule
---------
Co-authored-by: xiongziliang <771730766@qq.com>
- Add 1MiB cap on parameter set size to prevent memory exhaustion
- Validate SPS/VPS field ranges per H.264/H.265 spec (sps_id, bit_depth, poc_type, ref_frames, etc.)
- Fix Exp-Golomb reader EOF/overflow handling (throw instead of silent zero)
- Use wide integers for crop/delta_scale arithmetic to prevent overflow
- Commit output params only after full parse success (no partial metadata)
- Harden getExtraData with size checks, from_nalu API, AssertFailedException guard
- Avoid redundant update() in inputFrame_l (retry only on SPS change or first-ready)
### Motivation
- Restore the transport cleanup path on SRT session errors so
`SrtTransport::onShutdown` runs its unregister logic and prevents
unbounded growth of weak_ptr entries in the transport manager that could
lead to a memory-exhaustion DoS.
### Description
- Re-enabled shutdown cleanup in `srt/SrtSession.cpp` by capturing `err`
in the delayed callback and calling `transport->onShutdown(err)` from
the `getPoller()->async` lambda.
### Testing
- Ran `cmake -S . -B build` to sanity-check configuration; configuration
failed in this environment due to a missing `3rdpart/ZLToolKit`
submodule and unrelated CMake errors, not due to the patch.
------
[Codex
Task](https://chatgpt.com/codex/cloud/tasks/task_e_69b32b68f8ac8320b6a9b0fad53594c6)
---------
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
### Motivation
- Prevent unbounded memory growth in `FramePacedSender` when many frames
share identical or tightly clustered DTS values by restoring an
insertion-time frame-count guard independent of DTS-span-based pressure.
### Description
- Add a `kMaxCacheSize` constant and force a cache `flushCache(...)`
when `_cache.size()` exceeds `kMaxCacheSize`, keeping paced-sender
buffering bounded even if `buf_ms` remains small; the guard is applied
immediately after `_cache.emplace(...)` in
`FramePacedSender::inputFrame`.
### Testing
- Performed static discovery of call sites and symbols with `rg`/`sed`
to verify the paced sender is created when `_option.paced_sender_ms` is
nonzero and that frames are routed to `_paced_sender->inputFrame(...)`;
this succeeded.
- Attempted to configure and build with `cmake -S . -B build
-DCMAKE_BUILD_TYPE=Release && cmake --build build -j2` and `cmake
--build build -j2`, both failed during configuration or build due to
missing third-party artifacts (`3rdpart/ZLToolKit/CMakeLists.txt`) or no
existing `build` directory in the checkout, so no binary tests were
executed.
------
[Codex
Task](https://chatgpt.com/codex/cloud/tasks/task_e_6a512c4481a883209d56b8e7109a91ba)