mirror of
https://github.com/ZLMediaKit/ZLMediaKit.git
synced 2026-11-24 00:47:21 +08:00
VP9 RTP parser: add robust bounds checks, fix pictureID and references, add unit tests (#4790)
### 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)
This commit is contained in:
@@ -46,11 +46,12 @@ struct RTPPayloadVP9 {
|
|||||||
bool hasGof = false;
|
bool hasGof = false;
|
||||||
int numberOfFramesInGof = -1;
|
int numberOfFramesInGof = -1;
|
||||||
std::vector<VP9ResolutionLayer> resolutions;
|
std::vector<VP9ResolutionLayer> resolutions;
|
||||||
int parse(unsigned char* data, int dataLength);
|
|
||||||
|
int parse(const unsigned char *data, int dataLength);
|
||||||
bool keyFrame() const { return beginningOfLayerFrame && !interPicturePrediction; }
|
bool keyFrame() const { return beginningOfLayerFrame && !interPicturePrediction; }
|
||||||
std::string dump() const {
|
std::string dump() const {
|
||||||
char line[64] = {0};
|
char line[64] = {0};
|
||||||
snprintf(line, sizeof(line), "%c%c%c%c%c%c%c- %d %d, %d %d",
|
snprintf(line, sizeof(line), "%c%c%c%c%c%c%c- %d %d, %d %d",
|
||||||
hasPictureID ? 'I' : ' ',
|
hasPictureID ? 'I' : ' ',
|
||||||
interPicturePrediction ? 'P' : ' ',
|
interPicturePrediction ? 'P' : ' ',
|
||||||
hasLayerIndices ? 'L' : ' ',
|
hasLayerIndices ? 'L' : ' ',
|
||||||
@@ -107,102 +108,109 @@ struct RTPPayloadVP9 {
|
|||||||
#define kBBit 0x08
|
#define kBBit 0x08
|
||||||
#define kEBit 0x04
|
#define kEBit 0x04
|
||||||
#define kVBit 0x02
|
#define kVBit 0x02
|
||||||
int RTPPayloadVP9::parse(unsigned char *data, int dataLength) {
|
int RTPPayloadVP9::parse(const unsigned char *data, int dataLength) {
|
||||||
const unsigned char* dataPtr = data;
|
if (!data || dataLength <= 0) {
|
||||||
const unsigned char* dataEnd = data + dataLength;
|
return -1;
|
||||||
|
}
|
||||||
#define VP9_CHECK_BOUNDS(n) do { if (dataPtr + (n) > dataEnd) return -1; } while (0)
|
const unsigned char *dataPtr = data;
|
||||||
|
size_t remaining = static_cast<size_t>(dataLength);
|
||||||
|
auto readByte = [&]() -> int {
|
||||||
|
if (remaining < 1) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
--remaining;
|
||||||
|
return *dataPtr++;
|
||||||
|
};
|
||||||
|
auto skipBytes = [&](size_t count) -> bool {
|
||||||
|
if (remaining < count) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
remaining -= count;
|
||||||
|
dataPtr += count;
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
// Parse mandatory first byte of payload descriptor
|
// Parse mandatory first byte of payload descriptor
|
||||||
VP9_CHECK_BOUNDS(1);
|
int byte = readByte();
|
||||||
this->hasPictureID = (*dataPtr & kIBit); // I bit
|
if (byte < 0) return -1;
|
||||||
this->interPicturePrediction = (*dataPtr & kPBit); // P bit
|
this->hasPictureID = (byte & kIBit); // I bit
|
||||||
this->hasLayerIndices = (*dataPtr & kLBit); // L bit
|
this->interPicturePrediction = (byte & kPBit); // P bit
|
||||||
this->flexibleMode = (*dataPtr & kFBit); // F bit
|
this->hasLayerIndices = (byte & kLBit); // L bit
|
||||||
this->beginningOfLayerFrame = (*dataPtr & kBBit); // B bit
|
this->flexibleMode = (byte & kFBit); // F bit
|
||||||
this->endingOfLayerFrame = (*dataPtr & kEBit); // E bit
|
this->beginningOfLayerFrame = (byte & kBBit); // B bit
|
||||||
this->hasScalabilityStructure = (*dataPtr & kVBit); // V bit
|
this->endingOfLayerFrame = (byte & kEBit); // E bit
|
||||||
dataPtr++;
|
this->hasScalabilityStructure = (byte & kVBit); // V bit
|
||||||
|
|
||||||
if (this->hasPictureID) {
|
if (this->hasPictureID) {
|
||||||
VP9_CHECK_BOUNDS(1);
|
byte = readByte();
|
||||||
this->largePictureID = (*dataPtr & 0x80); // M bit
|
if (byte < 0) return -1;
|
||||||
this->pictureID = (*dataPtr & 0x7F);
|
this->largePictureID = (byte & 0x80); // M bit
|
||||||
|
this->pictureID = (byte & 0x7F);
|
||||||
if (this->largePictureID) {
|
if (this->largePictureID) {
|
||||||
dataPtr++;
|
byte = readByte();
|
||||||
VP9_CHECK_BOUNDS(1);
|
if (byte < 0) return -1;
|
||||||
this->pictureID = ntohs((this->pictureID << 16) + (*dataPtr & 0xFF));
|
this->pictureID = (this->pictureID << 8) | byte;
|
||||||
}
|
}
|
||||||
dataPtr++;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this->hasLayerIndices) {
|
if (this->hasLayerIndices) {
|
||||||
VP9_CHECK_BOUNDS(1);
|
byte = readByte();
|
||||||
this->temporalID = (*dataPtr & 0xE0) >> 5; // T bits
|
if (byte < 0) return -1;
|
||||||
this->isSwitchingUp = (*dataPtr & 0x10); // U bit
|
this->temporalID = (byte & 0xE0) >> 5; // T bits
|
||||||
this->spatialID = (*dataPtr & 0x0E) >> 1; // S bits
|
this->isSwitchingUp = (byte & 0x10); // U bit
|
||||||
this->isInterLayeredDepUsed = (*dataPtr & 0x01); // D bit
|
this->spatialID = (byte & 0x0E) >> 1; // S bits
|
||||||
if (this->flexibleMode) { // marked in webrtc code
|
this->isInterLayeredDepUsed = (byte & 0x01); // D bit
|
||||||
do {
|
if (!this->flexibleMode) {
|
||||||
dataPtr++;
|
byte = readByte();
|
||||||
VP9_CHECK_BOUNDS(1);
|
if (byte < 0) return -1;
|
||||||
this->referenceIdx = (*dataPtr & 0xFE) >> 1;
|
this->tl0PicIdx = byte;
|
||||||
this->additionalReferenceIdx = (*dataPtr & 0x01); // D bit
|
|
||||||
} while (this->additionalReferenceIdx);
|
|
||||||
} else {
|
|
||||||
dataPtr++;
|
|
||||||
VP9_CHECK_BOUNDS(1);
|
|
||||||
this->tl0PicIdx = (*dataPtr & 0xFF);
|
|
||||||
}
|
}
|
||||||
dataPtr++;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this->flexibleMode && this->interPicturePrediction) {
|
if (this->flexibleMode && this->interPicturePrediction) {
|
||||||
/* Skip reference indices */
|
// The VP9 payload descriptor permits at most three reference indices.
|
||||||
uint8_t nbit;
|
bool nbit;
|
||||||
|
int referenceCount = 0;
|
||||||
do {
|
do {
|
||||||
VP9_CHECK_BOUNDS(1);
|
if (++referenceCount > 3) return -1;
|
||||||
uint8_t p_diff = (*dataPtr & 0xFE) >> 1;
|
byte = readByte();
|
||||||
nbit = (*dataPtr & 0x01);
|
if (byte < 0) return -1;
|
||||||
dataPtr++;
|
this->referenceIdx = (byte & 0xFE) >> 1;
|
||||||
|
nbit = (byte & 0x01);
|
||||||
|
this->additionalReferenceIdx = nbit;
|
||||||
} while (nbit);
|
} while (nbit);
|
||||||
}
|
}
|
||||||
if (this->hasScalabilityStructure) {
|
if (this->hasScalabilityStructure) {
|
||||||
VP9_CHECK_BOUNDS(1);
|
byte = readByte();
|
||||||
this->spatialLayers = (*dataPtr & 0xE0) >> 5; // N_S bits
|
if (byte < 0) return -1;
|
||||||
this->hasResolution = (*dataPtr & 0x10); // Y bit
|
this->spatialLayers = (byte & 0xE0) >> 5; // N_S bits
|
||||||
this->hasGof = (*dataPtr & 0x08); // G bit
|
this->hasResolution = (byte & 0x10); // Y bit
|
||||||
dataPtr++;
|
this->hasGof = (byte & 0x08); // G bit
|
||||||
if (this->hasResolution) {
|
if (this->hasResolution) {
|
||||||
for (int i = 0; i <= this->spatialLayers; i++) {
|
for (int i = 0; i <= this->spatialLayers; i++) {
|
||||||
VP9_CHECK_BOUNDS(4);
|
if (remaining < 4) return -1;
|
||||||
int width = (dataPtr[0] << 8) + dataPtr[1];
|
int width = (dataPtr[0] << 8) + dataPtr[1];
|
||||||
dataPtr += 2;
|
int height = (dataPtr[2] << 8) + dataPtr[3];
|
||||||
int height = (dataPtr[0] << 8) + dataPtr[1];
|
|
||||||
dataPtr += 2;
|
|
||||||
// InfoL << "got vp9 " << width << "x" << height;
|
|
||||||
this->resolutions.push_back({ width, height });
|
this->resolutions.push_back({ width, height });
|
||||||
|
skipBytes(4);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (this->hasGof) {
|
if (this->hasGof) {
|
||||||
VP9_CHECK_BOUNDS(1);
|
byte = readByte();
|
||||||
this->numberOfFramesInGof = *dataPtr & 0xFF; // N_G bits
|
if (byte < 0) return -1;
|
||||||
dataPtr++;
|
this->numberOfFramesInGof = byte; // N_G bits
|
||||||
for (int frame_index = 0; frame_index < this->numberOfFramesInGof; frame_index++) {
|
for (int frame_index = 0; frame_index < this->numberOfFramesInGof; frame_index++) {
|
||||||
// TODO(javierc): Read these values if needed
|
// TODO(javierc): Read these values if needed
|
||||||
VP9_CHECK_BOUNDS(1);
|
byte = readByte();
|
||||||
int reference_indices = (*dataPtr & 0x0C) >> 2; // R bits
|
if (byte < 0) return -1;
|
||||||
dataPtr++;
|
int reference_indices = (byte & 0x0C) >> 2; // R bits
|
||||||
VP9_CHECK_BOUNDS(reference_indices);
|
if (!skipBytes(reference_indices)) return -1;
|
||||||
for (int reference_index = 0; reference_index < reference_indices; reference_index++) {
|
|
||||||
dataPtr++;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Downstream VP9 frame inspection reads the first frame-data byte, so a
|
||||||
#undef VP9_CHECK_BOUNDS
|
// payload descriptor without any frame data must not enter the frame path.
|
||||||
|
if (remaining == 0) return -1;
|
||||||
return dataPtr - data;
|
return dataPtr - data;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -239,8 +247,13 @@ bool VP9RtpDecoder::decodeRtp(const RtpPacket::Ptr &rtp) {
|
|||||||
|
|
||||||
RTPPayloadVP9 info;
|
RTPPayloadVP9 info;
|
||||||
int offset = info.parse(payload, payload_size);
|
int offset = info.parse(payload, payload_size);
|
||||||
if (offset < 0) {
|
// Keep this independent of the parser's internal checks: a successful
|
||||||
|
// descriptor must still leave at least one byte of VP9 frame payload.
|
||||||
|
if (offset < 0 || static_cast<size_t>(offset) >= payload_size) {
|
||||||
WarnL << "VP9 RTP payload parse failed, seq:" << seq;
|
WarnL << "VP9 RTP payload parse failed, seq:" << seq;
|
||||||
|
_gop_dropped = true;
|
||||||
|
_frame_drop = true;
|
||||||
|
_frame->_buffer.clear();
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
// InfoL << rtp->dumpString() << "\n" << info.dump();
|
// InfoL << rtp->dumpString() << "\n" << info.dump();
|
||||||
|
|||||||
153
tests/test_vp9_rtp.cpp
Normal file
153
tests/test_vp9_rtp.cpp
Normal file
@@ -0,0 +1,153 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2016-present The ZLMediaKit project authors. All Rights Reserved.
|
||||||
|
*
|
||||||
|
* This file is part of ZLMediaKit(https://github.com/ZLMediaKit/ZLMediaKit).
|
||||||
|
*
|
||||||
|
* Use of this source code is governed by MIT-like license that can be found in the
|
||||||
|
* LICENSE file in the root of the source tree. All contributing project authors
|
||||||
|
* may be found in the AUTHORS file in the root of the source tree.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include <cstdlib>
|
||||||
|
#include <iostream>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
#include "ext-codec/VP9Rtp.h"
|
||||||
|
|
||||||
|
using namespace mediakit;
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
struct ParseCase {
|
||||||
|
const char *name;
|
||||||
|
std::vector<unsigned char> packet;
|
||||||
|
int expected_offset;
|
||||||
|
};
|
||||||
|
|
||||||
|
void require(bool condition, const std::string &message) {
|
||||||
|
if (!condition) {
|
||||||
|
std::cerr << message << std::endl;
|
||||||
|
std::exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void runCase(const ParseCase &test) {
|
||||||
|
VP9RtpDecoder decoder;
|
||||||
|
std::vector<std::string> frames;
|
||||||
|
decoder.addDelegate([&](const Frame::Ptr &frame) {
|
||||||
|
frames.emplace_back(frame->data(), frame->size());
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
|
||||||
|
auto packet = test.packet;
|
||||||
|
packet[0] |= 0x0C; // B/E: make a successful descriptor dispatch one complete frame.
|
||||||
|
RtpInfo rtp_info(0x12345678, 1400, 90000, 98, 0, 0);
|
||||||
|
auto rtp = rtp_info.makeRtp(TrackVideo, packet.data(), packet.size(), true, 100);
|
||||||
|
require(rtp != nullptr, std::string(test.name) + ": failed to create RTP packet");
|
||||||
|
decoder.inputRtp(rtp, false);
|
||||||
|
|
||||||
|
const bool should_output = test.expected_offset >= 0;
|
||||||
|
require(frames.size() == (should_output ? 1U : 0U),
|
||||||
|
std::string(test.name) + ": unexpected decoded frame count " + std::to_string(frames.size()));
|
||||||
|
if (should_output) {
|
||||||
|
require(frames[0].size() == packet.size() - static_cast<size_t>(test.expected_offset),
|
||||||
|
std::string(test.name) + ": decoded frame has an unexpected size");
|
||||||
|
require(frames[0] == std::string(reinterpret_cast<const char *>(packet.data() + test.expected_offset),
|
||||||
|
packet.size() - static_cast<size_t>(test.expected_offset)),
|
||||||
|
std::string(test.name) + ": decoded frame payload does not match RTP frame payload");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void testParseFailureDropsCurrentFrame(const char *name, const std::vector<unsigned char> &invalid_payload) {
|
||||||
|
VP9RtpDecoder decoder;
|
||||||
|
std::vector<std::string> frames;
|
||||||
|
decoder.addDelegate([&](const Frame::Ptr &frame) {
|
||||||
|
frames.emplace_back(frame->data(), frame->size());
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
|
||||||
|
RtpInfo rtp_info(0x12345678, 1400, 90000, 98, 0, 0);
|
||||||
|
auto input = [&](const std::vector<unsigned char> &payload, bool mark) {
|
||||||
|
auto rtp = rtp_info.makeRtp(TrackVideo, payload.data(), payload.size(), mark, 100);
|
||||||
|
require(rtp != nullptr, std::string(name) + ": failed to create RTP packet");
|
||||||
|
decoder.inputRtp(rtp, false);
|
||||||
|
};
|
||||||
|
|
||||||
|
input({ 0x08, 0x80, 0x11 }, false); // B: begin assembling a frame.
|
||||||
|
input(invalid_payload, false);
|
||||||
|
input({ 0x04, 0x22 }, true); // E: must not emit the incomplete frame.
|
||||||
|
require(frames.empty(), std::string(name) + ": parse failure emitted a partial VP9 frame");
|
||||||
|
|
||||||
|
input({ 0x0C, 0x80, 0x33 }, true); // A new complete frame must recover normally.
|
||||||
|
require(frames.size() == 1, std::string(name) + ": decoder did not recover after a parse failure");
|
||||||
|
require(frames[0] == std::string("\x80\x33", 2),
|
||||||
|
std::string(name) + ": recovered VP9 frame payload does not match");
|
||||||
|
}
|
||||||
|
|
||||||
|
void testParseFailureDropsGop() {
|
||||||
|
VP9RtpDecoder decoder;
|
||||||
|
std::vector<std::string> frames;
|
||||||
|
decoder.addDelegate([&](const Frame::Ptr &frame) {
|
||||||
|
frames.emplace_back(frame->data(), frame->size());
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
|
||||||
|
RtpInfo rtp_info(0x12345678, 1400, 90000, 98, 0, 0);
|
||||||
|
auto input = [&](const std::vector<unsigned char> &payload) {
|
||||||
|
auto rtp = rtp_info.makeRtp(TrackVideo, payload.data(), payload.size(), true, 100);
|
||||||
|
require(rtp != nullptr, "failed to create RTP packet for GOP recovery test");
|
||||||
|
decoder.inputRtp(rtp, false);
|
||||||
|
};
|
||||||
|
|
||||||
|
input({ 0x50, 0x03 }); // Reject a truncated P_DIFF chain.
|
||||||
|
input({ 0x4C, 0x00, 0x44 }); // Suppress a dependent P-frame.
|
||||||
|
require(frames.empty(), "parse failure did not suppress the damaged GOP");
|
||||||
|
|
||||||
|
input({ 0x0C, 0x80, 0x55 }); // A keyframe starts a new GOP.
|
||||||
|
input({ 0x4C, 0x00, 0x66 }); // Its dependent P-frame is valid again.
|
||||||
|
require(frames.size() == 2, "decoder did not recover at the next VP9 keyframe");
|
||||||
|
require(frames[0] == std::string("\x80\x55", 2), "recovery keyframe payload does not match");
|
||||||
|
require(frames[1] == std::string("\x00\x66", 2), "recovered P-frame payload does not match");
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
// The last byte in every successful case is frame payload. These cases cover
|
||||||
|
// all L/F/P combinations and make incorrect descriptor consumption visible.
|
||||||
|
const std::vector<ParseCase> combinations = {
|
||||||
|
{ "L0 F0 P0", { 0x00, 0xAA }, 1 },
|
||||||
|
{ "L0 F0 P1", { 0x40, 0xAA }, 1 },
|
||||||
|
{ "L0 F1 P0", { 0x10, 0xAA }, 1 },
|
||||||
|
{ "L0 F1 P1", { 0x50, 0x02, 0xAA }, 2 },
|
||||||
|
{ "L1 F0 P0", { 0x20, 0x00, 0x33, 0xAA }, 3 },
|
||||||
|
{ "L1 F0 P1", { 0x60, 0x00, 0x33, 0xAA }, 3 },
|
||||||
|
{ "L1 F1 P0 does not consume P_DIFF", { 0x30, 0x00, 0xAA }, 2 },
|
||||||
|
{ "L1 F1 P1 consumes P_DIFF once", { 0x70, 0x00, 0x02, 0xAA }, 3 },
|
||||||
|
};
|
||||||
|
for (const auto &test : combinations) {
|
||||||
|
runCase(test);
|
||||||
|
}
|
||||||
|
|
||||||
|
runCase({ "three references", { 0x50, 0x03, 0x05, 0x06, 0xAA }, 4 });
|
||||||
|
runCase({ "truncated reference chain", { 0x50, 0x03 }, -1 });
|
||||||
|
runCase({ "more than three references", { 0x50, 0x03, 0x05, 0x07, 0x08, 0xAA }, -1 });
|
||||||
|
runCase({ "short picture ID", { 0x80, 0x12, 0xAA }, 2 });
|
||||||
|
runCase({ "large picture ID", { 0x80, 0x81, 0x23, 0xAA }, 3 });
|
||||||
|
runCase({ "truncated large picture ID", { 0x80, 0x81 }, -1 });
|
||||||
|
runCase({ "resolution", { 0x02, 0x10, 0x07, 0x80, 0x04, 0x38, 0xAA }, 6 });
|
||||||
|
runCase({ "truncated resolution", { 0x02, 0x10, 0x07, 0x80, 0x04 }, -1 });
|
||||||
|
|
||||||
|
// V=1, G=1, N_G=2. Each GOF frame byte is followed immediately by
|
||||||
|
// exactly the number of reference indices it declares.
|
||||||
|
runCase({ "GOF exact boundary", { 0x02, 0x08, 0x02, 0x04, 0x11, 0x08, 0x22, 0x33, 0xAA }, 8 });
|
||||||
|
runCase({ "GOF truncated references", { 0x02, 0x08, 0x01, 0x08, 0x22 }, -1 });
|
||||||
|
|
||||||
|
runCase({ "reject descriptor-only payload", { 0x00 }, -1 });
|
||||||
|
runCase({ "reject layer-descriptor-only payload", { 0x30, 0x00 }, -1 });
|
||||||
|
testParseFailureDropsCurrentFrame("truncated P_DIFF", { 0x50, 0x03 });
|
||||||
|
testParseFailureDropsCurrentFrame("descriptor-only middle packet", { 0x00 });
|
||||||
|
testParseFailureDropsGop();
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user