
#ifndef __AUDIO_CAPTURER_H__
#define __AUDIO_CAPTURER_H__

#include "iaudiocapturer.h"

#include <audioclient.h>
#include <combaseapi.h>
#include <mmdeviceapi.h>

#include <memory>
#include <thread>
#include <vector>
#include <mutex>

class AudioCapturer : public IAudioCapturer
{
public:
    bool Init(Type deviceType) override;
    bool Start() override;
    void Stop() override;

    const AudioFormat& GetFormat() const override { return _format; }
    int readAudioData(char* buf, int maxLen) override;

private:
    mutable AudioFormat _format;
    bool _isInit = false;
    Type _deviceType;
    IMMDeviceEnumerator* _pDeviceEnumerator = nullptr;
    IMMDevice* _pDevice = nullptr;
    IAudioClient* _pAudioClient = nullptr;
    IAudioCaptureClient* _pAudioCaptureClient = nullptr;
    std::thread* _captureThread = nullptr;
    bool _loopFlag = false;
    WAVEFORMATEXTENSIBLE _formatex;
    std::vector<char> _buffer;
    std::mutex _bufferMutex;
    
    // 静音播放器相关成员
    std::atomic<bool> _silencePlayerRunning{false};
    std::thread* _silencePlayerThread = nullptr;
    IMMDevice* _pSilenceDevice = nullptr;
    IAudioClient* _pSilenceAudioClient = nullptr;
    IAudioRenderClient* _pSilenceRenderClient = nullptr;

    bool _CreateDeviceEnumerator(IMMDeviceEnumerator** enumerator);
    bool _CreateDevice(IMMDeviceEnumerator* enumerator, IMMDevice** device);
    bool _CreateAudioClient(IMMDevice* device, IAudioClient** audioClient);
    bool _IsFormatSupported(IAudioClient* audioClient);
    bool _GetPreferFormat(IAudioClient* audioClient,
        WAVEFORMATEXTENSIBLE* formatex);
    bool _InitAudioClient(IAudioClient* audioClient,
        WAVEFORMATEXTENSIBLE* formatex);
    bool _CreateAudioCaptureClient(IAudioClient* audioClient,
        IAudioCaptureClient** audioCaptureClient);
    bool _ThreadRun(IAudioClient* audio_client,
        IAudioCaptureClient* audio_capture_client);
    
    // 静音播放器方法
    bool _InitializeSilencePlayer();
    void _CleanupSilencePlayer();
    void _SilencePlayerThreadFunc();
};

#endif
