#include "AudioCapture.h"
#include <QDebug>
#include <QDateTime>
#include <CCycleBuffer.h>
//#include "cameraLog.h"
#include "kylinlogger_cpp.h"
AudioCapture::AudioCapture(CCycleBuffer *buf)
{
    //QAudioDeviceInfo info(QAudioDeviceInfo::defaultInputDevice());
    //capture_init(info);

    m_audio_buf = buf;
    audioInput = NULL;
    m_audio_click = false;
#if 0
    for( QAudioDeviceInfo &deviceInfo: QAudioDeviceInfo::availableDevices(QAudio::AudioInput))
    {
        if(deviceInfo.deviceName().contains("Camera"))
        {
            qDebug()<<"您选择了录制系统内部设备:"<<deviceInfo.deviceName();
            capture_init(deviceInfo, 16000, 1, 16);
            break;
        }
        else
        {
             qDebug()<<deviceInfo.deviceName();
        }

    }
#endif
}

AudioCapture::~AudioCapture()
{
    m_audio_click = false;
    if(audioInput) {
        audioInput->stop();
        delete audioInput;
    }
}

void AudioCapture::capture_deinit()
{
    m_audio_click = false;
    if(audioInput) {
        audioInput->stop();
        delete audioInput;
    }
}

int AudioCapture::capture_init(const QAudioDeviceInfo &deviceInfo, int nsamplerate, int nchannels, int nsamplesize)
{
    m_format.setSampleRate(nsamplerate);
    m_format.setChannelCount(nchannels);
    m_format.setSampleSize(nsamplesize);
    m_format.setSampleType(QAudioFormat::SignedInt);
    m_format.setByteOrder(QAudioFormat::LittleEndian);
    m_format.setCodec("audio/pcm");

    if (!deviceInfo.isFormatSupported(m_format))
    {
        qWarning() << "Default format not supported - trying to use nearest";
        m_format = deviceInfo.nearestFormat(m_format);
    }

    audioInput = new QAudioInput(deviceInfo, m_format);

    audioInput->setBufferSize(4*1024);

    device = audioInput->start();
    LOG(CAMERA_LOG,NOTICE) << "Start audio capture ";
    connect(device, SIGNAL(readyRead()), this, SLOT(read_data()));

    return 0;
}

void AudioCapture::read_data()
{
    qint64 len = audioInput->bytesReady();
    if (len <= 0)
        return;

    QAudio::State state = audioInput->state();

    qint64 l = 0;
    l = device->read(m_buf, 8*1024);
    if (l <= 0)
	return;

    if (state == QAudio::ActiveState && m_audio_click == true)
        m_audio_buf->Write((uint8_t *)m_buf, l);
}

void AudioCapture::set_volume(qreal Volume)
{
    audioInput->setVolume(Volume);
}

qreal AudioCapture::volume()
{
    return audioInput->volume();
}

