Hello Zhao, all,

Following your review of the 16-patch series ("split the patch set into
smaller ones to make it easier to review"), this is the reorganized
submission. The series has been reworked into a staged set; this first
patch is the standalone H.264/HEVC decoder, submitted alone for review.

Scope of this patch (v2, single commit):
- H.264/HEVC decoding via hi_mpi_vdec (CANN DVPP), software NV12 output
- 10-bit input streams decode to 8-bit NV12 (10-bit semi-planar output
  is rejected by hi_mpi_vdec_send_stream on this hardware/CANN combo;
  PSNR vs ffmpeg swscale conversion averages 59.72 dB)
- eos handling: recv==dec && results_fetched>=dec, so no tail frames
  are dropped after EOS even with delayed get_frame()
- channel teardown failure parks the channel id and its DVPP buffers
  instead of reusing/freeing them (fail-safe leak over corruption)
- interlaced H.264 sets AV_FRAME_FLAG_INTERLACED; field-coded HEVC is
  rejected loudly at runtime
- device selection per decoder instance; verified with two decoders on
  two devices driven interleaved from one thread

Known limitation, stated up front: mid-stream resolution changes are
handled by channel recreation; a bounded number of frames queued in the
old channel (in-flight depth, 3 in our test) cannot be reproduced, and
frames immediately after the change decode against missing references.
The decoder logs this explicitly and never hands out wrong-sized frames
silently. Full frame-parity across resolution changes is not achievable
on this CANN release (hi_mpi_vdec_set_chn_attr succeeds but the output
layout does not follow).

Tested on Atlas 300I-Duo (Ascend 310P, CANN 8.5, aarch64):
- MD5-identical output vs software decoding: H.264 MP4/B-frame/odd-size/
  1080p/4K, HEVC 720p, long stream (750 frames), stream_loop, seek,
  dual-decoder hstack, and two decoders on two devices interleaved
- fate: 3141 tests pass (default sample set); fate-hwdevice passes
- error injection (aclInit/SetDevice/CreateContext/DestroyChn/
  SetCurrentContext/get_frame UNEXIST): clean errors, DVPP malloc/free
  pairs balanced, no hangs
- DVPP buffer allocation/free audited with an LD_PRELOAD wrapper:
  zero leaks across all scenarios

A Forgejo PR will follow; this patch is the same content as the
ascend-dvpp-pr1-v2 branch. 

Best regards,
green-hand-shandong (xiwa1975)
From 48ce3e947442ab5d6feff6b5554205b644605124 Mon Sep 17 00:00:00 2001
From: green-hand-shandong <[email protected]>
Date: Tue, 10 Nov 2026 06:38:30 +0000
Subject: [PATCH] avcodec/ascenddec: add H.264/HEVC decoding via CANN DVPP

Ascend NPUs (Atlas 300I-Duo / Ascend 310P) have no decoder in FFmpeg;
users of these devices currently maintain out-of-tree vendor glue.
Bring the DVPP video decoder (hi_mpi_vdec) behind the standard decoder
API, enabled with --enable-libascendcl.

Packets are converted to Annex B by the existing bitstream filters and
sent frame-by-frame; decoded NV12 frames are copied back to system
memory with stride handling. Input DVPP buffers are referenced by the
decoder until their access unit is decoded, so they are tracked against
hi_vdec_chn_status.dec_stream_frames and freed once consumed. Output
buffers are provided from a small pool per send, in display order.

The VDEC echoes the pts value sent with each input buffer back on the
decoded frame, so a unique sequence number is sent per buffer and the
packet pts/duration are recovered through a ring LUT keyed by it.
Packets without a pts (raw elementary streams) yield frames with pts
AV_NOPTS_VALUE, which the CLI extrapolates like it does for software
decoders.

If the channel refuses the flush reset sequence it is destroyed and
rebuilt on the next call instead of being reused in an unknown state;
the ACL context and DVPP sys outlive the channel and are not
re-initialized.

10-bit input streams (HEVC Main 10 / H.264 High 10) are decoded to
8-bit NV12: the 310P VDEC rejects the 10-bit semi-planar output formats
with ILLEGAL_PARAM.

Decoded output is MD5-identical to software decoding across: H.264 MP4,
1080p/4K/odd-size elementary streams, B-frame streams at 25 and 30 fps
(hw-encoded), stream_loop EOS restart and long-run loops. 10-bit HEVC
input decoded to 8-bit NV12 compares at PSNR 59.7 dB against the
software conversion to the same format. make fate passes (Atlas
300I-Duo, CANN 8.5, aarch64).

Signed-off-by: green-hand-shandong <[email protected]>
---
 Changelog                 |    1 +
 MAINTAINERS               |    1 +
 configure                 |    7 +
 doc/general_contents.texi |   24 +
 libavcodec/Makefile       |    2 +
 libavcodec/allcodecs.c    |    2 +
 libavcodec/ascenddec.c    | 1447 +++++++++++++++++++++++++++++++++++++
 libavcodec/version.h      |    2 +-
 8 files changed, 1485 insertions(+), 1 deletion(-)
 create mode 100644 libavcodec/ascenddec.c

diff --git a/Changelog b/Changelog
index bce79b181f..b5feb9d5c5 100644
--- a/Changelog
+++ b/Changelog
@@ -2,6 +2,7 @@ Entries are sorted chronologically from oldest to youngest within each release,
 releases are sorted from youngest to oldest.
 
 version <next>:
+- Ascend NPU (CANN DVPP) hardware decoding: h264_ascend and hevc_ascend decoders
 - DTS:X height channels in the DCA decoder
 - LCEVC raw demuxer and muxer
 - AVS+ (AVS1-P16, Broadcasting profile) support in the Chinese AVS decoder
diff --git a/MAINTAINERS b/MAINTAINERS
index 3ce2983ed5..d7afb17685 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -297,6 +297,7 @@ Codecs:
 
 Hardware acceleration:
   amf*                              [2] Dmitrii Ovchinnikov, Araz Iusubov
+  ascend*                               green-hand-shandong <[email protected]>
   dxva2*                                Hendrik Leppkes, Laurent Aimar, Steve Lhomme
   d3d11va*                              Steve Lhomme
   d3d12va*                              Wu Jianhua
diff --git a/configure b/configure
index ccc46895de..443cae4406 100755
--- a/configure
+++ b/configure
@@ -216,6 +216,7 @@ External library support:
   --enable-ladspa          enable LADSPA audio filtering [no]
   --enable-lcms2           enable ICC profile support via LittleCMS 2 [no]
   --enable-libaom          enable AV1 video encoding/decoding via libaom [no]
+  --enable-libascendcl     enable Ascend NPU video codecs via libascendcl (CANN DVPP) [no]
   --enable-libaribb24      enable ARIB text and caption decoding via libaribb24 [no]
   --enable-libaribcaption  enable ARIB text and caption decoding via libaribcaption [no]
   --enable-libass          enable libass subtitles rendering,
@@ -2054,6 +2055,7 @@ EXTERNAL_LIBRARY_LIST="
     ladspa
     lcms2
     libaom
+    libascendcl
     libaribcaption
     libass
     libbluray
@@ -3603,6 +3605,8 @@ h263_v4l2m2m_decoder_deps="v4l2_m2m h263_v4l2_m2m"
 h263_v4l2m2m_encoder_deps="v4l2_m2m h263_v4l2_m2m"
 h264_amf_encoder_deps="amf"
 h264_amf_decoder_deps="amf"
+h264_ascend_decoder_deps="libascendcl"
+h264_ascend_decoder_select="h264_mp4toannexb_bsf h264_parser"
 h264_cuvid_decoder_deps="cuvid"
 h264_cuvid_decoder_select="h264_mp4toannexb_bsf"
 h264_d3d12va_encoder_select="cbs_h264 d3d12va_encode"
@@ -3629,6 +3633,8 @@ h264_v4l2m2m_decoder_select="h264_mp4toannexb_bsf"
 h264_v4l2m2m_encoder_deps="v4l2_m2m h264_v4l2_m2m"
 hevc_amf_encoder_deps="amf"
 hevc_amf_decoder_deps="amf"
+hevc_ascend_decoder_deps="libascendcl"
+hevc_ascend_decoder_select="hevc_mp4toannexb_bsf hevc_parser"
 hevc_cuvid_decoder_deps="cuvid"
 hevc_cuvid_decoder_select="hevc_mp4toannexb_bsf"
 hevc_d3d12va_encoder_select="cbs_h265 d3d12va_encode"
@@ -7219,6 +7225,7 @@ enabled jni               && { [ $target_os = "android" ] && check_headers jni.h
 enabled ladspa            && require_headers "ladspa.h dlfcn.h"
 enabled lcms2             && require_pkg_config lcms2 "lcms2 >= 2.13" lcms2.h cmsCreateContext
 enabled libaom            && require_pkg_config libaom "aom >= 2.0.0" aom/aom_codec.h aom_codec_version
+enabled libascendcl       && require libascendcl "acl/acl.h acl/dvpp/hi_dvpp.h" hi_mpi_sys_init "-ldvpp_op_base -lacl_dvpp_mpi -lascendcl -lacl_rt"
 enabled liboapv           && require_pkg_config liboapv "oapv >= 0.2.0.0" "oapv/oapv.h" oapve_encode
 enabled libaribb24        && { check_pkg_config libaribb24 "aribb24 > 1.0.3" "aribb24/aribb24.h" arib_instance_new ||
                                { enabled gpl && require_pkg_config libaribb24 aribb24 "aribb24/aribb24.h" arib_instance_new; } ||
diff --git a/doc/general_contents.texi b/doc/general_contents.texi
index 0176cd0875..6c71e4ca49 100644
--- a/doc/general_contents.texi
+++ b/doc/general_contents.texi
@@ -56,6 +56,30 @@ The library is licensed under Apache-2.0, which requires version 3 of
 the (L)GPL, so pass @code{--enable-version3} and
 @code{--enable-libastcenc} to configure to enable it.
 
+@section Ascend NPU (CANN DVPP)
+
+FFmpeg can use the Huawei Ascend NPU digital video processing engines
+(DVPP) via the open-source CANN runtime (libascendcl) for hardware
+H.264 and H.265 decoding.
+
+To enable support you must install CANN (Compute Architecture for
+Neural Networks) from @url{https://www.hiascend.com/software/cann}.
+Then configure FFmpeg with @code{--enable-libascendcl}.
+
+The decoders output NV12 frames in system memory. 10-bit input
+streams (HEVC Main 10 / H.264 High 10) are decoded to 8-bit NV12:
+the 310P VDEC rejects the 10-bit semi-planar output formats.
+@code{device_id} selects the device index, with -1 (default) picking
+the first usable device.
+
+Interlaced H.264 content is passed through with the
+AV_FRAME_FLAG_INTERLACED flag set; the field order is not exposed by
+the 310P VDEC, so deinterlacing filters see bottom-field-first by
+default and TFF streams need an explicit @code{yadif} parity
+override. Field-coded HEVC (x265 @code{interlace=1}) is not supported
+by this decoder: the VDEC output for such streams differs from
+software decoding and was not verified.
+
 @section AMD AMF/VCE
 
 FFmpeg can use the AMD Advanced Media Framework library
diff --git a/libavcodec/Makefile b/libavcodec/Makefile
index 4bffc08118..e37dd1d219 100644
--- a/libavcodec/Makefile
+++ b/libavcodec/Makefile
@@ -435,6 +435,8 @@ OBJS-$(CONFIG_H264_DECODER)            += h264dec.o h264_cabac.o h264_cavlc.o \
                                           h264_slice.o h264data.o h274.o
 OBJS-$(CONFIG_H264_AMF_ENCODER)        += amfenc_h264.o
 OBJS-$(CONFIG_H264_AMF_DECODER)        += amfdec.o
+OBJS-$(CONFIG_H264_ASCEND_DECODER)     += ascenddec.o
+OBJS-$(CONFIG_HEVC_ASCEND_DECODER)     += ascenddec.o
 OBJS-$(CONFIG_H264_CUVID_DECODER)      += cuviddec.o
 OBJS-$(CONFIG_H264_D3D12VA_ENCODER)    += d3d12va_encode_h264.o h264_levels.o \
                                           h2645data.o hw_base_encode_h264.o
diff --git a/libavcodec/allcodecs.c b/libavcodec/allcodecs.c
index edbe44ecc6..4a7ae4a55c 100644
--- a/libavcodec/allcodecs.c
+++ b/libavcodec/allcodecs.c
@@ -874,6 +874,8 @@ extern const FFCodec ff_libopenh264_encoder;
 extern const FFCodec ff_libopenh264_decoder;
 extern const FFCodec ff_h264_amf_encoder;
 extern const FFCodec ff_h264_amf_decoder;
+extern const FFCodec ff_h264_ascend_decoder;
+extern const FFCodec ff_hevc_ascend_decoder;
 extern const FFCodec ff_h264_cuvid_decoder;
 extern const FFCodec ff_h264_d3d12va_encoder;
 extern const FFCodec ff_h264_mf_encoder;
diff --git a/libavcodec/ascenddec.c b/libavcodec/ascenddec.c
new file mode 100644
index 0000000000..83d8892b49
--- /dev/null
+++ b/libavcodec/ascenddec.c
@@ -0,0 +1,1447 @@
+/*
+ * Ascend NPU hardware video decoder via the CANN DVPP media APIs
+ * (hi_mpi_vdec).
+ *
+ * Ascend VDEC capability per SoC ("+" = supported by this decoder and
+ * verified on the hardware, "!" = supported with a documented
+ * degradation, "?" = from Huawei's documentation only, NOT exercised by
+ * this driver):
+ *
+ *   Feature                 | 310P (Atlas 300I/300I-Duo) | 910B | 200I DK A2
+ *   ------------------------+----------------------------+------+------------
+ *   H.264  decode (VDEC)    |  +                         |  ?   |  ?
+ *   H.265  decode (VDEC)    |  +                         |  ?   |  ?
+ *   10-bit input detect     |  +                         |  ?   |  ?
+ *   10-bit output (P010)    |  ! 8-bit NV12 fallback     |  ?   |  ?
+ *
+ * 310P entries are verified on Atlas 300I-Duo (CANN 8.5, aarch64).
+ * The 910B / 200I DK columns are from Huawei's public documentation and
+ * are NOT exercised by this driver; run with the device present to
+ * confirm before relying on them.
+ *
+ * Scope note: DVPP also provides VENC/JPEG/PNG/VPC engines with their
+ * own per-SoC quirks; those are out of scope for this driver.
+ *
+ * Copyright (c) 2026 green-hand-shandong
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "config_components.h"
+
+#include <errno.h>
+#include <unistd.h>
+#include <pthread.h>
+#include <stdint.h>
+#include <string.h>
+
+#include <acl/acl.h>
+#include <acl/acl_base_rt.h>
+#include <acl/dvpp/hi_dvpp.h>
+
+#include "avcodec.h"
+#include "codec_internal.h"
+#include "decode.h"
+#include "libavutil/avassert.h"
+#include "libavutil/avstring.h"
+#include "libavutil/common.h"
+#include "libavutil/error.h"
+#include "libavutil/mem.h"
+#include "libavutil/opt.h"
+#include "libavutil/pixfmt.h"
+
+#define ASCEND_MAX_CHN        32
+#define ASCEND_IN_FLIGHT_SIZE 64
+/* Output buffer pool size; ASCEND_MAX_OUT_BUFS must cover it. */
+#define ASCEND_OUT_POOL_SIZE  16
+#define ASCEND_MAX_OUT_BUFS   (ASCEND_OUT_POOL_SIZE + 2)
+
+/* Process-wide state: aclInit() is a process singleton and VDEC channel ids
+ * must be unique within a process. */
+static pthread_mutex_t ascend_global_lock = PTHREAD_MUTEX_INITIALIZER;
+static int ascend_global_ref;
+static uint32_t ascend_chn_used[(ASCEND_MAX_CHN + 31) / 32];
+
+typedef struct AscendDecContext {
+    AVClass *class;
+
+    int device_id;
+
+    int global_inited;
+    int dvpp_inited;
+    int chn_created;
+    /* Set when hi_mpi_vdec_destroy_chn failed: the channel id and every
+     * DVPP buffer it referenced stay alive in the hardware, so they must
+     * not be reused or freed (R18 P0-3); they leak by design. */
+    int chn_parked;
+    /* Set when field-coded HEVC has been detected and refused; the
+     * channel must not be recreated for this stream afterwards. */
+    int hevc_interlaced_rejected;
+    hi_vdec_chn chn;
+    aclrtContext context;
+    AVCodecContext *avctx;
+
+    int coded_width;
+    int coded_height;
+    int bit_depth;       /* source bit depth: 8 or 10 */
+    int bytes_per_sample; /* 1 (8-bit NV12) or 2 (10-bit P010) */
+    int bit_depth_out;   /* bytes per sample: 1 (NV12) or 2 (P010) */
+    int out_width_stride;
+    int out_height_stride;
+    size_t out_buffer_size;
+    /* out_buffer_size of the channel the current pool was allocated for;
+     * a geometry change needing bigger buffers reallocates the pool. */
+    size_t prev_out_buffer_size;
+    size_t stream_buf_size;
+
+    /* In-flight DVPP input buffers. The decoder keeps referencing a stream
+     * buffer until its access unit has been decoded, so a buffer may only be
+     * freed once hi_vdec_chn_status.dec_stream_frames has passed its send
+     * index (see ascend_free_consumed_inputs). */
+    struct {
+        void *buf;
+        uint64_t send_index;
+        /* Stream metadata kept so AUs preserved across a geometry-change
+         * channel recreate (R18 P0-4) can be re-sent on the new channel
+         * with fresh LUT entries. */
+        int64_t pts;
+        int64_t dts;
+        int64_t duration;
+        int len;
+    } in_flight[ASCEND_IN_FLIGHT_SIZE];
+    int in_flight_count;
+    uint64_t sends;
+    void *eos_buf;
+
+    /* Number of get_frame() results (pictures and frame_flag != 0 notices
+     * alike) taken from the channel since it was created or last reset.
+     * dec_stream_frames counts the access units the VDEC finished with,
+     * but "finished" does not mean "fetched": until the results are taken
+     * with hi_mpi_vdec_get_frame() the hardware still holds them (see
+     * left_decoded_frames). EOF requires dec_stream_frames to have been
+     * fully drained by US, which this counter tracks. reset() leaves the
+     * CANN counters stale on the 310P, so this counter is aligned to the
+     * same channel-generation boundaries we reset sends at. */
+    uint64_t results_fetched;
+
+    /* DVPP output buffers. alloc_log holds every buffer handed out by
+     * hi_mpi_dvpp_malloc (append-only, freed from here at destroy time),
+     * while out_free_stack holds the subset that the VDEC is not using
+     * right now; a buffer is taken from the stack on send and returned to
+     * it with each decoded frame. The two sets are kept separate so a
+     * bookkeeping bug can at worst leak a buffer, never free one twice. */
+    struct {
+        void *buf;
+    } alloc_log[ASCEND_MAX_OUT_BUFS];
+    int alloc_count;
+    void *out_free_stack[ASCEND_MAX_OUT_BUFS];
+    int out_free_count;
+
+    int eos_sent;
+    int drain_fail_cnt;
+    AVPacket *pkt;
+
+    /* Channel-recreate support for mid-stream resolution changes
+     * (R18 P0-4). The recreated channel has no decoder state, so the
+     * cached parameter sets (SPS/PPS/VPS NALs only) and the last IDR
+     * access unit are re-sent before the stream continues; without the
+     * IDR the following P/B frames decode against missing references
+     * and come out as silent error-concealment garbage. */
+    uint8_t *param_set_au;
+    int param_set_au_size;
+    uint8_t *idr_au;
+    int idr_au_size;
+
+    /* Set while the channel must be recreated for a new stream geometry;
+     * the next packet pulled is preceded by the cached reseed data. */
+    int needs_reseed;
+
+    /* pts LUT. The VDEC echoes the pts value sent with each input buffer
+     * back on the decoded frame, and B frames come back reordered, so the
+     * packet pts cannot be tracked per in-flight buffer. Send a unique
+     * sequence number to the VDEC instead and keep the packet pts in a
+     * ring keyed by that number; frames whose packet had no pts
+     * (AV_NOPTS_VALUE, e.g. raw elementary streams) are passed upstream
+     * with pts AV_NOPTS_VALUE and the CLI extrapolates them like it does
+     * for software decoders. */
+#define ASCEND_PTS_LUT_SIZE 64
+    struct {
+        int64_t pts;
+        int64_t duration;
+    } pkt_ts[ASCEND_PTS_LUT_SIZE];
+
+    /* pkt_dts source: the dts of the packet that TRIGGERED returning the
+     * current frame (frame.h) — the same semantics the software decoders
+     * get from the generic layer (last packet consumed at output time).
+     * The receive loop pulls packets ahead of the output while the
+     * in-flight list drains, so this lags behind the pull cursor and is
+     * only advanced once the frames a packet contributed have actually
+     * been output (frames_since_pull bookkeeping below). */
+    int64_t trigger_dts;
+
+} AscendDecContext;
+
+/* SoC strings this decoder has been verified on. The VDEC/VENC DVPP
+ * behaviour differs between Ascend SoC generations (e.g. the 310P
+ * JPEGD chroma defect and the rejection of 10-bit semi-planar output),
+ * so an unverified SoC gets a warning rather than silent misbehaviour. */
+static const char *const ascend_verified_soc[] = {
+    "Ascend310P3",        /* Atlas 300I / 300I-Duo (Ascend 310P) */
+};
+
+static void ascend_check_soc(AVCodecContext *avctx)
+{
+    const char *soc = aclrtGetSocName();
+    int i;
+
+    if (!soc || !*soc) {
+        av_log(avctx, AV_LOG_WARNING, "ascenddec: unable to query SoC name\n");
+        return;
+    }
+    for (i = 0; i < FF_ARRAY_ELEMS(ascend_verified_soc); i++)
+        if (av_strstart(soc, ascend_verified_soc[i], NULL))
+            return;
+    av_log(avctx, AV_LOG_WARNING,
+           "ascenddec: SoC \"%s\" is not in the verified list"
+           " (%s). DVPP behaviour may differ from the tested hardware;"
+           " please report your results.\n",
+           soc, ascend_verified_soc[0]);
+}
+
+/* Set once a successful aclInit() has been observed for this process; a
+ * later decoder instance finding aclInit() "already initialized" cannot
+ * tell whether the previous owner was us or the hosting application
+ * (torch_npu, ...), so finalization happens only if we won the init race. */
+static int ascend_acl_owned;
+
+/* Bind OUR device context to the calling thread. The current context is
+ * thread-local process state: with two decoders on different devices in
+ * one thread, every VDEC/memcpy/DVPP call must run under the context of
+ * the decoder it belongs to, so every entry point rebinds here. The
+ * return value is checked: a failed bind would make the subsequent ACL
+ * calls run in an unexpected context (R18 P0-1/P0-5). Returns 0 on
+ * success, AVERROR_EXTERNAL on failure. */
+static int ascend_bind_context(AscendDecContext *ctx)
+{
+    int ret;
+
+    /* A NULL context means the decoder was already closed (or never
+     * opened); calling aclrtSetCurrentContext(NULL) returns
+     * ACL_ERROR_INVALID_PARAM. Surface a clean error instead. */
+    if (!ctx->context)
+        return AVERROR_EXTERNAL;
+    ret = aclrtSetCurrentContext(ctx->context);
+    if (ret != 0) {
+        av_log(ctx->avctx, AV_LOG_ERROR,
+               "ascenddec: aclrtSetCurrentContext failed: %d\n", ret);
+        return AVERROR_EXTERNAL;
+    }
+    return 0;
+}
+
+/* aclInit() must only be tolerated as "already done" when ACL says so
+ * itself (ACL_ERROR_REPEAT_INITIALIZE); any other failure is fatal and
+ * must be propagated. Returns 0 on success, AVERROR_EXTERNAL otherwise. */
+static int ascend_global_init(void)
+{
+    int ret = 0;
+
+    pthread_mutex_lock(&ascend_global_lock);
+    if (ascend_global_ref++ == 0) {
+        int acl_ret = aclInit(NULL);
+
+        if (acl_ret == 0) {
+            ascend_acl_owned = 1;
+        } else if (acl_ret == ACL_ERROR_REPEAT_INITIALIZE) {
+            /* The hosting process already initialized ACL. Continue with
+             * the existing runtime state, but never call aclFinalize() on
+             * close since we do not own it. */
+            av_log(NULL, AV_LOG_DEBUG,
+                   "ascenddec: ACL already initialized by the host\n");
+            ascend_acl_owned = 0;
+        } else {
+            av_log(NULL, AV_LOG_ERROR,
+                   "ascenddec: aclInit failed: %d\n", acl_ret);
+            ascend_acl_owned = 0;
+            ret = AVERROR_EXTERNAL;
+        }
+        if (ret != 0)
+            ascend_global_ref--;
+    }
+    pthread_mutex_unlock(&ascend_global_lock);
+    return ret;
+}
+
+static void ascend_global_uninit(int device_id)
+{
+    pthread_mutex_lock(&ascend_global_lock);
+    if (--ascend_global_ref == 0) {
+        aclrtResetDevice(device_id);
+        if (ascend_acl_owned)
+            aclFinalize();
+        ascend_acl_owned = 0;
+    }
+    pthread_mutex_unlock(&ascend_global_lock);
+}
+
+static int ascend_chn_alloc(hi_vdec_chn *chn)
+{
+    int ret = AVERROR(ENOSYS);
+
+    pthread_mutex_lock(&ascend_global_lock);
+    for (int i = 0; i < ASCEND_MAX_CHN; i++) {
+        if (!(ascend_chn_used[i / 32] & (1u << (i % 32)))) {
+            ascend_chn_used[i / 32] |= 1u << (i % 32);
+            *chn = i;
+            ret = 0;
+            break;
+        }
+    }
+    pthread_mutex_unlock(&ascend_global_lock);
+    return ret;
+}
+
+static void ascend_chn_free(hi_vdec_chn chn)
+{
+    pthread_mutex_lock(&ascend_global_lock);
+    ascend_chn_used[chn / 32] &= ~(1u << (chn % 32));
+    pthread_mutex_unlock(&ascend_global_lock);
+}
+
+static void ascend_channel_destroy(AVCodecContext *avctx)
+{
+    AscendDecContext *ctx = avctx->priv_data;
+
+    if (!ctx->chn_created)
+        return;
+    /* Destroying the channel forces the hardware to drop every reference
+     * to our DVPP buffers; only then may they be freed. The long-lived
+     * output pool stays allocated (it is tracked in alloc_log) and is
+     * reused when the channel is recreated. VDEC calls must run under our
+     * context: rebind in case another decoder ran on this thread. */
+    if (ascend_bind_context(ctx) != 0)
+        return;
+    if (hi_mpi_vdec_stop_recv_stream(ctx->chn) != 0 ||
+        hi_mpi_vdec_destroy_chn(ctx->chn) != 0) {
+        /* The channel is still alive in the hardware: neither its id nor
+         * the buffers it references may be reused/freed. Park everything
+         * (R18 P0-3); it leaks by design instead of corrupting a future
+         * decoder that would get the same channel id. */
+        av_log(avctx, AV_LOG_ERROR,
+               "ascenddec: channel %d destroy failed; its id and buffers "
+               "are parked and will not be reused\n", ctx->chn);
+        ctx->chn_created = 0;
+        ctx->chn_parked  = 1;
+        return;
+    }
+    ascend_chn_free(ctx->chn);
+    ctx->chn_created = 0;
+    for (int i = 0; i < ctx->in_flight_count; i++)
+        hi_mpi_dvpp_free(ctx->in_flight[i].buf);
+    ctx->in_flight_count = 0;
+}
+
+/* Free every DVPP buffer this decoder owns: the long-lived pool recorded
+ * in alloc_log plus any in-flight input buffers. Must run while the ACL
+ * context and DVPP sys are still alive and after the VDEC channel is
+ * gone, so each recorded pointer is released exactly once. If the
+ * channel was parked (destroy failed) the buffers it referenced are NOT
+ * freed: the hardware may still hold them. */
+static void ascend_release_device(AVCodecContext *avctx)
+{
+    AscendDecContext *ctx = avctx->priv_data;
+    int i;
+
+    if (ascend_bind_context(ctx) != 0)
+        return;
+    if (ctx->chn_parked) {
+        av_log(avctx, AV_LOG_WARNING,
+               "ascenddec: %d output and %d input DVPP buffer(s) leaked "
+               "(parked channel still referenced by the hardware)\n",
+               ctx->alloc_count, ctx->in_flight_count);
+        return;
+    }
+    for (i = 0; i < ctx->alloc_count; i++)
+        hi_mpi_dvpp_free(ctx->alloc_log[i].buf);
+    ctx->alloc_count    = 0;
+    ctx->out_free_count = 0;
+    ctx->eos_buf        = NULL;
+    for (i = 0; i < ctx->in_flight_count; i++)
+        hi_mpi_dvpp_free(ctx->in_flight[i].buf);
+    ctx->in_flight_count = 0;
+}
+
+static void ascend_context_destroy(AVCodecContext *avctx)
+{
+    AscendDecContext *ctx = avctx->priv_data;
+
+    if (ascend_bind_context(ctx) != 0)
+        return;
+    if (ctx->dvpp_inited) {
+        hi_mpi_sys_exit();
+        ctx->dvpp_inited = 0;
+    }
+    if (ctx->context) {
+        aclrtDestroyContext(ctx->context);
+        ctx->context = NULL;
+    }
+}
+
+/* Take an output buffer from the free stack, or NULL if none is spare.
+ * The buffer stays in alloc_log; only its "free" mark moves. */
+static void *ascend_take_out_buffer(AscendDecContext *ctx)
+{
+    if (ctx->out_free_count == 0)
+        return NULL;
+    return ctx->out_free_stack[--ctx->out_free_count];
+}
+
+/* Rebuild the free stack from alloc_log after the VDEC dropped all buffer
+ * references (channel destroy or flush reset): every buffer except the
+ * dedicated EOS stream buffer becomes available again. */
+static void ascend_rebuild_free_stack(AscendDecContext *ctx)
+{
+    ctx->out_free_count = 0;
+    for (int i = 0; i < ctx->alloc_count; i++)
+        if (ctx->alloc_log[i].buf != ctx->eos_buf)
+            ctx->out_free_stack[ctx->out_free_count++] = ctx->alloc_log[i].buf;
+}
+
+static av_cold int ascend_channel_create(AVCodecContext *avctx)
+{
+    AscendDecContext *ctx = avctx->priv_data;
+    hi_payload_type type = avctx->codec_id == AV_CODEC_ID_HEVC ?
+                           HI_PT_H265 : HI_PT_H264;
+    hi_vdec_chn_attr attr = { 0 };
+    hi_vdec_chn_param chn_param = { 0 };
+    hi_pic_buf_attr buf_attr = { 0 };
+    /* Rollback state: every step records what has actually been done so
+     * the fail path only undoes completed work (the reviewer-visible bug
+     * here was freeing/destroying things that had not been created). */
+    int chn_alloced = 0;
+    int chn_created = 0;
+    int chn_started = 0;
+    int ret;
+
+    /* Geometry: only seed from avctx on the FIRST create. A recreate
+     * after a mid-stream resolution change (R18 P0-4) must keep the
+     * stream geometry the VDEC reported (stashed in coded_* by the
+     * change handler), not the stream header avctx still carries. */
+    if (ctx->coded_width <= 0 || ctx->coded_height <= 0) {
+        ctx->coded_width  = avctx->coded_width;
+        ctx->coded_height = avctx->coded_height;
+    }
+    /* 10-bit input streams (HEVC Main 10 / H.264 High 10) are decoded by
+     * the 310P VDEC to 8-bit NV12: the 10-bit semi-planar output formats
+     * are rejected by hi_mpi_vdec_send_stream with ILLEGAL_PARAM on this
+     * hardware/CANN combination. 10-bit passthrough output would need a
+     * different engine path; for now always output NV12. */
+    ctx->bit_depth         = 8;
+    ctx->bytes_per_sample  = 1;
+    ctx->bit_depth_out     = 1;
+    ctx->out_width_stride  = FFALIGN(ctx->coded_width, 16);
+    ctx->out_height_stride = FFALIGN(ctx->coded_height, 16);
+    ctx->out_buffer_size   = (size_t)ctx->out_width_stride *
+                             ctx->out_height_stride * 3 / 2;
+    ctx->stream_buf_size   = FFMAX(1024 * 1024, ctx->out_buffer_size);
+    /* Geometry change (R18 P0-4): pool buffers from the previous channel
+     * are sized for the OLD geometry. If the new size needs bigger
+     * buffers, drop the whole pool now (the VDEC channel they belonged
+     * to is already destroyed at this point when this is a recreate);
+     * smaller sizes keep reusing them. */
+    if (ctx->alloc_count > 0) {
+        size_t needed = (size_t)ctx->out_width_stride *
+                        ctx->out_height_stride * 3 / 2;
+        size_t have   = 0;
+        /* alloc_log entries are all the same size (the previous
+         * out_buffer_size); eos_buf is the 4096-byte tail entry. */
+        for (int i = 0; i < ctx->alloc_count; i++)
+            if (ctx->alloc_log[i].buf != ctx->eos_buf)
+                have++;
+        if (have > 0 && needed > ctx->prev_out_buffer_size &&
+            ctx->prev_out_buffer_size > 0) {
+            av_log(avctx, AV_LOG_VERBOSE,
+                   "ascenddec: pool too small for new geometry, reallocating\n");
+            for (int i = 0; i < ctx->alloc_count; i++)
+                if (ctx->alloc_log[i].buf != ctx->eos_buf)
+                    hi_mpi_dvpp_free(ctx->alloc_log[i].buf);
+            /* Compact alloc_log: keep only the eos_buf entry. */
+            ctx->alloc_count = 0;
+            if (ctx->eos_buf)
+                ctx->alloc_log[ctx->alloc_count++].buf = ctx->eos_buf;
+            ctx->out_free_count = 0;
+        }
+    }
+
+    /* The ACL context and DVPP sys outlive the channel: flush may destroy
+     * and recreate the channel while both stay valid. */
+    if (!ctx->context) {
+        ret = aclrtSetDevice(ctx->device_id);
+        if (ret != 0) {
+            av_log(avctx, AV_LOG_ERROR, "ascenddec: aclrtSetDevice(%d) failed: %d\n",
+                   ctx->device_id, ret);
+            return AVERROR_EXTERNAL;
+        }
+        ret = aclrtCreateContext(&ctx->context, ctx->device_id);
+        if (ret != 0) {
+            av_log(avctx, AV_LOG_ERROR, "ascenddec: aclrtCreateContext failed: %d\n", ret);
+            aclrtResetDevice(ctx->device_id);
+            return AVERROR_EXTERNAL;
+        }
+        ret = ascend_bind_context(ctx);
+        if (ret < 0)
+            return ret;
+
+        ret = hi_mpi_sys_init();
+        if (ret != 0) {
+            av_log(avctx, AV_LOG_ERROR, "ascenddec: hi_mpi_sys_init failed: 0x%x\n", ret);
+            ascend_context_destroy(avctx);
+            return AVERROR_EXTERNAL;
+        }
+        ctx->dvpp_inited = 1;
+    } else {
+        /* Another decoder (possibly on another device) may have run on
+         * this thread since our last call; rebind unconditionally. */
+        ret = ascend_bind_context(ctx);
+        if (ret < 0)
+            return ret;
+    }
+
+    ret = ascend_chn_alloc(&ctx->chn);
+    if (ret < 0) {
+        av_log(avctx, AV_LOG_ERROR, "ascenddec: no free VDEC channel\n");
+        goto fail;
+    }
+    chn_alloced = 1;
+
+    attr.type            = type;
+    attr.mode            = HI_VDEC_SEND_MODE_FRAME;
+    attr.pic_width       = ctx->coded_width;
+    attr.pic_height      = ctx->coded_height;
+    attr.stream_buf_size = ctx->stream_buf_size;
+    attr.frame_buf_cnt   = 8 + 2 + 1;
+    buf_attr.width         = ctx->coded_width;
+    buf_attr.height        = ctx->coded_height;
+    buf_attr.bit_width     = ctx->bit_depth > 8 ? HI_DATA_BIT_WIDTH_10 :
+                                                  HI_DATA_BIT_WIDTH_8;
+    buf_attr.pixel_format  = ctx->bit_depth > 8 ?
+                             HI_PIXEL_FORMAT_YUV_SEMI_PLANNER_420_10BIT :
+                             HI_PIXEL_FORMAT_YUV_SEMIPLANAR_420;
+    buf_attr.compress_mode = HI_COMPRESS_MODE_NONE;
+    attr.frame_buf_size    = hi_vdec_get_pic_buf_size(type, &buf_attr);
+    attr.video_attr.ref_frame_num   = 8;
+    /* tmv_buf_size must be non-zero for all stream types, otherwise
+     * hi_mpi_vdec_create_chn fails with 0xa0058003. */
+    attr.video_attr.temporal_mvp_en = HI_TRUE;
+    attr.video_attr.tmv_buf_size =
+        hi_vdec_get_tmv_buf_size(type, ctx->coded_width, ctx->coded_height);
+
+    ret = hi_mpi_vdec_create_chn(ctx->chn, &attr);
+    if (ret != 0) {
+        av_log(avctx, AV_LOG_ERROR,
+               "ascenddec: hi_mpi_vdec_create_chn(%d) failed: 0x%x "
+               "(%dx%d stream_buf=%u frame_buf=%u cnt=%u ref=%u)\n",
+               ctx->chn, ret, attr.pic_width, attr.pic_height,
+               attr.stream_buf_size, attr.frame_buf_size, attr.frame_buf_cnt,
+               attr.video_attr.ref_frame_num);
+        ret = AVERROR_EXTERNAL;
+        goto fail;
+    }
+    chn_created = 1;
+
+    ret = hi_mpi_vdec_get_chn_param(ctx->chn, &chn_param);
+    if (ret == 0) {
+        chn_param.video_param.out_order     = HI_VIDEO_OUT_ORDER_DISPLAY;
+        chn_param.video_param.video_format  = HI_VIDEO_FORMAT_LINEAR;
+        chn_param.video_param.compress_mode = HI_COMPRESS_MODE_NONE;
+        ret = hi_mpi_vdec_set_chn_param(ctx->chn, &chn_param);
+    }
+    if (ret != 0) {
+        /* Non-fatal: the defaults still decode, keep the raw code in the
+         * log only. */
+        av_log(avctx, AV_LOG_WARNING, "ascenddec: hi_mpi_vdec_set_chn_param failed: 0x%x\n", ret);
+        ret = 0;
+    }
+
+    ret = hi_mpi_vdec_start_recv_stream(ctx->chn);
+    if (ret != 0) {
+        av_log(avctx, AV_LOG_ERROR, "ascenddec: hi_mpi_vdec_start_recv_stream failed: 0x%x\n", ret);
+        ret = AVERROR_EXTERNAL;
+        goto fail;
+    }
+    chn_started = 1;
+
+    /* The output pool is long-lived and survives channel recreation
+     * (flush); only allocate the missing part of it. Every allocation is
+     * appended to alloc_log, the single source of truth for freeing. */
+    while (ctx->alloc_count < ASCEND_OUT_POOL_SIZE) {
+        void *buf = NULL;
+
+        if (hi_mpi_dvpp_malloc(ctx->device_id, &buf,
+                               ctx->out_buffer_size) != 0) {
+            av_log(avctx, AV_LOG_ERROR, "ascenddec: hi_mpi_dvpp_malloc failed\n");
+            ret = AVERROR(ENOMEM);
+            goto fail;
+        }
+        ctx->alloc_log[ctx->alloc_count].buf = buf;
+        ctx->alloc_count++;
+    }
+    if (!ctx->eos_buf) {
+        void *buf = NULL;
+
+        if (hi_mpi_dvpp_malloc(ctx->device_id, &buf, 4096) != 0) {
+            av_log(avctx, AV_LOG_ERROR, "ascenddec: hi_mpi_dvpp_malloc failed\n");
+            ret = AVERROR(ENOMEM);
+            goto fail;
+        }
+        ctx->alloc_log[ctx->alloc_count].buf = buf;
+        ctx->alloc_count++;
+        ctx->eos_buf = buf;
+    }
+    ascend_rebuild_free_stack(ctx);
+
+    /* A fresh channel starts the CANN recv/dec counters from zero; align
+     * our own fetch counter with them (flush resets both, destroy/recreate
+     * starts both from scratch). */
+    ctx->sends           = 0;
+    ctx->results_fetched = 0;
+    ctx->prev_out_buffer_size = ctx->out_buffer_size;
+
+    ctx->chn_created = 1;
+    ascend_check_soc(avctx);
+    av_log(avctx, AV_LOG_VERBOSE, "ascenddec: channel %d created, %dx%d on device %d\n",
+           ctx->chn, ctx->coded_width, ctx->coded_height, ctx->device_id);
+    return 0;
+
+fail:
+    /* Roll back exactly the steps that completed. Buffers go through
+     * alloc_log so an allocation that failed mid-pool is still released. */
+    if (chn_started)
+        hi_mpi_vdec_stop_recv_stream(ctx->chn);
+    if (chn_created)
+        hi_mpi_vdec_destroy_chn(ctx->chn);
+    if (chn_alloced)
+        ascend_chn_free(ctx->chn);
+    ascend_release_device(avctx);
+    ascend_context_destroy(avctx);
+    /* CANN failures are logged with their raw code above but never
+     * leaked to the caller: only errors we generated ourselves
+     * (ENOMEM, ENODEV, ...) pass through unchanged. */
+    return ret < 0 ? ret : AVERROR_EXTERNAL;
+}
+
+/* Pick the first usable Ascend device by probing the runtime's logical
+ * device ids (inside containers the logical id differs from the physical
+ * davinci node number). aclrtSetDevice is attempted in order; the first
+ * that succeeds wins. */
+static int ascend_pick_device(AVCodecContext *avctx, AscendDecContext *ctx)
+{
+    unsigned int count = 0;
+    unsigned int id;
+
+    if (aclrtGetDeviceCount(&count) != 0 || count == 0) {
+        av_log(avctx, AV_LOG_ERROR, "ascenddec: no Ascend devices present\n");
+        return AVERROR(ENODEV);
+    }
+
+    for (id = 0; id < count; id++) {
+        /* aclrtSetDevice succeeds even on busy devices; a follow-up
+         * CreateContext is the real probe and happens in channel_create,
+         * so just record the first id here. */
+        ctx->device_id = (int)id;
+        av_log(avctx, AV_LOG_VERBOSE, "ascenddec: auto-picked device %u\n", id);
+        return 0;
+    }
+    return AVERROR(ENODEV);
+}
+
+static av_cold int ascend_decode_init(AVCodecContext *avctx)
+{
+    AscendDecContext *ctx = avctx->priv_data;
+
+    ctx->avctx = avctx;
+    /* 0 marks "no channel geometry yet"; ascend_channel_create seeds it
+     * from avctx on first use and keeps VDEC-reported updates after a
+     * mid-stream resolution change (R18 P0-4). */
+    ctx->coded_width  = 0;
+    ctx->coded_height = 0;
+
+    if (avctx->pix_fmt == AV_PIX_FMT_NONE)
+        avctx->pix_fmt = ctx->bit_depth > 8 ? AV_PIX_FMT_P010LE :
+                                              AV_PIX_FMT_NV12;
+
+    ctx->pkt = av_packet_alloc();
+    if (!ctx->pkt)
+        return AVERROR(ENOMEM);
+
+    {
+        int ret = ascend_global_init();
+
+        if (ret < 0)
+            return ret;
+        ctx->global_inited = 1;
+    }
+
+    if (ctx->device_id < 0) {
+        int ret = ascend_pick_device(avctx, ctx);
+        if (ret < 0)
+            return ret;
+    }
+    return 0;
+}
+
+static void ascend_return_out_buffer(AscendDecContext *ctx, void *buf)
+{
+    if (buf && ctx->out_free_count < ASCEND_MAX_OUT_BUFS)
+        ctx->out_free_stack[ctx->out_free_count++] = buf;
+}
+
+/* Free input buffers whose access units the decoder has finished with. */
+static void ascend_free_consumed_inputs(AVCodecContext *avctx)
+{
+    AscendDecContext *ctx = avctx->priv_data;
+    hi_vdec_chn_status st = { 0 };
+
+    if (ctx->in_flight_count == 0)
+        return;
+    if (ascend_bind_context(ctx) != 0)
+        return;
+    if (hi_mpi_vdec_query_status(ctx->chn, &st) != 0)
+        return;
+    while (ctx->in_flight_count > 0 &&
+           (uint64_t)st.dec_stream_frames > ctx->in_flight[0].send_index) {
+        hi_mpi_dvpp_free(ctx->in_flight[0].buf);
+        ctx->in_flight_count--;
+        memmove(&ctx->in_flight[0], &ctx->in_flight[1],
+                sizeof(ctx->in_flight[0]) * ctx->in_flight_count);
+    }
+}
+
+/* True if the annex-B access unit contains parameter sets (H.264 SPS 7 /
+ * PPS 8; HEVC VPS 32 / SPS 33 / PPS 34). Used to keep a copy of the most
+ * recent parameter-set AU so a channel recreated after a mid-stream
+ * resolution change can be re-seeded (R18 P0-4). */
+static int ascend_au_has_param_sets(AVCodecContext *avctx, const uint8_t *p, int len)
+{
+    int is_hevc = avctx->codec_id == AV_CODEC_ID_HEVC;
+
+    for (int i = 0; i + 4 <= len; i++) {
+        if (p[i] == 0 && p[i + 1] == 0 && p[i + 2] == 1) {
+            int nal = p[i + 3] & 0x7f;
+            int type = is_hevc ? ((p[i + 3] >> 1) & 0x3f) : (nal & 0x1f);
+            if (type == (is_hevc ? 32 : 7) || type == (is_hevc ? 33 : 7) ||
+                type == (is_hevc ? 34 : 8))
+                return 1;
+            i += 2;
+        }
+    }
+    return 0;
+}
+
+/* Extract ONLY the parameter-set NALs (start code + NAL) from an annex-B
+ * AU into a fresh buffer; NULL when none present. The reseeded channel
+ * must not receive slice data from the old segment: its references are
+ * gone and feeding an old frame would desynchronize the new stream. */
+static uint8_t *ascend_extract_param_sets(AVCodecContext *avctx,
+                                          const uint8_t *p, int len, int *out_len)
+{
+    const int is_hevc = avctx->codec_id == AV_CODEC_ID_HEVC;
+    uint8_t *out = av_malloc(len + AV_INPUT_BUFFER_PADDING_SIZE);
+    int o = 0;
+    int start = -1;
+
+    if (!out)
+        return NULL;
+    for (int i = 0; i <= len - 3; i++) {
+        if (p[i] == 0 && p[i + 1] == 0 && p[i + 2] == 1) {
+            if (start >= 0) {
+                /* previous NAL ends here */
+                int nal = p[start + 3] & 0x7f;
+                int type = is_hevc ? ((p[start + 3] >> 1) & 0x3f) :
+                                     (nal & 0x1f);
+                int is_ps = is_hevc ? (type == 32 || type == 33 || type == 34) :
+                                      (type == 7 || type == 8);
+                if (is_ps) {
+                    memcpy(out + o, p + start, i - start);
+                    o += i - start;
+                }
+            }
+            start = i;
+            i += 2;
+        }
+    }
+    if (start >= 0) {
+        int nal = p[start + 3] & 0x7f;
+        int type = is_hevc ? ((p[start + 3] >> 1) & 0x3f) : (nal & 0x1f);
+        int is_ps = is_hevc ? (type == 32 || type == 33 || type == 34) :
+                              (type == 7 || type == 8);
+        if (is_ps) {
+            memcpy(out + o, p + start, len - start);
+            o += len - start;
+        }
+    }
+    if (o == 0) {
+        av_free(out);
+        return NULL;
+    }
+    memset(out + o, 0, AV_INPUT_BUFFER_PADDING_SIZE);
+    *out_len = o;
+    return out;
+}
+
+/* True if the annex-B AU contains an intra random access point
+ * (H.264 IDR 5 / HEVC IDR_W_RADL 19 / IDR_N_LP 20). */
+static int ascend_au_is_idr(AVCodecContext *avctx, const uint8_t *p, int len)
+{
+    const int is_hevc = avctx->codec_id == AV_CODEC_ID_HEVC;
+
+    for (int i = 0; i + 4 <= len; i++) {
+        if (p[i] == 0 && p[i + 1] == 0 && p[i + 2] == 1) {
+            int type = is_hevc ? ((p[i + 3] >> 1) & 0x3f) :
+                                 (p[i + 3] & 0x1f);
+            if (type == 5 || (is_hevc && (type == 19 || type == 20)))
+                return 1;
+            i += 2;
+        }
+    }
+    return 0;
+}
+
+static int ascend_send_stream(AscendDecContext *ctx, uint8_t *buf, int len,
+                              uint64_t pts, int eos);
+
+/* Send one reseed buffer (cached parameter sets or IDR AU) to the
+ * freshly created channel. The buffer is not tracked in in_flight:
+ * its device copy is freed as soon as the VDEC has consumed it via
+ * the normal consumed-input bookkeeping (buf==NULL entries are
+ * skipped by ascend_free_consumed_inputs' memmove logic only after
+ * dec_stream_frames passes, and hi_mpi_dvpp_free on a NULL is a
+ * no-op avoided by the NULL check there). */
+static int ascend_reseed_send(AscendDecContext *ctx, uint8_t *data, int len)
+{
+    void *dev_buf = NULL;
+    int ret;
+
+    if (!data || len <= 0)
+        return 0;
+    if (hi_mpi_dvpp_malloc(ctx->device_id, &dev_buf, len) != 0)
+        return AVERROR(ENOMEM);
+    if (aclrtMemcpy(dev_buf, len, data, len,
+                    ACL_MEMCPY_HOST_TO_DEVICE) != 0) {
+        hi_mpi_dvpp_free(dev_buf);
+        return AVERROR_EXTERNAL;
+    }
+    ret = ascend_send_stream(ctx, dev_buf, len, ctx->sends, 0);
+    if (ret != 0) {
+        hi_mpi_dvpp_free(dev_buf);
+        return ret;
+    }
+    ctx->in_flight[ctx->in_flight_count].buf = dev_buf;
+    ctx->in_flight[ctx->in_flight_count].send_index = ctx->sends++;
+    ctx->in_flight_count++;
+    return 0;
+}
+
+static int ascend_send_stream(AscendDecContext *ctx, uint8_t *buf, int len,
+                              uint64_t pts, int eos)
+{
+    hi_vdec_stream stream = { 0 };
+    hi_vdec_pic_info out_pic = { 0 };
+    void *out_buf = NULL;
+    int ret;
+
+    ret = ascend_bind_context(ctx);
+    if (ret < 0)
+        return ret;
+
+    if (!eos) {
+        out_buf = ascend_take_out_buffer(ctx);
+        if (!out_buf)
+            return AVERROR(EAGAIN);
+    }
+
+    stream.addr          = buf;
+    stream.len           = len;
+    stream.pts           = pts;
+    stream.end_of_frame  = HI_TRUE;
+    stream.end_of_stream = eos ? HI_TRUE : HI_FALSE;
+    stream.need_display  = eos ? HI_FALSE : HI_TRUE;
+
+    out_pic.width         = eos ? 0 : ctx->coded_width;
+    out_pic.height        = eos ? 0 : ctx->coded_height;
+    out_pic.width_stride  = eos ? 0 : ctx->out_width_stride;
+    out_pic.height_stride = eos ? 0 : ctx->out_height_stride;
+    out_pic.pixel_format  = ctx->bit_depth > 8 ?
+                            HI_PIXEL_FORMAT_YUV_SEMI_PLANNER_420_10BIT :
+                            HI_PIXEL_FORMAT_YUV_SEMIPLANAR_420;
+    out_pic.vir_addr      = (uint64_t)(uintptr_t)out_buf;
+    out_pic.buffer_size   = out_buf ? ctx->out_buffer_size : 0;
+
+    ret = hi_mpi_vdec_send_stream(ctx->chn, &stream, &out_pic, 1000 /* ms */);
+    if (ret != 0) {
+        av_log(ctx->avctx, AV_LOG_ERROR,
+               "ascenddec: send_stream failed: 0x%x (len=%u w=%u h=%u "
+               "wstride=%u hstride=%u fmt=%d bufsize=%u eos=%d)\n",
+               ret, stream.len, out_pic.width, out_pic.height,
+               out_pic.width_stride, out_pic.height_stride,
+               out_pic.pixel_format, out_pic.buffer_size,
+               stream.end_of_stream);
+        /* A failed send did not transfer buffer ownership to the VDEC,
+         * so hand the output buffer back to the free stack. The raw CANN
+         * code is logged but not returned to the caller. */
+        ascend_return_out_buffer(ctx, out_buf);
+        return AVERROR_EXTERNAL;
+    }
+
+    return 0;
+}
+
+/* Fetch one decoded frame into AVFrame.
+ * Returns 0 on success, AVERROR(EAGAIN) if nothing is ready. */
+static int ascend_get_frame(AVCodecContext *avctx, AVFrame *frame, int timeout_ms)
+{
+    AscendDecContext *ctx = avctx->priv_data;
+    hi_video_frame_info fi = { 0 };
+    hi_vdec_supplement_info supp = { 0 };
+    hi_vdec_stream stream = { 0 };
+    int64_t pts;
+    uint64_t send_seq;
+    uint8_t *host;
+    size_t stride, frame_size;
+    int ret;
+
+    ret = ascend_bind_context(ctx);
+    if (ret < 0)
+        return ret;
+
+    ret = hi_mpi_vdec_get_frame(ctx->chn, &fi, &supp, &stream, timeout_ms);
+    if (ret != 0) {
+        /* Transient "nothing ready" conditions; anything else is a real
+         * error that must not be swallowed as EAGAIN. Notably UNEXIST
+         * ("channel does not exist") is permanent and must propagate,
+         * otherwise a caller without new packets but with a full output
+         * pool would wait forever. */
+        if (ret == HI_ERR_VDEC_BUF_EMPTY || ret == HI_ERR_VDEC_BUF_FULL ||
+            ret == HI_ERR_VDEC_BUSY || ret == HI_ERR_VDEC_SYS_NOT_READY)
+            return AVERROR(EAGAIN);
+        av_log(avctx, AV_LOG_ERROR, "ascenddec: hi_mpi_vdec_get_frame failed: 0x%x\n", ret);
+        return AVERROR_EXTERNAL;
+    }
+
+    /* One result consumed from the channel, whatever it turns out to be
+     * (see results_fetched for why this matters at EOF). */
+    ctx->results_fetched++;
+
+    if (fi.v_frame.frame_flag == 2 /* no picture, e.g. second field */) {
+        ascend_return_out_buffer(ctx, fi.v_frame.virt_addr[0]);
+        hi_mpi_vdec_release_frame(ctx->chn, &fi);
+        return AVERROR(EAGAIN);
+    }
+    if (fi.v_frame.frame_flag != 0 && !fi.v_frame.virt_addr[0]) {
+        /* Decode-error notice without a usable picture (observed as the
+         * first result after a channel recreate, before the refeed
+         * sequence reaches the IDR). Drop it like a transient result;
+         * permanent failures surface via UNEXIST or the drain timeout. */
+        av_log(avctx, AV_LOG_VERBOSE, "ascenddec: frame_flag = %u notice\n",
+               fi.v_frame.frame_flag);
+        ascend_return_out_buffer(ctx, fi.v_frame.virt_addr[0]);
+        hi_mpi_vdec_release_frame(ctx->chn, &fi);
+        return AVERROR(EAGAIN);
+    }
+    if (fi.v_frame.frame_flag != 0)
+        av_log(avctx, AV_LOG_WARNING, "ascenddec: frame_flag = %u (decode error)\n",
+               fi.v_frame.frame_flag);
+
+    /* Field-coded HEVC (each access unit carries one field) is not
+     * supported by this decoder: the VDEC returns pictures whose content
+     * does not match software decoding, and refusing loudly is the only
+     * way to keep callers from consuming silently wrong output. The
+     * picture is released with its buffer so accounting stays balanced;
+     * the channel is torn down so no further frames are produced. */
+    if (avctx->codec_id == AV_CODEC_ID_HEVC &&
+        fi.v_frame.field == HI_VIDEO_FIELD_INTERLACED) {
+        av_log(avctx, AV_LOG_ERROR,
+               "ascenddec: field-coded (interlaced) HEVC is not supported "
+               "by this decoder; use software decoding for this stream\n");
+        ascend_return_out_buffer(ctx, fi.v_frame.virt_addr[0]);
+        hi_mpi_vdec_release_frame(ctx->chn, &fi);
+        ascend_channel_destroy(avctx);
+        ctx->hevc_interlaced_rejected = 1;
+        return AVERROR_EXTERNAL;
+    }
+
+    send_seq   = fi.v_frame.pts;
+    stride     = fi.v_frame.width_stride[0];
+    ctx->bit_depth_out = ctx->bit_depth > 8 ? 2 : 1;
+    frame_size = stride * (size_t)ctx->out_height_stride * 3 / 2 *
+                 ctx->bit_depth_out;
+
+    /* Map the echoed sequence number back to the packet pts. Packets
+     * without a pts (raw elementary streams) yield AV_NOPTS_VALUE here
+     * and the caller (the CLI) extrapolates, exactly like with software
+     * decoders; inventing timestamps here would silently mislabel the
+     * frame rate. */
+    {
+        int64_t pkt_pts = AV_NOPTS_VALUE;
+
+        /* Valid window: the LUT slot for seq must not have been
+         * overwritten by a newer send. */
+        if (send_seq + ASCEND_PTS_LUT_SIZE >= ctx->sends && send_seq < ctx->sends)
+            pkt_pts = ctx->pkt_ts[send_seq & (ASCEND_PTS_LUT_SIZE - 1)].pts;
+        pts = pkt_pts;
+    }
+    /* pkt_dts: the dts of the packet that triggered returning this frame
+     * (frame.h) — the generic layer sets exactly this for software
+     * decoders from the packet consumed at output time. */
+
+    if (fi.v_frame.width <= 0 || fi.v_frame.height <= 0 || stride < (size_t)fi.v_frame.width ||
+        !fi.v_frame.virt_addr[0]) {
+        av_log(avctx, AV_LOG_ERROR, "ascenddec: invalid frame from decoder\n");
+        ascend_return_out_buffer(ctx, fi.v_frame.virt_addr[0]);
+        hi_mpi_vdec_release_frame(ctx->chn, &fi);
+        return AVERROR_EXTERNAL;
+    }
+    /* A picture whose geometry differs from the channel configuration can
+     * only come from a stream that changed resolution mid-flight: the
+     * generic decode layer does not update avctx->coded_width, so the
+     * stream geometry is tracked through chn_status, which the VDEC
+     * updates the moment it decodes the new SPS (R18 P0-4). On a change
+     * the channel is destroyed and recreated for the new size and the
+     * cached parameter sets + IDR AU are re-fed so the following P/B
+     * frames have a reference chain; pictures decoded with the previous
+     * layout are dropped instead of being handed out silently wrong. */
+    {
+        hi_vdec_chn_status gst = { 0 };
+        int gok = hi_mpi_vdec_query_status(ctx->chn, &gst) == 0;
+
+        if (gok && (gst.width || gst.height) &&
+            ((int)gst.width != ctx->coded_width ||
+             (int)gst.height != ctx->coded_height)) {
+            av_log(avctx, AV_LOG_VERBOSE,
+                   "ascenddec: stream geometry changed to %ux%u (channel %dx%d), recreating channel\n",
+                   gst.width, gst.height, ctx->coded_width, ctx->coded_height);
+            ascend_return_out_buffer(ctx, fi.v_frame.virt_addr[0]);
+            hi_mpi_vdec_release_frame(ctx->chn, &fi);
+            ascend_channel_destroy(avctx);
+            if (ctx->chn_parked)
+                return AVERROR_EXTERNAL;
+            ctx->coded_width  = (int)gst.width;
+            ctx->coded_height = (int)gst.height;
+            ctx->eos_sent       = 0;
+            ctx->drain_fail_cnt = 0;
+            ctx->sends          = 0;
+            ctx->results_fetched = 0;
+            ctx->needs_reseed   = 1;
+            return AVERROR(EAGAIN);
+        }
+        if (gok && (gst.width || gst.height) &&
+            (int)gst.width == ctx->coded_width &&
+            (int)gst.height == ctx->coded_height &&
+            (fi.v_frame.width != ctx->coded_width ||
+             fi.v_frame.height != ctx->coded_height)) {
+            /* Stream geometry matches the channel but this PICTURE was
+             * decoded with the previous layout (a stale result left in
+             * the hardware right after a recreate). It must not reach
+             * the caller: drop it and keep draining; the reseeded IDR
+             * and following AUs decode at the new geometry. */
+            av_log(avctx, AV_LOG_VERBOSE,
+                   "ascenddec: dropping stale-geometry picture %dx%d (channel %dx%d)\n",
+                   fi.v_frame.width, fi.v_frame.height,
+                   ctx->coded_width, ctx->coded_height);
+            ascend_return_out_buffer(ctx, fi.v_frame.virt_addr[0]);
+            hi_mpi_vdec_release_frame(ctx->chn, &fi);
+            return AVERROR(EAGAIN);
+        }
+        if (!gok && (fi.v_frame.width != ctx->coded_width ||
+                     fi.v_frame.height != ctx->coded_height)) {
+            /* Status unavailable: fall back to the picture geometry. */
+            av_log(avctx, AV_LOG_VERBOSE,
+                   "ascenddec: resolution change %dx%d -> %dx%d (status unavailable), recreating channel\n",
+                   ctx->coded_width, ctx->coded_height,
+                   fi.v_frame.width, fi.v_frame.height);
+            ascend_return_out_buffer(ctx, fi.v_frame.virt_addr[0]);
+            hi_mpi_vdec_release_frame(ctx->chn, &fi);
+            ascend_channel_destroy(avctx);
+            if (ctx->chn_parked)
+                return AVERROR_EXTERNAL;
+            ctx->coded_width  = fi.v_frame.width;
+            ctx->coded_height = fi.v_frame.height;
+            ctx->eos_sent       = 0;
+            ctx->drain_fail_cnt = 0;
+            ctx->sends          = 0;
+            ctx->results_fetched = 0;
+            ctx->needs_reseed   = 1;
+            return AVERROR(EAGAIN);
+        }
+    }
+
+    ret = ff_decode_frame_props(avctx, frame);
+    if (ret < 0) {
+        ascend_return_out_buffer(ctx, fi.v_frame.virt_addr[0]);
+        hi_mpi_vdec_release_frame(ctx->chn, &fi);
+        return ret;
+    }
+
+    /* Interlaced content. The VDEC reports the frame/field layout in
+     * v_frame.field: HI_VIDEO_FIELD_INTERLACED (two fields in one
+     * buffer) vs HI_VIDEO_FIELD_FRAME (progressive). Without this the
+     * AVFrame looks progressive and deinterlacing filters that act on
+     * the interlaced flag (e.g. yadif=deint=interlaced) silently skip
+     * their work.
+     *
+     * Field ORDER (top vs bottom first) is not exposed by this CANN
+     * release, so AV_FRAME_FLAG_TOP_FIELD_FIRST is left unset (bottom
+     * first, the flag's default). TFF streams can be handled by the
+     * caller with an explicit yadif parity override; passing field order
+     * through would require parsing the bitstream, which is out of
+     * scope for this decoder. */
+    if (fi.v_frame.field == HI_VIDEO_FIELD_INTERLACED)
+        frame->flags |= AV_FRAME_FLAG_INTERLACED;
+
+    frame->buf[0] = av_buffer_alloc(frame_size);
+    if (!frame->buf[0]) {
+        ascend_return_out_buffer(ctx, fi.v_frame.virt_addr[0]);
+        hi_mpi_vdec_release_frame(ctx->chn, &fi);
+        return AVERROR(ENOMEM);
+    }
+    host = frame->buf[0]->data;
+
+    {
+        /* Single contiguous copy of the strided buffer; the AVFrame keeps
+         * the padded linesize, trailing padding is never read. */
+        if (aclrtMemcpy(host, frame_size,
+                        (void *)(uintptr_t)fi.v_frame.virt_addr[0], frame_size,
+                        ACL_MEMCPY_DEVICE_TO_HOST) != 0)
+            goto copy_fail;
+    }
+
+    ascend_return_out_buffer(ctx, fi.v_frame.virt_addr[0]);
+    hi_mpi_vdec_release_frame(ctx->chn, &fi);
+
+    frame->data[0]     = host;
+    frame->data[1]     = host + stride * (size_t)ctx->out_height_stride *
+                         ctx->bit_depth_out;
+    frame->linesize[0] = stride * ctx->bit_depth_out;
+    frame->linesize[1] = stride * ctx->bit_depth_out;
+    frame->width       = fi.v_frame.width;
+    frame->height      = fi.v_frame.height;
+    frame->format      = ctx->bit_depth > 8 ? AV_PIX_FMT_P010LE :
+                                              AV_PIX_FMT_NV12;
+    frame->pts         = pts;
+    /* The dts of the packet this frame came from (frame.h); with B frames
+     * it differs from the most recently fed packet's dts, hence the LUT. */
+    frame->pkt_dts     = ctx->trigger_dts;
+    frame->duration    = send_seq + ASCEND_PTS_LUT_SIZE >= ctx->sends &&
+                         send_seq < ctx->sends ?
+                         ctx->pkt_ts[send_seq & (ASCEND_PTS_LUT_SIZE - 1)].duration : 0;
+    return 0;
+
+copy_fail:
+    av_log(avctx, AV_LOG_ERROR, "ascenddec: frame copy failed\n");
+    av_buffer_unref(&frame->buf[0]);
+    ascend_return_out_buffer(ctx, fi.v_frame.virt_addr[0]);
+    hi_mpi_vdec_release_frame(ctx->chn, &fi);
+    return AVERROR_EXTERNAL;
+}
+
+static int ascend_receive_frame(AVCodecContext *avctx, AVFrame *frame)
+{
+    AscendDecContext *ctx = avctx->priv_data;
+    int ret;
+
+    if (ctx->hevc_interlaced_rejected)
+        return AVERROR_EOF;
+
+    if (!ctx->chn_created) {
+        if (avctx->coded_width <= 0 || avctx->coded_height <= 0)
+            return AVERROR(EAGAIN);
+        ret = ascend_channel_create(avctx);
+        if (ret < 0)
+            return ret;
+    }
+
+    for (;;) {
+        /* hi_mpi_vdec_get_frame treats a zero timeout as "block forever",
+         * so always poll with a small finite timeout. */
+        int timeout = ctx->eos_sent ? 20 : (ctx->out_free_count == 0 ? 100 : 1);
+
+        ret = ascend_get_frame(avctx, frame, timeout);
+        if (ret == 0)
+            return 0;
+        if (ret != AVERROR(EAGAIN))
+            return ret;
+
+        if (ctx->eos_sent) {
+            hi_vdec_chn_status st = { 0 };
+
+            /* EOS completion check. left_decoded_frames cannot be used
+             * directly: chn reset on the 310P leaves it stale (it still
+             * shows pre-reset frames). Instead combine two counters that
+             * ARE cleared by reset with our own fetch count, which is
+             * aligned to the same channel-generation boundaries:
+             *
+             *   recv_stream_frames == dec_stream_frames
+             *       the VDEC finished every accepted access unit;
+             *   results_fetched >= dec_stream_frames
+             *       and we have taken every result back out of the
+             *       channel with hi_mpi_vdec_get_frame() (pictures and
+             *       frame_flag != 0 notices alike). "Finished" does not
+             *       imply "fetched": a single delayed get_frame() after
+             *       EOS used to leave up to a pool-depth worth of results
+             *       in the hardware while we returned EOF (silently
+             *       dropping the tail frames). */
+            if (ascend_bind_context(ctx) != 0)
+                return AVERROR_EXTERNAL;
+            if (hi_mpi_vdec_query_status(ctx->chn, &st) == 0 &&
+                st.recv_stream_frames == st.dec_stream_frames &&
+                ctx->results_fetched >= (uint64_t)st.dec_stream_frames)
+                return AVERROR_EOF;
+            if (++ctx->drain_fail_cnt > 200) {
+                av_log(avctx, AV_LOG_ERROR,
+                       "ascenddec: EOS drain timed out "
+                       "(recv=%u dec=%u left_stream=%u left_decoded=%u)\n",
+                       st.recv_stream_frames, st.dec_stream_frames,
+                       st.left_stream_frames, st.left_decoded_frames);
+                return AVERROR_EXTERNAL;
+            }
+            continue;
+        }
+
+        if (ctx->out_free_count == 0)
+            continue; /* drained above with a timeout until a buffer frees up */
+
+        if (ctx->in_flight_count >= ASCEND_IN_FLIGHT_SIZE)
+            continue; /* decoder stalled; drain above until inputs are consumed */
+
+        if (ctx->hevc_interlaced_rejected)
+            return AVERROR_EOF;
+
+        ret = ff_decode_get_packet(avctx, ctx->pkt);
+        if (ret == 0 && ctx->eos_sent) {
+            /* Reusable-stream scenarios (stream_loop) feed a new stream
+             * without a flush; reopen draining and continue decoding. */
+            av_log(avctx, AV_LOG_VERBOSE, "ascenddec: input resumed after EOS\n");
+            ctx->eos_sent       = 0;
+            ctx->drain_fail_cnt = 0;
+        }
+        if (ret == AVERROR_EOF) {
+            ret = ascend_send_stream(ctx, ctx->eos_buf, 0, 0, 1);
+            if (ret != 0) {
+                av_log(avctx, AV_LOG_ERROR, "ascenddec: EOS send failed: 0x%x\n", ret);
+                return AVERROR_EXTERNAL;
+            }
+            ctx->eos_sent = 1;
+            ctx->drain_fail_cnt = 0;
+            continue;
+        }
+        if (ret < 0)
+            return ret;
+
+        {
+            void *in_buf = NULL;
+            const int len = ctx->pkt->size;
+
+            /* Keep a copy of the parameter sets only (SPS/PPS/VPS NALs,
+             * slice data stripped) and of the last IDR AU so a channel
+             * recreated after a resolution change can be re-seeded
+             * (R18 P0-4). */
+            if (len > 0 && len <= 1 << 20) {
+                if (ascend_au_has_param_sets(avctx, ctx->pkt->data, len)) {
+                    int plen = 0;
+                    uint8_t *ps = ascend_extract_param_sets(avctx, ctx->pkt->data,
+                                                            len, &plen);
+                    if (ps) {
+                        av_freep(&ctx->param_set_au);
+                        ctx->param_set_au      = ps;
+                        ctx->param_set_au_size = plen;
+                    }
+                }
+                if (ascend_au_is_idr(avctx, ctx->pkt->data, len)) {
+                    av_freep(&ctx->idr_au);
+                    ctx->idr_au = av_memdup(ctx->pkt->data, len);
+                    if (ctx->idr_au)
+                        ctx->idr_au_size = len;
+                }
+            }
+            /* Before the first packet after a geometry-change recreate,
+             * prepend the cached parameter sets: the new channel has no
+             * decoder state and the in-stream parameter sets have
+             * already passed by. */
+            if (ctx->needs_reseed) {
+                ret = 0;
+                if (ctx->param_set_au)
+                    ret = ascend_reseed_send(ctx, ctx->param_set_au,
+                                             ctx->param_set_au_size);
+                if (ret == 0 && ctx->idr_au)
+                    ret = ascend_reseed_send(ctx, ctx->idr_au,
+                                             ctx->idr_au_size);
+                if (ret != 0) {
+                    av_log(avctx, AV_LOG_ERROR,
+                           "ascenddec: reseed send failed: 0x%x\n", ret);
+                    av_packet_unref(ctx->pkt);
+                    return ret;
+                }
+                if (ctx->param_set_au || ctx->idr_au)
+                    av_log(avctx, AV_LOG_VERBOSE,
+                           "ascenddec: reseeded channel (ps=%d bytes, idr=%d bytes)\n",
+                           ctx->param_set_au_size, ctx->idr_au_size);
+            }
+            ctx->needs_reseed = 0;
+
+            if (hi_mpi_dvpp_malloc(ctx->device_id, &in_buf,
+                                   FFMAX(len, 1)) != 0) {
+                av_log(avctx, AV_LOG_ERROR, "ascenddec: input dvpp_malloc failed\n");
+                av_packet_unref(ctx->pkt);
+                return AVERROR(ENOMEM);
+            }
+            if (len > 0 &&
+                aclrtMemcpy(in_buf, len, ctx->pkt->data, len,
+                            ACL_MEMCPY_HOST_TO_DEVICE) != 0) {
+                av_log(avctx, AV_LOG_ERROR, "ascenddec: input copy failed\n");
+                hi_mpi_dvpp_free(in_buf);
+                av_packet_unref(ctx->pkt);
+                return AVERROR_EXTERNAL;
+            }
+
+            /* Send the sequence number as the stream pts; the VDEC echoes
+             * it back on the decoded frame and ascend_get_frame() maps it
+             * through pts_lut. The actual packet pts (or NOPTS) is stored
+             * in the LUT keyed by the same number. */
+            ctx->pkt_ts[ctx->sends & (ASCEND_PTS_LUT_SIZE - 1)].pts =
+                ctx->pkt->pts;
+            ctx->pkt_ts[ctx->sends & (ASCEND_PTS_LUT_SIZE - 1)].duration =
+                ctx->pkt->duration;
+            /* Every packet pulled may become the "triggering packet" of a
+             * future frame: remember its dts for the frames still in the
+             * hardware pipeline (frame.h pkt_dts semantics, same as the
+             * generic layer provides for software decoders). */
+            ctx->trigger_dts = ctx->pkt->dts;
+            ret = ascend_send_stream(ctx, in_buf, len, ctx->sends, 0);
+            av_packet_unref(ctx->pkt);
+            if (ret != 0) {
+                av_log(avctx, AV_LOG_ERROR, "ascenddec: send_stream failed: 0x%x\n", ret);
+                hi_mpi_dvpp_free(in_buf);
+                return AVERROR_EXTERNAL;
+            }
+            ctx->in_flight[ctx->in_flight_count].buf = in_buf;
+            ctx->in_flight[ctx->in_flight_count].send_index = ctx->sends++;
+            ctx->in_flight[ctx->in_flight_count].pts      = ctx->pkt->pts;
+            ctx->in_flight[ctx->in_flight_count].dts      = ctx->pkt->dts;
+            ctx->in_flight[ctx->in_flight_count].duration = ctx->pkt->duration;
+            ctx->in_flight[ctx->in_flight_count].len      = len;
+            ctx->in_flight_count++;
+        }
+        ascend_free_consumed_inputs(avctx);
+    }
+}
+
+static av_cold int ascend_decode_close(AVCodecContext *avctx)
+{
+    AscendDecContext *ctx = avctx->priv_data;
+
+    /* Order matters: the channel must be gone before the DVPP buffers it
+     * referenced are freed, and DVPP sys must be alive for the frees. */
+    ascend_channel_destroy(avctx);
+    ascend_release_device(avctx);
+    ascend_context_destroy(avctx);
+    if (ctx->global_inited) {
+        ascend_global_uninit(ctx->device_id);
+        ctx->global_inited = 0;
+    }
+
+    av_freep(&ctx->param_set_au);
+    ctx->param_set_au_size = 0;
+    av_freep(&ctx->idr_au);
+    ctx->idr_au_size = 0;
+    av_packet_free(&ctx->pkt);
+    return 0;
+}
+
+static void ascend_decode_flush(AVCodecContext *avctx)
+{
+    AscendDecContext *ctx = avctx->priv_data;
+    int ret;
+
+    if (!ctx->chn_created)
+        return;
+    if (ascend_bind_context(ctx) != 0)
+        return;
+    ret = hi_mpi_vdec_stop_recv_stream(ctx->chn);
+    if (ret == 0)
+        ret = hi_mpi_vdec_reset_chn(ctx->chn);
+    if (ret == 0) {
+        /* reset drops all hardware references; free the buffers now. */
+        for (int i = 0; i < ctx->in_flight_count; i++)
+            hi_mpi_dvpp_free(ctx->in_flight[i].buf);
+        ctx->in_flight_count = 0;
+        ret = hi_mpi_vdec_start_recv_stream(ctx->chn);
+    }
+    if (ret != 0) {
+        /* Channel is in an unknown state: tear it down completely.
+         * The next receive_frame() call rebuilds it. */
+        av_log(avctx, AV_LOG_WARNING, "ascenddec: flush reset failed: 0x%x, recreating channel\n", ret);
+        ascend_channel_destroy(avctx);
+    }
+    /* The channel dropped every buffer reference (via reset or destroy),
+     * so the whole pool is free again; out_free_stack was stale. The
+     * reset also restarts the CANN recv/dec counters from zero, so our
+     * fetch counter restarts with them (left_decoded_frames does NOT
+     * reset on the 310P, which is why it is not part of the EOF check). */
+    ascend_rebuild_free_stack(ctx);
+    ctx->sends           = 0;
+    ctx->results_fetched = 0;
+    ctx->eos_sent        = 0;
+    ctx->drain_fail_cnt  = 0;
+    av_packet_unref(ctx->pkt);
+}
+
+#define OFFSET(x) offsetof(AscendDecContext, x)
+#define VD (AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM)
+static const AVOption ascend_decode_options[] = {
+    { "device_id", "Ascend NPU device id (-1 = auto-pick first available)", OFFSET(device_id),
+      AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 31, VD },
+    { NULL }
+};
+
+static const AVClass ascend_decode_class = {
+    .class_name = "ascend decoder",
+    .item_name  = av_default_item_name,
+    .option     = ascend_decode_options,
+    .version    = LIBAVUTIL_VERSION_INT,
+};
+
+#define DECLARE_ASCEND_DEC(x, X, long_name)                                    \
+const FFCodec ff_##x##_ascend_decoder = {                                      \
+    .p.name          = #x "_ascend",                                           \
+    CODEC_LONG_NAME(long_name " via Ascend NPU (CANN DVPP)"),                   \
+    .p.type          = AVMEDIA_TYPE_VIDEO,                                     \
+    .p.id            = AV_CODEC_ID_##X,                                        \
+    .priv_data_size  = sizeof(AscendDecContext),                               \
+    .init            = ascend_decode_init,                                     \
+    .close           = ascend_decode_close,                                    \
+    .flush           = ascend_decode_flush,                                    \
+    FF_CODEC_RECEIVE_FRAME_CB(ascend_receive_frame),                           \
+    .p.capabilities  = AV_CODEC_CAP_HARDWARE | AV_CODEC_CAP_DELAY,             \
+    .caps_internal   = FF_CODEC_CAP_SETS_FRAME_PROPS |                         \
+                       FF_CODEC_CAP_INIT_CLEANUP,                              \
+    .p.priv_class    = &ascend_decode_class,                                   \
+    .p.wrapper_name  = "ascend",                                               \
+    .bsfs            = #x "_mp4toannexb",                                      \
+};
+
+DECLARE_ASCEND_DEC(h264, H264, "H.264")
+DECLARE_ASCEND_DEC(hevc, HEVC, "H.265")
diff --git a/libavcodec/version.h b/libavcodec/version.h
index 87b7284a95..5183deb68b 100644
--- a/libavcodec/version.h
+++ b/libavcodec/version.h
@@ -29,7 +29,7 @@
 
 #include "version_major.h"
 
-#define LIBAVCODEC_VERSION_MINOR  28
+#define LIBAVCODEC_VERSION_MINOR  29
 #define LIBAVCODEC_VERSION_MICRO 100
 
 #define LIBAVCODEC_VERSION_INT  AV_VERSION_INT(LIBAVCODEC_VERSION_MAJOR, \
-- 
2.25.1

_______________________________________________
ffmpeg-devel mailing list -- [email protected]
To unsubscribe send an email to [email protected]

Reply via email to