Fix publish failure from non-standard RTMP publishers (#4800)

## 问题 / 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.
This commit is contained in:
Caner Ateş
2026-08-14 08:29:23 +03:00
committed by GitHub
parent 0e9e59bf43
commit 992e34ab90
5 changed files with 36 additions and 15 deletions

View File

@@ -97,24 +97,19 @@ void FlvSplitter::onRecvContent(const char *data, size_t len) {
case MSG_DATA3: {
BufferLikeString buffer(string(data, len));
AMFDecoder dec(buffer, _type == MSG_DATA3 ? 3 : 0);
auto first = dec.load<AMFValue>();
auto type = amfLoadLeadingString(dec);
bool flag = true;
if (first.type() == AMFType::AMF_STRING) {
auto type = first.as_string();
if (type == "@setDataFrame") {
type = dec.load<std::string>();
if (type == "onMetaData") {
flag = onRecvMetadata(dec.load<AMFValue>());
} else {
WarnL << "unknown type:" << type;
}
} else if (type == "onMetaData") {
if (type == "@setDataFrame") {
type = amfLoadLeadingString(dec);
if (type == "onMetaData") {
flag = onRecvMetadata(dec.load<AMFValue>());
} else {
WarnL << "unknown notify:" << type;
WarnL << "unknown type:" << type;
}
} else if (type == "onMetaData") {
flag = onRecvMetadata(dec.load<AMFValue>());
} else {
WarnL << "Parse flv script data failed, invalid amf value: " << first.to_string();
WarnL << "unknown notify:" << type;
}
if (!flag) {
throw std::invalid_argument("check rtmp metadata failed");

View File

@@ -391,7 +391,7 @@ void RtmpPlayer::onRtmpChunk(RtmpPacket::Ptr packet) {
case MSG_DATA:
case MSG_DATA3: {
AMFDecoder dec(chunk_data.buffer, 0, (chunk_data.type_id == MSG_DATA3 || chunk_data.type_id == MSG_CMD3) ? 3 : 0);
std::string type = dec.load<std::string>();
std::string type = amfLoadLeadingString(dec);
auto it = s_func_map.find(type);
if (it != s_func_map.end()) {
auto fun = it->second;

View File

@@ -515,7 +515,7 @@ void RtmpSession::onRtmpChunk(RtmpPacket::Ptr packet) {
case MSG_DATA:
case MSG_DATA3: {
AMFDecoder dec(chunk_data.buffer, chunk_data.type_id == MSG_DATA3 ? 3 : 0);
std::string type = dec.load<std::string>();
std::string type = amfLoadLeadingString(dec);
if (type == "@setDataFrame") {
setMetaData(dec);
} else if (type == "onMetaData") {

View File

@@ -463,6 +463,10 @@ AMFDecoder::DepthGuard::~DepthGuard() {
--_decoder.depth;
}
size_t AMFDecoder::remain() const {
return pos < buf.size() ? buf.size() - pos : 0;
}
uint8_t AMFDecoder::front() {
if (pos >= buf.size()) {
throw std::runtime_error("Not enough data");
@@ -703,3 +707,13 @@ AMFValue AMFDecoder::load_arr() {
AMFDecoder::AMFDecoder(const BufferLikeString &buf_in, size_t pos_in, int version_in) :
buf(buf_in), pos(pos_in), version(version_in) {
}
std::string amfLoadLeadingString(AMFDecoder &dec) {
while (dec.remain()) {
auto val = dec.load<AMFValue>();
if (val.type() == AMF_STRING) {
return val.as_string();
}
}
return "";
}

View File

@@ -88,6 +88,10 @@ public:
template<typename TP>
TP load();
// 剩余未解析的字节数
// Number of bytes not yet parsed
size_t remain() const;
private:
class DepthGuard {
public:
@@ -118,6 +122,14 @@ private:
static constexpr size_t kMaxDepth = 64;
};
// 加载首个字符串, 自动跳过前置的非字符串AMF值; 若不存在字符串则返回空字符串
// 兼容某些不规范的推流器(例如宇视摄像机在@setDataFrame前插入多余的AMF number)
// Load the first string, skipping any leading non-string AMF values;
// returns an empty string if the stream contains none.
// Compatible with some non-standard publishers (e.g. Uniview cameras insert
// redundant AMF numbers before @setDataFrame)
std::string amfLoadLeadingString(AMFDecoder &dec);
class AMFEncoder {
public:
AMFEncoder & operator <<(const char *s);