#ifndef DXGICAPTURER_H
#define DXGICAPTURER_H

#include "IVideoCapturer.h"

#include "d3d/buffer_filler.h"
#include "d3d/convert.h"
#include <d3d11.h>
#include <dxgi1_2.h>
#include <mutex>

namespace avrecorder {
namespace video {

class DxgiCapturerPrivate {
public:
    DxgiCapturerPrivate() = default;
    ~DxgiCapturerPrivate() = default;
    bool Open(int left, int top, int width, int height);
    void Close();
    void CloseInternal(); // 内部清理方法，不使用锁
    AVFrame* GetFrame(bool drawCursor, int left, int top, int right, int bottom);
    bool _bInit = false;
    bool _isCaptureSuccess = false;
    ID3D11Device* _hDevice = nullptr;
    ID3D11DeviceContext* _hContext = nullptr;
    IDXGIOutputDuplication* _hDeskDupl = nullptr;
    IDXGISurface1* _hStagingSurf = nullptr;
    ID3D11Texture2D* _gdiImage = nullptr;
    D3D11_TEXTURE2D_DESC _desc{};
    bool _isAttached = false;
    AVFrame* _xrgbFrame = nullptr;
    AVFrame* _nv12Frame = nullptr;
    BufferFiller _xrgbBuffers;
    BufferFiller _nv12Buffers;
    D3dConverter _rgbToNv12;
    mutable std::mutex _deviceMutex; // D3D设备访问的线程同步
private:
    void drawCursor(HDC hdc, int left, int top, int right, int bottom);
};

class DxgiCapturer : public IVideoCapturer {
public:
    DxgiCapturer();
    ~DxgiCapturer() override;
    bool open(const CaptureTarget& target, int width, int height) override;
    void close() override;
    AVFrame* getFrame() override;
    void setDrawCursor(bool enable) override { m_drawCursor = enable; }
private:
    DxgiCapturerPrivate* d;
    bool m_drawCursor = true;
    int m_left = 0, m_top = 0, m_width = 0, m_height = 0;
    int m_right = 0, m_bottom = 0;
};

} // namespace video
} // namespace avrecorder

#endif // DXGICAPTURER_H
