#include <audiodecoder.h>
#include <except.h>
#include <stdio.h>

#define __MODULE__ "IAudioDecoder"

IAudioDecoder::IAudioDecoder(const CodecInfo& info, const WAVEFORMATEX* inw)
    :record(info)
{
    if (inw == 0)
	throw FATAL("Bad argument: NULL");
    in_fmt = *inw;
}

int IAudioDecoder::GetOutputFormat(WAVEFORMATEX* destfmt)
{
    if (!destfmt)
	return -1;
    WAVEFORMATEX* srcfmt = &in_fmt;

    switch (in_fmt.wBitsPerSample)
    {
    case 0:
    case 2: // IMC
    case 4: // ADPCM
	in_fmt.wBitsPerSample = 16;
	break;
    }

    if (in_fmt.nChannels == 5)
	in_fmt.nChannels = 2; // AC3

    *destfmt = in_fmt;
    switch (in_fmt.wFormatTag)
    {
    case 6: // ALaw  8 -> 16b
    case 7: // uLaw  8 -> 16b
        destfmt->wBitsPerSample = 16;
	break;
    }

    destfmt->wFormatTag = 1;//PCM
    destfmt->nBlockAlign = destfmt->nChannels * destfmt->wBitsPerSample / 8;
    destfmt->nAvgBytesPerSec = destfmt->nSamplesPerSec * destfmt->nBlockAlign;
    destfmt->cbSize = 0;
    printf("src [wFormatTag=%u, nChannels=%u, nSamplesPerSec=%u, nAvgBytesPerSec=%u, nBlockAlign=%u, wBitsPerSample=%u, cbSize=%u]\n",
	   srcfmt->wFormatTag, srcfmt->nChannels, srcfmt->nSamplesPerSec, srcfmt->nAvgBytesPerSec,
	   srcfmt->nBlockAlign, srcfmt->wBitsPerSample, srcfmt->cbSize);

    printf("dst [wFormatTag=%u, nChannels=%u, nSamplesPerSec=%u, nAvgBytesPerSec=%u, nBlockAlign=%u, wBitsPerSample=%u, cbSize=%u]\n",
	   destfmt->wFormatTag, destfmt->nChannels, destfmt->nSamplesPerSec, destfmt->nAvgBytesPerSec,
	   destfmt->nBlockAlign, destfmt->wBitsPerSample, destfmt->cbSize);

    return 0;
}
