//#include "stdafx.h"
#include <stdint.h>
#include "x264.h"
#include <atlimage.h>


#define WTH	680
#define HIG	382

int SRCW;
int SRCH;

extern "C"
{
	void GetSrcWH();
	void GetDesktopYuv();
	x264_picture_t pic;
}
void GetSrcWH()
{
	HDC hdcSrc = GetDC(NULL);//创建了屏幕的HDC
	SRCW = GetDeviceCaps(hdcSrc, HORZRES);
	SRCH = GetDeviceCaps(hdcSrc, VERTRES);
}

void GetDesktopYuv()
{
	COLORREF  color ;
	HDC hdcSrc = GetDC(NULL);//创建了屏幕的HDC
	int i,j,t;
	int nBitPerPixel = GetDeviceCaps(hdcSrc, BITSPIXEL);
	CImage image;
	image.Create(WTH,HIG, nBitPerPixel);

	SetStretchBltMode(image.GetDC(),HALFTONE);
	image.ReleaseDC();
	SetBrushOrgEx(image.GetDC(), 0, 0, NULL);
	image.ReleaseDC();
	StretchBlt(image.GetDC(),0,0,WTH,HIG,hdcSrc,0,0,SRCW,SRCH,SRCCOPY);
	ReleaseDC(NULL, hdcSrc);
	image.ReleaseDC();


	unsigned char*bufY, *bufU, *bufV; 
	unsigned char y, u, v,r,g,b;    
	double tempy = 0.0;
    bufY = pic.img.plane[0];    
    bufU = pic.img.plane[1];    
    bufV = pic.img.plane[2]; 
	for(i=0;i<HIG;i++)
	{
		for(j=0;j<WTH;j++)
		{
			//修改，直接读内存
			color = (*(COLORREF*)(image.GetPixelAddress(j, i)));
			b = GetRValue(color);   //lpBits[i*nWidthbytes+j*3+2];
			g = GetGValue(color); // lpBits[i*nWidthbytes+j*3+1];
			r = GetBValue(color); //lpBits[i*nWidthbytes+j*3+0];

			//计算可优化，计算已得到优化
		//	tempy = 0.299*r + 0.587*g + 0.114*b;
			y =	( (  66 * r + 129 * g +  25 * b + 128) >> 8) +  16;//(unsigned char)tempy;            
            u = ( ( -38 * r -  74 * g + 112 * b + 128) >> 8) + 128;//(unsigned char)(0.564 * ((double)b - tempy) + 128.0);              
            v = ( ( 112 * r -  94 * g -  18 * b + 128) >> 8) + 128;//(unsigned char)(0.713 * ((double)r - tempy) + 128.0);

			*(bufY++) = y;
              
			t = HIG-1-j;
            if (t%2==0 && i%2==0)   
            {   
                
                *(bufU++) =u;   
                //存u分量   
				*(bufV++) =v; 
				  
            }
		}
	}

}


