GStreamer 1.28 中 prepare-window-handle 被误判为 False
数据小陈
结论
不建议用 bool(struct) 或 if struct: 判断 prepare-window-handle 消息是否有效。这个 element message 本身没有字段,但结构对象仍然存在。从现象看,在 GStreamer 1.28 下,Python 绑定可能会把“空字段 Structure”的真值判断结果映射为 False;这种行为的可移植性不稳定,不能依赖。
判断时应先检查 message.type == Gst.MessageType.ELEMENT,再用 struct is not None 确认结构存在,最后用 struct.get_name() 或 GstStructure 名称匹配来识别消息。
原因说明
prepare-window-handle 不需要 payload,消息名本身就是关键信息。have-window-handle 带有 window-handle=(guint64)... 字段,bool(struct) 在这里为 True 只是因为有字段,并不能说明用 bool 判断结构有效是正确做法。
在 C API 语义里,gst_message_get_structure() 返回 GstStructure *,可靠判断是 != NULL,名称判断用 gst_structure_has_name() 或 gst_structure_get_name()。Python 侧应尽量对应到 is not None 和 get_name(),不要依赖 __bool__ 的实现细节。
推荐写法
import gi
gi.require_version("Gst", "1.0")
from gi.repository import Gst
def on_sync_message(self, _, message):
if message.type != Gst.MessageType.ELEMENT:
return Gst.BusSyncReply.PASS
struct = message.get_structure()
if struct is None:
return Gst.BusSyncReply.PASS
name = struct.get_name()
if name == "prepare-window-handle":
if self.window_id is not None:
message.src.set_window_handle(self.window_id)
else:
self.window_handle_set = True
return Gst.BusSyncReply.HANDLED
if name == "have-window-handle":
# 可选:这里只做记录或状态处理,不要再用 bool(struct) 判断有效性
pass
return Gst.BusSyncReply.PASS
注意事项
if self.window_id:建议改成if self.window_id is not None:,避免窗口句柄为 0 或其他边界值时被误判。prepare-window-handle没有 payload 是正常的,不要把它当成无效消息。- 如果 bus sync handler 有返回值要求,按需要返回
Gst.BusSyncReply.HANDLED、PASS或DROP;不要依赖隐式返回值。 - 版本差异可能来自 PyGObject/GStreamer Python 绑定对
Gst.Structure真值判断的实现变化,具体行为应以目标版本实测为准;但业务代码应使用is not None+get_name()这种稳定判断。 - 如果同时处理
have-window-handle,建议把两个消息名分开分支,不要把prepare-window-handle和携带 handle 的消息混在一起判断。
备注:内容仅供参考。
