1 /*
2 * GDI video grab interface
3 *
4 * This file is part of FFmpeg.
5 *
6 * Copyright (C) 2013 Calvin Walton <calvin.walton@kepstin.ca>
7 * Copyright (C) 2007-2010 Christophe Gisquet <word1.word2@gmail.com>
8 *
9 * FFmpeg is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public License
11 * as published by the Free Software Foundation; either version 2.1
12 * of the License, or (at your option) any later version.
13 *
14 * FFmpeg is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU Lesser General Public License for more details.
18 *
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with FFmpeg; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 */
23
24 /**
25 * @file
26 * GDI frame device demuxer
27 * @author Calvin Walton <calvin.walton@kepstin.ca>
28 * @author Christophe Gisquet <word1.word2@gmail.com>
29 */
30
35 #include <windows.h>
36
37 /**
38 * GDI Device Demuxer context
39 */
41 const AVClass *
class;
/**< Class for private options */
42
43 int frame_size;
/**< Size in bytes of the frame pixel data */
47
48 int draw_mouse;
/**< Draw mouse cursor (private option) */
51 int width;
/**< Width of the grab frame (private option) */
52 int height;
/**< Height of the grab frame (private option) */
53 int offset_x;
/**< Capture x offset (private option) */
54 int offset_y;
/**< Capture y offset (private option) */
55
56 HWND hwnd;
/**< Handle of the window for the grab */
59 BITMAPINFO
bmi;
/**< Information describing DIB format */
61 void *
buffer;
/**< The buffer containing the bitmap image data */
62 RECT
clip_rect;
/**< The subarea of the screen or window to clip */
63
65
67 };
68
69 #define WIN32_API_ERROR(str) \
70 av_log(s1, AV_LOG_ERROR, str " (error %li)\n", GetLastError())
71
72 #define REGION_WND_BORDER 3
73
74 /**
75 * Callback to handle Windows messages for the region outline window.
76 *
77 * In particular, this handles painting the frame rectangle.
78 *
79 * @param hwnd The region outline window handle.
80 * @param msg The Windows message.
81 * @param wparam First Windows message parameter.
82 * @param lparam Second Windows message parameter.
83 * @return 0 success, !0 failure
84 */
87 {
88 PAINTSTRUCT ps;
91
92 switch (msg) {
93 case WM_PAINT:
94 hdc = BeginPaint(hwnd, &ps);
95
96 GetClientRect(hwnd, &rect);
97 FrameRect(hdc, &rect, GetStockObject(BLACK_BRUSH));
98
99 rect.left++; rect.top++; rect.right--; rect.bottom--;
100 FrameRect(hdc, &rect, GetStockObject(WHITE_BRUSH));
101
102 rect.left++; rect.top++; rect.right--; rect.bottom--;
103 FrameRect(hdc, &rect, GetStockObject(BLACK_BRUSH));
104
105 EndPaint(hwnd, &ps);
106 break;
107 default:
108 return DefWindowProc(hwnd, msg, wparam, lparam);
109 }
110 return 0;
111 }
112
113 /**
114 * Initialize the region outline window.
115 *
116 * @param s1 The format context.
117 * @param gdigrab gdigrab context.
118 * @return 0 success, !0 failure
119 */
120 static int
122 {
126 HRGN region_interior =
NULL;
127
128 DWORD style = WS_POPUP | WS_VISIBLE;
129 DWORD ex = WS_EX_TOOLWINDOW | WS_EX_TOPMOST | WS_EX_TRANSPARENT;
130
133
134 AdjustWindowRectEx(&rect, style,
FALSE, ex);
135
136 // Create a window with no owner; use WC_DIALOG instead of writing a custom
137 // window class
138 hwnd = CreateWindowEx(ex, WC_DIALOG,
NULL, style, rect.left, rect.top,
139 rect.right - rect.left, rect.bottom - rect.top,
141 if (!hwnd) {
143 goto error;
144 }
145
146 // Set the window shape to only include the border area
147 GetClientRect(hwnd, &rect);
148 region = CreateRectRgn(0, 0,
149 rect.right - rect.left, rect.bottom - rect.top);
153 CombineRgn(region, region, region_interior, RGN_DIFF);
154 if (!SetWindowRgn(hwnd, region,
FALSE)) {
156 goto error;
157 }
158 // The "region" memory is now owned by the window
160 DeleteObject(region_interior);
161
163
164 ShowWindow(hwnd, SW_SHOW);
165
167
168 return 0;
169
170 error:
171 if (region)
172 DeleteObject(region);
173 if (region_interior)
174 DeleteObject(region_interior);
175 if (hwnd)
176 DestroyWindow(hwnd);
177 return 1;
178 }
179
180 /**
181 * Cleanup/free the region outline window.
182 *
183 * @param s1 The format context.
184 * @param gdigrab gdigrab context.
185 */
186 static void
188 {
192 }
193
194 /**
195 * Process the Windows message queue.
196 *
197 * This is important to prevent Windows from thinking the window has become
198 * unresponsive. As well, things like WM_PAINT (to actually draw the window
199 * contents) are handled from the message queue context.
200 *
201 * @param s1 The format context.
202 * @param gdigrab gdigrab context.
203 */
204 static void
206 {
208 MSG msg;
209
210 while (PeekMessage(&msg, hwnd, 0, 0, PM_REMOVE)) {
211 DispatchMessage(&msg);
212 }
213 }
214
215 /**
216 * Initializes the gdi grab device demuxer (public device demuxer API).
217 *
218 * @param s1 Context from avformat core
219 * @return AVERROR_IO error, 0 success
220 */
221 static int
223 {
225
232
233 const char *filename = s1->
filename;
236
237 int bpp;
238 int vertres;
239 int desktopvertres;
240 RECT virtual_rect;
242 BITMAP bmp;
243 int ret;
244
245 if (!strncmp(filename, "title=", 6)) {
246 name = filename + 6;
247 hwnd = FindWindow(
NULL, name);
248 if (!hwnd) {
250 "Can't find window '%s', aborting.\n", name);
252 goto error;
253 }
256 "Can't show region when grabbing a window.\n");
258 }
259 } else if (!strcmp(filename, "desktop")) {
261 } else {
263 "Please use \"desktop\" or \"title=<windowname>\" to specify your target.\n");
265 goto error;
266 }
267
268 /* This will get the device context for the selected window, or if
269 * none, the primary screen */
270 source_hdc = GetDC(hwnd);
271 if (!source_hdc) {
274 goto error;
275 }
276 bpp = GetDeviceCaps(source_hdc, BITSPIXEL);
277
278 if (hwnd) {
279 GetClientRect(hwnd, &virtual_rect);
280 } else {
281 /* desktop -- get the right height and width for scaling DPI */
282 vertres = GetDeviceCaps(source_hdc, VERTRES);
283 desktopvertres = GetDeviceCaps(source_hdc, DESKTOPVERTRES);
284 virtual_rect.left = GetSystemMetrics(SM_XVIRTUALSCREEN);
285 virtual_rect.top = GetSystemMetrics(SM_YVIRTUALSCREEN);
286 virtual_rect.right = (virtual_rect.left + GetSystemMetrics(SM_CXVIRTUALSCREEN)) * desktopvertres / vertres;
287 virtual_rect.bottom = (virtual_rect.top + GetSystemMetrics(SM_CYVIRTUALSCREEN)) * desktopvertres / vertres;
288 }
289
290 /* If no width or height set, use full screen/window area */
292 clip_rect.left = virtual_rect.left;
293 clip_rect.top = virtual_rect.top;
294 clip_rect.right = virtual_rect.right;
295 clip_rect.bottom = virtual_rect.bottom;
296 } else {
301 }
302
303 if (clip_rect.left < virtual_rect.left ||
304 clip_rect.top < virtual_rect.top ||
305 clip_rect.right > virtual_rect.right ||
306 clip_rect.bottom > virtual_rect.bottom) {
308 "Capture area (%li,%li),(%li,%li) extends outside window area (%li,%li),(%li,%li)",
309 clip_rect.left, clip_rect.top,
310 clip_rect.right, clip_rect.bottom,
311 virtual_rect.left, virtual_rect.top,
312 virtual_rect.right, virtual_rect.bottom);
314 goto error;
315 }
316
317
318 if (name) {
320 "Found window %s, capturing %lix%lix%i at (%li,%li)\n",
321 name,
322 clip_rect.right - clip_rect.left,
323 clip_rect.bottom - clip_rect.top,
324 bpp, clip_rect.left, clip_rect.top);
325 } else {
327 "Capturing whole desktop as %lix%lix%i at (%li,%li)\n",
328 clip_rect.right - clip_rect.left,
329 clip_rect.bottom - clip_rect.top,
330 bpp, clip_rect.left, clip_rect.top);
331 }
332
333 if (clip_rect.right - clip_rect.left <= 0 ||
334 clip_rect.bottom - clip_rect.top <= 0 || bpp%8) {
337 goto error;
338 }
339
340 dest_hdc = CreateCompatibleDC(source_hdc);
341 if (!dest_hdc) {
344 goto error;
345 }
346
347 /* Create a DIB and select it into the dest_hdc */
348 bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
349 bmi.bmiHeader.biWidth = clip_rect.right - clip_rect.left;
350 bmi.bmiHeader.biHeight = -(clip_rect.bottom - clip_rect.top);
351 bmi.bmiHeader.biPlanes = 1;
352 bmi.bmiHeader.biBitCount = bpp;
353 bmi.bmiHeader.biCompression = BI_RGB;
354 bmi.bmiHeader.biSizeImage = 0;
355 bmi.bmiHeader.biXPelsPerMeter = 0;
356 bmi.bmiHeader.biYPelsPerMeter = 0;
357 bmi.bmiHeader.biClrUsed = 0;
358 bmi.bmiHeader.biClrImportant = 0;
359 hbmp = CreateDIBSection(dest_hdc, &bmi, DIB_RGB_COLORS,
361 if (!hbmp) {
364 goto error;
365 }
366
367 if (!SelectObject(dest_hdc, hbmp)) {
370 goto error;
371 }
372
373 /* Get info from the bitmap */
374 GetObject(hbmp, sizeof(BITMAP), &bmp);
375
377 if (!st) {
379 goto error;
380 }
382
383 gdigrab->
frame_size = bmp.bmWidthBytes * bmp.bmHeight * bmp.bmPlanes;
384 gdigrab->
header_size =
sizeof(BITMAPFILEHEADER) +
sizeof(BITMAPINFOHEADER) +
385 (bpp <= 8 ? (1 << bpp) : 0) * sizeof(RGBQUAD) /* palette size */;
388
396
398
402 goto error;
403 }
404 }
405
410
411 return 0;
412
413 error:
414 if (source_hdc)
415 ReleaseDC(hwnd, source_hdc);
416 if (dest_hdc)
417 DeleteDC(dest_hdc);
418 if (hbmp)
419 DeleteObject(hbmp);
420 if (source_hdc)
421 DeleteDC(source_hdc);
422 return ret;
423 }
424
425 /**
426 * Paints a mouse pointer in a Win32 image.
427 *
428 * @param s1 Context of the log information
429 * @param s Current grad structure
430 */
432 {
433 CURSORINFO ci = {0};
434
435 #define CURSOR_ERROR(str) \
436 if (!gdigrab->cursor_error_printed) { \
437 WIN32_API_ERROR(str); \
438 gdigrab->cursor_error_printed = 1; \
439 }
440
441 ci.cbSize = sizeof(ci);
442
443 if (GetCursorInfo(&ci)) {
444 HCURSOR icon = CopyCursor(ci.hCursor);
445 ICONINFO info;
446 POINT pos;
450 info.hbmColor =
NULL;
451
452 if (ci.flags != CURSOR_SHOWING)
453 return;
454
455 if (!icon) {
456 /* Use the standard arrow cursor as a fallback.
457 * You'll probably only hit this in Wine, which can't fetch
458 * the current system cursor. */
459 icon = CopyCursor(LoadCursor(
NULL, IDC_ARROW));
460 }
461
462 if (!GetIconInfo(icon, &info)) {
464 goto icon_error;
465 }
466
467 pos.x = ci.ptScreenPos.x - clip_rect.left - info.xHotspot;
468 pos.y = ci.ptScreenPos.y - clip_rect.top - info.yHotspot;
469
470 if (hwnd) {
472
473 if (GetWindowRect(hwnd, &rect)) {
475 pos.y -= rect.top;
476 } else {
478 goto icon_error;
479 }
480 }
481
483 ci.ptScreenPos.x, ci.ptScreenPos.y, pos.x, pos.y);
484
485 if (pos.x >= 0 && pos.x <= clip_rect.right - clip_rect.left &&
486 pos.y >= 0 && pos.y <= clip_rect.bottom - clip_rect.top) {
487 if (!DrawIcon(gdigrab->
dest_hdc, pos.x, pos.y, icon))
489 }
490
491 icon_error:
492 if (info.hbmMask)
493 DeleteObject(info.hbmMask);
494 if (info.hbmColor)
495 DeleteObject(info.hbmColor);
496 if (icon)
497 DestroyCursor(icon);
498 } else {
500 }
501 }
502
503 /**
504 * Grabs a frame from gdi (public device demuxer API).
505 *
506 * @param s1 Context from avformat core
507 * @param pkt Packet holding the grabbed frame
508 * @return frame size in bytes
509 */
511 {
513
519
520 BITMAPFILEHEADER bfh;
522
523 int64_t curtime, delay;
524
525 /* Calculate the time of the next frame */
526 time_frame += INT64_C(1000000);
527
528 /* Run Window message processing queue */
531
532 /* wait based on the frame rate */
533 for (;;) {
535 delay = time_frame *
av_q2d(time_base) - curtime;
536 if (delay <= 0) {
537 if (delay < INT64_C(-1000000) *
av_q2d(time_base)) {
538 time_frame += INT64_C(1000000);
539 }
540 break;
541 }
544 } else {
546 }
547 }
548
552
553 /* Blit screen grab */
554 if (!BitBlt(dest_hdc, 0, 0,
555 clip_rect.right - clip_rect.left,
556 clip_rect.bottom - clip_rect.top,
557 source_hdc,
558 clip_rect.left, clip_rect.top, SRCCOPY | CAPTUREBLT)) {
561 }
564
565 /* Copy bits to packet data */
566
567 bfh.bfType = 0x4d42; /* "BM" in little-endian */
568 bfh.bfSize = file_size;
569 bfh.bfReserved1 = 0;
570 bfh.bfReserved2 = 0;
572
573 memcpy(pkt->
data, &bfh,
sizeof(bfh));
574
575 memcpy(pkt->
data +
sizeof(bfh), &gdigrab->
bmi.bmiHeader,
sizeof(gdigrab->
bmi.bmiHeader));
576
577 if (gdigrab->
bmi.bmiHeader.biBitCount <= 8)
578 GetDIBColorTable(dest_hdc, 0, 1 << gdigrab->
bmi.bmiHeader.biBitCount,
579 (RGBQUAD *) (pkt->
data +
sizeof(bfh) +
sizeof(gdigrab->
bmi.bmiHeader)));
580
582
584
586 }
587
588 /**
589 * Closes gdi frame grabber (public device demuxer API).
590 *
591 * @param s1 Context from avformat core
592 * @return 0 success, !0 failure
593 */
595 {
597
600
606 DeleteObject(s->
hbmp);
609
610 return 0;
611 }
612
613 #define OFFSET(x) offsetof(struct gdigrab, x)
614 #define DEC AV_OPT_FLAG_DECODING_PARAM
623 };
624
630 };
631
632 /** gdi grabber device demuxer declaration */
636 .priv_data_size =
sizeof(
struct gdigrab),
642 };
static int gdigrab_read_packet(AVFormatContext *s1, AVPacket *pkt)
Grabs a frame from gdi (public device demuxer API).
int show_region
Draw border (private option)
#define AV_LOG_WARNING
Something somehow does not look correct.
int64_t bit_rate
the average bitrate
#define LIBAVUTIL_VERSION_INT
static const AVOption options[]
int frame_size
Size in bytes of the frame pixel data.
BITMAPINFO bmi
Information describing DIB format.
int av_usleep(unsigned usec)
Sleep for a period of time.
HWND region_hwnd
Handle of the region border window.
static int gdigrab_read_close(AVFormatContext *s1)
Closes gdi frame grabber (public device demuxer API).
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
static void gdigrab_region_wnd_destroy(AVFormatContext *s1, struct gdigrab *gdigrab)
Cleanup/free the region outline window.
const char * class_name
The name of the class; usually it is the same name as the context structure type to which the AVClass...
AVStream * avformat_new_stream(AVFormatContext *s, const AVCodec *c)
Add a new stream to a media file.
RECT clip_rect
The subarea of the screen or window to clip.
static LRESULT CALLBACK gdigrab_region_wnd_proc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
Callback to handle Windows messages for the region outline window.
static double av_q2d(AVRational a)
Convert rational to double.
int flags
Flags modifying the (de)muxer behaviour.
AVInputFormat ff_gdigrab_demuxer
gdi grabber device demuxer declaration
int av_new_packet(AVPacket *pkt, int size)
Allocate the payload of a packet and initialize its fields with default values.
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
static int gdigrab_read_header(AVFormatContext *s1)
Initializes the gdi grab device demuxer (public device demuxer API).
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
HBITMAP hbmp
Information on the bitmap captured.
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
AVRational framerate
Capture framerate (private option)
int64_t time_frame
Current time.
static void paint_mouse_pointer(AVFormatContext *s1, struct gdigrab *gdigrab)
Paints a mouse pointer in a Win32 image.
static const AVClass gdigrab_class
int height
Height of the grab frame (private option)
AVCodecContext * codec
Codec context associated with this stream.
AVRational time_base
Time base.
int header_size
Size in bytes of the DIB header.
char filename[1024]
input or output filename
HDC dest_hdc
Destination, source-compatible DC.
#define REGION_WND_BORDER
GDI Device Demuxer context.
void * buffer
The buffer containing the bitmap image data.
#define WIN32_API_ERROR(str)
int64_t av_gettime(void)
Get the current time in microseconds.
HWND hwnd
Handle of the window for the grab.
#define AV_LOG_INFO
Standard information.
enum AVMediaType codec_type
int offset_y
Capture y offset (private option)
Describe the class of an AVClass context structure.
rational number numerator/denominator
HDC source_hdc
Source device context.
offset must point to AVRational
offset must point to two consecutive integers
static av_always_inline AVRational av_inv_q(AVRational q)
Invert a rational.
int width
Width of the grab frame (private option)
int draw_mouse
Draw mouse cursor (private option)
static int gdigrab_region_wnd_init(AVFormatContext *s1, struct gdigrab *gdigrab)
Initialize the region outline window.
void * priv_data
Format private data.
int offset_x
Capture x offset (private option)
#define CURSOR_ERROR(str)
This structure stores compressed data.
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
static void gdigrab_region_wnd_update(AVFormatContext *s1, struct gdigrab *gdigrab)
Process the Windows message queue.