From 8ac957f338609365d6a93dc00748b8c5c724b800 Mon Sep 17 00:00:00 2001 From: xia-chu <771730766@qq.com> Date: Thu, 9 May 2024 18:06:19 +0800 Subject: [PATCH] bugfix: Fix the memory overflow issue in H264Splitter --- api/source/mk_h264_splitter.cpp | 39 ++++++++++++--------------------- 1 file changed, 14 insertions(+), 25 deletions(-) diff --git a/api/source/mk_h264_splitter.cpp b/api/source/mk_h264_splitter.cpp index a6c412f4..b5cd06a3 100644 --- a/api/source/mk_h264_splitter.cpp +++ b/api/source/mk_h264_splitter.cpp @@ -27,8 +27,9 @@ protected: private: bool _h265 = false; + bool _have_decode_frame = false; onH264 _cb; - size_t _search_pos = 0; + toolkit::BufferLikeString _buffer; }; void H264Splitter::setOnSplitted(H264Splitter::onH264 cb) { @@ -42,11 +43,21 @@ H264Splitter::~H264Splitter() { } ssize_t H264Splitter::onRecvHeader(const char *data, size_t len) { - _cb(data, len); + auto frame = Factory::getFrameFromPtr(_h265 ? CodecH265 : CodecH264, (char *)data, len, 0, 0); + if (_have_decode_frame && (frame->decodeAble() || frame->configFrame())) { + // 缓存中存在可解码帧,且下一帧是可解码帧或者配置帧,那么flush缓存 + _cb(_buffer.data(), _buffer.size()); + _buffer.assign(data, len); + _have_decode_frame = frame->decodeAble(); + } else { + // 还需要缓存 + _buffer.append(data, len); + _have_decode_frame = _have_decode_frame || frame->decodeAble(); + } return 0; } -static const char *onSearchPacketTail_l(const char *data, size_t len) { +const char *H264Splitter::onSearchPacketTail(const char *data, size_t len) { for (size_t i = 2; len > 2 && i < len - 2; ++i) { //判断0x00 00 01 if (data[i] == 0 && data[i + 1] == 0 && data[i + 2] == 1) { @@ -60,28 +71,6 @@ static const char *onSearchPacketTail_l(const char *data, size_t len) { return nullptr; } -const char *H264Splitter::onSearchPacketTail(const char *data, size_t len) { - auto last_frame = data + _search_pos; - auto next_frame = onSearchPacketTail_l(last_frame, len - _search_pos); - if (!next_frame) { - return nullptr; - } - - auto last_frame_len = next_frame - last_frame; - Frame::Ptr frame; - if (_h265) { - frame = Factory::getFrameFromPtr(CodecH265, (char *)last_frame, last_frame_len, 0, 0); - } else { - frame = Factory::getFrameFromPtr(CodecH264, (char *)last_frame, last_frame_len, 0, 0); - } - if (frame->decodeAble()) { - _search_pos = 0; - return next_frame; - } - _search_pos += last_frame_len; - return nullptr; -} - //////////////////////////////////////////////////////////////////////////////////////////////////////// API_EXPORT mk_h264_splitter API_CALL mk_h264_splitter_create(on_mk_h264_splitter_frame cb, void *user_data, int is_h265) {