#include "mjpeg_encoder.h"
#include <except.h>

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

#define __MODULE__ "MJPEG video encoder"

MJPEG_VideoEncoder::MJPEG_VideoEncoder(const CodecInfo& info, fourcc_t compressor, const BITMAPINFOHEADER& bh)
    :IVideoEncoder(info)
{
    if (!CImage::Supported(bh))
	throw FATAL("Unsupported video format");
    of = bh;
    header = bh;
    of.biCompression = compressor;
}

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

void MJPEG_VideoEncoder::Start()
{
    //cout << "JPEG START" << endl;
    mjpg_rgb_init(header.biWidth, -header.biHeight);
}

void MJPEG_VideoEncoder::Stop()
{
    //cout << "JPEG STOP" << endl;
    mjpg_cleanup();
}

int MJPEG_VideoEncoder::EncodeFrame(CImage* src, void* dest, int* is_keyframe, size_t* size, int* lpckid=0)
{
    if ((dest == 0) || (src == 0))
    {
	if (size)
	    *size = 0;
	return 0;
    }
    CImage* tmp;
    if (header.biBitCount != 24 || header.biCompression)
    {
	BitmapInfo supp(header);
	supp.SetBits(24);
	supp.biBitCount=24;
	supp.biCompression=0;
	tmp = new CImage(src, &supp);
    }
    else
    {
	tmp = new CImage(src);
    }
    tmp->ByteSwap();
    int sz = mjpg_rgb_compress((unsigned char*)dest, tmp->Data(),
			       tmp->Pixels());
    if (size)
	*size = sz;
    if (is_keyframe)
	*is_keyframe = 16;//AVIIF_KEYFRAME
    delete tmp;
    return 0;
}

int MJPEG_VideoEncoder::SetQuality(int quality)
{
    mjpg_set_quality(quality / 100);
    return 0;
}

int MJPEG_VideoEncoder::GetQuality() const
{
    return mjpg_get_quality();
}
