mirror of
https://github.com/ZLMediaKit/ZLMediaKit.git
synced 2026-11-24 00:47:21 +08:00
Fix Enhanced RTMP AV1 metadata and VPx packet framing (#4840)
Co-authored-by: xiongziliang <771730766@qq.com>
This commit is contained in:
@@ -20,10 +20,14 @@ namespace mediakit {
|
||||
|
||||
bool AV1Track::inputFrame(const Frame::Ptr &frame) {
|
||||
char *dataPtr = frame->data() + frame->prefixSize();
|
||||
if (0 == aom_av1_codec_configuration_record_init(&_context, dataPtr, frame->size() - frame->prefixSize())) {
|
||||
_width = _context.width;
|
||||
_height = _context.height;
|
||||
//InfoL << _width << "x" << _height;
|
||||
// init() appends configuration OBUs and may partially modify its context on
|
||||
// failure. Parse into a fresh context; ordinary inter frames have no dimensions.
|
||||
aom_av1_t context {};
|
||||
if (0 == aom_av1_codec_configuration_record_init(&context, dataPtr, frame->size() - frame->prefixSize())
|
||||
&& context.width && context.height) {
|
||||
_context = context;
|
||||
_width = context.width;
|
||||
_height = context.height;
|
||||
}
|
||||
return VideoTrackImp::inputFrame(frame);
|
||||
}
|
||||
@@ -41,10 +45,27 @@ Buffer::Ptr AV1Track::getExtraData() const {
|
||||
}
|
||||
|
||||
void AV1Track::setExtraData(const uint8_t *data, size_t size) {
|
||||
if (aom_av1_codec_configuration_record_load(data, size, &_context) > 0) {
|
||||
_width = _context.width;
|
||||
_height = _context.height;
|
||||
aom_av1_t context {};
|
||||
if (size < 4 || data[0] != 0x81 || aom_av1_codec_configuration_record_load(data, size, &context) <= 0) {
|
||||
WarnL << "Invalid AV1 codec configuration record, size: " << size << ", first byte: " << (size ? (int)data[0] : -1);
|
||||
return;
|
||||
}
|
||||
// load() only copies av1C fields/configOBUs; dimensions come from the
|
||||
// sequence header inside configOBUs. Use a separate context to avoid
|
||||
// appending into the same buffer that init() is reading.
|
||||
aom_av1_t parsed {};
|
||||
if (context.bytes && aom_av1_codec_configuration_record_init(&parsed, context.data, context.bytes) != 0) {
|
||||
return;
|
||||
}
|
||||
_context = context;
|
||||
// A valid av1C may omit the sequence header. Keep dimensions already
|
||||
// learned from frames until a new sequence header supplies replacements.
|
||||
if (parsed.width && parsed.height) {
|
||||
_width = parsed.width;
|
||||
_height = parsed.height;
|
||||
}
|
||||
_context.width = _width;
|
||||
_context.height = _height;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
@@ -49,7 +49,7 @@ class AV1Track : public VideoTrackImp {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<AV1Track>;
|
||||
|
||||
AV1Track() : VideoTrackImp(CodecAV1) {}
|
||||
AV1Track() : VideoTrackImp(CodecAV1, 0, 0, 0) {}
|
||||
|
||||
Track::Ptr clone() const override;
|
||||
|
||||
|
||||
@@ -40,16 +40,11 @@ void VpxRtmpDecoder::inputRtmp(const RtmpPacket::Ptr &pkt) {
|
||||
|
||||
case RtmpPacketType::PacketTypeCodedFramesX:
|
||||
case RtmpPacketType::PacketTypeCodedFrames: {
|
||||
auto pts = pkt->time_stamp;
|
||||
if (RtmpPacketType::PacketTypeCodedFrames == _info.video.pkt_type) {
|
||||
CHECK_RET(size > 3);
|
||||
// SI24 = [CompositionTime Offset]
|
||||
int32_t cts = (load_be24(data) + 0xff800000) ^ 0xff800000;
|
||||
pts += cts;
|
||||
data += 3;
|
||||
size -= 3;
|
||||
}
|
||||
outputFrame((char*)data, size, pkt->time_stamp, pts);
|
||||
// Enhanced AV1/VP8/VP9 carry coded data immediately after FourCC.
|
||||
// Only AVC/HEVC/VVC CodedFrames have an SI24 composition offset.
|
||||
// Older ZLM CodedFrames with an SI24 prefix are intentionally
|
||||
// unsupported: the wire format cannot identify that legacy layout.
|
||||
outputFrame((char*)data, size, pkt->time_stamp, pkt->time_stamp);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
@@ -81,22 +76,19 @@ VpxRtmpEncoder::VpxRtmpEncoder(const Track::Ptr &track) : RtmpCodec(track) {
|
||||
|
||||
bool VpxRtmpEncoder::inputFrame(const Frame::Ptr &frame) {
|
||||
auto packet = RtmpPacket::create();
|
||||
packet->buffer.resize(8 + frame->size());
|
||||
char *buff = packet->data();
|
||||
int32_t cts = frame->pts() - frame->dts();
|
||||
auto payload = frame->data() + frame->prefixSize();
|
||||
auto payload_size = frame->size() - frame->prefixSize();
|
||||
// 一次性按"头部 + 载荷"的实际长度分配,全程一次分配、一次 memcpy。
|
||||
auto header_size = _enhanced ? (size_t)RtmpPacketInfo::kEnhancedRtmpHeaderSize : (size_t)5;
|
||||
packet->buffer.resize(header_size + payload_size);
|
||||
auto buff = packet->data();
|
||||
if (_enhanced) {
|
||||
auto header = (RtmpVideoHeaderEnhanced *)buff;
|
||||
header->enhanced = 1;
|
||||
header->frame_type = frame->keyFrame() ? (int)RtmpFrameType::key_frame : (int)RtmpFrameType::inter_frame;
|
||||
header->fourcc = htonl(getCodecFourCC(frame->getCodecId()));
|
||||
buff += RtmpPacketInfo::kEnhancedRtmpHeaderSize;
|
||||
if (cts) {
|
||||
header->pkt_type = (uint8_t)RtmpPacketType::PacketTypeCodedFrames;
|
||||
set_be24(buff, cts);
|
||||
buff += 3;
|
||||
} else {
|
||||
header->pkt_type = (uint8_t)RtmpPacketType::PacketTypeCodedFramesX;
|
||||
}
|
||||
// Enhanced AV1/VP8/VP9 have no composition offset, so always use CodedFrames.
|
||||
header->pkt_type = (uint8_t)RtmpPacketType::PacketTypeCodedFrames;
|
||||
} else {
|
||||
// flags
|
||||
uint8_t flags = getCodecFlags(frame->getCodecId());
|
||||
@@ -104,15 +96,15 @@ bool VpxRtmpEncoder::inputFrame(const Frame::Ptr &frame) {
|
||||
|
||||
buff[0] = flags;
|
||||
buff[1] = (uint8_t)RtmpH264PacketType::h264_nalu;
|
||||
// cts
|
||||
// Preserve the low 24 bits of the signed composition offset, including
|
||||
// negative offsets, without narrowing an unsigned difference to int32_t.
|
||||
auto cts = static_cast<uint32_t>(frame->pts() - frame->dts());
|
||||
set_be24(&buff[2], cts);
|
||||
buff += 5;
|
||||
}
|
||||
memcpy(buff + header_size, payload, payload_size);
|
||||
|
||||
packet->time_stamp = frame->dts();
|
||||
memcpy(buff, frame->data(), frame->size());
|
||||
buff += frame->size();
|
||||
packet->body_size = buff - packet->data();
|
||||
packet->time_stamp = _enhanced ? frame->pts() : frame->dts();
|
||||
packet->body_size = packet->buffer.size();
|
||||
packet->chunk_id = CHUNK_VIDEO;
|
||||
packet->stream_index = STREAM_MEDIA;
|
||||
packet->type_id = MSG_VIDEO;
|
||||
|
||||
@@ -203,6 +203,7 @@ public:
|
||||
int getVideoWidth() const override { return _width; }
|
||||
int getVideoHeight() const override { return _height; }
|
||||
float getVideoFps() const override { return _fps; }
|
||||
void setVideoFps(float fps) { _fps = fps; }
|
||||
bool ready() const override { return _width > 0 && _height > 0; }
|
||||
|
||||
Track::Ptr clone() const override { return std::make_shared<VideoTrackImp>(*this); }
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
* 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 <cmath>
|
||||
#include "RtmpCodec.h"
|
||||
#include "RtmpDemuxer.h"
|
||||
#include "Extension/Factory.h"
|
||||
@@ -49,6 +50,13 @@ bool RtmpDemuxer::loadMetaData(const AMFValue &val) {
|
||||
_duration = (float)val.as_number();
|
||||
return;
|
||||
}
|
||||
if (key == "framerate" && val.type() == AMF_NUMBER) {
|
||||
float fps = val.as_number();
|
||||
if (std::isfinite(fps) && fps > 0) {
|
||||
_video_fps = fps;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (key == "audiosamplerate") {
|
||||
audiosamplerate = val.as_integer();
|
||||
return;
|
||||
@@ -114,7 +122,7 @@ void RtmpDemuxer::inputRtmp(const RtmpPacket::Ptr &pkt) {
|
||||
switch (pkt->type_id) {
|
||||
case MSG_VIDEO: {
|
||||
if (!_try_get_video_track) {
|
||||
_try_get_video_track = true;
|
||||
// Retry until makeVideoTrack has created a usable decoder.
|
||||
auto codec_id = parseVideoRtmpPacket((uint8_t *)pkt->data(), pkt->size());
|
||||
makeVideoTrack(Factory::getTrackByCodecId(codec_id), 0);
|
||||
}
|
||||
@@ -162,6 +170,12 @@ void RtmpDemuxer::makeVideoTrack(const Track::Ptr &track, int bit_rate) {
|
||||
_video_track.reset();
|
||||
return;
|
||||
}
|
||||
// AV1/VPx do not derive FPS from their bitstream. Preserve the publisher's
|
||||
// nominal rate before addTrack() clones the track into the media sink.
|
||||
auto video = dynamic_pointer_cast<VideoTrackImp>(_video_track);
|
||||
if (video && _video_fps > 0) {
|
||||
video->setVideoFps(_video_fps);
|
||||
}
|
||||
_video_track->setBitRate(bit_rate);
|
||||
addTrack(_video_track);
|
||||
_try_get_video_track = true;
|
||||
|
||||
@@ -58,6 +58,7 @@ private:
|
||||
bool _try_get_video_track = false;
|
||||
bool _try_get_audio_track = false;
|
||||
float _duration = 0;
|
||||
float _video_fps = 0;
|
||||
AudioTrack::Ptr _audio_track;
|
||||
VideoTrack::Ptr _video_track;
|
||||
RtmpCodec::Ptr _audio_rtmp_decoder;
|
||||
|
||||
@@ -40,6 +40,7 @@ find_package(PCAP QUIET)
|
||||
# candidates: test_vp9_rtp currently fails and will be added once fixed; test_rtcp_nack and
|
||||
# test_webrtc_regression are built only with WebRTC enabled and are not verified yet.
|
||||
set(GATING_TESTS
|
||||
test_av1_rtmp
|
||||
test_amf
|
||||
test_hls_cookie_data
|
||||
test_sortor)
|
||||
|
||||
208
tests/integration/av1_rtmp_metadata.py
Normal file
208
tests/integration/av1_rtmp_metadata.py
Normal file
@@ -0,0 +1,208 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Local FFmpeg integration test; needs a DISABLE_REPORT=ON MediaServer build.
|
||||
|
||||
Runs two concurrent 1440p60 AV1/AAC publishers plus H.264 and HEVC controls.
|
||||
The server binds only loopback; all generated media/config/logs live in a temp dir.
|
||||
This supplements, but does not replace, OBS AMD AV1 + mpegts.js acceptance testing.
|
||||
"""
|
||||
import argparse
|
||||
import configparser
|
||||
from contextlib import contextmanager
|
||||
import json
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import secrets
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
@contextmanager
|
||||
def reserve_ports():
|
||||
# Hold both sockets at once so the kernel cannot allocate the same port twice.
|
||||
with socket.socket() as rtmp, socket.socket() as http:
|
||||
rtmp.bind(('127.0.0.1', 0))
|
||||
http.bind(('127.0.0.1', 0))
|
||||
yield rtmp.getsockname()[1], http.getsockname()[1]
|
||||
|
||||
|
||||
def start_server(server, cfg, work, start):
|
||||
for attempt in range(3):
|
||||
# Allocate after fixture generation and release immediately before spawn.
|
||||
# MediaServer cannot inherit these sockets, so retry the unavoidable bind race.
|
||||
with reserve_ports() as (rtmp_port, http_port):
|
||||
cfg['rtmp']['port'] = str(rtmp_port)
|
||||
cfg['http']['port'] = str(http_port)
|
||||
config_path = work / 'config.ini'
|
||||
with config_path.open('w') as out:
|
||||
cfg.write(out)
|
||||
srv = start([str(server), '-c', str(config_path), '-t', '2', '--affinity', '0',
|
||||
'--log-dir', str(work / 'logs')], 'server-%d' % (attempt + 1))
|
||||
api = 'http://127.0.0.1:%d/index/api/getMediaList?secret=%s' % (http_port, cfg['api']['secret'])
|
||||
for _ in range(100):
|
||||
if srv.poll() is not None:
|
||||
break
|
||||
try:
|
||||
with urllib.request.urlopen(api, timeout=1) as response:
|
||||
# A per-run secret prevents accepting another concurrent test's API.
|
||||
if json.load(response).get('code') == 0 and srv.poll() is None:
|
||||
return rtmp_port, http_port, api
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
time.sleep(0.1)
|
||||
if srv.poll() is None:
|
||||
srv.terminate()
|
||||
try:
|
||||
srv.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
srv.kill()
|
||||
srv.wait()
|
||||
print('MediaServer startup attempt %d failed; log: server-%d.log' % (attempt + 1, attempt + 1), flush=True)
|
||||
raise RuntimeError('local MediaServer did not start after 3 attempts; see server logs')
|
||||
|
||||
|
||||
def run(args, **kwargs):
|
||||
return subprocess.run(args, check=True, timeout=90, **kwargs)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--server', type=Path, required=True)
|
||||
parser.add_argument('--report', type=Path)
|
||||
parser.add_argument('--all-intra', action='store_true', help='Use AV1 keyframes only to isolate unready-track timeout')
|
||||
args = parser.parse_args()
|
||||
server = args.server.resolve()
|
||||
results = {}
|
||||
processes = []
|
||||
logs = []
|
||||
with tempfile.TemporaryDirectory(prefix='zlm-av1-') as tmp:
|
||||
work = Path(tmp)
|
||||
cfg = configparser.ConfigParser(interpolation=None)
|
||||
cfg.optionxform = str
|
||||
cfg.read(ROOT / 'conf/config.ini')
|
||||
overrides = {
|
||||
'general': {'listen_ip': '127.0.0.1'},
|
||||
'api': {'secret': secrets.token_hex(16)},
|
||||
'http': {'port': '0', 'sslport': '0', 'rootPath': str(work)},
|
||||
'rtmp': {'port': '0', 'sslport': '0', 'directProxy': '1', 'enhanced': '1'},
|
||||
'rtsp': {'port': '0', 'sslport': '0'},
|
||||
'rtp_proxy': {'port': '0'},
|
||||
'rtc': {'port': '0', 'tcpPort': '0'},
|
||||
'srt': {'port': '0'},
|
||||
'shell': {'port': '0'},
|
||||
'protocol': {'continue_push_ms': '0', 'enable_audio': '1', 'add_mute_audio': '0',
|
||||
'enable_rtmp': '1', 'enable_rtsp': '0', 'enable_hls': '0',
|
||||
'enable_hls_fmp4': '0', 'enable_mp4': '0', 'enable_ts': '0', 'enable_fmp4': '0'},
|
||||
}
|
||||
for section, values in overrides.items():
|
||||
if section not in cfg:
|
||||
cfg.add_section(section)
|
||||
cfg[section].update(values)
|
||||
|
||||
def start(command, name):
|
||||
logfile = (work / (name + '.log')).open('w+')
|
||||
logs.append((name, logfile))
|
||||
process = subprocess.Popen(command, cwd=work, stdout=logfile, stderr=subprocess.STDOUT)
|
||||
processes.append(process)
|
||||
return process
|
||||
|
||||
base_ffmpeg = ['ffmpeg', '-hide_banner', '-loglevel', 'error', '-nostdin']
|
||||
codecs = {
|
||||
'av1': ['-c:v', 'libaom-av1', '-cpu-used', '8', '-threads', '4', '-row-mt', '1', '-lag-in-frames', '0'],
|
||||
'h264': ['-c:v', 'libx264', '-preset', 'ultrafast', '-tune', 'zerolatency', '-threads', '4'],
|
||||
'hevc': ['-c:v', 'libx265', '-preset', 'ultrafast', '-x265-params', 'pools=2:frame-threads=2:log-level=error'],
|
||||
}
|
||||
try:
|
||||
for codec, options in codecs.items():
|
||||
size = '2560x1440' if codec == 'av1' else '640x360'
|
||||
run(base_ffmpeg + ['-f', 'lavfi', '-i', 'color=c=blue:size=' + size + ':rate=60',
|
||||
'-f', 'lavfi', '-i', 'sine=frequency=440:sample_rate=48000', '-t', '2']
|
||||
+ options + ['-g', '1' if args.all_intra and codec == 'av1' else '60', '-pix_fmt', 'yuv420p', '-c:a', 'aac', '-ac', '2', '-ar', '48000',
|
||||
'-f', 'mp4', str(work / (codec + '.mp4'))], stdout=subprocess.DEVNULL)
|
||||
run(base_ffmpeg + ['-i', str(work / 'av1.mp4'), '-c', 'copy', '-f', 'flv', str(work / 'av1.flv')])
|
||||
raw = (work / 'av1.flv').read_bytes()
|
||||
offset = 13
|
||||
packets = []
|
||||
while offset + 11 < len(raw) and len(packets) < 4:
|
||||
kind = raw[offset]
|
||||
size = int.from_bytes(raw[offset + 1:offset + 4], 'big')
|
||||
body = raw[offset + 11:offset + 11 + size]
|
||||
if kind == 9:
|
||||
packets.append({'type': body[0] & 15, 'fourcc': body[1:5].decode('ascii'),
|
||||
'size': size, 'payload_hex': body[5:29].hex()})
|
||||
offset += size + 15
|
||||
results['av1_packets'] = packets
|
||||
print('AV1 packet prefixes:', packets, flush=True)
|
||||
rtmp_port, http_port, api = start_server(server, cfg, work, start)
|
||||
streams = {'av1-a': 'av1', 'av1-b': 'av1', 'h264': 'h264', 'hevc': 'hevc'}
|
||||
for name, codec in streams.items():
|
||||
start(base_ffmpeg + ['-re', '-stream_loop', '-1', '-i', str(work / (codec + '.mp4')),
|
||||
'-c', 'copy'] + (['-bsf:v', 'av1_metadata=td=' + ('insert' if name == 'av1-a' else 'remove')] if codec == 'av1' else [])
|
||||
+ ['-f', 'flv', 'rtmp://127.0.0.1:%d/live/%s' % (rtmp_port, name)], name)
|
||||
# Allow the baseline's unready-track timeout to surface audio-only results.
|
||||
time.sleep(12)
|
||||
with urllib.request.urlopen(api, timeout=3) as response:
|
||||
data = json.load(response)
|
||||
if data.get('code') != 0:
|
||||
raise RuntimeError('getMediaList failed: ' + str(data))
|
||||
media = {entry['stream']: entry for entry in data.get('data', []) if entry['schema'] == 'rtmp'}
|
||||
results['tracks'] = {name: media.get(name, {}).get('tracks', []) for name in streams}
|
||||
errors = []
|
||||
for name, codec in streams.items():
|
||||
tracks = results['tracks'][name]
|
||||
print(name, json.dumps(tracks), flush=True)
|
||||
video = next((t for t in tracks if t['codec_type'] == 0), {})
|
||||
audio = next((t for t in tracks if t['codec_type'] == 1), {})
|
||||
expected = (2560, 1440) if codec == 'av1' else (640, 360)
|
||||
if not (video.get('ready') and (video.get('width'), video.get('height')) == expected):
|
||||
errors.append(name + ': missing/unready/wrong video dimensions')
|
||||
expected_codec = {'av1': 'AV1', 'h264': 'H264', 'hevc': 'H265'}[codec]
|
||||
if video.get('codec_id_name') != expected_codec:
|
||||
errors.append(name + ': wrong/missing video codec')
|
||||
if codec == 'av1' and abs(video.get('fps', 0) - 60) > 1:
|
||||
errors.append(name + ': FPS is not approximately 60')
|
||||
if not (audio.get('ready') and audio.get('sample_rate') == 48000 and audio.get('channels') == 2):
|
||||
errors.append(name + ': missing/wrong AAC metadata')
|
||||
# Decode both tracks, so byte forwarding without playable video cannot pass.
|
||||
playback = subprocess.run(base_ffmpeg + ['-xerror', '-i', 'http://127.0.0.1:%d/live/%s.live.flv' % (http_port, name),
|
||||
'-t', '1', '-map', '0:v:0', '-map', '0:a:0', '-f', 'null', '-'],
|
||||
capture_output=True, text=True, timeout=20)
|
||||
results.setdefault('playback', {})[name] = playback.returncode == 0
|
||||
if playback.returncode:
|
||||
errors.append(name + ': HTTP-FLV decode failed: ' + playback.stderr)
|
||||
results['errors'] = errors
|
||||
if args.report:
|
||||
args.report.resolve().write_text(json.dumps(results, indent=2) + '\n')
|
||||
print('HTTP-FLV decoding:', results['playback'], flush=True)
|
||||
if errors:
|
||||
raise RuntimeError('; '.join(errors))
|
||||
print('PASS: two AV1 1440p60/AAC streams, H.264, HEVC, API metadata and HTTP-FLV decoding')
|
||||
except Exception:
|
||||
for name, logfile in logs:
|
||||
logfile.flush()
|
||||
logfile.seek(0)
|
||||
print(name + ' log tail:\n' + logfile.read()[-2500:])
|
||||
raise
|
||||
finally:
|
||||
for proc in reversed(processes):
|
||||
if proc.poll() is None:
|
||||
proc.terminate()
|
||||
for proc in processes:
|
||||
try:
|
||||
proc.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
proc.wait()
|
||||
for name, logfile in logs:
|
||||
if args.report and name.startswith('server-'):
|
||||
logfile.flush()
|
||||
logfile.seek(0)
|
||||
args.report.resolve().with_suffix('.' + name + '.log').write_text(logfile.read())
|
||||
logfile.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
79
tests/integration/test_av1_rtmp_startup.py
Normal file
79
tests/integration/test_av1_rtmp_startup.py
Normal file
@@ -0,0 +1,79 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline startup regressions; no FFmpeg or MediaServer process required."""
|
||||
import configparser
|
||||
import io
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import av1_rtmp_metadata as integration
|
||||
|
||||
|
||||
class StartupTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory(prefix='zlm-startup-test-')
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.work = Path(self.temp.name)
|
||||
self.cfg = configparser.ConfigParser()
|
||||
self.cfg.read_dict({'rtmp': {'port': '0'}, 'http': {'port': '0'}, 'api': {'secret': 'test-secret'}})
|
||||
|
||||
def test_both_ports_are_distinct_and_reserved(self):
|
||||
with integration.reserve_ports() as ports:
|
||||
self.assertNotEqual(*ports)
|
||||
for port in ports:
|
||||
with socket.socket() as contender:
|
||||
with self.assertRaises(OSError):
|
||||
contender.bind(('127.0.0.1', port))
|
||||
|
||||
def test_failed_bind_retries_with_fresh_config(self):
|
||||
failed, healthy = Mock(), Mock()
|
||||
failed.poll.return_value = 1
|
||||
healthy.poll.return_value = None
|
||||
attempts = []
|
||||
|
||||
def start(command, name):
|
||||
config = configparser.ConfigParser()
|
||||
config.read(command[command.index('-c') + 1])
|
||||
ports = [int(config[section]['port']) for section in ('rtmp', 'http')]
|
||||
self.assertNotEqual(*ports)
|
||||
# The reservations must have been released before spawning the server.
|
||||
for port in ports:
|
||||
with socket.socket() as listener:
|
||||
listener.bind(('127.0.0.1', port))
|
||||
attempts.append((name, ports))
|
||||
return failed if len(attempts) == 1 else healthy
|
||||
|
||||
with patch.object(integration.urllib.request, 'urlopen', return_value=io.BytesIO(b'{"code":0}')):
|
||||
rtmp, http, api = integration.start_server('MediaServer', self.cfg, self.work, start)
|
||||
self.assertEqual(len(attempts), 2)
|
||||
self.assertEqual([rtmp, http], attempts[-1][1])
|
||||
self.assertIn(':%d/' % http, api)
|
||||
failed.wait.assert_called_once()
|
||||
healthy.terminate.assert_not_called()
|
||||
|
||||
def test_failed_readiness_stops_process_before_retry(self):
|
||||
failed, healthy = Mock(), Mock()
|
||||
failed.poll.return_value = healthy.poll.return_value = None
|
||||
start = Mock(side_effect=[failed, healthy])
|
||||
responses = [OSError('port not listening')] * 100 + [io.BytesIO(b'{"code":0}')]
|
||||
with patch.object(integration.urllib.request, 'urlopen', side_effect=responses), \
|
||||
patch.object(integration.time, 'sleep'):
|
||||
integration.start_server('MediaServer', self.cfg, self.work, start)
|
||||
self.assertEqual(start.call_count, 2)
|
||||
failed.terminate.assert_called_once()
|
||||
failed.wait.assert_called_once()
|
||||
healthy.terminate.assert_not_called()
|
||||
|
||||
def test_startup_failure_is_bounded(self):
|
||||
failed = Mock()
|
||||
failed.poll.return_value = 1
|
||||
start = Mock(return_value=failed)
|
||||
with self.assertRaisesRegex(RuntimeError, 'after 3 attempts'):
|
||||
integration.start_server('MediaServer', self.cfg, self.work, start)
|
||||
self.assertEqual(start.call_count, 3)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
371
tests/test_av1_rtmp.cpp
Normal file
371
tests/test_av1_rtmp.cpp
Normal file
@@ -0,0 +1,371 @@
|
||||
/*
|
||||
* 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 <cmath>
|
||||
#include <iostream>
|
||||
#include <limits>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "Extension/Factory.h"
|
||||
#include "Common/config.h"
|
||||
#include "Rtmp/RtmpDemuxer.h"
|
||||
#include "ext-codec/AV1.h"
|
||||
#include "ext-codec/VpxRtmp.h"
|
||||
|
||||
using namespace mediakit;
|
||||
|
||||
namespace {
|
||||
int failures = 0;
|
||||
void require(bool condition, const std::string &message) {
|
||||
if (!condition) {
|
||||
++failures;
|
||||
std::cerr << "FAIL: " << message << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
std::string unhex(const std::string &hex) {
|
||||
std::string bytes;
|
||||
for (size_t i = 0; i < hex.size(); i += 2) {
|
||||
bytes.push_back(static_cast<char>(std::stoul(hex.substr(i, 2), nullptr, 16)));
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
// Generated with FFmpeg/libaom: color=c=blue:size=2560x1440:rate=60,
|
||||
// -frames:v 4 -cpu-used 8 -lag-in-frames 0 -g 2 -f ivf.
|
||||
// Keep a real temporal delimiter + sequence header + keyframe, not a ZLM encoder round trip.
|
||||
const auto keyframe = unhex("12000a0c00000062ea7fecfb95f200803233100085a000008000200c58f6de6dde4989ff832ffe1dbcaea584f44d6e528c552631c8ae61c48bc4561172a7963fac64cd2d7d");
|
||||
const auto interframe = unhex("12003224300380800000468a20000090000800fbc4ef4f40dc1b8975fc537624dc4d9213db48b1c0");
|
||||
const auto av1c = unhex("810c0c000a0c00000062ea7fecfb95f20080");
|
||||
|
||||
RtmpPacket::Ptr packet(const std::string &body, uint32_t dts = 0, uint8_t type = MSG_VIDEO) {
|
||||
auto pkt = RtmpPacket::create();
|
||||
pkt->buffer.assign(body.data(), body.size());
|
||||
pkt->body_size = body.size();
|
||||
pkt->type_id = type;
|
||||
pkt->time_stamp = dts;
|
||||
pkt->chunk_id = type == MSG_VIDEO ? CHUNK_VIDEO : CHUNK_AUDIO;
|
||||
pkt->stream_index = STREAM_MEDIA;
|
||||
return pkt;
|
||||
}
|
||||
RtmpPacket::Ptr enhanced(uint8_t type, const std::string &body, uint32_t dts = 0,
|
||||
const std::string &fourcc = "av01") {
|
||||
return packet(std::string(1, static_cast<char>(0x90 | type)) + fourcc + body, dts);
|
||||
}
|
||||
|
||||
void testCodedFrames() {
|
||||
auto track = std::make_shared<AV1Track>();
|
||||
VpxRtmpDecoder decoder(track);
|
||||
size_t frames = 0;
|
||||
track->addDelegate([&](const Frame::Ptr &frame) {
|
||||
++frames;
|
||||
std::cout << "decoded frame size=" << frame->size() << " dts=" << frame->dts()
|
||||
<< " pts=" << frame->pts() << " dimensions=" << track->getVideoWidth()
|
||||
<< 'x' << track->getVideoHeight() << " fps=" << track->getVideoFps() << '\n';
|
||||
const auto &expected = frames == 1 ? keyframe : interframe;
|
||||
require(std::string(frame->data(), frame->size()) == expected, "AV1 CodedFrames preserves every OBU byte");
|
||||
require(frame->dts() == frame->pts(), "AV1 has no composition-time field");
|
||||
require(frame->dts() == (frames == 1 ? 100U : 117U), "AV1 DTS is preserved");
|
||||
return true;
|
||||
});
|
||||
decoder.inputRtmp(enhanced(0, av1c));
|
||||
decoder.inputRtmp(enhanced(1, keyframe, 100));
|
||||
decoder.inputRtmp(enhanced(1, interframe, 117));
|
||||
require(frames == 2, "both AV1 temporal units are delivered");
|
||||
require(track->getVideoWidth() == 2560 && track->getVideoHeight() == 1440,
|
||||
"AV1 CodedFrames produces 2560x1440 metadata");
|
||||
|
||||
// Older ZLM senders used CodedFramesX with no CTS. Continue accepting that layout.
|
||||
auto compatibility = std::make_shared<AV1Track>();
|
||||
VpxRtmpDecoder old_decoder(compatibility);
|
||||
old_decoder.inputRtmp(enhanced(3, keyframe, 100));
|
||||
require(compatibility->getVideoWidth() == 2560 && compatibility->getVideoHeight() == 1440,
|
||||
"legacy ZLM CodedFramesX remains readable");
|
||||
}
|
||||
|
||||
void testWithoutTemporalDelimiter() {
|
||||
// A temporal delimiter is optional in the low-overhead bitstream. Removing
|
||||
// it must not damage the sequence header.
|
||||
auto track = std::make_shared<AV1Track>();
|
||||
VpxRtmpDecoder decoder(track);
|
||||
decoder.inputRtmp(enhanced(0, av1c));
|
||||
decoder.inputRtmp(enhanced(1, keyframe.substr(2), 100));
|
||||
require(track->ready() && track->getVideoWidth() == 2560 && track->getVideoHeight() == 1440,
|
||||
"AV1 without a temporal delimiter is a ready video track");
|
||||
}
|
||||
|
||||
void testConfiguration() {
|
||||
aom_av1_t context {};
|
||||
auto loaded = aom_av1_codec_configuration_record_load(
|
||||
reinterpret_cast<const uint8_t *>(av1c.data()), av1c.size(), &context);
|
||||
std::cout << "av1C load=" << loaded << " dimensions=" << context.width << 'x' << context.height;
|
||||
auto parsed = aom_av1_codec_configuration_record_init(&context, keyframe.data(), keyframe.size());
|
||||
std::cout << "; intact frame init=" << parsed << " dimensions=" << context.width << 'x' << context.height << '\n';
|
||||
require(loaded == static_cast<int>(av1c.size()) && parsed == 0
|
||||
&& context.width == 2560 && context.height == 1440, "pinned parser accepts the intact fixture");
|
||||
|
||||
AV1Track track;
|
||||
track.setExtraData(reinterpret_cast<const uint8_t *>(av1c.data()), av1c.size());
|
||||
require(track.ready() && track.getVideoWidth() == 2560 && track.getVideoHeight() == 1440,
|
||||
"SequenceStart parses configOBUs before any coded frame");
|
||||
auto extra = track.getExtraData();
|
||||
require(extra && std::string(extra->data(), extra->size()) == av1c, "av1C round trip preserves configuration");
|
||||
for (unsigned i = 0; i < 200; ++i) {
|
||||
track.inputFrame(Factory::getFrameFromPtr(CodecAV1, keyframe.data(), keyframe.size(), i * 17, i * 17));
|
||||
}
|
||||
extra = track.getExtraData();
|
||||
require(extra && extra->size() == av1c.size(), "repeated sequence headers do not accumulate in av1C");
|
||||
track.setExtraData(reinterpret_cast<const uint8_t *>("\x81"), 1);
|
||||
require(track.getVideoWidth() == 2560 && track.getVideoHeight() == 1440,
|
||||
"truncated av1C does not destroy known dimensions");
|
||||
// Failed frame parsing must not overwrite the last good configuration.
|
||||
const auto truncated = unhex("0a0c0000");
|
||||
track.inputFrame(Factory::getFrameFromPtr(CodecAV1, truncated.data(), truncated.size(), 4000, 4000));
|
||||
track.inputFrame(Factory::getFrameFromPtr(CodecAV1, interframe.data(), interframe.size(), 4017, 4017));
|
||||
require(track.getVideoWidth() == 2560 && track.getVideoHeight() == 1440,
|
||||
"bad or sequence-header-free frames retain known dimensions");
|
||||
auto clone = std::dynamic_pointer_cast<VideoTrack>(track.clone());
|
||||
require(clone->ready() && clone->getVideoWidth() == 2560, "track clones retain configuration");
|
||||
}
|
||||
|
||||
void testConfigurationWithoutSequenceHeader() {
|
||||
// AV1 ISOBMFF section 2.3.4 permits zero configOBUs, or metadata without
|
||||
// a sequence header. Neither contains replacement dimensions.
|
||||
const auto header_only = av1c.substr(0, 4);
|
||||
const auto metadata_only = header_only + unhex("2a060103e8019080"); // HDR_CLL metadata
|
||||
for (const auto &config : {header_only, metadata_only}) {
|
||||
auto track = std::make_shared<AV1Track>();
|
||||
VpxRtmpDecoder decoder(track);
|
||||
decoder.inputRtmp(enhanced(0, config));
|
||||
require(!track->ready() && track->getVideoWidth() == 0 && track->getVideoHeight() == 0,
|
||||
"configuration without a sequence header cannot invent dimensions");
|
||||
decoder.inputRtmp(enhanced(1, keyframe, 100));
|
||||
require(track->ready(), "a sequence header in a frame makes the track ready");
|
||||
decoder.inputRtmp(enhanced(0, config, 117));
|
||||
require(track->ready() && track->getVideoWidth() == 2560 && track->getVideoHeight() == 1440,
|
||||
"later SequenceStart without sequence header preserves known dimensions");
|
||||
auto extra = track->getExtraData();
|
||||
require(config == header_only ? !extra : extra && std::string(extra->data(), extra->size()) == config,
|
||||
"dimension preservation still commits the replacement configuration");
|
||||
decoder.inputRtmp(enhanced(1, interframe, 134));
|
||||
auto clone = std::dynamic_pointer_cast<VideoTrack>(track->clone());
|
||||
require(clone->ready() && clone->getVideoWidth() == 2560 && clone->getVideoHeight() == 1440,
|
||||
"preserved dimensions survive inter frames and track cloning");
|
||||
}
|
||||
}
|
||||
|
||||
void testDiscovery() {
|
||||
RtmpDemuxer demuxer;
|
||||
// Unknown FourCC followed by a usable AV1 SequenceStart. No onMetaData rescue.
|
||||
demuxer.inputRtmp(enhanced(0, av1c, 0, "????"));
|
||||
require(demuxer.getTracks(false).empty(), "unknown codec does not invent a track");
|
||||
demuxer.inputRtmp(enhanced(0, av1c));
|
||||
demuxer.inputRtmp(enhanced(1, keyframe));
|
||||
auto tracks = demuxer.getTracks(false);
|
||||
require(tracks.size() == 1 && tracks[0]->getCodecId() == CodecAV1,
|
||||
"video discovery retries after an unsupported first packet");
|
||||
}
|
||||
|
||||
// Inspect output at the wire boundary, not through a decoder sharing the same bug.
|
||||
class CapturingVpxEncoder : public VpxRtmpEncoder {
|
||||
public:
|
||||
explicit CapturingVpxEncoder(const Track::Ptr &track) : VpxRtmpEncoder(track) {
|
||||
auto ring = std::make_shared<RingType>();
|
||||
ring->setDelegate(std::make_shared<Capture>(output));
|
||||
setRtmpRing(ring);
|
||||
}
|
||||
RtmpPacket::Ptr output;
|
||||
private:
|
||||
class Capture : public toolkit::RingDelegate<RtmpPacket::Ptr> {
|
||||
public:
|
||||
explicit Capture(RtmpPacket::Ptr &output) : _output(output) {}
|
||||
void onWrite(RtmpPacket::Ptr packet, bool) override { _output = packet; }
|
||||
private:
|
||||
RtmpPacket::Ptr &_output;
|
||||
};
|
||||
};
|
||||
|
||||
void testVpxPacketLayouts() {
|
||||
for (auto codec : {CodecAV1, CodecVP8, CodecVP9}) {
|
||||
const std::string payload = codec == CodecAV1 ? unhex("1a0180") : unhex("010203040506");
|
||||
const std::string fourcc = codec == CodecAV1 ? "av01" : codec == CodecVP8 ? "vp08" : "vp09";
|
||||
auto track = std::make_shared<VideoTrackImp>(codec, 2560, 1440, 60);
|
||||
VpxRtmpDecoder decoder(track);
|
||||
size_t frames = 0;
|
||||
track->addDelegate([&](const Frame::Ptr &frame) {
|
||||
++frames;
|
||||
require(std::string(frame->data(), frame->size()) == payload, "short VPx CodedFrames remains intact");
|
||||
require(frame->dts() == 100 && frame->pts() == 100, "VPx CodedFrames uses the RTMP timestamp");
|
||||
return true;
|
||||
});
|
||||
decoder.inputRtmp(enhanced(1, payload, 100, fourcc));
|
||||
require(frames == 1, "short VPx payload is delivered");
|
||||
|
||||
toolkit::mINI::Instance()[Rtmp::kEnhanced] = true;
|
||||
CapturingVpxEncoder encoder(track);
|
||||
// Even if the caller supplies different PTS, enhanced VPx has no CTS field.
|
||||
auto frame = Factory::getFrameFromPtr(codec, payload.data(), payload.size(), 100, 117);
|
||||
encoder.inputFrame(frame);
|
||||
require(encoder.output != nullptr, "VPx encoder emits a packet");
|
||||
if (encoder.output) {
|
||||
require(encoder.output->time_stamp == 117, "enhanced VPx carries presentation time without CTS");
|
||||
const auto expected = std::string(1, static_cast<char>(0xa1)) + fourcc + payload;
|
||||
require(std::string(encoder.output->data(), encoder.output->size()) == expected,
|
||||
"VPx encoder emits CodedFrames with no CTS bytes");
|
||||
}
|
||||
|
||||
// Classic domestic-extension packets still have their SI24 offset.
|
||||
VpxRtmpDecoder classic_decoder(track);
|
||||
track->clear();
|
||||
bool classic_frame = false;
|
||||
track->addDelegate([&](const Frame::Ptr &decoded) {
|
||||
classic_frame = true;
|
||||
require(decoded->dts() == 100 && decoded->pts() == 117, "classic VPx preserves composition time");
|
||||
require(std::string(decoded->data(), decoded->size()) == payload, "classic VPx preserves payload");
|
||||
return true;
|
||||
});
|
||||
auto body = std::string(1, static_cast<char>(0x20 | getCodecFlags(codec))) + unhex("01000011") + payload;
|
||||
classic_decoder.inputRtmp(packet(body, 100));
|
||||
require(classic_frame, "classic VPx still decodes");
|
||||
}
|
||||
}
|
||||
|
||||
void testClassicEncoderOffsets() {
|
||||
const auto previous = toolkit::mINI::Instance()[Rtmp::kEnhanced];
|
||||
toolkit::mINI::Instance()[Rtmp::kEnhanced] = false;
|
||||
toolkit::NoticeCenter::Instance().emitEvent(Broadcast::kBroadcastReloadConfig);
|
||||
for (auto codec : {CodecAV1, CodecVP8, CodecVP9}) {
|
||||
const auto payload = codec == CodecAV1 ? unhex("1a0180") : unhex("010203040506");
|
||||
auto track = std::make_shared<VideoTrackImp>(codec, 2560, 1440, 60);
|
||||
CapturingVpxEncoder encoder(track);
|
||||
for (uint64_t pts : {83, 100, 117}) {
|
||||
encoder.inputFrame(Factory::getFrameFromPtr(codec, payload.data(), payload.size(), 100, pts));
|
||||
require(encoder.output != nullptr, "classic VPx encoder emits a packet");
|
||||
if (encoder.output) {
|
||||
const auto offset = pts == 83 ? unhex("ffffef") : pts == 100 ? unhex("000000") : unhex("000011");
|
||||
const auto expected = std::string(1, static_cast<char>(0x20 | getCodecFlags(codec)))
|
||||
+ unhex("01") + offset + payload;
|
||||
require(std::string(encoder.output->data(), encoder.output->size()) == expected,
|
||||
"classic VPx encoder preserves negative, zero and positive SI24 offsets");
|
||||
require(encoder.output->time_stamp == 100, "classic VPx encoder keeps decode time");
|
||||
}
|
||||
}
|
||||
}
|
||||
toolkit::mINI::Instance()[Rtmp::kEnhanced] = previous;
|
||||
toolkit::NoticeCenter::Instance().emitEvent(Broadcast::kBroadcastReloadConfig);
|
||||
}
|
||||
|
||||
void testLegacyEnhancedCtsIsNotInterpreted() {
|
||||
for (auto codec : {CodecAV1, CodecVP8, CodecVP9}) {
|
||||
const std::string fourcc = codec == CodecAV1 ? "av01" : codec == CodecVP8 ? "vp08" : "vp09";
|
||||
const auto payload = codec == CodecAV1 ? keyframe : unhex("010203040506");
|
||||
// Observe the RTMP framing boundary without asking a codec parser to
|
||||
// accept the nonconforming payload. This is not a decodability test.
|
||||
for (const auto &offset : {unhex("000011"), unhex("ffffef")}) {
|
||||
auto track = std::make_shared<VideoTrackImp>(codec, 2560, 1440, 60);
|
||||
VpxRtmpDecoder decoder(track);
|
||||
const auto legacy_payload = offset + payload;
|
||||
size_t frames = 0;
|
||||
track->addDelegate([&](const Frame::Ptr &frame) {
|
||||
++frames;
|
||||
require(std::string(frame->data(), frame->size()) == legacy_payload,
|
||||
"legacy enhanced CTS bytes remain payload; no offset heuristic");
|
||||
require(frame->dts() == 100 && frame->pts() == 100,
|
||||
"legacy enhanced CTS does not change presentation time");
|
||||
return true;
|
||||
});
|
||||
decoder.inputRtmp(enhanced(1, legacy_payload, 100, fourcc));
|
||||
require(frames == 1, "legacy enhanced layout is passed through at the framing boundary");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void testTruncatedEnhancedHeaders() {
|
||||
for (bool initialized : {false, true}) {
|
||||
for (uint8_t type : {0, 1, 3}) {
|
||||
const auto header = std::string(1, static_cast<char>(0x90 | type)) + "av01";
|
||||
for (size_t size = 0; size <= header.size(); ++size) {
|
||||
auto track = std::make_shared<AV1Track>();
|
||||
VpxRtmpDecoder decoder(track);
|
||||
if (initialized) {
|
||||
decoder.inputRtmp(enhanced(0, av1c));
|
||||
}
|
||||
bool rejected = false;
|
||||
try {
|
||||
decoder.inputRtmp(packet(header.substr(0, size)));
|
||||
} catch (const std::exception &) {
|
||||
rejected = true;
|
||||
}
|
||||
require(rejected, "enhanced parser rejects missing/truncated headers and empty payloads");
|
||||
require(track->ready() == initialized, "rejected packet preserves track readiness");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void testMissingOrInvalidFps() {
|
||||
const std::vector<AMFValue> invalid_rates = {
|
||||
AMFValue(), AMFValue("60"), AMFValue(0.0), AMFValue(-1.0),
|
||||
AMFValue(std::numeric_limits<double>::infinity()),
|
||||
AMFValue(std::numeric_limits<double>::quiet_NaN())
|
||||
};
|
||||
for (const auto &fps : invalid_rates) {
|
||||
RtmpDemuxer demuxer;
|
||||
AMFValue metadata(AMF_OBJECT);
|
||||
metadata.set("videocodecid", static_cast<int>(RtmpVideoCodec::fourcc_av1));
|
||||
metadata.set("framerate", fps);
|
||||
demuxer.loadMetaData(metadata);
|
||||
auto tracks = demuxer.getTracks(false);
|
||||
require(tracks.size() == 1, "invalid FPS does not prevent track discovery");
|
||||
if (!tracks.empty()) {
|
||||
auto video = std::dynamic_pointer_cast<VideoTrack>(tracks[0]);
|
||||
require(video->getVideoFps() == 0, "invalid/unknown AV1 FPS is not fabricated as 30");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void testMetadataFps() {
|
||||
for (double fps : {60.0, 60000.0 / 1001.0}) {
|
||||
RtmpDemuxer demuxer;
|
||||
AMFValue metadata(AMF_OBJECT);
|
||||
metadata.set("videocodecid", static_cast<int>(RtmpVideoCodec::fourcc_av1));
|
||||
metadata.set("framerate", fps);
|
||||
demuxer.loadMetaData(metadata);
|
||||
demuxer.inputRtmp(enhanced(0, av1c));
|
||||
demuxer.inputRtmp(enhanced(1, keyframe));
|
||||
auto tracks = demuxer.getTracks(false);
|
||||
require(tracks.size() == 1, "onMetaData creates AV1 track");
|
||||
if (!tracks.empty()) {
|
||||
auto video = std::dynamic_pointer_cast<VideoTrack>(tracks[0]);
|
||||
std::cout << "onMetaData fps=" << fps << " track fps=" << video->getVideoFps() << '\n';
|
||||
require(std::abs(video->getVideoFps() - fps) < 0.001, "AV1 honors fractional onMetaData framerate");
|
||||
auto clone = std::dynamic_pointer_cast<VideoTrack>(video->clone());
|
||||
require(std::abs(clone->getVideoFps() - fps) < 0.001, "AV1 FPS survives cloning into the media sink");
|
||||
}
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
testDiscovery();
|
||||
testConfiguration();
|
||||
testConfigurationWithoutSequenceHeader();
|
||||
testWithoutTemporalDelimiter();
|
||||
testCodedFrames();
|
||||
testMetadataFps();
|
||||
testMissingOrInvalidFps();
|
||||
testVpxPacketLayouts();
|
||||
testClassicEncoderOffsets();
|
||||
testLegacyEnhancedCtsIsNotInterpreted();
|
||||
testTruncatedEnhancedHeaders();
|
||||
std::cout << failures << " failed checks\n";
|
||||
return failures ? 1 : 0;
|
||||
}
|
||||
173
tools/av1-metadata/README.md
Normal file
173
tools/av1-metadata/README.md
Normal file
@@ -0,0 +1,173 @@
|
||||
# Enhanced RTMP AV1 metadata regression
|
||||
|
||||
Related issue: [ZLMediaKit/ZLMediaKit#4839](https://github.com/ZLMediaKit/ZLMediaKit/issues/4839).
|
||||
The reproduction baseline is `10268396b89748bc2b0d19dda79bc29219e97815`, with
|
||||
`3rdpart/media-server` at `21c4451ff2e4c4bb1c817e606c8b4e5deac1e719`.
|
||||
|
||||
## Cause and correction
|
||||
|
||||
Enhanced AV1/VP8/VP9 `CodedFrames` starts immediately after FourCC, without the
|
||||
three-byte composition offset used by AVC/HEVC/VVC. The old shared VPx decoder
|
||||
consumed the first three encoded bytes as that offset. Depending on the valid
|
||||
OBU layout, it produced garbage dimensions, left the video track unready until
|
||||
MediaSink discarded it, or rejected a short frame. `rtmp.directProxy=1` can still
|
||||
forward the original playable packets while internal track metadata is wrong.
|
||||
|
||||
The patch preserves the coded bytes, fixes the matching encoder format and
|
||||
packet length, and continues accepting the old ZLM `CodedFramesX` layout.
|
||||
Classic domestic-extension packets retain their composition offsets.
|
||||
|
||||
Compatibility decision: older ZLM enhanced `CodedFrames` packets that insert an
|
||||
SI24 offset before AV1/VP8/VP9 data are intentionally unsupported. The decoder
|
||||
treats all bytes after FourCC as coded payload and sets PTS equal to the RTMP
|
||||
timestamp; it does not guess whether the first three bytes are a legacy offset.
|
||||
This breaks that nonconforming old-publisher layout, not classic non-enhanced
|
||||
CTS or the older zero-offset `CodedFramesX` layout. Upgrade publishers that emit
|
||||
enhanced CTS packets. `directProxy=1` forwards their original wire format and
|
||||
does not convert them into conforming packets.
|
||||
|
||||
The pinned `aom_av1_codec_configuration_record_load()` copies av1C/configOBUs;
|
||||
it does not populate dimensions. AV1Track now explicitly parses configOBUs.
|
||||
Frame parsing uses a fresh context and only commits a successful sequence header,
|
||||
so repeated headers cannot fill the 2 KiB configuration buffer and failed/inter
|
||||
frames cannot overwrite known dimensions. Valid header-only or metadata-only
|
||||
av1C updates also preserve previously learned dimensions while replacing the
|
||||
configuration; they do not make a new track ready without a sequence header. The pinned submodule is unchanged.
|
||||
|
||||
The constant 30 FPS was the inherited VideoTrackImp default, not an observed
|
||||
rate. AV1 now starts with unknown FPS, and RtmpDemuxer carries the publisher's
|
||||
finite positive `onMetaData.framerate` into AV1/VPx tracks before cloning. Missing
|
||||
or invalid metadata stays unknown for AV1; this is not a general AV1 timing-info
|
||||
parser or a new timestamp-based estimator. H.264/HEVC retain their bitstream FPS.
|
||||
The frame rate must arrive before video-track creation (including creation by a
|
||||
SequenceStart packet). Late metadata does not update existing tracks or their
|
||||
clones, so AV1 FPS can remain unknown even if a later metadata message supplies
|
||||
a valid rate. Back-filling those tracks is outside this change.
|
||||
|
||||
The premature video discovery flag is also removed. A separate regression proves
|
||||
that an unsupported first packet no longer prevents a later valid AV1 packet
|
||||
from creating a track. This recovery defect is distinct from the reproduced
|
||||
unready-track timeout; an unsupported first OBS packet has not been established.
|
||||
|
||||
Primary references:
|
||||
|
||||
- [Enhanced RTMP video layout](https://veovera.org/docs/enhanced/enhanced-rtmp-v2.html#enhanced-video)
|
||||
- [OBS 32.2.2 FLV muxer](https://github.com/obsproject/obs-studio/blob/32.2.2/plugins/obs-outputs/flv-mux.c):
|
||||
`flv_packet_ex()` only writes CTS for H.264/HEVC; `build_flv_meta_data()` writes frame rate.
|
||||
- [Pinned AV1 parser](https://github.com/ireader/media-server/blob/21c4451ff2e4c4bb1c817e606c8b4e5deac1e719/libflv/source/aom-av1.c).
|
||||
|
||||
## Native local build and tests
|
||||
|
||||
Run from the repository root in WSL2. Keep the production checkout separate.
|
||||
|
||||
```sh
|
||||
git submodule update --init --recursive
|
||||
cmake -S . -B build-av1 -DCMAKE_BUILD_TYPE=Debug -DDISABLE_REPORT=ON -DENABLE_TESTS=ON
|
||||
cmake --build build-av1 --target MediaServer test_av1_rtmp test_amf test_sortor -j 12
|
||||
ctest --test-dir build-av1 --output-on-failure
|
||||
```
|
||||
|
||||
`test_av1_rtmp` embeds a tiny independently encoded 2560x1440 libaom fixture.
|
||||
It checks discovery recovery, av1C parsing and round trips, 200 repeated sequence
|
||||
headers, failed-frame recovery, header-only/metadata-only SequenceStart updates,
|
||||
packet bytes/timestamps, 60 and 59.94 FPS and
|
||||
cloning, invalid FPS, short AV1/VP8/VP9 packets, encoder bytes, classic CTS, and
|
||||
older ZLM `CodedFramesX` compatibility. Explicit legacy enhanced CTS vectors pin
|
||||
the decision to preserve those bytes as payload without interpreting an offset;
|
||||
they do not establish that the resulting codec data is decodable. Truncated
|
||||
enhanced headers are rejected both before and after decoder initialization.
|
||||
It requires no network or external files.
|
||||
|
||||
The startup regressions use only Python 3 and local sockets, without FFmpeg or a
|
||||
server process. They cover simultaneous reservations, startup retry, timeout
|
||||
cleanup, and bounded failure:
|
||||
|
||||
```sh
|
||||
PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover \
|
||||
-s tests/integration -p test_av1_rtmp_startup.py -v
|
||||
```
|
||||
|
||||
The optional integration test needs Python 3 and FFmpeg with libaom-av1, libx264,
|
||||
libx265, AAC, Enhanced FLV, and the `av1_metadata` bitstream filter:
|
||||
|
||||
```sh
|
||||
python3 tests/integration/av1_rtmp_metadata.py \
|
||||
--server release/linux/Debug/MediaServer --report /tmp/av1-inter.json
|
||||
python3 tests/integration/av1_rtmp_metadata.py \
|
||||
--server release/linux/Debug/MediaServer --all-intra --report /tmp/av1-intra.json
|
||||
```
|
||||
|
||||
It binds the server to loopback on temporary ports and runs two simultaneous
|
||||
2560x1440@60 AV1/AAC publishers, one with temporal delimiters and one without,
|
||||
plus H.264/HEVC controls. It checks `getMediaList` and decodes both HTTP-FLV audio
|
||||
and video with FFmpeg. Generated media/configs and child processes are cleaned up;
|
||||
Ports are reserved together after fixture generation, released immediately before
|
||||
launch, and startup is retried up to three times if binding/readiness fails.
|
||||
A per-run API secret distinguishes concurrently running test servers.
|
||||
`--report` retains JSON results and sibling `.server-1.log` files (one per attempt).
|
||||
|
||||
Observed with the all-intra fixture on the pinned baseline versus the patch:
|
||||
|
||||
| Stream | Baseline API | Patched API | HTTP-FLV decode, both versions |
|
||||
|---|---|---|---|
|
||||
| AV1 with delimiter | AV1 1005x64406, 30 FPS | AV1 2560x1440, 60 FPS, ready | Pass |
|
||||
| AV1 without delimiter | AAC only after 10-second track timeout | AV1 2560x1440, 60 FPS, ready | Pass |
|
||||
| H.264/AAC | 640x360, 60 FPS | 640x360, 60 FPS | Pass |
|
||||
| HEVC/AAC | 640x360, 60 FPS | 640x360, 60 FPS | Pass |
|
||||
|
||||
The inter-frame case also passes after the patch. Its delimiter-free baseline
|
||||
can disconnect on a short AV1 payload. These generated fixtures establish the
|
||||
code defects; the exact reported `1x235` value and the original AMD packets have
|
||||
not been captured locally.
|
||||
|
||||
## Optional finite diagnostics
|
||||
|
||||
The normal patch does not log packet contents. To instrument a local test build:
|
||||
|
||||
```sh
|
||||
git apply --unidiff-zero --check tools/av1-metadata/diagnostics.patch
|
||||
git apply --unidiff-zero tools/av1-metadata/diagnostics.patch
|
||||
cmake --build build-av1 --target MediaServer -j 12
|
||||
```
|
||||
|
||||
`AV1_DIAG` lines capture the first 16 packets per demuxer/AV1 decoder, first 3
|
||||
configurations per AV1 track, and first 12 frames per AV1 track. They include
|
||||
packet type/FourCC/sizes, up to 32 initial payload bytes, parser return values and
|
||||
dimensions, DTS/PTS, metadata FPS, track FPS, and GOP values used by the API's
|
||||
fallback. Track pointers distinguish cloned tracks. Logging stops at those caps;
|
||||
direct proxy may stop demuxing earlier once all tracks are ready.
|
||||
|
||||
After collecting logs:
|
||||
|
||||
```sh
|
||||
git apply --unidiff-zero -R tools/av1-metadata/diagnostics.patch
|
||||
cmake --build build-av1 --target MediaServer -j 12
|
||||
```
|
||||
|
||||
## Local Docker build
|
||||
|
||||
Use the existing Docker recipe with only the requested reporting option added.
|
||||
The stdin Dockerfile keeps the repository's normal recipe unchanged:
|
||||
|
||||
```sh
|
||||
sed 's/RUN cmake /RUN cmake -DDISABLE_REPORT=ON /' dockerfile | \
|
||||
docker build -f - -t zlmediakit:av1-metadata .
|
||||
docker run --rm --name zlm-av1-local \
|
||||
-p 127.0.0.1:19350:1935 -p 127.0.0.1:18080:80 \
|
||||
zlmediakit:av1-metadata
|
||||
```
|
||||
|
||||
The native builds and tests above were run with `DISABLE_REPORT=ON`. The Docker
|
||||
image was not built in this workspace because no Docker daemon was running.
|
||||
|
||||
For production acceptance on another deployment, test two real OBS AMD AV1 2560x1440@60 publishers with
|
||||
`directProxy=1`, `enhanced=1`, `continue_push_ms=0`, audio and RTMP enabled. Confirm
|
||||
both ready AV1 tracks, dimensions and approximately 60 FPS, AAC, mpegts.js browser
|
||||
playback, and H.264/HEVC controls. The local FFmpeg tests do not substitute for
|
||||
that hardware-encoder/browser acceptance test.
|
||||
|
||||
|
||||
Production update (2026-09-26): the operator confirmed the original fixes were
|
||||
deployed and stable, including correctly reported 1440p90 AV1. The subsequent
|
||||
Copilot-review fixes for configuration-only updates and test startup have been
|
||||
validated locally; that deployment confirmation applies to the original fixes.
|
||||
71
tools/av1-metadata/diagnostics.patch
Normal file
71
tools/av1-metadata/diagnostics.patch
Normal file
@@ -0,0 +1,71 @@
|
||||
--- a/ext-codec/AV1.h
|
||||
+++ b/ext-codec/AV1.h
|
||||
@@ -60,0 +61,2 @@
|
||||
+ size_t _diagnostic_frames = 0;
|
||||
+ size_t _diagnostic_configs = 0;
|
||||
--- a/ext-codec/AV1.cpp
|
||||
+++ b/ext-codec/AV1.cpp
|
||||
@@ -11,0 +12 @@
|
||||
+#include "Util/util.h"
|
||||
@@ -26,2 +27,11 @@
|
||||
- if (0 == aom_av1_codec_configuration_record_init(&context, dataPtr, frame->size() - frame->prefixSize())
|
||||
- && context.width && context.height) {
|
||||
+ auto result = aom_av1_codec_configuration_record_init(&context, dataPtr, frame->size() - frame->prefixSize());
|
||||
+ if (_diagnostic_frames < 12) {
|
||||
+ ++_diagnostic_frames;
|
||||
+ InfoL << "AV1_DIAG track=" << this << " frame=" << _diagnostic_frames
|
||||
+ << " bytes=" << frame->size() << " dts=" << frame->dts() << " pts=" << frame->pts()
|
||||
+ << " init=" << result << " parsed=" << context.width << "x" << context.height
|
||||
+ << " previous=" << _width << "x" << _height << " fps=" << getVideoFps()
|
||||
+ << " gop_size=" << getVideoGopSize() << " gop_ms=" << getVideoGopInterval()
|
||||
+ << " prefix=" << hexmem(dataPtr, std::min<size_t>(32, frame->size() - frame->prefixSize()));
|
||||
+ }
|
||||
+ if (0 == result && context.width && context.height) {
|
||||
@@ -49,2 +59,9 @@
|
||||
- if (size < 4 || data[0] != 0x81
|
||||
- || aom_av1_codec_configuration_record_load(data, size, &context) <= 0) {
|
||||
+ auto result = aom_av1_codec_configuration_record_load(data, size, &context);
|
||||
+ bool diagnostic = _diagnostic_configs < 3;
|
||||
+ if (diagnostic) {
|
||||
+ ++_diagnostic_configs;
|
||||
+ InfoL << "AV1_DIAG track=" << this << " av1C_size=" << size << " load=" << result
|
||||
+ << " loaded=" << context.width << "x" << context.height
|
||||
+ << " prefix=" << hexmem(data, std::min<size_t>(32, size));
|
||||
+ }
|
||||
+ if (size < 4 || data[0] != 0x81 || result <= 0) {
|
||||
@@ -57 +74,6 @@
|
||||
- if (context.bytes && aom_av1_codec_configuration_record_init(&parsed, context.data, context.bytes) != 0) {
|
||||
+ auto parsed_result = context.bytes ? aom_av1_codec_configuration_record_init(&parsed, context.data, context.bytes) : 0;
|
||||
+ if (diagnostic) {
|
||||
+ InfoL << "AV1_DIAG track=" << this << " config_init=" << parsed_result
|
||||
+ << " parsed=" << parsed.width << "x" << parsed.height << " fps=" << getVideoFps();
|
||||
+ }
|
||||
+ if (parsed_result != 0) {
|
||||
--- a/ext-codec/VpxRtmp.h
|
||||
+++ b/ext-codec/VpxRtmp.h
|
||||
@@ -34,0 +35 @@
|
||||
+ size_t _diagnostic_packets = 0;
|
||||
--- a/ext-codec/VpxRtmp.cpp
|
||||
+++ b/ext-codec/VpxRtmp.cpp
|
||||
@@ -34,0 +35,6 @@
|
||||
+ if (getTrack()->getCodecId() == CodecAV1 && _diagnostic_packets < 16) {
|
||||
+ ++_diagnostic_packets;
|
||||
+ InfoL << "AV1_DIAG decoder=" << this << " packet=" << _diagnostic_packets
|
||||
+ << " type=" << (int)_info.video.pkt_type << " fourcc=" << std::string(pkt->data() + 1, 4)
|
||||
+ << " packet_size=" << pkt->size() << " payload_size=" << size << " dts=" << pkt->time_stamp;
|
||||
+ }
|
||||
--- a/src/Rtmp/RtmpDemuxer.h
|
||||
+++ b/src/Rtmp/RtmpDemuxer.h
|
||||
@@ -61,0 +62 @@
|
||||
+ size_t _diagnostic_packets = 0;
|
||||
--- a/src/Rtmp/RtmpDemuxer.cpp
|
||||
+++ b/src/Rtmp/RtmpDemuxer.cpp
|
||||
@@ -123,0 +124,8 @@
|
||||
+ if (_diagnostic_packets < 16) {
|
||||
+ ++_diagnostic_packets;
|
||||
+ InfoL << "AV1_DIAG demuxer=" << this << " video_packet=" << _diagnostic_packets
|
||||
+ << " size=" << pkt->size() << " header="
|
||||
+ << toolkit::hexmem(pkt->data(), std::min<size_t>(16, pkt->size()))
|
||||
+ << " discovered=" << _try_get_video_track << " decoder=" << (bool)_video_rtmp_decoder
|
||||
+ << " metadata_fps=" << _video_fps;
|
||||
+ }
|
||||
Reference in New Issue
Block a user