Repository navigation
Open
Description
问题描述
线上在销毁播放器时出现 ANR。Flutter 在 Android 上把 Dart 跑在平台线程上(平台线程和 UI 线程合并),所以 dispose() 会在 Android 主线程上同步调用 mdkPlayerAPI_reset。随后 mdk::abi::Player::~Player 等待一个 std::future,但这个 future 一直没有完成:解码线程卡在 AMediaCodec_stop → MediaCodec::stop → AMessage::postAndAwaitResponse,一直没返回。主线程因此持续阻塞,直到系统判定 ANR 并杀掉进程。
使用场景:列表页的卡片里播放短视频,每张卡片一个播放器。用户切换筛选条件后列表重建,旧卡片会 dispose 各自的播放器。ANR 发生前最后能看到的就是这次重建,之后界面冻住,大约 14 秒后上报了 ANR。
期望行为
硬件解码器对 stop() 没有响应时,销毁播放器不应该无限期阻塞调用线程。比如 stop 可以带超时,或者在内部线程异步释放解码器。
日志
拿不到受影响用户的 logcat。下面是其中一次 ANR(OPPO 设备)trace 里的相关线程:
主线程
main (native):tid=1 systid=14936
#00 pc 0xb2d9c libc.so (syscall + 28)
#01 pc 0x8da70 libc.so (__futex_wait_ex + 144)
#02 pc 0x9b908 libc.so (pthread_cond_wait + 72)
#03 pc 0xda5a0 libc++_shared.so (std::__ndk1::condition_variable::wait + 24)
#04 pc 0xdaeb8 libc++_shared.so (std::__ndk1::__assoc_sub_state::wait + 68)
#05 pc 0xf15b4 libmdk.so
#06 pc 0xdb208 libmdk.so
#07 pc 0x104d50 libmdk.so
#08 pc 0x105074 libmdk.so
#09 pc 0x11f718 libmdk.so
#10 pc 0xd44c4 libmdk.so
#11 pc 0x123318 libmdk.so (mdk::abi::Player::~Player + 564)
#12 pc 0xbf2d0 libmdk.so
#13 pc 0xbf5ac libmdk.so (mdkPlayerAPI_reset + 576)
#14 pc 0x1bc1628 libapp.so
... (Dart 帧)
#40 pc 0x90c228 libflutter.so
...
#45 pc 0x16d94 libutils.so (android::Looper::pollOnce + 1188)
#46 pc 0x1e7e0c libandroid_runtime.so (android::android_os_MessageQueue_nativePollOnce + 44)
at android.os.MessageQueue.nativePollOnce(Native method)
at android.os.Looper.loop(Looper.java:416)
at android.app.ActivityThread.main(ActivityThread.java:10001)
解码线程(卡在 AMediaCodec_stop)
Thread-14 (native):tid=54 systid=19112
#00 pc 0xb2d9c libc.so (syscall + 28)
#01 pc 0x8da70 libc.so (__futex_wait_ex + 144)
#02 pc 0x9b908 libc.so (pthread_cond_wait + 72)
#03 pc 0x1f330 libstagefright_foundation.so (android::ALooper::awaitResponse + 288)
#04 pc 0x24250 libstagefright_foundation.so (android::AMessage::postAndAwaitResponse + 448)
#05 pc 0x179020 libstagefright.so (android::MediaCodec::stop + 400)
#06 pc 0x236f8 libmediandk.so (AMediaCodec_stop.cfi + 72)
#07 pc 0xd50f0 libmdk.so
#08 pc 0xcfeb8 libmdk.so
#09 pc 0x137890 libmdk.so
#10 pc 0xd8138 libmdk.so
#11 pc 0xd80b4 libmdk.so
#12 pc 0xe47b0 libmdk.so
#13 pc 0xe06b8 libmdk.so
#14 pc 0x9c778 libc.so (__pthread_start + 232)
其他相关线程
mdk.read@76a070 (unknown):tid=18872
#00 pc 0xb2d9c libc.so (syscall + 28)
#01 pc 0x9d6b0 libc.so (pthread_join + 240)
#02 pc 0xdc040 libc++_shared.so (std::__ndk1::thread::join + 32)
#03 pc 0xf2cdc libmdk.so
#04 pc 0xf1618 libmdk.so
NDK MediaCodec_looper (native):tid=74 -> 空闲,停在 ALooper::loop
CodecLooper / CCodecWatchdog -> 空闲,停在 ALooper::loop
ImageReader-16x16f22u256m5-14936-0 -> 空闲,停在 ALooper::loop
libmdk.so BuildId:64fc0477ddd65879a6c7e1db0d2e70cc1fa1095c
环境
- fvp:0.39.1
- mdk:fvp 0.39.1 构建时拉取的 libmdk(BuildId 见上)
- Flutter:3.44.9(平台线程和 UI 线程合并:默认开启)
- 出现 ANR 的机型:Samsung SM-S9280;OPPO CPH2739、CPH2599、CPH2811
问题
Player析构或reset能否不再同步等待解码器stop()完成?比如加超时,或者把释放放到内部线程去做。- 现在有没有选项可以让 dispose 不阻塞,或者有没有推荐的方式在平台线程之外释放播放器?
- 改用
'video.decoders': ['MediaCodec', 'FFmpeg'](用 Java MediaCodec 代替 AMediaCodec)在这种情况下会不会有区别?还是对这些机型只有 FFmpeg 软解才可靠?
Metadata
Metadata
Assignees
Labels
No labels
Activity
wang-bin commentedon Oct 19, 2026
容易复现吗?什么app我来测下?
LinXunFeng commentedon Oct 19, 2026
我自己用了几台都没有复现,
firebase上上报的量不算太多不知道是否可以从上述 AI 分析的问题来做尝试修复?
wang-bin commentedon Oct 19, 2026
正在让ai帮忙
mag-joong commentedon Nov 9, 2026
You asked above whether this is easy to reproduce. We have a case that reproduces within minutes on a stock Android emulator, with the same main-thread stack, on libmdk 0.39.0, 0.40.1 and the 2026-11-07 nightly. It may be a sibling rather than the same bug: here the decode thread never gets as far as
AMediaCodec_stop; it is still looping inMediaCodecBase::processInput. If you'd rather track it separately, I can move it to a new mdk-sdk issue.Environment
google/sdk_gphone16k_arm64/emu64a16k:17/CP31.260623.009/15923651(Android 17, arm64, 16 KB pages). Hardware decoding goes through the goldfish Codec2 service (android.hardware.media.c2-service-goldfish).dispose()→mdkPlayerAPI_deleteruns on Android's main thread.7fda099393b30d60193e5a4fb52516162b8ccd2aFVP_DEPS_URL:1c723ae5013f236b674575dad40d936f90d43990876817920979275ac71e6ca9aedb78dc57ee07c2Steps
The test at the end does this with fvp's
mdk.Playerdirectly. Each round:videoDecoders = ['AMediaCodec', 'FFmpeg', 'dav1d'],setBufferRange(min: 0, max: 1000, drop: true)andavformat.rtsp_transport=tcp. Thenprepare(),updateTexture(), play, wait for1st_frameon all four, and play 1.5 s more.updateTexture(width: -1), which is what fvp'sdispose()does first, and leave the players playing for 3 s.dispose()all four and time the main isolate.A passing round usually holds the main thread for 70–300 ms. After 6–8 clean rounds, one deletion never returns:
AMediaCodec:async=1stoppedawaited, then the texture released, thendispose()In our app (libmdk 0.39.0), fvp's own
dispose()(no gap) ran into the same hang about once in 10–20 closes of a camera grid on a loaded machine, and 0 times in 40 on a quiet one. Holding the gap open makes it reproduce on a quiet machine. We have only seen it on the emulator so far.Stacks
0.40.1 release, innermost frame first, trimmed to the libmdk frames. I can share the full symbolized dumps for all five runs.
AMediaCodec_dequeueInputBufferfromprocessInput(inlined intodecodePacketat MediaCodecBase.cpp:127).AMediaCodec:async=1: the decode thread waits instead on the condition variable indecodePacket(MediaCodecBase.cpp:194), using the predicatewait()with no timeout. It is blocked there (92 timeslices in the dump), not spinning.The decode thread spins, and the player has already said
stopped/proc/<pid>/task/<tid>/statuswhile frozen:voluntary_ctxt_switcheswent from 106,820 to 109,654 in 5 s (about 570 a second), and its CPU time kept rising.schedstatin the ANR dumps: the looping decode threads show 78k–111k timeslices, mostly kernel time (e.g.utm=28 stm=152). A healthy decode thread of another player in the same nightly dump, idle inBlockingFIFO::pop, shows 18k (utm=66 stm=63).PlaybackState.stoppedthroughonStateChangedbefore their textures were released. Even so, the decode thread of the player whose deletion then hung was still inprocessInput. So no stop order on the app side avoids it.How the 0.40.1 loop reads from the symbols
We read this from the disassembly, not the source, so please correct us.
processInput(MediaCodecBase.cpp:257–273) callsdequeueInputBuffer(0). If that fails, it loops:processOutput(0), leave if that reported output, thendequeueInputBuffer(2000 µs), and repeat until an input buffer comes. Nothing in the loop checks for a stop or flush request, or for a deadline. So when the codec gives neither an input buffer nor any output, the thread stays there for ever, and so do the reader'sjoinand~MediaControlPushon the main thread. The exit that 0.39.0's loop didn't have (presumably 0.40.0's "fix sync mode stalls if a packet can not be consumed") only fires once the drain has produced output. The emulator's codec may well be the one misbehaving here, as the phones' codecs are in this issue's report, but on libmdk's side nothing bounds the wait.What would help
processInput's loop, and of the async wait at MediaCodecBase.cpp:194, once the decoder is being stopped or flushed (or after a deadline), returning the packet unconsumed.mdkPlayerAPI_deleteshouldn't wait without bound on the decoder threads. With Flutter on Android the caller is the main thread, so one stuck codec becomes an ANR. [Windows] Disposal hangs in MDK audio flush or FrameReader teardown #402 shows the same unbounded wait in~MediaControlPush→waitThreadon Windows.I'm happy to run a nightly with a fix against this test.
Repro: a Flutter integration test using only fvp's
mdk.Playerwang-bin commentedon Nov 9, 2026
@mag-joong another issue
wang-bin commentedon Nov 9, 2026
@mag-joong can you try https://github.com/wang-bin/mdk-sdk/actions/runs/42598303979 ? i add a deadline in the loop and treat timeout as an error. returning unconsumed packet will have the same result if stopping but won't help if still playing. i don't know why both input and output are not available, so that change is not merged
wang-bin commentedon Nov 11, 2026
what about
mediacodec:ndk_codec=1@LinXunFeng @mag-joongabdelaziz-mahdy commentedon Nov 19, 2026
follow-up from the TCL tv running #413 (delete on a helper isolate): the ANRs are gone, but when the delete hangs, the whole player now leaks for the rest of the process.
this morning one process had 3
mdk.read@…threads (plus theirNDK MediaCodec_/CodecLooper/mdk.adecthreads) with only one video open.dumpsys audio/dumpsys media.aaudiostill listed the AAudio streams of the two disposed players. both were episode players (mkv, h264 + aac). one was disposed after the tv had been in standby overnight, the other 12 s into playback right after a resume seek. theirstoplines appear in the mdk log, but the delete never returned.besides holding decoders, the leaked AAudio streams kept a dead shared endpoint alive after an eARC re-handshake, which silenced every later player at the same sample rate (details in #386).
could the destructor time out on the stuck decoder thread, or release audio and the codec before waiting on it? then a hang would at least not take the audio output and the codec with it.
fix(video): stop freezing the app when a preview player is released (#…
LinXunFeng commentedon Nov 24, 2026
@wang-bin in reply to your suggestion:
Thanks for the suggestion. I tested the following with FVP 0.40.0 and a freshly downloaded MDK 0.40.1 nightly (git 3343262):
With NDK enabled, an independent Flutter reproduction app crashes during player disposal. It uses generated local media, without our application code or network video. This is a native SIGBUS, not the original
AMediaCodec_stopANR; I have not established a shared root cause.Test environment
libmdk.soBuild ID:49e89d07838068c97b0a4b96ad2123b9b53f2213, verified in both the SDK and the installed test APK.Reproduction and comparison
Each cycle initializes one controller, plays a generated H.264/AAC video for 350 ms, removes it from the widget tree and awaits
dispose(). No controllers are retained between cycles (KEEP=0). Each run starts a fresh process.USE_NDK=falseThe control is one run on this device/media, not a general stability guarantee or evidence that the original ANR is fixed.
Native stack
Both NDK-enabled runs reported
SIGBUS / BUS_ADRALN, with an invalid branch target at PC0x7e. Matching MDK symbols identifyavclass_item_nameinffmpeg/glue/AVGlue.cppon the following path (outermost to innermost):The exact underlying lifetime error has not been confirmed. This package/native-library combination does not eliminate the observed NDK disposal crash.
Attachment
fvp-412-sanitized-repro.zip contains the reproduction source with
fvp: 0.40.0, generated media, redacted stacks and progress markers from both NDK runs and the default-decoder control, plus native Build ID/checksum metadata.FVP 0.40.0 is the Dart package version; MDK 0.40.1 is the native SDK version. Pinning the FVP package alone does not pin the downloaded MDK binary. The README records the tested SDK archive SHA-256 and Build ID; native libraries are not bundled. The shared hosted-dependency manifest has not been independently rebuilt; device runs used the published FVP source extracted into an isolated directory.
Earlier FVP 0.39.1 / MDK 0.39.0 testing also produced disposal SIGSEGVs, but with different top frames. Those records are retained only under
history/in the attachment and are not presented as identical crash signatures.Would you prefer this tracked as a separate mdk-sdk issue? Is there a specific MDK build you would recommend testing for this disposal crash?
LinXunFeng commentedon Nov 25, 2026
@abdelaziz-mahdy, following up on your report:
Thanks for the follow-up. #413 prevents native deletion from blocking the main isolate, but the resource retention needs to be fixed inside MDK.
I reproduced similar symptoms on an emulator, although I have not confirmed they share the root cause of your TCL/eARC issue.
Environment
118ae74), MDK 0.40.1 nightly (3343262)AMediaCodec, native buffer defaultsSteps
disposeAsync().Deletion remained pending for the entire 70-second observation. The main isolate’s heartbeat continued, while reader/decoder threads and an inactive 48 kHz audio track remained. Changing only the decoder to FFmpeg completed all three seek/disposal cycles.
fvp-413-repro.zip contains the standalone Flutter project, pinned FVP/MDK, test media, key logs, and run instructions.