gdi_capturer.cpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #include "gdi_capturer.h"
  2. #include "basic/basic.h"
  3. bool GdiCapturer::Open(HWND hwnd, int width, int height)
  4. {
  5. Close();
  6. m_width = width;
  7. m_height = height;
  8. _srcHdc = GetWindowDC(hwnd);
  9. _dstHdc = CreateCompatibleDC(_srcHdc);
  10. _bitmap = CreateCompatibleBitmap(_srcHdc, width, height);
  11. SelectObject(_dstHdc, _bitmap);
  12. _bitmapInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
  13. _bitmapInfo.bmiHeader.biPlanes = 1;
  14. _bitmapInfo.bmiHeader.biBitCount = 24;
  15. _bitmapInfo.bmiHeader.biWidth = width;
  16. _bitmapInfo.bmiHeader.biHeight = height;
  17. _bitmapInfo.bmiHeader.biCompression = BI_RGB;
  18. _bitmapInfo.bmiHeader.biSizeImage = width * height;
  19. // 创建缓存帧
  20. _frame = Frame<MediaType::VIDEO>::Alloc(AV_PIX_FMT_BGR24, width, height);
  21. return true;
  22. }
  23. HDC GdiCapturer::GetHdc(int borderWidth, int borderHeight)
  24. {
  25. __CheckNullptr(
  26. BitBlt(_dstHdc, 0, 0, m_width, m_height,
  27. _srcHdc, borderWidth / 2, borderHeight - borderWidth / 2, SRCCOPY));
  28. return _dstHdc;
  29. }
  30. AVFrame* GdiCapturer::GetFrame()
  31. {
  32. auto linesize = _frame->linesize[0];
  33. for (int row = 0; row < m_height; ++row) {
  34. __CheckNullptr(GetDIBits(_dstHdc, _bitmap, m_height - 1 - row, 1, _frame->data[0] + row * linesize, &_bitmapInfo, DIB_RGB_COLORS));
  35. }
  36. return _frame;
  37. }
  38. void GdiCapturer::Close()
  39. {
  40. Free(_frame, [this] { av_frame_free(&_frame); });
  41. Free(_dstHdc, [this] { DeleteObject(_dstHdc); });
  42. Free(_bitmap, [this] { DeleteObject(_bitmap); });
  43. }
  44. GdiCapturer::~GdiCapturer()
  45. {
  46. Close();
  47. }