You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xlib返回指针与窗口ID不匹配,如何获取FFmpeg可用的X11窗口ID?

获取FFmpeg可识别的X11窗口ID

问题背景

我使用X11绑定查询窗口信息并传递给FFmpeg,FFmpeg要求传入十六进制格式的窗口ID——这是xwininfo、wmctrl等工具的标准返回格式,用这类工具返回的ID能正常捕获窗口:

$ xwininfo

xwininfo: Please select the window about which you
          would like information by clicking the
          mouse in that window.

xwininfo: Window id: 0x2800014 "Desktop — Plasma"

$ ffmpeg -f x11grab -window_id 0x2800014 -i :0+0,0 -f apng -vframes 1 out.png
# 执行正常

但调用XQueryTree获取窗口指针并转为十六进制字符串时,结果里找不到像0x2800014这样的有效ID,把生成的ID传给FFmpeg会报错:

var root = Window.None;
var parent = Window.None;
Xlib.XQueryTree(_display, Xlib.XDefaultRootWindow(_display), ref root, ref parent, out var children);

var ids = children
    .Select(ptr => $"0x{(ulong) ptr:x}")
    .ToArray();

FFmpeg报错信息:

$ ffmpeg -f x11grab -window_id 0x4400003 -i :0+0,0 -f apng -vframes 1

# 省略部分内容

Trailing option(s) found in the command: may be ignored.
[x11grab @ 0x55b811a8da40] Cannot get the image data event_error: response_type:0 error_code:8 sequence:10 resource_id:167772160 minor_code:4 major_code:130.
[x11grab @ 0x55b811a8da40] Continuing without shared memory.
[x11grab @ 0x55b811a8da40] Cannot get the image data event_error: response_type:0 error_code:8 sequence:11 resource_id:71303171 minor_code:0 major_code:73.
Input #0, x11grab, from ':0+0,0':
  Duration: N/A, bitrate: 38361 kb/s
  Stream #0:0: Video: rawvideo (BGR[0] / 0x524742), bgr0, 200x200, 38361 kb/s, 29.97 fps, 1000k tbr, 1000k tbn
At least one output file must be specified

解决方法

问题根源

你混淆了窗口指针和窗口ID的概念。XQueryTree返回的children是Window类型的实例(X11系统中代表窗口的句柄),直接将其当作指针转ulong得到的是内存地址,而非X11真正的窗口ID。

正确代码实现

X11中的Window本质是无符号整数类型,直接将其转换为十六进制字符串即可得到FFmpeg认可的格式:

var root = Window.None;
var parent = Window.None;
Xlib.XQueryTree(_display, Xlib.XDefaultRootWindow(_display), ref root, ref parent, out var children);

var ids = children
    .Select(window => $"0x{(ulong) window:x}")
    .ToArray();

关键说明

  • X11的Window类型底层对应系统中的窗口ID(unsigned long类型)
  • xwininfo返回的0x2800014就是该整数的十六进制表示
  • 直接将Window实例强制转换为ulong再格式化,就能生成FFmpeg可识别的窗口ID字符串

内容的提问来源于Stack Exchange,提问作者Kroltan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 19:03:31