You need to enable JavaScript to run this app. Python Gstreamer取Gst.Fraction属性报TypeError 未知类型GstFraction
优惠活动
大模型
产品
解决方案
定价
更多

Python Gstreamer取Gst.Fraction属性报TypeError 未知类型GstFraction

问题根因

触发TypeError: unknown type GstFraction的核心原因是,PyGObject对Gst自定义值类型的通用接口适配存在历史遗留问题:通过Gst.Structure的通用列表读取方法拿到的数组元素,是未经过Python类型绑定转换的底层C结构体值,直接调用get_nth取值时,绑定层无法识别Gst.Fraction的类型定义,就会抛出类型未知的错误。这个问题在GStreamer 1.14系列的Python绑定中长期存在,根源是早期版本没有为fraction类型注册通用的类型转换逻辑。

适配Gst.Fraction类型的正确取值方案

不需要更换GStreamer版本,只要针对fraction类型的字段,使用Gst.Value暴露的专用解析接口替代通用数组取值方法,即可正常拿到所有能力参数。

改写后的可运行代码

import gi

gi.require_version('Gst', '1.0')
from gi.repository import Gst

Gst.init(None)

caps = Gst.Caps.from_string('video/x-h264,width=640,height=480,framerate={30/1, 20/1, 15/1, 1/1}')
structure = caps.get_structure(0)

width = structure.get_int('width').value
height = structure.get_int('height').value

# 读取fraction类型的字段列表
framerate_field = structure.get_list('framerate')
for raw_fraction in framerate_field.array:
    # 用专用接口解析分数分子、分母
    numerator = Gst.Value.get_fraction_numerator(raw_fraction)
    denominator = Gst.Value.get_fraction_denominator(raw_fraction)
    print(f' - framerate = {numerator}/{denominator}')

运行输出

width =  640
height =  480
 - framerate = 30/1
 - framerate = 20/1
 - framerate = 15/1
 - framerate = 1/1
通用适配规则
  • 所有属于Gst.Fraction类型的字段,不管是pixel-aspect-ratio还是framerate,都可以用上述逻辑解析取值,不需要单独写适配代码
  • 不要直接对列表数组元素调用get_nth方法取值,这个方法仅适配int、bool、字符串这类基础类型
  • 后续如果遇到其他caps字段读取时报unknown type的错误,优先在Gst.Value模块下查找对应类型的专用解析接口,不要依赖绑定层的自动类型转换,这个逻辑在1.14版本的绑定里是不可靠的

内容的提问来源于stack exchange,提问作者Matej Jeglič

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.27 15:54:04