
#include "stdafx.h"
#include "windows.h"
#include "ImageFmtExchg.h"


unsigned char *RawStrmToRaw10(unsigned char *pImgStrmBuffer, ULONG lImgStrmSiz, ULONG *lRaw10Siz, int *errState)
{
	ULONG l, n;
	ULONG nRaw10Size = lImgStrmSiz / 5 * 8;
	unsigned char *pRaw10Buffer = NULL;
	unsigned char raw10Ext[4];

	if (lImgStrmSiz == 0)
	{
		if (errState) *errState = __ILLEGAL_STRM_DATA_SIZE__;
		return pRaw10Buffer;
	}

	if (lImgStrmSiz % 5) nRaw10Size += 8;	// to extra data size

	pRaw10Buffer = (unsigned char *)malloc(nRaw10Size);
	if (pRaw10Buffer == NULL)
	{
		if (errState) *errState = __FAIL_ALLOCATED_RAW10_BUFFER__;
		return pRaw10Buffer;
	}

	if (errState) *errState = __NO_ERROR_EXCHG__;
	*lRaw10Siz = nRaw10Size;

	l = n = 0;
	while (l < lImgStrmSiz)
	{
		int m;
		/*
		AAAA-AAAA BBBB-BBBB
		CCCC-CCCC DDDD-DDDD
		aabbccdd

		little ending raw8
		BBBB-BBBB AAAA-AAAA DDDD-DDDD CCCC-CCCC aabbccdd

		0000-00BB BBBB-BBbb
		0000-00AA AAAA-AAaa
		0000-00DD DDDD-DDdd
		0000-00CC CCCC-CCcc

		little ending => raw10
		BBBB-BBbb 0000-00BB AAAA-AAaa 0000-00AA DDDD-DDdd 0000-00DD CCCC-CCcc 0000-00CC
		*/
		raw10Ext[0] = (pImgStrmBuffer[l + 4] >> 4) & 0x03;
		raw10Ext[1] = (pImgStrmBuffer[l + 4] >> 6) & 0x03;
		raw10Ext[2] = (pImgStrmBuffer[l + 4] >> 0) & 0x03;
		raw10Ext[3] = (pImgStrmBuffer[l + 4] >> 2) & 0x03;
		for (m = 0; m < 4; m++)
		{
			pRaw10Buffer[n++] = (pImgStrmBuffer[l] << 2) + raw10Ext[m];	// low byte
			pRaw10Buffer[n++] = (pImgStrmBuffer[l++] >> 6);				// High byte only b1 b0
		}
		l++;	// skip padding
	}

	return pRaw10Buffer;
}


void freeRawExchgBuffer(unsigned char *pRawStrmBuffer)
{
	free(pRawStrmBuffer);
}