Skip to content

[android] ANR:AMediaCodec_stop 不返回,mdkPlayerAPI_reset 阻塞主线程 #412

Open

Description

@LinXunFeng

问题描述

线上在销毁播放器时出现 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

问题

  1. Player 析构或 reset 能否不再同步等待解码器 stop() 完成?比如加超时,或者把释放放到内部线程去做。
  2. 现在有没有选项可以让 dispose 不阻塞,或者有没有推荐的方式在平台线程之外释放播放器?
  3. 改用 'video.decoders': ['MediaCodec', 'FFmpeg'](用 Java MediaCodec 代替 AMediaCodec)在这种情况下会不会有区别?还是对这些机型只有 FFmpeg 软解才可靠?

Activity

  1. wang-bin commented on Oct 19, 2026

    @wang-bin
    Owner

    容易复现吗?什么app我来测下?

  2. LinXunFeng commented on Oct 19, 2026

    @LinXunFeng
    ContributorAuthor

    我自己用了几台都没有复现,firebase 上上报的量不算太多

    不知道是否可以从上述 AI 分析的问题来做尝试修复?

  3. wang-bin commented on Oct 19, 2026

    @wang-bin
    Owner

    正在让ai帮忙

  4. mag-joong commented on Nov 9, 2026

    @mag-joong

    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 in MediaCodecBase::processInput. If you'd rather track it separately, I can move it to a new mdk-sdk issue.

    Environment

    • Android Emulator 37.2.13 on an Apple M2 Mac, system image 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).
    • Flutter 3.47.3 with the platform and UI threads merged (the default), so dispose() → mdkPlayerAPI_delete runs on Android's main thread.
    • fvp 0.39.0 and 0.40.0, with these libmdk builds (arm64 Build IDs):
      • 0.39.0, the 2026-10-10 nightly that fvp 0.39.0 downloaded: 7fda099393b30d60193e5a4fb52516162b8ccd2a
      • 0.40.1 release, pinned with FVP_DEPS_URL: 1c723ae5013f236b674575dad40d936f90d43990
      • 2026-11-07 nightly (reports 0.40.1): 876817920979275ac71e6ca9aedb78dc57ee07c2
    • 4 RTSP streams over TCP from MediaMTX on the same Mac: H.264, 640×360 at 15 fps, x264 ultrafast/zerolatency, no B-frames, about 384 kb/s.

    Steps

    The test at the end does this with fvp's mdk.Player directly. Each round:

    1. Open 4 players with videoDecoders = ['AMediaCodec', 'FFmpeg', 'dav1d'], setBufferRange(min: 0, max: 1000, drop: true) and avformat.rtsp_transport=tcp. Then prepare(), updateTexture(), play, wait for 1st_frame on all four, and play 1.5 s more.
    2. Release the textures with updateTexture(width: -1), which is what fvp's dispose() does first, and leave the players playing for 3 s.
    3. 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:

    libmdk clean rounds then
    0.39.0 (2026-10-10 nightly) 6 frozen in round 7
    0.40.1 release 8 frozen in round 9
    0.40.1 with AMediaCodec:async=1 7, some already holding the main thread for 1.4–3.6 s frozen in round 8
    0.40.1, each player first stopped and stopped awaited, then the texture released, then dispose() 7 frozen in round 8
    2026-11-07 nightly 6 frozen in round 7

    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.

    main thread
      std::__assoc_sub_state::wait                                 (a std::future)
      FrameReaderImpl::waitThread()             core/FrameReader.cpp:1455
      FrameReaderImpl::waitFor(State, long)     core/FrameReader.cpp:1276
      MediaControlPush::~MediaControlPush()     core/MediaControl.cpp:85
      ~Private ← ~MediaPlayer                   core/MediaPlayer.cpp:35, :199
      Player::~Player()                         core/Player.cpp:142
      mdkPlayerAPI_reset                        c/Player.cpp:679
      (Dart)
    
    mdk.read@…
      pthread_join ← std::thread::join
      FrameReaderImpl::load() lambda            core/FrameReader.cpp:1678
    
    decode thread
      AMessage::postAndAwaitResponse ← android::MediaCodec::dequeueInputBuffer
      AMediaCodec_dequeueInputBuffer
      processInput                              base/MediaCodecBase.cpp:267
      MediaCodecBase::decodePacket              base/MediaCodecBase.cpp:226
      MediaCodecVideoDecoder::decode            video/codec/MediaCodecVideoDecoder.cpp:67
      FrameReaderImpl::decodeLoop<Video>        core/FrameReader.cpp:2546
      (or instead: AMediaCodec_dequeueOutputBuffer ← processOutput :311 ← processInput :261)
    
    • 0.39.0: the same path, at MediaControl.cpp:84, FrameReader.cpp:1264/1443, the reader's join at FrameReader.cpp:1663, and the decode thread in AMediaCodec_dequeueInputBuffer from processInput (inlined into decodePacket at MediaCodecBase.cpp:127).
    • 2026-11-07 nightly: the same lines as 0.40.1.
    • AMediaCodec:async=1: the decode thread waits instead on the condition variable in decodePacket (MediaCodecBase.cpp:194), using the predicate wait() 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

    • 0.39.0, read live from /proc/<pid>/task/<tid>/status while frozen: voluntary_ctxt_switches went from 106,820 to 109,654 in 5 s (about 570 a second), and its CPU time kept rising.
    • 0.40.1 and the nightly, from the schedstat in 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 in BlockingFIFO::pop, shows 18k (utm=66 stm=63).
    • All three decode threads still alive in the 0.40.1 dump are in this loop, about 110k timeslices each. One belongs to the player being deleted; the other two belong to players that haven't been disposed yet. So the loop seems to start while a player is still playing without a texture, before its deletion begins.
    • In the stop-first run, all four players reported PlaybackState.stopped through onStateChanged before their textures were released. Even so, the decode thread of the player whose deletion then hung was still in processInput. 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) calls dequeueInputBuffer(0). If that fails, it loops: processOutput(0), leave if that reported output, then dequeueInputBuffer(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's join and ~MediaControlPush on 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

    1. A way out of 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.
    2. What this issue already asks for: mdkPlayerAPI_delete shouldn'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 → waitThread on Windows.

    I'm happy to run a nightly with a fix against this test.

    Repro: a Flutter integration test using only fvp's mdk.Player
    import 'dart:async';
    
    import 'package:flutter_test/flutter_test.dart';
    import 'package:fvp/fvp.dart' as fvp;
    import 'package:fvp/mdk.dart' as mdk;
    import 'package:integration_test/integration_test.dart';
    
    /// Players torn down the way fvp's dispose() does it, texture first and then
    /// the player, with the gap between the two held open. Each round prints how
    /// long the main isolate was held after dispose(); a round that never prints
    /// is the freeze. `cam1` in the URL becomes cam1..cam4.
    ///
    ///     flutter test integration_test/player_teardown_stall_test.dart -d emulator-5554 \
    ///       --dart-define=KW_URL=rtsp://<host>:8554/cam1/subStream --dart-define=KW_GAP_MS=3000
    ///
    /// Variants: --dart-define=KW_DECODER=AMediaCodec:async=1, --dart-define=KW_STOP_FIRST=true
    void main() {
      IntegrationTestWidgetsFlutterBinding.ensureInitialized();
      setUpAll(fvp.registerWith);
    
      testWidgets('players disposed after their texture is released', (tester) async {
        const url = String.fromEnvironment('KW_URL');
        const rounds = int.fromEnvironment('KW_ROUNDS', defaultValue: 12);
        const gapMs = int.fromEnvironment('KW_GAP_MS', defaultValue: 3000);
        const players = int.fromEnvironment('KW_PLAYERS', defaultValue: 4);
        const decoder = String.fromEnvironment('KW_DECODER', defaultValue: 'AMediaCodec');
        // Stop each player and wait for it to say so while its texture is still up, before the rest.
        const stopFirst = bool.fromEnvironment('KW_STOP_FIRST');
    
        Future<void> wait(int ms) => tester.runAsync(() => Future<void>.delayed(Duration(milliseconds: ms)));
    
        final holds = <int>[];
        for (var round = 1; round <= rounds; round++) {
          final open = <mdk.Player>[];
          final firstFrames = <Future<void>>[];
          for (var i = 0; i < players; i++) {
            final player = mdk.Player();
            player.setProperty('avformat.rtsp_transport', 'tcp');
            player.setProperty('avformat.allowed_media_types', 'video');
            player.setProperty('avformat.timeout', '5000000');
            player.setProperty('avformat.analyzeduration', '100000');
            player.setProperty('avformat.fpsprobesize', '0');
            player.setBufferRange(min: 0, max: 1000, drop: true);
            player.videoDecoders = const [decoder, 'FFmpeg', 'dav1d'];
            final first = Completer<void>();
            player.onEvent.listen((event) {
              if (event.category == 'render.video' && event.detail == '1st_frame' && !first.isCompleted) {
                first.complete();
              }
            });
            player.media = url.replaceFirst('cam1', 'cam${i + 1}');
            firstFrames.add(first.future);
            open.add(player);
          }
          await tester.runAsync(() async {
            for (final player in open) {
              await player.prepare().timeout(const Duration(seconds: 15));
              await player.updateTexture().timeout(const Duration(seconds: 10));
              player.volume = 0;
              player.state = mdk.PlaybackState.playing;
            }
            await Future.wait(firstFrames).timeout(const Duration(seconds: 20));
          });
          await wait(1500);
          if (stopFirst) {
            await tester.runAsync(() => Future.wait([
              for (final player in open)
                () async {
                  final stopped = player.onStateChanged.firstWhere((c) => c.newValue == mdk.PlaybackState.stopped);
                  player.state = mdk.PlaybackState.stopped;
                  await stopped.timeout(const Duration(seconds: 10));
                }(),
            ]));
          }
          // What fvp's dispose() does first: the texture goes, the player plays on.
          await tester.runAsync(() => Future.wait([for (final player in open) player.updateTexture(width: -1)]));
          await wait(gapMs);
          final held = Stopwatch()..start();
          await tester.runAsync(() async {
            for (final player in open) {
              player.dispose();
            }
            // The deletion runs on this thread once dispose()'s own awaits are
            // done; this timer can only fire after it has returned.
            await Future<void>.delayed(const Duration(milliseconds: 20));
          });
          held.stop();
          holds.add(held.elapsedMilliseconds);
          // ignore: avoid_print
          print('KW-TEARDOWN round $round: main isolate held ${held.elapsedMilliseconds} ms after dispose');
          await wait(1000);
        }
        holds.sort();
        // ignore: avoid_print
        print('KW-DONE $rounds rounds of $players players on $decoder, stop first $stopFirst, gap ${gapMs}ms; held ms sorted: $holds');
      }, timeout: const Timeout(Duration(minutes: 20)));
    }
    
  5. self-assigned this
    on Nov 9, 2026
  6. wang-bin commented on Nov 9, 2026

    @wang-bin
    Owner

    @mag-joong another issue

  7. wang-bin commented on Nov 9, 2026

    @wang-bin
    Owner

    @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

  8. wang-bin commented on Nov 11, 2026

    @wang-bin
    Owner

    what about mediacodec:ndk_codec=1 @LinXunFeng @mag-joong

  9. abdelaziz-mahdy commented on Nov 19, 2026

    @abdelaziz-mahdy
    Contributor

    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 their NDK MediaCodec_ / CodecLooper / mdk.adec threads) with only one video open. dumpsys audio / dumpsys media.aaudio still 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. their stop lines 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.

  10. LinXunFeng commented on Nov 24, 2026

    @LinXunFeng
    ContributorAuthor

    @wang-bin in reply to your suggestion:

    what about mediacodec:ndk_codec=1

    Thanks for the suggestion. I tested the following with FVP 0.40.0 and a freshly downloaded MDK 0.40.1 nightly (git 3343262):

    fvp.registerWith(options: {
      'video.decoders': ['mediacodec:ndk_codec=1', 'FFmpeg', 'dav1d'],
    });

    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_stop ANR; I have not established a shared root cause.

    Test environment

    • Pixel 7, Android 17, arm64-v8a, 4 KB pages.
    • Flutter 3.44.9 / Dart 3.12.2; video_player 2.14.1.
    • FVP 0.40.0, extracted from its published archive into an isolated directory.
    • MDK 0.40.1 nightly (git 3343262), downloaded on 2026-11-24.
    • arm64 libmdk.so Build 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.

    Configuration Observation
    NDK enabled, target 50 cycles, run 1 SIGBUS during disposal at cycle 0
    NDK enabled, target 50 cycles, run 2 SIGBUS during disposal at cycle 21
    Same build/version combination, only USE_NDK=false All 50 cycles completed; process remained alive

    The 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 PC 0x7e. Matching MDK symbols identify avclass_item_name in ffmpeg/glue/AVGlue.cpp on the following path (outermost to innermost):

    mdkPlayerAPI_reset
    Player::~Player
    MediaControlPush::~MediaControlPush
    VideoFrame teardown
    av_frame_free / av_frame_unref
    libffmpeg.so + 0x562360
    av_log / av_vlog
    avclass_item_name                         ffmpeg/glue/AVGlue.cpp
    invalid branch target (PC 0x7e)
    

    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?

  11. LinXunFeng commented on Nov 25, 2026

    @LinXunFeng
    ContributorAuthor

    @abdelaziz-mahdy, following up on your report:

    the ANRs are gone, but when the delete hangs, the whole player now leaks for the rest of the process.

    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

    Steps

    1. Play the included local 20-second H.264/AAC MKV and wait for the first frame.
    2. Seek to 12 seconds. If the callback remains pending after 3 seconds, continue.
    3. Wait another 1.5 seconds, release the texture, then immediately await 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.

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

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions