PR #26314 opened by mengbinghan
URL: https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/26314
Patch URL: https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/26314.patch

## Summary of changes

Add stcodec wrappers for hardware-accelerated video decoding and encoding
through the SpacemiT MPP library on SpacemiT.

- Register decoders for AVS, AVS2, H.264, HEVC, MJPEG, MPEG-2,
  MPEG-4, VC-1, VP8 and VP9.
- Register encoders for H.264, HEVC, MJPEG, VP8 and VP9.
- Support DRM PRIME and software-frame paths.
- Add configure checks and codec build integration.

MPP remains an external dependency; no MPP source code is included.

## Dependencies

- spacemit_mpp >= 1.0.0
- libdrm

MPP repository: https://github.com/spacemit-com/mpp


>From 22bc253560ca4566abb809f33ca0ef85e2b58b0d Mon Sep 17 00:00:00 2001
From: mengbinghan <[email protected]>
Date: Thu, 19 Nov 2026 15:37:07 +0800
Subject: [PATCH] avcodec: add SpacemiT MPP hardware codecs

Add stcodec wrappers for SpacemiT MPP decoding and encoding, with
DRM PRIME and software-frame paths.

Require spacemit_mpp >= 1.0.0 and libdrm.
---
 configure               |  24 +
 libavcodec/Makefile     |  16 +
 libavcodec/allcodecs.c  |  15 +
 libavcodec/stcodecdec.c | 941 ++++++++++++++++++++++++++++++++++++++++
 libavcodec/stcodecenc.c | 477 ++++++++++++++++++++
 5 files changed, 1473 insertions(+)
 create mode 100644 libavcodec/stcodecdec.c
 create mode 100644 libavcodec/stcodecenc.c

diff --git a/configure b/configure
index eed7a76aa92..f0b1f82870c 100755
--- a/configure
+++ b/configure
@@ -365,6 +365,7 @@ External library support:
   --disable-nvdec          disable Nvidia video decoding acceleration (via 
hwaccel) [autodetect]
   --disable-nvenc          disable Nvidia video encoding code [autodetect]
   --enable-rkmpp           enable Rockchip Media Process Platform code [no]
+  --enable-stcodec         enable SpacemiT Media Process Platform support [no]
   --disable-v4l2-m2m       disable V4L2 mem2mem code [autodetect]
   --disable-vaapi          disable Video Acceleration API (mainly Unix/Intel) 
code [autodetect]
   --disable-vdpau          disable Nvidia Video Decode and Presentation API 
for Unix code [autodetect]
@@ -2146,6 +2147,7 @@ EXTERNAL_LIBRARY_LIST="
     openal
     openssl
     pocketsphinx
+    stcodec
     vapoursynth
     vulkan_static
     whisper
@@ -3549,6 +3551,24 @@ wmv3_vaapi_hwaccel_select="vc1_vaapi_hwaccel"
 wmv3_vdpau_hwaccel_select="vc1_vdpau_hwaccel"
 
 # hardware-accelerated codecs
+avs_stcodec_decoder_deps="stcodec"
+avs2_stcodec_decoder_deps="stcodec"
+h264_stcodec_decoder_deps="stcodec"
+hevc_stcodec_decoder_deps="stcodec"
+mjpeg_stcodec_decoder_deps="stcodec"
+mpeg2_stcodec_decoder_deps="stcodec"
+mpeg4_stcodec_decoder_deps="stcodec"
+vc1_stcodec_decoder_deps="stcodec"
+vp8_stcodec_decoder_deps="stcodec"
+vp9_stcodec_decoder_deps="stcodec"
+h264_stcodec_encoder_deps="stcodec"
+hevc_stcodec_encoder_deps="stcodec"
+mjpeg_stcodec_encoder_deps="stcodec"
+vp8_stcodec_encoder_deps="stcodec"
+vp9_stcodec_encoder_deps="stcodec"
+h264_stcodec_decoder_select="h264_mp4toannexb_bsf"
+hevc_stcodec_decoder_select="hevc_mp4toannexb_bsf"
+
 d3d12va_encode_deps="d3d12va ID3D12VideoEncoder d3d12_encoder_feature"
 mediafoundation_deps="mftransform_h MFCreateAlignedMemoryBuffer"
 qsv_deps="libmfx"
@@ -7539,6 +7559,10 @@ enabled rkmpp             && { require_pkg_config rkmpp 
"rockchip_mpp >= 1.3.8"
                                { enabled libdrm ||
                                  die "ERROR: rkmpp requires --enable-libdrm"; }
                              }
+if enabled stcodec; then
+    enabled libdrm || die "ERROR: stcodec requires --enable-libdrm"
+    require_pkg_config stcodec "spacemit_mpp >= 1.0.0" sys/sys_api.h SYS_Init
+fi
 enabled vapoursynth       && require_headers "vapoursynth/VSScript4.h 
vapoursynth/VapourSynth4.h"
 
 if enabled gcrypt; then
diff --git a/libavcodec/Makefile b/libavcodec/Makefile
index c3da8412c60..d12db131af9 100644
--- a/libavcodec/Makefile
+++ b/libavcodec/Makefile
@@ -1165,6 +1165,22 @@ STLIBOBJS-$(CONFIG_SPDIF_MUXER)        += 
dca_sample_rate_tab.o
 OBJS-$(CONFIG_ELBG_FILTER)             += elbg.o
 
 # external codec libraries
+OBJS-$(CONFIG_AVS_STCODEC_DECODER)          += stcodecdec.o
+OBJS-$(CONFIG_AVS2_STCODEC_DECODER)         += stcodecdec.o
+OBJS-$(CONFIG_H264_STCODEC_DECODER)         += stcodecdec.o
+OBJS-$(CONFIG_HEVC_STCODEC_DECODER)         += stcodecdec.o
+OBJS-$(CONFIG_MJPEG_STCODEC_DECODER)        += stcodecdec.o
+OBJS-$(CONFIG_MPEG2_STCODEC_DECODER)        += stcodecdec.o
+OBJS-$(CONFIG_MPEG4_STCODEC_DECODER)        += stcodecdec.o
+OBJS-$(CONFIG_VC1_STCODEC_DECODER)          += stcodecdec.o
+OBJS-$(CONFIG_VP8_STCODEC_DECODER)          += stcodecdec.o
+OBJS-$(CONFIG_VP9_STCODEC_DECODER)          += stcodecdec.o
+OBJS-$(CONFIG_H264_STCODEC_ENCODER)         += stcodecenc.o
+OBJS-$(CONFIG_HEVC_STCODEC_ENCODER)         += stcodecenc.o
+OBJS-$(CONFIG_MJPEG_STCODEC_ENCODER)        += stcodecenc.o
+OBJS-$(CONFIG_VP8_STCODEC_ENCODER)          += stcodecenc.o
+OBJS-$(CONFIG_VP9_STCODEC_ENCODER)          += stcodecenc.o
+
 OBJS-$(CONFIG_AAC_AT_DECODER)             += audiotoolboxdec.o
 OBJS-$(CONFIG_AC3_AT_DECODER)             += audiotoolboxdec.o
 OBJS-$(CONFIG_ADPCM_IMA_QT_AT_DECODER)    += audiotoolboxdec.o
diff --git a/libavcodec/allcodecs.c b/libavcodec/allcodecs.c
index edbe44ecc61..c9672fce1ee 100644
--- a/libavcodec/allcodecs.c
+++ b/libavcodec/allcodecs.c
@@ -849,6 +849,21 @@ extern const FFCodec ff_idf_decoder;
 
 /* external libraries, that shouldn't be used by default if one of the
  * above is available */
+extern const FFCodec ff_avs_stcodec_decoder;
+extern const FFCodec ff_avs2_stcodec_decoder;
+extern const FFCodec ff_h264_stcodec_decoder;
+extern const FFCodec ff_hevc_stcodec_decoder;
+extern const FFCodec ff_mjpeg_stcodec_decoder;
+extern const FFCodec ff_mpeg2_stcodec_decoder;
+extern const FFCodec ff_mpeg4_stcodec_decoder;
+extern const FFCodec ff_vc1_stcodec_decoder;
+extern const FFCodec ff_vp8_stcodec_decoder;
+extern const FFCodec ff_vp9_stcodec_decoder;
+extern const FFCodec ff_h264_stcodec_encoder;
+extern const FFCodec ff_hevc_stcodec_encoder;
+extern const FFCodec ff_mjpeg_stcodec_encoder;
+extern const FFCodec ff_vp8_stcodec_encoder;
+extern const FFCodec ff_vp9_stcodec_encoder;
 extern const FFCodec ff_aac_mediacodec_decoder;
 extern const FFCodec ff_aac_mf_encoder;
 extern const FFCodec ff_ac3_mf_encoder;
diff --git a/libavcodec/stcodecdec.c b/libavcodec/stcodecdec.c
new file mode 100644
index 00000000000..3a5bb2e6684
--- /dev/null
+++ b/libavcodec/stcodecdec.c
@@ -0,0 +1,941 @@
+/*
+ * Spacemit MPP Video Decoder
+ * Copyright 2022-2023 SPACEMIT. All rights reserved.
+ *
+ * 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 <drm_fourcc.h>
+#include <errno.h>
+#include <limits.h>
+
+#include "avcodec.h"
+#include "codec_internal.h"
+#include "decode.h"
+#include "hwconfig.h"
+#include "libavutil/buffer.h"
+#include "libavutil/common.h"
+#include "libavutil/frame.h"
+#include "libavutil/hwcontext.h"
+#include "libavutil/hwcontext_drm.h"
+#include "libavutil/imgutils.h"
+#include "libavutil/log.h"
+#include "libavutil/opt.h"
+#include "libavutil/mem.h"
+#include "libavutil/time.h"
+#include "vdec/vdec_api.h"
+#include "sys/sys_api.h"
+#include "sys/vb_api.h"
+
+#define STCODEC_OUTPUT_WAIT_MS 10
+#define STCODEC_STALL_TIMEOUT_US (5 * 1000000LL)
+#define MAX_SUPPORT_WIDTH (4096)
+#define MAX_SUPPORT_HEIGHT (4096)
+#define MIN_SUPPORT_WIDTH (640)
+#define MIN_SUPPORT_HEIGHT (320)
+#define STRIDE_ALIGN (4)
+
+typedef struct {
+  S32 chnId;
+
+  int runtime_initialized;
+  int enabled;
+  int input_eof;
+  int eos_sent;
+  int output_eof;
+  int error;
+  char no_pts;
+  char first_packet;
+  char use_dts;
+
+  AVBufferRef* frames_ref;
+  AVBufferRef* device_ref;
+} STCODECDecoder;
+
+typedef struct {
+  AVClass* av_class;
+  AVBufferRef* decoder_ref;
+  AVPacket pending_pkt;
+  int pending_pkt_valid;
+
+  // AVOption parameter
+  // defalut: 1
+  // support: 1,2,4
+  int scale;
+
+  // AVOption parameter
+  // defalut: 0
+  // support: 0,90,180,270
+  int rotate;
+} STCODECDecodeContext;
+
+typedef struct {
+  AVBufferRef* decoder_ref;
+  S32 chnId;
+  UL ulBufferId;
+} STCODECFrameContext;
+
+static const enum AVPixelFormat stcodec_pix_fmts[] = {
+    AV_PIX_FMT_DRM_PRIME, AV_PIX_FMT_NV12, AV_PIX_FMT_NV21,
+    AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE,
+};
+
+static MppPixelFormat stcodec_get_pixelformat(AVCodecContext* avctx) {
+  switch (avctx->pix_fmt) {
+    case AV_PIX_FMT_NV12:
+      return MPP_PIXEL_FORMAT_NV12;
+    case AV_PIX_FMT_NV21:
+      return MPP_PIXEL_FORMAT_NV21;
+    case AV_PIX_FMT_YUV420P:
+      return MPP_PIXEL_FORMAT_I420;
+    case AV_PIX_FMT_DRM_PRIME:
+      av_log(avctx, AV_LOG_DEBUG, "sw_pix_fmt %d.\n", avctx->sw_pix_fmt);
+      switch (avctx->sw_pix_fmt) {
+        case AV_PIX_FMT_NV12:
+        case AV_PIX_FMT_NONE:
+          return MPP_PIXEL_FORMAT_NV12;
+        case AV_PIX_FMT_NV21:
+          return MPP_PIXEL_FORMAT_NV21;
+        case AV_PIX_FMT_YUV420P:
+          return MPP_PIXEL_FORMAT_I420;
+        default:
+          return MPP_PIXEL_FORMAT_NV12;
+      }
+    default:
+      av_log(avctx, AV_LOG_ERROR,
+             "stcodec supports only NV12, NV21, YUV420P and DRM_PRIME 
output.\n");
+      return MPP_PIXEL_FORMAT_UNKNOWN;
+  }
+}
+
+static MppStreamCodecType stcodec_get_codingtype(AVCodecContext* avctx) {
+  switch (avctx->codec_id) {
+    case AV_CODEC_ID_H264:
+      return MPP_STREAM_CODEC_H264;
+    case AV_CODEC_ID_HEVC:
+      return MPP_STREAM_CODEC_H265;
+    case AV_CODEC_ID_VP8:
+      return MPP_STREAM_CODEC_VP8;
+    case AV_CODEC_ID_VP9:
+      return MPP_STREAM_CODEC_VP9;
+    case AV_CODEC_ID_MJPEG:
+      return MPP_STREAM_CODEC_MJPEG;
+    case AV_CODEC_ID_VC1:
+      return MPP_STREAM_CODEC_VC1;
+    case AV_CODEC_ID_MPEG2VIDEO:
+      return MPP_STREAM_CODEC_MPEG2;
+    case AV_CODEC_ID_MPEG4:
+      return MPP_STREAM_CODEC_MPEG4;
+    case AV_CODEC_ID_AVS:
+      return MPP_STREAM_CODEC_AVS;
+    case AV_CODEC_ID_AVS2:
+      return MPP_STREAM_CODEC_AVS2;
+    default:
+      av_log(avctx, AV_LOG_ERROR, "MPP do not support this coding type.\n");
+      return MPP_STREAM_CODEC_UNKNOWN;
+  }
+}
+
+
+static int stcodec_send_data_to_decoder(AVCodecContext* avctx, uint8_t* buffer,
+                                        int size, int64_t pts, int64_t dts,
+                                        int key_frame) {
+  STCODECDecodeContext* context = avctx->priv_data;
+  STCODECDecoder* decoder = (STCODECDecoder*)context->decoder_ref->data;
+  StreamBufferInfo streamInfo;
+  int ret = 0;
+
+  memset(&streamInfo, 0, sizeof(streamInfo));
+
+  if (!buffer && 0 == size) {
+    streamInfo.bEndOfStream = 1;
+    streamInfo.u32Size = 0;
+    streamInfo.pu8Addr = NULL;
+  } else {
+    streamInfo.pu8Addr = buffer;
+    streamInfo.u32Size = size;
+    streamInfo.bEndOfStream = 0;
+
+    if (pts != AV_NOPTS_VALUE) {
+      streamInfo.u64PTS = pts;
+    } else if (dts != AV_NOPTS_VALUE) {
+      streamInfo.u64PTS = dts;
+    }
+    av_log(avctx, AV_LOG_DEBUG, "Input packet pts: %ld.\n", pts);
+  }
+
+  streamInfo.eCodecType = stcodec_get_codingtype(avctx);
+  streamInfo.bKeyFrame = key_frame;
+  /* PULL readout also recycles CAPTURE buffers. Never wait for input space
+   * on this thread: preserve the packet and drive GetFrame on backpressure. */
+  ret = VDEC_SendStream(decoder->chnId, &streamInfo, 0);
+
+  if (ret) {
+    if (ret == ERR_VDEC_BUSY || ret == ERR_VDEC_TIMEOUT) {
+      av_log(avctx, AV_LOG_DEBUG, "Buffer is full, cannot write %d bytes.\n", 
size);
+      ret = AVERROR(EAGAIN);
+    } else {
+      av_log(avctx, AV_LOG_ERROR, "VDEC_SendStream error: %d.\n", ret);
+      ret = AVERROR_EXTERNAL;
+    }
+  } else {
+    if (size && pts == AV_NOPTS_VALUE) {
+      if (dts != AV_NOPTS_VALUE)
+        decoder->use_dts = 1;
+      else
+        decoder->no_pts = 1;
+    }
+    av_log(avctx, AV_LOG_DEBUG, "Wrote %d bytes to decoder.\n", size);
+  }
+
+  return ret;
+}
+
+
+static int stcodec_close_decoder(AVCodecContext* avctx) {
+  STCODECDecodeContext* context = avctx->priv_data;
+  STCODECDecoder* decoder = context->decoder_ref ?
+      (STCODECDecoder*)context->decoder_ref->data : NULL;
+  av_log(avctx, AV_LOG_DEBUG, "Stcodec close decoder.\n");
+  av_packet_unref(&context->pending_pkt);
+  context->pending_pkt_valid = 0;
+  /* Stop hardware now. Exported AVFrames keep the disabled channel and its
+   * retired pools alive until their last release callback has run. */
+  if (decoder && decoder->enabled) {
+    int ret = VDEC_DisableChn(decoder->chnId);
+    if (ret != ERR_VDEC_OK)
+      av_log(avctx, AV_LOG_ERROR, "VDEC_DisableChn failed: %d\n", ret);
+    else
+      decoder->enabled = 0;
+  }
+  av_buffer_unref(&context->decoder_ref);
+  return 0;
+}
+
+static void stcodec_release_decoder(void* opaque, uint8_t* data) {
+  STCODECDecoder* decoder = (STCODECDecoder*)data;
+  int ret;
+
+  if (decoder->chnId >= 0) {
+    if (decoder->enabled) {
+      ret = VDEC_DisableChn(decoder->chnId);
+      if (ret != ERR_VDEC_OK) {
+        av_log(NULL, AV_LOG_ERROR, "VDEC_DisableChn(%d) failed: %d\n",
+               decoder->chnId, ret);
+        goto done;
+      }
+    }
+    ret = VDEC_DestroyChn(decoder->chnId);
+    if (ret != ERR_VDEC_OK) {
+      av_log(NULL, AV_LOG_ERROR, "VDEC_DestroyChn(%d) failed: %d\n",
+             decoder->chnId, ret);
+      goto done;
+    }
+    decoder->chnId = -1;
+  }
+
+  /* Exported frames retain decoder_ref, so all MPP frames are released here.
+   * Keep the runtime alive if channel cleanup fails instead of freeing
+   * resources that the channel may still use. */
+  if (decoder->runtime_initialized) {
+    ret = VDEC_Exit();
+    if (ret != ERR_VDEC_OK) {
+      av_log(NULL, AV_LOG_ERROR, "VDEC_Exit failed: %d\n", ret);
+      goto done;
+    }
+    ret = VB_Exit();
+    if (ret != 0) {
+      av_log(NULL, AV_LOG_ERROR, "VB_Exit failed: %d\n", ret);
+      goto done;
+    }
+    ret = SYS_Exit();
+    if (ret != 0)
+      av_log(NULL, AV_LOG_ERROR, "SYS_Exit failed: %d\n", ret);
+  }
+
+done:
+  av_buffer_unref(&decoder->frames_ref);
+  av_buffer_unref(&decoder->device_ref);
+  av_free(decoder);
+}
+
+static int stcodec_ensure_hwframes(AVCodecContext* avctx,
+                                   STCODECDecoder* decoder,
+                                   int width, int height) {
+  enum AVPixelFormat sw_format = avctx->sw_pix_fmt == AV_PIX_FMT_NONE ?
+      AV_PIX_FMT_NV12 : avctx->sw_pix_fmt;
+  AVHWFramesContext* hwframes = NULL;
+  int ret;
+
+  if (!decoder->device_ref && avctx->hw_device_ctx &&
+      ((AVHWDeviceContext*)avctx->hw_device_ctx->data)->type == 
AV_HWDEVICE_TYPE_DRM) {
+    decoder->device_ref = av_buffer_ref(avctx->hw_device_ctx);
+    if (!decoder->device_ref)
+      return AVERROR(ENOMEM);
+  }
+
+  if (!decoder->device_ref) {
+    decoder->device_ref = av_hwdevice_ctx_alloc(AV_HWDEVICE_TYPE_DRM);
+    if (!decoder->device_ref)
+      return AVERROR(ENOMEM);
+
+    ret = av_hwdevice_ctx_init(decoder->device_ref);
+    if (ret < 0) {
+      av_buffer_unref(&decoder->device_ref);
+      return ret;
+    }
+  }
+
+  if (decoder->frames_ref) {
+    hwframes = (AVHWFramesContext*)decoder->frames_ref->data;
+    if (hwframes->width == width && hwframes->height == height &&
+        hwframes->sw_format == sw_format)
+      return 0;
+    av_buffer_unref(&decoder->frames_ref);
+  }
+
+  decoder->frames_ref = av_hwframe_ctx_alloc(decoder->device_ref);
+  if (!decoder->frames_ref)
+    return AVERROR(ENOMEM);
+
+  hwframes = (AVHWFramesContext*)decoder->frames_ref->data;
+  hwframes->format = AV_PIX_FMT_DRM_PRIME;
+  hwframes->sw_format = sw_format;
+  hwframes->width = width;
+  hwframes->height = height;
+
+  ret = av_hwframe_ctx_init(decoder->frames_ref);
+  if (ret < 0)
+    av_buffer_unref(&decoder->frames_ref);
+
+  return ret;
+}
+
+static av_cold int stcodec_init_decoder(AVCodecContext* avctx) {
+  STCODECDecodeContext* context = avctx->priv_data;
+  STCODECDecoder* decoder = NULL;
+  MppStreamCodecType codectype;
+  MppPixelFormat pixfmt;
+  VdecChnAttr attr;
+  int ret;
+
+  if (avctx->width > MAX_SUPPORT_WIDTH || avctx->height > MAX_SUPPORT_HEIGHT ||
+      avctx->width < MIN_SUPPORT_WIDTH || avctx->height < MIN_SUPPORT_HEIGHT) {
+    av_log(avctx, AV_LOG_ERROR,
+           "Stcodec decoder does not support size (%d x %d)\n",
+           avctx->width, avctx->height);
+    return AVERROR(EINVAL);
+  }
+
+  codectype = stcodec_get_codingtype(avctx);
+  if (codectype == MPP_STREAM_CODEC_UNKNOWN) {
+    av_log(avctx, AV_LOG_ERROR, "Unsupported codec\n");
+    return AVERROR(EINVAL);
+  }
+
+  decoder = av_mallocz(sizeof(STCODECDecoder));
+  if (!decoder) {
+    av_log(avctx, AV_LOG_ERROR, "Failed to allocate decoder\n");
+    return AVERROR(ENOMEM);
+  }
+  decoder->chnId = -1;
+  av_packet_unref(&context->pending_pkt);
+  context->pending_pkt_valid = 0;
+
+  context->decoder_ref = av_buffer_create((uint8_t*)decoder, sizeof(*decoder),
+                                         stcodec_release_decoder, NULL,
+                                         AV_BUFFER_FLAG_READONLY);
+  if (!context->decoder_ref) {
+    av_log(avctx, AV_LOG_ERROR, "Failed to create buffer ref\n");
+    av_free(decoder);
+    return AVERROR(ENOMEM);
+  }
+
+  avctx->pix_fmt = ff_get_format(avctx, stcodec_pix_fmts);
+  if (avctx->pix_fmt == AV_PIX_FMT_NONE) {
+    av_log(avctx, AV_LOG_ERROR, "No supported pixel format\n");
+    return AVERROR(EINVAL);
+  }
+  /* ff_get_format defaults sw_pix_fmt to the last software choice (I420).
+   * DRM output uses the decoder's NV12 capture layout; do not accidentally
+   * request planar I420 because of the software fallback list ordering. */
+  if (avctx->pix_fmt == AV_PIX_FMT_DRM_PRIME)
+    avctx->sw_pix_fmt = AV_PIX_FMT_NV12;
+
+  pixfmt = stcodec_get_pixelformat(avctx);
+  if (pixfmt == MPP_PIXEL_FORMAT_UNKNOWN) {
+    av_log(avctx, AV_LOG_ERROR, "Unsupported pixel format\n");
+    return AVERROR(EINVAL);
+  }
+
+  ret = SYS_Init();
+  if (ret != 0) {
+    av_log(avctx, AV_LOG_ERROR, "SYS_Init failed: %d\n", ret);
+    return AVERROR_EXTERNAL;
+  }
+  ret = VB_Init();
+  if (ret != 0) {
+    av_log(avctx, AV_LOG_ERROR, "VB_Init failed: %d\n", ret);
+    goto fail_sys;
+  }
+  /* Requires reference-counted VDEC_Init: every success owns one reference. */
+  ret = VDEC_Init();
+  if (ret != ERR_VDEC_OK) {
+    av_log(avctx, AV_LOG_ERROR, "VDEC_Init failed: %d\n", ret);
+    goto fail_vb;
+  }
+  decoder->runtime_initialized = 1;
+
+  memset(&attr, 0, sizeof(attr));
+  attr.eCodecType = codectype;
+  attr.eOutputPixelFormat = pixfmt;
+  attr.u32Align = STRIDE_ALIGN;
+  attr.u32Width = avctx->width;
+  attr.u32Height = avctx->height;
+  attr.bDispErrorFrame = 0;
+  attr.eOutputMode = VDEC_OUTPUT_PULL;
+
+  if (context->scale != 1) {
+    /* Explicit user-requested downscale via the "scale" AVOption. */
+    attr.stScale.bScaleEnable = 1;
+    attr.stScale.u32Width = avctx->width / context->scale;
+    attr.stScale.u32Height = avctx->height / context->scale;
+    attr.stScale.u32Align = 16;
+  } else if (avctx->width >= 3840 || avctx->height >= 2160) {
+    /*
+     * Auto-downscale 4K to 1080p (matches the legacy plugin behaviour):
+     * decoding 4K at full resolution needs a very deep DPB / high memory
+     * bandwidth on this hardware and is far slower than real time. The
+     * hardware scaler downsamples during decode, cutting DPB pressure and
+     * keeping playback smooth. Output frames are delivered at the scaled
+     * size (reported back via VDEC_GetFrame's frame geometry).
+     */
+    attr.stScale.bScaleEnable = 1;
+    attr.stScale.u32Width = 1920;
+    attr.stScale.u32Height = 1080;
+    attr.stScale.u32Align = 16;
+    av_log(avctx, AV_LOG_INFO,
+           "Auto-downscaling 4K (%dx%d) to 1920x1080 for smooth decode.\n",
+           avctx->width, avctx->height);
+  }
+
+  attr.u32RotateDegree = context->rotate;
+
+  /* An exported frame can outlive its AVCodecContext. Probe free channels
+   * instead of wrapping a counter onto a channel still owned by those frames. 
*/
+  for (int chn = 0; chn < VDEC_MAX_CHN; chn++) {
+    ret = VDEC_CreateChn(chn, &attr);
+    if (ret == ERR_VDEC_OK) {
+      decoder->chnId = chn;
+      break;
+    }
+    if (ret != ERR_VDEC_BUSY)
+      break;
+  }
+  if (ret != 0) {
+    av_log(avctx, AV_LOG_ERROR, "VDEC_CreateChn failed: %d\n", ret);
+    return AVERROR_EXTERNAL;
+  }
+
+  ret = VDEC_EnableChn(decoder->chnId);
+  if (ret != 0) {
+    av_log(avctx, AV_LOG_ERROR, "VDEC_EnableChn failed: %d\n", ret);
+    return AVERROR_EXTERNAL;
+  }
+  decoder->enabled = 1;
+
+  decoder->first_packet = 1;
+
+  if (avctx->pix_fmt == AV_PIX_FMT_DRM_PRIME) {
+    ret = stcodec_ensure_hwframes(avctx, decoder, avctx->width, avctx->height);
+    if (ret < 0) {
+      av_log(avctx, AV_LOG_ERROR, "Failed to initialize DRM hwframes: %d\n",
+             ret);
+      return ret;
+    }
+  }
+
+  av_log(avctx, AV_LOG_INFO, "VDEC channel %d initialized\n", decoder->chnId);
+  return 0;
+
+  /* Partial MPP initialization. FFmpeg's close callback releases decoder_ref. 
*/
+fail_vb:
+  VB_Exit();
+fail_sys:
+  SYS_Exit();
+  return AVERROR_EXTERNAL;
+}
+
+
+static int stcodec_send_packet(AVCodecContext* avctx, const AVPacket* avpkt) {
+  STCODECDecodeContext* context = avctx->priv_data;
+  STCODECDecoder* decoder = (STCODECDecoder*)context->decoder_ref->data;
+  int ret;
+  av_log(avctx, AV_LOG_DEBUG,
+         "Start send packet, pts(%ld) dts(%ld) duration(%ld).\n", avpkt->pts,
+         avpkt->dts, avpkt->duration);
+
+  /* Only ff_decode_get_packet's EOF starts draining, not a side-data packet. 
*/
+  if (!avpkt->size)
+    return 0;
+
+  // on first packet, send extradata
+  if (decoder->first_packet) {
+    if (avctx->extradata_size) {
+      if (avctx->codec_id == AV_CODEC_ID_H264 ||
+          avctx->codec_id == AV_CODEC_ID_HEVC ||
+          avctx->codec_id == AV_CODEC_ID_MPEG4 ||
+          avctx->codec_id == AV_CODEC_ID_VC1) {
+        ret = stcodec_send_data_to_decoder(avctx, avctx->extradata,
+                                           avctx->extradata_size, avpkt->pts,
+                                           avpkt->dts, 0);
+        if (ret) {
+          av_log(avctx, AV_LOG_DEBUG,
+                 "Failed to write extradata to decoder (ret = %d).\n", ret);
+          return ret;
+        } else {
+          av_log(avctx, AV_LOG_DEBUG,
+                 "Write extradata to decoder (size = %d).\n",
+                 avctx->extradata_size);
+        }
+      }
+    }
+    decoder->first_packet = 0;
+  }
+
+  // now send packet
+  ret = stcodec_send_data_to_decoder(avctx, avpkt->data, avpkt->size,
+                                     avpkt->pts, avpkt->dts,
+                                     !!(avpkt->flags & AV_PKT_FLAG_KEY));
+  if (ret) {
+    av_log(avctx, AV_LOG_DEBUG,
+           "Failed to write data to decoder (code = %d (%s)).\n", ret,
+           av_err2str(ret));
+  } else {
+    av_log(avctx, AV_LOG_DEBUG,
+           "Write data to decoder, (size = %d) (ret = %d).\n", avpkt->size,
+           ret);
+  }
+
+  return ret;
+}
+
+static void stcodec_release_frame(void* opaque, uint8_t* data) {
+  STCODECFrameContext* framecontext = (STCODECFrameContext*)opaque;
+
+  if (framecontext) {
+    VDEC_ReleaseFrame(framecontext->chnId, framecontext->ulBufferId);
+    av_buffer_unref(&framecontext->decoder_ref);
+    av_free(framecontext);
+  }
+
+  /* data belongs to MPP; only VDEC_ReleaseFrame may release it. */
+}
+
+static void stcodec_release_drm_frame(void* opaque, uint8_t* data) {
+  stcodec_release_frame(opaque, data);
+  av_free(data);
+}
+
+static void stcodec_release_plane(void* opaque, uint8_t* data) {
+  AVBufferRef* frame_ref = opaque;
+
+  av_buffer_unref(&frame_ref);
+}
+
+static int stcodec_export_sw_frame(AVCodecContext* avctx, AVFrame* frame,
+                                   const VideoFrameInfo* frame_info) {
+  STCODECDecodeContext* context = avctx->priv_data;
+  STCODECDecoder* decoder = (STCODECDecoder*)context->decoder_ref->data;
+  const VideoFrame* video = &frame_info->stVFrame;
+  STCODECFrameContext* framecontext;
+  int planes = frame->format == AV_PIX_FMT_YUV420P ? 3 : 2;
+  int ret = AVERROR_INVALIDDATA;
+
+  if (frame->width <= 0 || frame->height <= 0 ||
+      frame_info->stVdecFrameInfo.stCommFrameInfo.ePixelFormat !=
+          stcodec_get_pixelformat(avctx) ||
+      video->u32PlaneNum < planes) {
+    av_log(avctx, AV_LOG_ERROR, "Invalid MPP software frame layout.\n");
+    goto fail;
+  }
+
+  for (int i = 0; i < planes; i++) {
+    int rows = i ? AV_CEIL_RSHIFT(frame->height, 1) : frame->height;
+    int row_bytes = av_image_get_linesize(frame->format, frame->width, i);
+
+    if (!video->ulPlaneVirAddr[i] || row_bytes <= 0 ||
+        video->u32PlaneStride[i] > INT_MAX ||
+        video->u32PlaneStride[i] < row_bytes ||
+        video->u32PlaneSize[i] <
+            (uint64_t)(rows - 1) * video->u32PlaneStride[i] + row_bytes) {
+      av_log(avctx, AV_LOG_ERROR, "Invalid MPP software frame plane %d.\n", i);
+      goto fail;
+    }
+    frame->data[i] = (uint8_t*)(uintptr_t)video->ulPlaneVirAddr[i];
+    frame->linesize[i] = video->u32PlaneStride[i];
+  }
+
+  ret = AVERROR(ENOMEM);
+  framecontext = av_mallocz(sizeof(*framecontext));
+  if (!framecontext)
+    goto fail;
+  framecontext->decoder_ref = av_buffer_ref(context->decoder_ref);
+  if (!framecontext->decoder_ref) {
+    av_free(framecontext);
+    goto fail;
+  }
+  framecontext->chnId = decoder->chnId;
+  framecontext->ulBufferId = frame_info->ulBufferId;
+
+  frame->buf[0] = av_buffer_create(frame->data[0], video->u32PlaneSize[0],
+                                   stcodec_release_frame, framecontext,
+                                   AV_BUFFER_FLAG_READONLY);
+  if (!frame->buf[0]) {
+    av_buffer_unref(&framecontext->decoder_ref);
+    av_free(framecontext);
+    goto fail;
+  }
+
+  for (int i = 1; i < planes; i++) {
+    AVBufferRef* frame_ref = av_buffer_ref(frame->buf[0]);
+    if (!frame_ref)
+      goto fail_owned;
+    frame->buf[i] = av_buffer_create(frame->data[i], video->u32PlaneSize[i],
+                                     stcodec_release_plane, frame_ref,
+                                     AV_BUFFER_FLAG_READONLY);
+    if (!frame->buf[i]) {
+      av_buffer_unref(&frame_ref);
+      goto fail_owned;
+    }
+  }
+
+  return 0;
+
+fail:
+  VDEC_ReleaseFrame(decoder->chnId, frame_info->ulBufferId);
+fail_owned:
+  av_frame_unref(frame);
+  return ret;
+}
+
+
+static int stcodec_receive_frame(AVCodecContext* avctx, AVFrame* frame) {
+  STCODECDecodeContext* context = avctx->priv_data;
+  STCODECDecoder* decoder = (STCODECDecoder*)context->decoder_ref->data;
+  VideoFrameInfo frameInfo;
+  int64_t progress = av_gettime_relative();
+  int ret;
+
+  if (decoder->error)
+    return decoder->error;
+  if (decoder->output_eof)
+    return AVERROR_EOF;
+
+  for (;;) {
+    /* PULL mode: each read also returns released buffers to CAPTURE. */
+    ret = VDEC_GetFrame(decoder->chnId, &frameInfo, 0);
+    if (ret == 0)
+      break;
+    if (ret == ERR_VDEC_EOS) {
+      av_log(avctx, AV_LOG_DEBUG, "Received EOS from decoder.\n");
+      decoder->output_eof = 1;
+      return AVERROR_EOF;
+    }
+    if (ret != ERR_VDEC_NO_FRAME && ret != ERR_VDEC_TIMEOUT) {
+      av_log(avctx, AV_LOG_ERROR, "VDEC_GetFrame failed: %d\n", ret);
+      return decoder->error = AVERROR_EXTERNAL;
+    }
+
+    if (!decoder->input_eof && !context->pending_pkt_valid) {
+      ret = ff_decode_get_packet(avctx, &context->pending_pkt);
+      if (ret == AVERROR_EOF) {
+        decoder->input_eof = 1;
+      } else if (ret < 0) {
+        return ret;
+      } else {
+        context->pending_pkt_valid = 1;
+      }
+    }
+
+    if (context->pending_pkt_valid) {
+      ret = stcodec_send_packet(avctx, &context->pending_pkt);
+      if (ret == 0) {
+        av_packet_unref(&context->pending_pkt);
+        context->pending_pkt_valid = 0;
+        progress = av_gettime_relative();
+        continue;
+      }
+      if (ret != AVERROR(EAGAIN)) {
+        av_packet_unref(&context->pending_pkt);
+        context->pending_pkt_valid = 0;
+        return decoder->error = ret;
+      }
+    } else if (decoder->input_eof && !decoder->eos_sent) {
+      ret = stcodec_send_data_to_decoder(avctx, NULL, 0, 0, 0, 0);
+      if (ret == 0) {
+        decoder->eos_sent = 1;
+        progress = av_gettime_relative();
+        continue;
+      }
+      if (ret != AVERROR(EAGAIN))
+        return decoder->error = ret;
+    }
+
+    /* Input backpressure and EOS draining both need readout, not another
+     * blocking SendStream. A retained packet (including extradata/EOS retries)
+     * is retried before consuming any newer packet from libavcodec. */
+    ret = VDEC_GetFrame(decoder->chnId, &frameInfo, STCODEC_OUTPUT_WAIT_MS);
+    if (ret == 0)
+      break;
+    if (ret == ERR_VDEC_EOS) {
+      decoder->output_eof = 1;
+      return AVERROR_EOF;
+    }
+    if (ret != ERR_VDEC_NO_FRAME && ret != ERR_VDEC_TIMEOUT) {
+      av_log(avctx, AV_LOG_ERROR, "VDEC_GetFrame failed: %d\n", ret);
+      return decoder->error = AVERROR_EXTERNAL;
+    }
+    if (av_gettime_relative() - progress >= STCODEC_STALL_TIMEOUT_US) {
+      av_log(avctx, AV_LOG_ERROR, "VDEC made no progress for 5 seconds%s.\n",
+             decoder->eos_sent ? " while draining" : " under input 
backpressure");
+      return decoder->error = AVERROR(ETIMEDOUT);
+    }
+  }
+
+  /* Successful GetFrame owns a real frame, even when it carries the LAST
+   * flag. Deliver it before reporting EOF on the next receive call. */
+  if (frameInfo.stVdecFrameInfo.bEndOfStream)
+    decoder->output_eof = 1;
+
+  frame->width = frameInfo.stVdecFrameInfo.stCommFrameInfo.u32Width;
+  frame->height = frameInfo.stVdecFrameInfo.stCommFrameInfo.u32Height;
+  frame->format = avctx->pix_fmt;
+
+  if (!decoder->no_pts) {
+    if (!decoder->use_dts) {
+      frame->pts = frameInfo.stVFrame.u64PTS;
+    } else {
+      frame->pkt_dts = frameInfo.stVFrame.u64PTS;
+    }
+  }
+
+  if (avctx->pix_fmt == AV_PIX_FMT_DRM_PRIME) {
+    AVDRMFrameDescriptor* desc = av_mallocz(sizeof(AVDRMFrameDescriptor));
+    STCODECFrameContext* framecontext = NULL;
+
+    if (!desc) {
+      VDEC_ReleaseFrame(decoder->chnId, frameInfo.ulBufferId);
+      return AVERROR(ENOMEM);
+    }
+
+    MppPixelFormat frame_pixfmt =
+        frameInfo.stVdecFrameInfo.stCommFrameInfo.ePixelFormat;
+    enum AVPixelFormat sw_pix_fmt = avctx->sw_pix_fmt == AV_PIX_FMT_NONE ?
+        AV_PIX_FMT_NV12 : avctx->sw_pix_fmt;
+
+    if (!((frame_pixfmt == MPP_PIXEL_FORMAT_NV12 &&
+           sw_pix_fmt == AV_PIX_FMT_NV12 &&
+           frameInfo.stVFrame.u32PlaneNum >= 2) ||
+          (frame_pixfmt == MPP_PIXEL_FORMAT_NV21 &&
+           sw_pix_fmt == AV_PIX_FMT_NV21 &&
+           frameInfo.stVFrame.u32PlaneNum >= 2) ||
+          (frame_pixfmt == MPP_PIXEL_FORMAT_I420 &&
+           sw_pix_fmt == AV_PIX_FMT_YUV420P &&
+           frameInfo.stVFrame.u32PlaneNum >= 3)) ||
+        frameInfo.stVFrame.u32Fd[0] == (UL)-1) {
+      av_log(avctx, AV_LOG_ERROR,
+             "DRM_PRIME zero-copy supports only NV12, NV21 and YUV420P dmabuf 
frames.\n");
+      av_free(desc);
+      VDEC_ReleaseFrame(decoder->chnId, frameInfo.ulBufferId);
+      return AVERROR(EINVAL);
+    }
+
+    framecontext = av_mallocz(sizeof(*framecontext));
+    if (!framecontext) {
+      av_free(desc);
+      VDEC_ReleaseFrame(decoder->chnId, frameInfo.ulBufferId);
+      return AVERROR(ENOMEM);
+    }
+
+    framecontext->decoder_ref = av_buffer_ref(context->decoder_ref);
+    if (!framecontext->decoder_ref) {
+      av_free(framecontext);
+      av_free(desc);
+      VDEC_ReleaseFrame(decoder->chnId, frameInfo.ulBufferId);
+      return AVERROR(ENOMEM);
+    }
+    framecontext->chnId = decoder->chnId;
+    framecontext->ulBufferId = frameInfo.ulBufferId;
+
+    desc->nb_objects = 1;
+    desc->objects[0].fd = (int)frameInfo.stVFrame.u32Fd[0];
+
+    desc->nb_layers = 1;
+    if (sw_pix_fmt == AV_PIX_FMT_NV12) {
+      desc->layers[0].format = DRM_FORMAT_NV12;
+      desc->layers[0].nb_planes = 2;
+    } else if (sw_pix_fmt == AV_PIX_FMT_NV21) {
+      desc->layers[0].format = DRM_FORMAT_NV21;
+      desc->layers[0].nb_planes = 2;
+    } else {
+      desc->layers[0].format = DRM_FORMAT_YUV420;
+      desc->layers[0].nb_planes = 3;
+    }
+
+    for (int i = 0; i < desc->layers[0].nb_planes; i++) {
+      desc->layers[0].planes[i].object_index = 0;
+      desc->layers[0].planes[i].pitch = frameInfo.stVFrame.u32PlaneStride[i];
+      desc->layers[0].planes[i].offset = i == 0 ? 0 :
+          desc->layers[0].planes[i - 1].offset +
+          frameInfo.stVFrame.u32PlaneSize[i - 1];
+      desc->objects[0].size += frameInfo.stVFrame.u32PlaneSize[i];
+    }
+
+    ret = stcodec_ensure_hwframes(avctx, decoder, frame->width, frame->height);
+    if (ret < 0) {
+      av_buffer_unref(&framecontext->decoder_ref);
+      av_free(framecontext);
+      av_free(desc);
+      VDEC_ReleaseFrame(decoder->chnId, frameInfo.ulBufferId);
+      return ret;
+    }
+
+    frame->data[0] = (uint8_t*)desc;
+    frame->buf[0] = av_buffer_create((uint8_t*)desc, sizeof(*desc),
+                                     stcodec_release_drm_frame, framecontext,
+                                     AV_BUFFER_FLAG_READONLY);
+    if (!frame->buf[0]) {
+      av_buffer_unref(&framecontext->decoder_ref);
+      av_free(framecontext);
+      av_free(desc);
+      VDEC_ReleaseFrame(decoder->chnId, frameInfo.ulBufferId);
+      return AVERROR(ENOMEM);
+    }
+
+    frame->hw_frames_ctx = av_buffer_ref(decoder->frames_ref);
+    if (!frame->hw_frames_ctx) {
+      av_buffer_unref(&frame->buf[0]);
+      return AVERROR(ENOMEM);
+    }
+  } else {
+    return stcodec_export_sw_frame(avctx, frame, &frameInfo);
+  }
+
+  return 0;
+}
+
+
+static void stcodec_flush(AVCodecContext* avctx) {
+  STCODECDecodeContext* context = avctx->priv_data;
+  STCODECDecoder* decoder = (STCODECDecoder*)context->decoder_ref->data;
+  int ret = -1;
+
+  /* ff_decode_flush_buffers() only clears packets owned by AVCodecInternal.
+   * Drop the private packet retained during MPP input backpressure as well,
+   * otherwise a pre-seek packet can be submitted into the new timeline. */
+  av_packet_unref(&context->pending_pkt);
+  context->pending_pkt_valid = 0;
+
+  av_log(avctx, AV_LOG_DEBUG, "Flush.\n");
+
+  /* MPP serializes input/readout and preserves consumer-owned buffers across
+   * flush. The same API handles seek and restart after EOS. */
+  ret = VDEC_Flush(decoder->chnId);
+  if (ret)
+    av_log(avctx, AV_LOG_ERROR, "Failed to flush VDEC Channel (code = %d).\n",
+           ret);
+
+  decoder->error = ret ? AVERROR_EXTERNAL : 0;
+  decoder->input_eof = 0;
+  decoder->eos_sent = 0;
+  decoder->output_eof = 0;
+  decoder->no_pts = 0;
+  decoder->first_packet = 1;
+  decoder->use_dts = 0;
+}
+
+static const AVCodecHWConfigInternal* const stcodec_hw_configs[] = {
+    HW_CONFIG_INTERNAL(DRM_PRIME),
+    &(const AVCodecHWConfigInternal) {
+        .public = {
+            .pix_fmt     = AV_PIX_FMT_DRM_PRIME,
+            .methods     = AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX,
+            .device_type = AV_HWDEVICE_TYPE_DRM,
+        },
+    },
+    NULL};
+
+#define OFFSET(x) offsetof(STCODECDecodeContext, x)
+#define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
+static const AVOption options[] = {{"scale",
+                                    "set the decoding scale parameter",
+                                    OFFSET(scale),
+                                    AV_OPT_TYPE_INT,
+                                    {1},
+                                    1,
+                                    4,
+                                    VD},
+                                   {"rotate",
+                                    "set the decoding rotate parameter",
+                                    OFFSET(rotate),
+                                    AV_OPT_TYPE_INT,
+                                    {0},
+                                    0,
+                                    270,
+                                    VD},
+                                   {NULL}};
+
+#define STCODEC_DEC_CLASS(NAME)                       \
+  static const AVClass stcodec_##NAME##_dec_class = { \
+      .class_name = "stcodec_" #NAME "_dec",          \
+      .option = options,                              \
+      .version = LIBAVUTIL_VERSION_INT,               \
+  };
+
+#define STCODEC_DEC(NAME, ID, BSFS)                                           \
+  STCODEC_DEC_CLASS(NAME)                                                     \
+  const FFCodec ff_##NAME##_stcodec_decoder = {                               \
+      .p.name = #NAME "_stcodec",                                             \
+      .p.long_name = NULL_IF_CONFIG_SMALL(#NAME " (stcodec decoder)"),        \
+      .p.type = AVMEDIA_TYPE_VIDEO,                                           \
+      .p.id = ID,                                                             \
+      .priv_data_size = sizeof(STCODECDecodeContext),                         \
+      .init = stcodec_init_decoder,                                           \
+      .close = stcodec_close_decoder,                                         \
+      FF_CODEC_RECEIVE_FRAME_CB(stcodec_receive_frame),                       \
+      .flush = stcodec_flush,                                                 \
+      .p.priv_class = &stcodec_##NAME##_dec_class,                            \
+      .p.capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_AVOID_PROBING |     \
+                        AV_CODEC_CAP_HARDWARE,                                \
+      CODEC_PIXFMTS_ARRAY(stcodec_pix_fmts),                                  \
+      .caps_internal = FF_CODEC_CAP_INIT_CLEANUP,                             \
+      .hw_configs = stcodec_hw_configs,                                       \
+      .bsfs = BSFS,                                                           \
+      .p.wrapper_name = "stcodec",                                            \
+  };
+
+STCODEC_DEC(h264, AV_CODEC_ID_H264, "h264_mp4toannexb")
+STCODEC_DEC(hevc, AV_CODEC_ID_HEVC, "hevc_mp4toannexb")
+STCODEC_DEC(vp8, AV_CODEC_ID_VP8, NULL)
+STCODEC_DEC(vp9, AV_CODEC_ID_VP9, NULL)
+STCODEC_DEC(mjpeg, AV_CODEC_ID_MJPEG, NULL)
+STCODEC_DEC(mpeg4, AV_CODEC_ID_MPEG4, NULL)
+STCODEC_DEC(mpeg2, AV_CODEC_ID_MPEG2VIDEO, NULL)
+STCODEC_DEC(vc1, AV_CODEC_ID_VC1, NULL)
+STCODEC_DEC(avs, AV_CODEC_ID_AVS, NULL)
+STCODEC_DEC(avs2, AV_CODEC_ID_AVS2, NULL)
diff --git a/libavcodec/stcodecenc.c b/libavcodec/stcodecenc.c
new file mode 100644
index 00000000000..c2a434aaf8f
--- /dev/null
+++ b/libavcodec/stcodecenc.c
@@ -0,0 +1,477 @@
+/*
+ * Spacemit MPP Video Encoder
+ * Copyright 2022-2023 SPACEMIT. All rights reserved.
+ *
+ * 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 <drm_fourcc.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <linux/dma-buf.h>
+#include <linux/dma-heap.h>
+#include <pthread.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/mman.h>
+#include <time.h>
+#include <unistd.h>
+
+#include "avcodec.h"
+#include "codec_internal.h"
+#include "encode.h"
+#include "hwconfig.h"
+#include "libavutil/buffer.h"
+#include "libavutil/common.h"
+#include "libavutil/frame.h"
+#include "libavutil/hwcontext.h"
+#include "libavutil/hwcontext_drm.h"
+#include "libavutil/log.h"
+#include "libavutil/opt.h"
+#include "libavutil/mem.h"
+#include "venc/venc_api.h"
+#include "sys/sys_api.h"
+#include "sys/vb_api.h"
+
+#define MAX_SUPPORT_WIDTH (4096)
+#define MAX_SUPPORT_HEIGHT (4096)
+#define MIN_SUPPORT_WIDTH (640)
+#define MIN_SUPPORT_HEIGHT (320)
+#define STRIDE_ALIGN (8)
+
+typedef struct {
+  S32 chnId;
+  int runtime_initialized;
+  int enabled;
+  int draining;
+} STCODECEncoder;
+
+typedef struct {
+  AVClass* av_class;
+  AVBufferRef* encoder_ref;
+
+  int scale;
+} STCODECEncodeContext;
+
+static MppPixelFormat stcodec_get_pixelformat(AVCodecContext* avctx) {
+  switch (avctx->pix_fmt) {
+    case AV_PIX_FMT_NV12:
+      return MPP_PIXEL_FORMAT_NV12;
+    case AV_PIX_FMT_NV21:
+      return MPP_PIXEL_FORMAT_NV21;
+    case AV_PIX_FMT_YUV420P:
+      return MPP_PIXEL_FORMAT_I420;
+    case AV_PIX_FMT_DRM_PRIME:
+      return MPP_PIXEL_FORMAT_NV12;
+    case AV_PIX_FMT_YUYV422:
+      return MPP_PIXEL_FORMAT_YUYV;
+    case AV_PIX_FMT_UYVY422:
+      return MPP_PIXEL_FORMAT_UYVY;
+    case AV_PIX_FMT_RGBA:
+      return MPP_PIXEL_FORMAT_RGBA;
+    case AV_PIX_FMT_ARGB:
+      return MPP_PIXEL_FORMAT_ARGB;
+    case AV_PIX_FMT_BGRA:
+      return MPP_PIXEL_FORMAT_BGRA;
+    case AV_PIX_FMT_ABGR:
+      return MPP_PIXEL_FORMAT_ABGR;
+    default:
+      av_log(avctx, AV_LOG_ERROR, "MPP do not support this pixel format.\n");
+      return MPP_PIXEL_FORMAT_UNKNOWN;
+  }
+}
+
+static MppStreamCodecType stcodec_get_codingtype(AVCodecContext* avctx) {
+  switch (avctx->codec_id) {
+    case AV_CODEC_ID_H264:
+      return MPP_STREAM_CODEC_H264;
+    case AV_CODEC_ID_HEVC:
+      return MPP_STREAM_CODEC_H265;
+    case AV_CODEC_ID_VP8:
+      return MPP_STREAM_CODEC_VP8;
+    case AV_CODEC_ID_VP9:
+      return MPP_STREAM_CODEC_VP9;
+    case AV_CODEC_ID_MJPEG:
+      return MPP_STREAM_CODEC_MJPEG;
+    default:
+      av_log(avctx, AV_LOG_ERROR, "MPP do not support this coding type.\n");
+      return MPP_STREAM_CODEC_UNKNOWN;
+  }
+}
+
+static int stcodec_receive_packet(AVCodecContext* avctx, AVPacket* avpkt) {
+  STCODECEncodeContext* context = avctx->priv_data;
+  STCODECEncoder* encoder = (STCODECEncoder*)context->encoder_ref->data;
+  VideoFrameInfo mppframe = {0};
+  StreamBufferInfo stream = {0};
+  AVFrame* frame = NULL;
+  int ret;
+  int packets;
+
+  if (encoder->draining)
+    goto output;
+
+  frame = av_frame_alloc();
+  if (!frame)
+    return AVERROR(ENOMEM);
+  ret = ff_encode_get_frame(avctx, frame);
+  if (ret < 0 && ret != AVERROR_EOF) {
+    av_log(avctx, AV_LOG_DEBUG, "ff_encode_get_frame fail, return.\n");
+    goto done;
+  }
+
+  mppframe.eFrameType = FRAME_TYPE_VENC;
+  mppframe.eModId = MPP_ID_VENC;
+  if (ret == AVERROR_EOF) {
+    av_log(avctx, AV_LOG_ERROR, "ff_encode_get_frame get EOS.\n");
+    mppframe.stVFrame.u32FrameFlag = MPP_FRAME_FLAG_EOS;
+  } else {
+    if (frame->format == AV_PIX_FMT_NV12 || frame->format == AV_PIX_FMT_NV21) {
+      mppframe.stVFrame.u32PlaneNum = 2;
+    } else if (frame->format == AV_PIX_FMT_YUV420P) {
+      mppframe.stVFrame.u32PlaneNum = 3;
+    } else if (frame->format == AV_PIX_FMT_YUYV422 ||
+               frame->format == AV_PIX_FMT_UYVY422 ||
+               frame->format == AV_PIX_FMT_RGBA ||
+               frame->format == AV_PIX_FMT_ARGB ||
+               frame->format == AV_PIX_FMT_BGRA ||
+               frame->format == AV_PIX_FMT_ABGR) {
+      mppframe.stVFrame.u32PlaneNum = 1;
+    } else if (frame->format == AV_PIX_FMT_DRM_PRIME) {
+      const AVDRMFrameDescriptor* desc = (const 
AVDRMFrameDescriptor*)frame->data[0];
+      U32 stride = FFALIGN(avctx->width, STRIDE_ALIGN);
+      size_t y_size = (size_t)stride * avctx->height;
+      if (!desc || desc->nb_objects != 1 || desc->nb_layers != 1 ||
+          desc->objects[0].fd < 0 ||
+          (desc->objects[0].format_modifier != DRM_FORMAT_MOD_LINEAR &&
+           desc->objects[0].format_modifier != DRM_FORMAT_MOD_INVALID) ||
+          desc->layers[0].format != DRM_FORMAT_NV12 || 
desc->layers[0].nb_planes != 2 ||
+          desc->layers[0].planes[0].object_index != 0 ||
+          desc->layers[0].planes[1].object_index != 0 ||
+          desc->layers[0].planes[0].offset != 0 ||
+          desc->layers[0].planes[1].offset != y_size ||
+          desc->layers[0].planes[0].pitch != stride ||
+          desc->layers[0].planes[1].pitch != stride ||
+          desc->objects[0].size < y_size + (size_t)stride * 
AV_CEIL_RSHIFT(avctx->height, 1)) {
+        ret = AVERROR(EINVAL);
+        goto done;
+      }
+      mppframe.stVFrame.u32PlaneNum = 2;
+      mppframe.stVFrame.u32Fd[0] = desc->objects[0].fd;
+    } else {
+      av_log(avctx, AV_LOG_ERROR, "Format(%d) not supported.", frame->format);
+      ret = AVERROR(EINVAL);
+      goto done;
+    }
+
+    if (frame->format != avctx->pix_fmt || frame->width != avctx->width ||
+        frame->height != avctx->height) {
+      ret = AVERROR(EINVAL);
+      goto done;
+    }
+    if (frame->format != AV_PIX_FMT_DRM_PRIME) {
+      for (int i = 0; i < mppframe.stVFrame.u32PlaneNum; i++) {
+        AVBufferRef* buffer = av_frame_get_plane_buffer(frame, i);
+        uintptr_t address = (uintptr_t)frame->data[i];
+        size_t offset, capacity;
+        if (!buffer || frame->linesize[i] <= 0) {
+          ret = AVERROR(EINVAL);
+          goto done;
+        }
+        offset = address - (uintptr_t)buffer->data;
+        capacity = buffer->size - offset;
+        for (int j = 0; j < mppframe.stVFrame.u32PlaneNum; j++) {
+          AVBufferRef* other = av_frame_get_plane_buffer(frame, j);
+          uintptr_t next = (uintptr_t)frame->data[j];
+          if (other && other->buffer == buffer->buffer && next > address)
+            capacity = FFMIN(capacity, next - address);
+        }
+        mppframe.stVFrame.ulPlaneVirAddr[i] = address;
+        mppframe.stVFrame.u32PlaneStride[i] = frame->linesize[i];
+        mppframe.stVFrame.u32PlaneSize[i] = FFMIN(capacity, UINT32_MAX);
+      }
+    }
+    mppframe.stVFrame.u64PTS = frame->pts;
+  }
+
+  /* Sync replaces SendInputFrame + ReturnInputFrame and ends the input 
borrow. */
+  ret = VENC_SendFrameSync(encoder->chnId, &mppframe);
+  av_frame_free(&frame);
+  if (ret != ERR_VENC_OK) {
+    av_log(avctx, AV_LOG_ERROR, "VENC_SendFrameSync failed: %d.\n", ret);
+    return AVERROR_EXTERNAL;
+  }
+  if (mppframe.stVFrame.u32FrameFlag & MPP_FRAME_FLAG_EOS)
+    encoder->draining = 1;
+
+output:
+  /* VP8/VP9 return two partitions per input frame, as in the legacy API. */
+  packets = !encoder->draining &&
+      (avctx->codec_id == AV_CODEC_ID_VP8 || avctx->codec_id == 
AV_CODEC_ID_VP9) ? 2 : 1;
+  for (int i = 0; i < packets; i++) {
+    int offset = i ? avpkt->size : 0;
+    int release_ret;
+    ret = VENC_GetStream(encoder->chnId, &stream, (U32)-1);
+    if (ret == ERR_VENC_EOS) {
+      av_log(avctx, AV_LOG_ERROR, "Get final EOS.\n");
+      return AVERROR_EOF;
+    }
+    if (ret != ERR_VENC_OK) {
+      av_log(avctx, AV_LOG_ERROR, "VENC_GetStream failed: %d.\n", ret);
+      return AVERROR_EXTERNAL;
+    }
+    ret = i ? av_grow_packet(avpkt, stream.u32Size) : av_new_packet(avpkt, 
stream.u32Size);
+    if (ret >= 0) {
+      if (!i)
+        avpkt->pts = stream.u64PTS;
+      memcpy(avpkt->data + offset, stream.pu8Addr, stream.u32Size);
+    }
+    release_ret = VENC_ReleaseStream(encoder->chnId, &stream);
+    if (ret < 0)
+      return ret;
+    if (release_ret != ERR_VENC_OK) {
+      av_log(avctx, AV_LOG_ERROR, "VENC_ReleaseStream failed: %d.\n", 
release_ret);
+      return AVERROR_EXTERNAL;
+    }
+  }
+  return 0;
+
+done:
+  av_frame_free(&frame);
+  return ret;
+}
+
+static av_cold int stcodec_close_encoder(AVCodecContext* avctx) {
+  STCODECEncodeContext* context = avctx->priv_data;
+  av_log(avctx, AV_LOG_ERROR, "Stcodec close encoder.\n");
+  av_buffer_unref(&context->encoder_ref);
+  return 0;
+}
+
+static void stcodec_release_encoder(void* opaque, uint8_t* data) {
+  STCODECEncoder* encoder = (STCODECEncoder*)data;
+  int ret;
+  av_log(NULL, AV_LOG_ERROR, "Stcodec release encoder.\n");
+
+  if (encoder->chnId >= 0) {
+    if (encoder->enabled) {
+      ret = VENC_DisableChn(encoder->chnId);
+      if (ret != ERR_VENC_OK) {
+        av_log(NULL, AV_LOG_ERROR, "VENC_DisableChn(%d) failed: %d\n",
+               encoder->chnId, ret);
+        goto done;
+      }
+      encoder->enabled = 0;
+    }
+    ret = VENC_DestroyChn(encoder->chnId);
+    if (ret != ERR_VENC_OK) {
+      av_log(NULL, AV_LOG_ERROR, "VENC_DestroyChn(%d) failed: %d\n",
+             encoder->chnId, ret);
+      goto done;
+    }
+    encoder->chnId = -1;
+  }
+
+  /* Release this instance's initialization references only after its channel
+   * is gone. Retain the runtime if resource cleanup fails. */
+  if (encoder->runtime_initialized) {
+    ret = VENC_Exit();
+    if (ret != ERR_VENC_OK) {
+      av_log(NULL, AV_LOG_ERROR, "VENC_Exit failed: %d\n", ret);
+      goto done;
+    }
+    ret = VB_Exit();
+    if (ret != 0) {
+      av_log(NULL, AV_LOG_ERROR, "VB_Exit failed: %d\n", ret);
+      goto done;
+    }
+    ret = SYS_Exit();
+    if (ret != 0)
+      av_log(NULL, AV_LOG_ERROR, "SYS_Exit failed: %d\n", ret);
+  }
+
+done:
+  av_free(encoder);
+}
+
+static av_cold int stcodec_init_encoder(AVCodecContext* avctx) {
+  STCODECEncodeContext* context = avctx->priv_data;
+  STCODECEncoder* encoder = NULL;
+  MppStreamCodecType codectype = MPP_STREAM_CODEC_UNKNOWN;
+  MppPixelFormat pixfmt = MPP_PIXEL_FORMAT_UNKNOWN;
+  VencChnAttr attr;
+  S32 chnId;
+  int ret;
+
+  if (avctx->width > MAX_SUPPORT_WIDTH || avctx->height > MAX_SUPPORT_HEIGHT ||
+      avctx->width < MIN_SUPPORT_WIDTH || avctx->height < MIN_SUPPORT_HEIGHT) {
+    av_log(avctx, AV_LOG_ERROR,
+           "Stcodec encoder do not support the size(%d x %d), too big or too "
+           "small.\n",
+           avctx->width, avctx->height);
+    return AVERROR(EINVAL);
+  }
+
+  av_log(avctx, AV_LOG_ERROR, "Use pixel format (%d).\n", avctx->pix_fmt);
+
+  // create a encoder and a ref to it
+  encoder = av_mallocz(sizeof(STCODECEncoder));
+  if (!encoder) {
+    av_log(avctx, AV_LOG_ERROR, "Failed to av_mallocz stcodec encoder.\n");
+    return AVERROR(ENOMEM);
+  }
+  encoder->chnId = -1;
+
+  context->encoder_ref =
+      av_buffer_create((uint8_t*)encoder, sizeof(*encoder),
+                       stcodec_release_encoder, NULL, AV_BUFFER_FLAG_READONLY);
+  if (!context->encoder_ref) {
+    av_log(avctx, AV_LOG_ERROR, "Failed to create ref of stcodec encoder.\n");
+    av_free(encoder);
+    return AVERROR(ENOMEM);
+  }
+
+  codectype = stcodec_get_codingtype(avctx);
+  if (codectype == MPP_STREAM_CODEC_UNKNOWN) {
+    av_log(avctx, AV_LOG_ERROR, "Unknown codec type (%d).\n", avctx->codec_id);
+    ret = AVERROR(EINVAL);
+    goto fail;
+  }
+
+  pixfmt = stcodec_get_pixelformat(avctx);
+  if (pixfmt == MPP_PIXEL_FORMAT_UNKNOWN) {
+    av_log(avctx, AV_LOG_ERROR, "Unsupported pixel format (%d).\n",
+           avctx->pix_fmt);
+    ret = AVERROR(EINVAL);
+    goto fail;
+  }
+
+  ret = SYS_Init();
+  if (ret != 0) {
+    av_log(avctx, AV_LOG_ERROR, "SYS_Init failed: %d\n", ret);
+    ret = AVERROR_EXTERNAL;
+    goto fail;
+  }
+  ret = VB_Init();
+  if (ret != 0) {
+    SYS_Exit();
+    av_log(avctx, AV_LOG_ERROR, "VB_Init failed: %d\n", ret);
+    ret = AVERROR_EXTERNAL;
+    goto fail;
+  }
+  /* Requires reference-counted VENC_Init: every success owns one reference. */
+  ret = VENC_Init();
+  if (ret != ERR_VENC_OK) {
+    VB_Exit();
+    SYS_Exit();
+    av_log(avctx, AV_LOG_ERROR, "VENC_Init failed: %d\n", ret);
+    ret = AVERROR_EXTERNAL;
+    goto fail;
+  }
+  encoder->runtime_initialized = 1;
+
+  // Configure and create the VENC channel.
+  memset(&attr, 0, sizeof(attr));
+  attr.eCodecType = codectype;
+  attr.eInputPixelFormat = pixfmt;
+  attr.u32Width = avctx->width;
+  attr.u32Height = avctx->height;
+  attr.u32Align = STRIDE_ALIGN;
+  attr.eFrameBufMode = avctx->pix_fmt == AV_PIX_FMT_DRM_PRIME ?
+      VENC_FRAME_BUF_DMABUF_EXTERNAL : VENC_FRAME_BUF_USERPTR_EXTERNAL;
+
+  for (chnId = 0; chnId < VENC_MAX_CHN; chnId++) {
+    ret = VENC_CreateChn(chnId, &attr);
+    if (ret != ERR_VENC_BUSY)
+      break;
+  }
+  if (ret != ERR_VENC_OK) {
+    av_log(avctx, AV_LOG_ERROR, "VENC_CreateChn failed: %d.\n", ret);
+    ret = AVERROR_EXTERNAL;
+    goto fail;
+  }
+
+  encoder->chnId = chnId;
+  ret = VENC_EnableChn(encoder->chnId);
+  if (ret != ERR_VENC_OK) {
+    av_log(avctx, AV_LOG_ERROR, "VENC_EnableChn failed: %d.\n", ret);
+    ret = AVERROR_EXTERNAL;
+    goto fail;
+  }
+
+  encoder->enabled = 1;
+
+  av_log(avctx, AV_LOG_ERROR, "Initialized successfully.\n");
+  return 0;
+
+fail:
+  av_log(avctx, AV_LOG_ERROR, "Failed to initialize stcodec encoder.\n");
+  stcodec_close_encoder(avctx);
+  return ret;
+}
+
+static const AVCodecHWConfigInternal* const stcodec_hw_configs[] = {
+    HW_CONFIG_INTERNAL(DRM_PRIME), NULL};
+
+#define OFFSET(x) offsetof(STCODECEncodeContext, x)
+#define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
+static const AVOption options[] = {{"scale",
+                                    "set the decoding scale parameter",
+                                    OFFSET(scale),
+                                    AV_OPT_TYPE_INT,
+                                    {1},
+                                    1,
+                                    4,
+                                    VE},
+                                   {NULL}};
+
+#define STCODEC_ENC_CLASS(NAME)                       \
+  static const AVClass stcodec_##NAME##_enc_class = { \
+      .class_name = "stcodec_" #NAME "_enc",          \
+      .option = options,                              \
+      .version = LIBAVUTIL_VERSION_INT,               \
+  };
+
+#define STCODEC_ENC(NAME, ID)                                             \
+  STCODEC_ENC_CLASS(NAME)                                                 \
+  const FFCodec ff_##NAME##_stcodec_encoder = {                           \
+      .p.name = #NAME "_stcodec",                                         \
+      .p.long_name = NULL_IF_CONFIG_SMALL(#NAME " (stcodec encoder)"),    \
+      .p.type = AVMEDIA_TYPE_VIDEO,                                       \
+      .p.id = ID,                                                         \
+      .priv_data_size = sizeof(STCODECEncodeContext),                     \
+      .p.priv_class = &stcodec_##NAME##_enc_class,                        \
+      .init = stcodec_init_encoder,                                       \
+      FF_CODEC_RECEIVE_PACKET_CB(stcodec_receive_packet),                 \
+      .close = stcodec_close_encoder,                                     \
+      .p.capabilities = AV_CODEC_CAP_HARDWARE | AV_CODEC_CAP_DELAY,       \
+      .p.wrapper_name = "stcodec",                                        \
+      CODEC_PIXFMTS(                                                     \
+              AV_PIX_FMT_DRM_PRIME, AV_PIX_FMT_NV12, AV_PIX_FMT_NV21,     \
+              AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUYV422, AV_PIX_FMT_UYVY422, \
+              AV_PIX_FMT_RGBA, AV_PIX_FMT_ARGB, AV_PIX_FMT_BGRA,          \
+              AV_PIX_FMT_ABGR),                                          \
+      .hw_configs = stcodec_hw_configs,                                   \
+  };
+
+STCODEC_ENC(h264, AV_CODEC_ID_H264)
+STCODEC_ENC(hevc, AV_CODEC_ID_HEVC)
+STCODEC_ENC(mjpeg, AV_CODEC_ID_MJPEG)
+STCODEC_ENC(vp8, AV_CODEC_ID_VP8)
+STCODEC_ENC(vp9, AV_CODEC_ID_VP9)
-- 
2.54.1

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

Reply via email to