Skip to content

Fix iOS video decoder crash when VideoToolbox delivers a frame after the decode call - #3822

Open
CodeJhF wants to merge 5 commits into
mainfrom
bugfix/markffan_hardware_decoder
Open

CodeJhF wants to merge 5 commits into
mainfrom
bugfix/markffan_hardware_decoder

Conversation

@CodeJhF

@CodeJhF CodeJhF commented Nov 6, 2026 •

Copy link
Copy Markdown
Collaborator

背景

关联 issue:#3780

线上 iOS 崩溃发生在 pag::HardwareDecoder::~HardwareDecoder() 内部,栈顶是 std::mutex::lock() 加一段无法符号化的帧。社区提供的反汇编指向了问题的位置:

0x...8cc <+12>: str  x0, [sp, #0x8]
0x...8d8 <+24>: bl   <真正的析构体>
0x...8dc <+28>: ldr  x0, [sp]        ← 崩在这里,此时 sp 已是堆地址
0x...8e0 <+32>: bl   operator delete

根因

onDecodeFrame() 把栈上局部变量 outputPixelBuffer 的地址作为 sourceFrameRefCon 传给 VTDecompressionSessionDecodeFrame。

flags = 0 时回调一定在 VTDecompressionSessionDecodeFrame 返回前被调用(见 VTDecompressionSession.h),但 VTDecompressionSessionFinishDelayedFrames 允许在所有帧吐出前返回,被 session 推迟的帧会在这之后才回调(issue #3780 实测 8 次迟到)。析构函数里的这次冲刷会让回调落在早已返回的栈帧上,写入的 CVPixelBufferRef(堆指针)覆盖了当前调用链保存的帧指针,后续 mov sp, x29 把 sp 置成堆地址,于是删除析构器取 this 时崩溃。

4.5.97/98 引入的 fallback 逻辑让解码器销毁重建更频繁,而每次析构都会调一次冲刷,命中窗口随之变大。

改动

新增 src/platform/cocoa/private/HardwareDecodeContext.{h,mm}(iOS / macOS 共用),统一所有权模型:

  1. 堆上解码上下文 VTDecodeOutputContext:回调把 CVPixelBuffer 写进上下文而非调用方栈槽,彻底消除原始崩溃。上下文由 VTDecodeContextPool 持有,回调只写数据、从不删除对象。
  2. 单一回收路径:解码器持有全部在飞上下文;常态同步帧在 onDecodeFrame() 内就地回收(reclaimResolved()),延迟帧 / 被丢弃帧 / 失败后迟到的上下文,在 resetVideoToolBox() 或析构的 teardown 屏障之后统一回收(reclaimAll())。消除了旧设计里 noErr-无回调的永久泄漏,以及"Invalidate 后立即 delete"的堆 UAF。
  3. 显式屏障:reset / 析构在 VTDecompressionSessionInvalidate 之前统一调用 VTDecompressionSessionWaitForAsynchronousFrames(mac 侧原本缺失,已补),保证回收时 VideoToolbox 不再有在飞回调。
  4. 去重:DidDecompress 与上下文 / 池下沉到共享 .mm(单一定义,消除两份逐字节相同函数的 ODR 风险),两个 decoder 头里的裸 vector 与重复回收循环删除。

iOS 侧 willResignActive 加固(与本次崩溃不同路径,并发 invalidate 可在本地稳定复现 VT 内部崩溃):

  1. 锁外 invalidate + 生命周期令牌:全局注册表改存 weak_ptr<DecoderToken>;观察者在 GetActiveDecodersMutex 内只做快照,锁外逐个 invalidate,整批共享一个 now + 200ms deadline —— 总等待封顶 200ms(不再 N×200ms),且不再在持有注册表锁时阻塞解码器的构造 / 析构。令牌的 mutex 保证观察者要么作用于存活 decoder、要么见 decoder == nullptr 跳过,与析构无竞态。

验证

  • macOS:PAGFullTest_OpenGL 构建通过;PAGSequenceTest、VideoSequenceFallbackTest、PAGDiskCacheTest、MultiThreadCase、PAGANRRegressionTest 共 43 例全部通过。
  • 上下文时序(回调先到 / 回调后到 / 失败后迟到 / 永不回调 / 空帧):macOS 原生与 iOS 模拟器 ASan 下均通过,CVPixelBuffer 引用计数无多释放 / 少释放。
  • VideoToolbox 竞态探针:并发 invalidate 10/10 崩溃,串行 invalidate 0/10 崩溃,macOS 与 iOS 模拟器结果一致。

已知限制

本地环境(macOS / iOS 模拟器)无法复现"VideoToolbox 延迟帧"这一触发前提(连续 300 帧回调全部同步),因此线上崩溃的最终确认仍需报告者在必现的真机上验证。

@CodeJhF
CodeJhF force-pushed the bugfix/markffan_hardware_decoder branch from a4f1312 to caa3c77 Compare November 6, 2026 09:46
@codecov-commenter

codecov-commenter commented Nov 6, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 83.70%. Comparing base (eb4412a) to head (ec36059).
⚠️ Report is 7 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3822      +/-   ##
==========================================
+ Coverage   83.42%   83.70%   +0.28%     
==========================================
  Files         748      762      +14     
  Lines      105944   113586    +7642     
  Branches    29587    31607    +2020     
==========================================
+ Hits        88386    95081    +6695     
- Misses      10766    11230     +464     
- Partials     6792     7275     +483     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@armitis

armitis commented Nov 10, 2026

Copy link
Copy Markdown

请问这个问题修复在哪个版本上了

@CodeJhF

CodeJhF commented Nov 10, 2026

Copy link
Copy Markdown
Collaborator Author

请问这个问题修复在哪个版本上了

目前修改还没合入,合入之后我们会发布新版本并告知您的

@CodeJhF
CodeJhF force-pushed the bugfix/markffan_hardware_decoder branch from caa3c77 to a61d644 Compare November 10, 2026 07:47
namespace pag {
/**
* Carries the pixel buffer produced by one VideoToolbox decode call. VideoToolbox may invoke the
* output callback on another thread and does not promise that it has returned by the time

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

建议把根因依据写进代码,否则后续维护者按 SDK 文档读一遍,很可能把堆上 context 当成多余防御删掉。VTDecompressionSession.h 对 decodeFlags 的说明是:两个 flag 都清零时,回调一定在 VTDecompressionSessionDecodeFrame 返回前被调用;而本仓库传的就是 0。真正支持迟到投递的是 FinishDelayedFrames 的 may-return-before-all-frames-emitted,以及 issue #3780 里的迟到投递实测(8 次),这两点目前只存在于 issue 讨论里。建议此处补一句实测依据,并说明为什么 infoFlags 这个栈出参不受影响。堆上 context 本身是更彻底的修法,不建议回退。

// return first, and only invalidate underneath it once it is really stuck, because unblocking a
// stuck decode is what this method exists for.
const bool hasDecodeLocker =
decodeLocker.try_lock_for(std::chrono::milliseconds(MAX_INVALIDATE_WAIT_TIME_MS));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里的等待发生在 willResignActive 观察者里,而该循环(74-79 行)是在持有 GetActiveDecodersMutex 的情况下逐个 decoder 调用 invalidateSession,每个最多 200ms,N 个即 N×200ms;didBecomeActive 与它同处一条串行队列(maxConcurrentOperationCount = 1),会推迟 appInactive 复位,让后续解码持续返回 Error,触发 VideoReader 的 destroyVideoDecoder + factoryIndex++ 降级。同一条锁也是构造/析构必须持有的,会让解码线程在 device.locker 内被额外阻塞,与这段代码尽快让 worker 释放 device.locker 的目的相反。建议:锁内只做快照、锁外 invalidate(需配生命周期令牌避免与析构并发),或整个循环共用一个 now+200ms 预算,让总耗时封顶。

cleanResources();
// Released only after the session has been invalidated and released, so no callback delivered by
// VideoToolbox can write into them anymore.
for (auto* context : staleContexts) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里的释放与 staleContexts 的保活理由互相矛盾:保活是为了防失败后仍回调(HardwareDecodeContext.h:67-69),而这里在 Invalidate + CFRelease 之后立即 delete,又假设此时不可能再有回调。若迟到回调真能跨越 session 释放,这里就是把栈 UAF 换成堆 UAF(complete 会锁一个已释放的 mutex);若不能,整个 staleContexts 机制就只是泄漏。另外 macOS 侧没有 FinishDelayedFrames(mac:52-53)却做同样的释放,两平台必有一侧不成立。建议二选一:用 VTDecompressionSessionWaitForAsynchronousFrames 建立明确屏障后统一释放,或信任失败无回调查文档、直接立即释放并删掉 staleContexts。

Comment on lines +80 to +84
if (callbackDone) {
shouldDelete = true;
} else if (!callbackExpected) {
abandoned = true;
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

当 DecodeFrame 返回 noErr 但回调始终不到(session 先被 invalidate、帧被丢弃等)时,这里既不删除也不上报 abandoned,此后没有任何指针能到达该 context,会永久泄漏;这也与错误分支不信任 VT 承诺的立场不一致。类注释(29-31 行)的 whichever finishes last releases it 在 abandoned 路径上同样不成立,两侧都不释放,靠 decoder 兜底。建议改为 decoder 统一持有所有在飞 context,session 拆除后统一回收。


void DidDecompress(void*, void* sourceFrameRefCon, OSStatus status, VTDecodeInfoFlags,
CVImageBufferRef pixelBuffer, CMTime, CMTime) {
auto* context = static_cast<HardwareDecodeContext*>(sourceFrameRefCon);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DidDecompress 在本文件 97-108 行与 ios 175-186 行逐字节相同,且都是 namespace pag 下的外部链接函数:目前靠恰好一致满足 ODR,任何单边修改都会变成静默的 ODR 违规。本次还新增了 4 份相同的 stale 回收循环(ios 143/243、mac 65/158)和 2 份解码交接块。建议把 DidDecompress 与 abandoned 池挪到本 PR 已创建的 cocoa/private/HardwareDecodeContext(顺带补一个 .mm),两个 decoder 头里的裸 vector 也可一并去掉。两个文件历史重复的 200 行不必在本 PR 处理。

* Aborts any in-progress synchronous decompression by invalidating the underlying VT session.
* Safe to call from any thread. Used by the willResignActive observer to unblock the worker
* thread so it can release device.locker before the main thread enters EAGLDevice::finish().
* A decode that is still running is given a short grace period to return first, the session is

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

注释与实现不符:实际是无条件调用 VTDecompressionSessionInvalidate(:99-102),hasDecodeLocker 只决定要不要解锁;按 PR 描述里探针的结论(并发 invalidate 10/10 崩溃),解码卡死超过 200ms 时仍会走回这条崩溃路径,这里只是把窗口收窄。另外既没写最多阻塞 200ms,Safe to call from any thread 在改后也不成立(从解码线程自身调用会对已持有的 timed_mutex 做 try_lock_for,属 UB;与析构的免竞态还依赖调用方持有 GetActiveDecodersMutex)。建议按实际语义重写,并说明 200ms 来自哪个预算。

* whichever finishes last releases it, which keeps the storage and the buffer valid until both
* sides are done.
*/
class HardwareDecodeContext {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

命名与接口建议:该类只服务 VideoToolbox(持有 CVPixelBufferRef,仅因 DecodeFrame 的 refcon 约定而存在),HardwareDecodeContext 与 HardwareDecoder 概念容易混淆,建议 VTDecodeOutputContext;complete 建议改为 deliverBuffer/abandon 自解释;takeOutput(bool, bool*) 用可空返回值加出参加自删编码了 4 种状态,建议返回一个小 struct(buffer + 是否 abandoned)。

…date sessions off the registry lock via a lifecycle token.
@CodeJhF

CodeJhF commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator Author

@shlzxjp 感谢细致评审,已按建议整体收敛为单一所有权模型(commit 42fc773),逐条回应:

1(HardwareDecodeContext.h:27,根因依据) 类注释已补:VTDecompressionSession.h 明确 flags=0 回调必在 DecodeFrame 返回前;迟到窗口来自 WaitForAsynchronousFrames/FinishDelayedFrames 的 may-return-before-all-emitted 与 #3780 实测 8 次;并说明 infoFlags 是 VT 同步填充的栈出参、故不受影响。堆上 context 保留。

4 + 2(永久泄漏 / willResignActive 循环)→ 统一所有权 + 锁外令牌

  • decoder 经 VTDecodeContextPool 持有全部在飞 context,回调只写数据不删对象。消除了 noErr-回调永不到达的泄漏路径。
  • 采纳"锁外 invalidate + 生命周期令牌":注册表改存 weak_ptr<DecoderToken>,观察者锁内只做快照、锁外逐个 invalidate,整批共享一个 now+200ms deadline —— 总等待封顶而非 N×200ms,不再在持锁期间阻塞构造/析构;令牌 mutex 保证与析构无竞态。

3(staleContexts 矛盾)→ 显式屏障(选"WaitForAsynchronousFrames 屏障后统一释放"):reset/析构在 Invalidate 前统一 VTDecompressionSessionWaitForAsynchronousFrames(mac 侧原缺失已补),之后 reclaimAll()。不再出现"Invalidate 后立即 delete 却假设无回调"的堆 UAF;staleContexts 机制删除。

5(ODR / 重复) DidDecompress 与 context/pool 下沉到新建共享 .mm(单一定义),两个 decoder 头里的裸 vector 与 4 份重复回收循环删除。native-mac/iOS 递归 glob 自动纳入,QT-mac 路径已显式补进 CMake。历史重复的 200 行按建议不在本 PR 处理。

6(ios HardwareDecoder.h:51 注释与实现不符) 文档重写为真实语义:无条件 Invalidate,try_lock_until 只给在飞解码 200ms 宽限;明确 200ms 预算来源(并发 invalidate 探针)、不能从解码线程自身调用、免竞态依赖观察者持有令牌 mutex。

7(命名/接口) 类改名 VTDecodeOutputContext;complete → deliverBuffer;takeOutput(bool,bool*) 四态拆为 takeBuffer() + resolved()。

验证:PAGFullTest_OpenGL 构建通过,相关 43 例全绿(详见描述)。线上延迟帧前提本地仍无法复现,最终确认仍需真机。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants