• FFmpeg源代码简单分析-其他-libavdevice的gdigrab


    参考链接

    libavdevice的gdigrab

    • GDIGrab用于在Windows下屏幕录像(抓屏)
    • gdigrab的源代码位于libavdevice\gdigrab.c。
    • 关键函数的调用关系图如下图所示。
    • 图中绿色背景的函数代表源代码中自己声明的函数,紫色背景的函数代表Win32的API函数。

     

    ff_gdigrab_demuxer

    • 在FFmpeg中Device也被当做是一种Format,因为GDIGrab是一个输入设备,因此被当作一个AVInputFormat。
    • GDIGrab对应的AVInputFormat结构体如下所示。
    1. /** gdi grabber device demuxer declaration */
    2. const AVInputFormat ff_gdigrab_demuxer = {
    3. .name = "gdigrab",
    4. .long_name = NULL_IF_CONFIG_SMALL("GDI API Windows frame grabber"),
    5. .priv_data_size = sizeof(struct gdigrab),
    6. .read_header = gdigrab_read_header,
    7. .read_packet = gdigrab_read_packet,
    8. .read_close = gdigrab_read_close,
    9. .flags = AVFMT_NOFILE,
    10. .priv_class = &gdigrab_class,
    11. };
    • 从该结构体可以看出:
      • 设备名称是“gdigrab”;
      • 设备完整名称是“GDI API Windows frame grabber”;
      • 初始化函数指针read_header()指向gdigrab_read_header();
      • 读取数据函数指针read_packet()指向gdigrab_read_packet();
      • 关闭函数指针read_close()指向gdigrab_read_close();
      • Flags设置为AVFMT_NOFILE;
      • AVClass指定为gdigrab_class。
    • 下面分析一下这些数据。

    gdigrab_class

    • ff_gdigrab_demuxer指定它的AVClass为一个名称为“gdigrab_class”的静态变量。
    • gdigrab_class的定义如下。
    1. static const AVClass gdigrab_class = {
    2. .class_name = "GDIgrab indev",
    3. .item_name = av_default_item_name,
    4. .option = options,
    5. .version = LIBAVUTIL_VERSION_INT,
    6. .category = AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT,
    7. };
    • 从gdigrab_class的定义可以看出,它指定了一个名称为“options”的数组作为它的选项数组(赋值给AVClass的option变量)

    options

    • 下面看一下这个options数组的定义,如下所示。
    1. #define OFFSET(x) offsetof(struct gdigrab, x)
    2. #define DEC AV_OPT_FLAG_DECODING_PARAM
    3. static const AVOption options[] = {
    4. { "draw_mouse", "draw the mouse pointer", OFFSET(draw_mouse), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, DEC },
    5. { "show_region", "draw border around capture area", OFFSET(show_region), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, DEC },
    6. { "framerate", "set video frame rate", OFFSET(framerate), AV_OPT_TYPE_VIDEO_RATE, {.str = "ntsc"}, 0, INT_MAX, DEC },
    7. { "video_size", "set video frame size", OFFSET(width), AV_OPT_TYPE_IMAGE_SIZE, {.str = NULL}, 0, 0, DEC },
    8. { "offset_x", "capture area x offset", OFFSET(offset_x), AV_OPT_TYPE_INT, {.i64 = 0}, INT_MIN, INT_MAX, DEC },
    9. { "offset_y", "capture area y offset", OFFSET(offset_y), AV_OPT_TYPE_INT, {.i64 = 0}, INT_MIN, INT_MAX, DEC },
    10. { NULL },
    11. };
    • options数组中包含了该Device支持的选项。可以看出GDIGrab支持如下选项:
      • draw_mouse:画出鼠标指针。
      • show_region:划出抓屏区域的边界。
      • framerate:抓屏帧率。
      • video_size:抓屏的大小。
      • offset_x:抓屏起始点x轴坐标。
      • offset_y:抓屏起始点y轴坐标。
    • 从宏定义“#define OFFSET(x) offsetof(struct gdigrab, x)”中可以看出,这些选项都存储在一个名称为“gdigrab”的结构体中。

    Gdigrab 上下文结构体

    • Gdigrab上下文结构体中存储了GDIGrab设备用到的各种变量,定义如下所示。
    1. /**
    2. * GDI Device Demuxer context
    3. */
    4. struct gdigrab {
    5. const AVClass *class; /**< Class for private options */
    6. int frame_size; /**< Size in bytes of the frame pixel data */
    7. int header_size; /**< Size in bytes of the DIB header */
    8. AVRational time_base; /**< Time base */
    9. int64_t time_frame; /**< Current time */
    10. int draw_mouse; /**< Draw mouse cursor (private option) */
    11. int show_region; /**< Draw border (private option) */
    12. AVRational framerate; /**< Capture framerate (private option) */
    13. int width; /**< Width of the grab frame (private option) */
    14. int height; /**< Height of the grab frame (private option) */
    15. int offset_x; /**< Capture x offset (private option) */
    16. int offset_y; /**< Capture y offset (private option) */
    17. HWND hwnd; /**< Handle of the window for the grab */
    18. HDC source_hdc; /**< Source device context */
    19. HDC dest_hdc; /**< Destination, source-compatible DC */
    20. BITMAPINFO bmi; /**< Information describing DIB format */
    21. HBITMAP hbmp; /**< Information on the bitmap captured */
    22. void *buffer; /**< The buffer containing the bitmap image data */
    23. RECT clip_rect; /**< The subarea of the screen or window to clip */
    24. HWND region_hwnd; /**< Handle of the region border window */
    25. int cursor_error_printed;
    26. };

    gdigrab_read_header()

    • gdigrab_read_header()用于初始化gdigrab。
    • 函数的定义如下所示。
    1. /**
    2. * Initializes the gdi grab device demuxer (public device demuxer API).
    3. *
    4. * @param s1 Context from avformat core
    5. * @return AVERROR_IO error, 0 success
    6. */
    7. static int
    8. gdigrab_read_header(AVFormatContext *s1)
    9. {
    10. struct gdigrab *gdigrab = s1->priv_data;
    11. HWND hwnd;
    12. HDC source_hdc = NULL;
    13. HDC dest_hdc = NULL;
    14. BITMAPINFO bmi;
    15. HBITMAP hbmp = NULL;
    16. void *buffer = NULL;
    17. const char *filename = s1->url;
    18. const char *name = NULL;
    19. AVStream *st = NULL;
    20. int bpp;
    21. int horzres;
    22. int vertres;
    23. int desktophorzres;
    24. int desktopvertres;
    25. RECT virtual_rect;
    26. RECT clip_rect;
    27. BITMAP bmp;
    28. int ret;
    29. if (!strncmp(filename, "title=", 6)) {
    30. wchar_t *name_w = NULL;
    31. name = filename + 6;
    32. if(utf8towchar(name, &name_w)) {
    33. ret = AVERROR(errno);
    34. goto error;
    35. }
    36. if(!name_w) {
    37. ret = AVERROR(EINVAL);
    38. goto error;
    39. }
    40. hwnd = FindWindowW(NULL, name_w);
    41. av_freep(&name_w);
    42. if (!hwnd) {
    43. av_log(s1, AV_LOG_ERROR,
    44. "Can't find window '%s', aborting.\n", name);
    45. ret = AVERROR(EIO);
    46. goto error;
    47. }
    48. if (gdigrab->show_region) {
    49. av_log(s1, AV_LOG_WARNING,
    50. "Can't show region when grabbing a window.\n");
    51. gdigrab->show_region = 0;
    52. }
    53. } else if (!strcmp(filename, "desktop")) {
    54. hwnd = NULL;
    55. } else {
    56. av_log(s1, AV_LOG_ERROR,
    57. "Please use \"desktop\" or \"title=<windowname>\" to specify your target.\n");
    58. ret = AVERROR(EIO);
    59. goto error;
    60. }
    61. /* This will get the device context for the selected window, or if
    62. * none, the primary screen */
    63. source_hdc = GetDC(hwnd);
    64. if (!source_hdc) {
    65. WIN32_API_ERROR("Couldn't get window device context");
    66. ret = AVERROR(EIO);
    67. goto error;
    68. }
    69. bpp = GetDeviceCaps(source_hdc, BITSPIXEL);
    70. horzres = GetDeviceCaps(source_hdc, HORZRES);
    71. vertres = GetDeviceCaps(source_hdc, VERTRES);
    72. desktophorzres = GetDeviceCaps(source_hdc, DESKTOPHORZRES);
    73. desktopvertres = GetDeviceCaps(source_hdc, DESKTOPVERTRES);
    74. if (hwnd) {
    75. GetClientRect(hwnd, &virtual_rect);
    76. /* window -- get the right height and width for scaling DPI */
    77. virtual_rect.left = virtual_rect.left * desktophorzres / horzres;
    78. virtual_rect.right = virtual_rect.right * desktophorzres / horzres;
    79. virtual_rect.top = virtual_rect.top * desktopvertres / vertres;
    80. virtual_rect.bottom = virtual_rect.bottom * desktopvertres / vertres;
    81. } else {
    82. /* desktop -- get the right height and width for scaling DPI */
    83. virtual_rect.left = GetSystemMetrics(SM_XVIRTUALSCREEN);
    84. virtual_rect.top = GetSystemMetrics(SM_YVIRTUALSCREEN);
    85. virtual_rect.right = (virtual_rect.left + GetSystemMetrics(SM_CXVIRTUALSCREEN)) * desktophorzres / horzres;
    86. virtual_rect.bottom = (virtual_rect.top + GetSystemMetrics(SM_CYVIRTUALSCREEN)) * desktopvertres / vertres;
    87. }
    88. /* If no width or height set, use full screen/window area */
    89. if (!gdigrab->width || !gdigrab->height) {
    90. clip_rect.left = virtual_rect.left;
    91. clip_rect.top = virtual_rect.top;
    92. clip_rect.right = virtual_rect.right;
    93. clip_rect.bottom = virtual_rect.bottom;
    94. } else {
    95. clip_rect.left = gdigrab->offset_x;
    96. clip_rect.top = gdigrab->offset_y;
    97. clip_rect.right = gdigrab->width + gdigrab->offset_x;
    98. clip_rect.bottom = gdigrab->height + gdigrab->offset_y;
    99. }
    100. if (clip_rect.left < virtual_rect.left ||
    101. clip_rect.top < virtual_rect.top ||
    102. clip_rect.right > virtual_rect.right ||
    103. clip_rect.bottom > virtual_rect.bottom) {
    104. av_log(s1, AV_LOG_ERROR,
    105. "Capture area (%li,%li),(%li,%li) extends outside window area (%li,%li),(%li,%li)",
    106. clip_rect.left, clip_rect.top,
    107. clip_rect.right, clip_rect.bottom,
    108. virtual_rect.left, virtual_rect.top,
    109. virtual_rect.right, virtual_rect.bottom);
    110. ret = AVERROR(EIO);
    111. goto error;
    112. }
    113. if (name) {
    114. av_log(s1, AV_LOG_INFO,
    115. "Found window %s, capturing %lix%lix%i at (%li,%li)\n",
    116. name,
    117. clip_rect.right - clip_rect.left,
    118. clip_rect.bottom - clip_rect.top,
    119. bpp, clip_rect.left, clip_rect.top);
    120. } else {
    121. av_log(s1, AV_LOG_INFO,
    122. "Capturing whole desktop as %lix%lix%i at (%li,%li)\n",
    123. clip_rect.right - clip_rect.left,
    124. clip_rect.bottom - clip_rect.top,
    125. bpp, clip_rect.left, clip_rect.top);
    126. }
    127. if (clip_rect.right - clip_rect.left <= 0 ||
    128. clip_rect.bottom - clip_rect.top <= 0 || bpp%8) {
    129. av_log(s1, AV_LOG_ERROR, "Invalid properties, aborting\n");
    130. ret = AVERROR(EIO);
    131. goto error;
    132. }
    133. dest_hdc = CreateCompatibleDC(source_hdc);
    134. if (!dest_hdc) {
    135. WIN32_API_ERROR("Screen DC CreateCompatibleDC");
    136. ret = AVERROR(EIO);
    137. goto error;
    138. }
    139. /* Create a DIB and select it into the dest_hdc */
    140. bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    141. bmi.bmiHeader.biWidth = clip_rect.right - clip_rect.left;
    142. bmi.bmiHeader.biHeight = -(clip_rect.bottom - clip_rect.top);
    143. bmi.bmiHeader.biPlanes = 1;
    144. bmi.bmiHeader.biBitCount = bpp;
    145. bmi.bmiHeader.biCompression = BI_RGB;
    146. bmi.bmiHeader.biSizeImage = 0;
    147. bmi.bmiHeader.biXPelsPerMeter = 0;
    148. bmi.bmiHeader.biYPelsPerMeter = 0;
    149. bmi.bmiHeader.biClrUsed = 0;
    150. bmi.bmiHeader.biClrImportant = 0;
    151. hbmp = CreateDIBSection(dest_hdc, &bmi, DIB_RGB_COLORS,
    152. &buffer, NULL, 0);
    153. if (!hbmp) {
    154. WIN32_API_ERROR("Creating DIB Section");
    155. ret = AVERROR(EIO);
    156. goto error;
    157. }
    158. if (!SelectObject(dest_hdc, hbmp)) {
    159. WIN32_API_ERROR("SelectObject");
    160. ret = AVERROR(EIO);
    161. goto error;
    162. }
    163. /* Get info from the bitmap */
    164. GetObject(hbmp, sizeof(BITMAP), &bmp);
    165. st = avformat_new_stream(s1, NULL);
    166. if (!st) {
    167. ret = AVERROR(ENOMEM);
    168. goto error;
    169. }
    170. avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
    171. gdigrab->frame_size = bmp.bmWidthBytes * bmp.bmHeight * bmp.bmPlanes;
    172. gdigrab->header_size = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) +
    173. (bpp <= 8 ? (1 << bpp) : 0) * sizeof(RGBQUAD) /* palette size */;
    174. gdigrab->time_base = av_inv_q(gdigrab->framerate);
    175. gdigrab->time_frame = av_gettime_relative() / av_q2d(gdigrab->time_base);
    176. gdigrab->hwnd = hwnd;
    177. gdigrab->source_hdc = source_hdc;
    178. gdigrab->dest_hdc = dest_hdc;
    179. gdigrab->hbmp = hbmp;
    180. gdigrab->bmi = bmi;
    181. gdigrab->buffer = buffer;
    182. gdigrab->clip_rect = clip_rect;
    183. gdigrab->cursor_error_printed = 0;
    184. if (gdigrab->show_region) {
    185. if (gdigrab_region_wnd_init(s1, gdigrab)) {
    186. ret = AVERROR(EIO);
    187. goto error;
    188. }
    189. }
    190. st->avg_frame_rate = av_inv_q(gdigrab->time_base);
    191. st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
    192. st->codecpar->codec_id = AV_CODEC_ID_BMP;
    193. st->codecpar->bit_rate = (gdigrab->header_size + gdigrab->frame_size) * 1/av_q2d(gdigrab->time_base) * 8;
    194. return 0;
    195. error:
    196. if (source_hdc)
    197. ReleaseDC(hwnd, source_hdc);
    198. if (dest_hdc)
    199. DeleteDC(dest_hdc);
    200. if (hbmp)
    201. DeleteObject(hbmp);
    202. if (source_hdc)
    203. DeleteDC(source_hdc);
    204. return ret;
    205. }
    • 从源代码可以看出,gdigrab_read_header()的流程大致如下所示:
      • (1)确定窗口的句柄hwnd。如果指定了“title=”的话,调用FindWindow()获取hwnd;如果指定了“desktop”,则设定hwnd为NULL。
      • (2)根据窗口的句柄hwnd确定抓屏的矩形区域。如果抓取指定窗口,则通过GetClientRect()函数;否则就抓取整个屏幕。
      • (3)调用GDI的API完成抓屏的一些初始化工作。包括:
        • a)通过GetDC()获得某个窗口句柄的HDC(在这里是source_hdc)。
        • b)通过CreateCompatibleDC()创建一个与指定设备兼容的HDC(在这里是dest_hdc)
        • c)通过CreateDIBSection()创建HBITMAP
        • d)通过SelectObject()绑定HBITMAP和HDC(指的是dest_hdc)
    • (4)通过avformat_new_stream()创建一个AVStream。
    • (5)将初始化时候的一些参数保存至GDIGrab的上下文结构体。

    gdigrab_read_packet()

    • gdigrab_read_packet()用于读取一帧抓屏数据。
    • 该函数的定义如下所示。
    1. /**
    2. * Grabs a frame from gdi (public device demuxer API).
    3. *
    4. * @param s1 Context from avformat core
    5. * @param pkt Packet holding the grabbed frame
    6. * @return frame size in bytes
    7. */
    8. static int gdigrab_read_packet(AVFormatContext *s1, AVPacket *pkt)
    9. {
    10. struct gdigrab *gdigrab = s1->priv_data;
    11. //读取参数
    12. HDC dest_hdc = gdigrab->dest_hdc;
    13. HDC source_hdc = gdigrab->source_hdc;
    14. RECT clip_rect = gdigrab->clip_rect;
    15. AVRational time_base = gdigrab->time_base;
    16. int64_t time_frame = gdigrab->time_frame;
    17. BITMAPFILEHEADER bfh;
    18. int file_size = gdigrab->header_size + gdigrab->frame_size;
    19. int64_t curtime, delay;
    20. /* Calculate the time of the next frame */
    21. time_frame += INT64_C(1000000);
    22. /* Run Window message processing queue */
    23. if (gdigrab->show_region)
    24. gdigrab_region_wnd_update(s1, gdigrab);
    25. /* wait based on the frame rate */
    26. //延时
    27. for (;;) {
    28. curtime = av_gettime();
    29. delay = time_frame * av_q2d(time_base) - curtime;
    30. if (delay <= 0) {
    31. if (delay < INT64_C(-1000000) * av_q2d(time_base)) {
    32. time_frame += INT64_C(1000000);
    33. }
    34. break;
    35. }
    36. if (s1->flags & AVFMT_FLAG_NONBLOCK) {
    37. return AVERROR(EAGAIN);
    38. } else {
    39. av_usleep(delay);
    40. }
    41. }
    42. //新建一个AVPacket
    43. if (av_new_packet(pkt, file_size) < 0)
    44. return AVERROR(ENOMEM);
    45. pkt->pts = curtime;
    46. /* Blit screen grab */
    47. //关键:BitBlt()完成抓屏功能
    48. if (!BitBlt(dest_hdc, 0, 0,
    49. clip_rect.right - clip_rect.left,
    50. clip_rect.bottom - clip_rect.top,
    51. source_hdc,
    52. clip_rect.left, clip_rect.top, SRCCOPY | CAPTUREBLT)) {
    53. WIN32_API_ERROR("Failed to capture image");
    54. return AVERROR(EIO);
    55. }
    56. //画鼠标指针?
    57. if (gdigrab->draw_mouse)
    58. paint_mouse_pointer(s1, gdigrab);
    59. /* Copy bits to packet data */
    60. //BMP文件头BITMAPFILEHEADER
    61. bfh.bfType = 0x4d42; /* "BM" in little-endian */
    62. bfh.bfSize = file_size;
    63. bfh.bfReserved1 = 0;
    64. bfh.bfReserved2 = 0;
    65. bfh.bfOffBits = gdigrab->header_size;
    66. //往AVPacket中拷贝数据
    67. //拷贝BITMAPFILEHEADER
    68. memcpy(pkt->data, &bfh, sizeof(bfh));
    69. //拷贝BITMAPINFOHEADER
    70. memcpy(pkt->data + sizeof(bfh), &gdigrab->bmi.bmiHeader, sizeof(gdigrab->bmi.bmiHeader));
    71. //不常见
    72. if (gdigrab->bmi.bmiHeader.biBitCount <= 8)
    73. GetDIBColorTable(dest_hdc, 0, 1 << gdigrab->bmi.bmiHeader.biBitCount,
    74. (RGBQUAD *) (pkt->data + sizeof(bfh) + sizeof(gdigrab->bmi.bmiHeader)));
    75. //拷贝像素数据
    76. memcpy(pkt->data + gdigrab->header_size, gdigrab->buffer, gdigrab->frame_size);
    77. gdigrab->time_frame = time_frame;
    78. return gdigrab->header_size + gdigrab->frame_size;
    79. }
    • 从源代码可以看出,gdigrab_read_packet()的流程大致如下所示:
    • (1)从GDIGrab上下文结构体读取初始化时候设定的参数。
    • (2)根据帧率参数进行延时。
    • (3)通过av_new_packet()新建一个AVPacket。
    • (4)通过BitBlt()完成抓屏功能。
    • (5)如果需要画鼠标指针的话,调用paint_mouse_pointer(),这里不做分析。
    • (6)按照顺序拷贝以下3项内容至AVPacket的data指向的内存:
      • a)BITMAPFILEHEADER
      • b)BITMAPINFOHEADER
      • c)抓屏的到的像素数据

    gdigrab_read_close()

    • gdigrab_read_close()用于关闭gdigrab。
    • 该函数的定义如下所示。
    • 从源代码可以看出,gdigrab_read_close ()完成了各种变量的清理工作。
    1. /**
    2. * Closes gdi frame grabber (public device demuxer API).
    3. *
    4. * @param s1 Context from avformat core
    5. * @return 0 success, !0 failure
    6. */
    7. static int gdigrab_read_close(AVFormatContext *s1)
    8. {
    9. struct gdigrab *s = s1->priv_data;
    10. if (s->show_region)
    11. gdigrab_region_wnd_destroy(s1, s);
    12. if (s->source_hdc)
    13. ReleaseDC(s->hwnd, s->source_hdc);
    14. if (s->dest_hdc)
    15. DeleteDC(s->dest_hdc);
    16. if (s->hbmp)
    17. DeleteObject(s->hbmp);
    18. if (s->source_hdc)
    19. DeleteDC(s->source_hdc);
    20. return 0;
    21. }

  • 相关阅读:
    【每天学会一个渗透测试工具】dirsearch安装及使用指南
    Stable Diffusion基础:ControlNet之重新上色(黑白照片换新颜)
    蓝桥oj 顺子日期
    第五章 图像处理
    便捷在线导入:完整Axure元件库集合,让你的设计更高效!
    abaqus Isight学习
    运动蓝牙耳机哪个品牌好,五款运动专业户必备的耳机推荐
    【C++】C++学习(一)
    阿里云Linux中安装MySQL,并使用navicat连接以及报错解决
    MySQL的DDL操作数据库
  • 原文地址:https://blog.csdn.net/CHYabc123456hh/article/details/125435895