#include "mjpeg_decoder.h"
extern "C"
{
#include "mjpeg.h"
}

MJPEG_VideoDecoder::MJPEG_VideoDecoder(const CodecInfo& info, const BITMAPINFOHEADER& format, int flip)
    :IVideoDecoder(info, format)
{
    m_obh = format;
    m_obh.SetBits(24);
    m_decoder = m_obh;
    if(!flip)
	m_obh.biHeight*=-1;
}

MJPEG_VideoDecoder::~MJPEG_VideoDecoder()
{
    Stop();
}

static int bgr24_to_bgr32(char *dest, char *src, int p)
{
    register char *s = src;
    register char *d = dest;

    while (p--) {
        *(d++) = s[0];
        *(d++) = s[1];
        *(d++) = s[2];
	*(d++) = 0;
	s +=3;
    }
    return d-dest;
}

int MJPEG_VideoDecoder::DecodeInternal(void* src, size_t size, int is_keyframe, CImage* pImage)
{
    mjpg_bgr_decompress(pImage->Data(), (unsigned char*)src, size);
    return 0;
}

void MJPEG_VideoDecoder::StartInternal()
{
    mjpg_dec_rgb_init(m_obh.biWidth, m_obh.biHeight);
}

void MJPEG_VideoDecoder::StopInternal()
{
    mjpg_dec_cleanup();
}

int MJPEG_VideoDecoder::SetDestFmt(int bits, fourcc_t csp)
{
    if (!CImage::Supported(csp, bits))
	return -1;

    if (!csp)
	switch (bits)
	{
	case 15:
	case 16:
	case 24:
	case 32:
	    m_obh.SetBits(bits);
	    Restart();
	    return 0;
	}

    if (csp)
	m_obh.SetSpace(csp);
    else
	m_obh.SetBits(bits);

    m_decoder = m_obh;

    return 0;
}
