#version 330

#include "commonMLDX.h"
#include "alpha.h"
#include "inputShaderHelperGL.h"
#include "inputColorHelper.h"

uniform sampler2DRect inputTex0;
uniform sampler2DRect inputTex1;
uniform sampler2DRect inputTex2;
uniform sampler2DRect inputTex3;
uniform sampler2DRect inputTexMask;
uniform vec4 endColor;
uniform float endOpacity;

#ifdef FULL_RANGE
//full range values from wikipedia https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.709_conversion
const vec4 yuv2R = vec4( 1.402,1., 0.0,0.0  );
const vec4 yuv2G = vec4(-0.714136,1.,-0.344136,0.0  );
const vec4 yuv2B = vec4( 0.000000,1., 1.772,0.0  );
const vec4 stdbias = vec4(-0.5  , 0.0,  -0.5   ,0.0  );
#else
const vec4 yuv2R = vec4( 1.793,1.164383, 0.000000,0.0  );
const vec4 yuv2G = vec4(-0.534,1.164383,-0.213,0.0  );
const vec4 yuv2B = vec4( 0.000000,1.164383, 2.115,0.0  );
const vec4 stdbias = vec4(-0.5  , -0.0625,  -0.5   ,0.0  );
#endif

const vec4 scale10to16 = vec4(64.0, 64.0, 64.0, 64.0);
const vec4 scale12to16 = vec4(16.0, 16.0, 16.0, 16.0);

in vec2 fsTexY;
in vec2 fsTexUV;
in vec2 fsTexA;
in vec2 fsTextureMask;
out vec4 outColor;

void main()
{
    vec4 yuvIn;
    vec4 yuvOut;

    yuvIn.g = texture(inputTex0, fsTexY).r;
    yuvIn.b = texture(inputTex1, fsTexUV).r;
    yuvIn.r = texture(inputTex2, fsTexUV).r;

#ifdef HAS_ALPHA
    yuvIn.a = texture(inputTex3, fsTexA).r;
#endif

#ifdef IS_10BIT
    yuvIn*=scale10to16;
#endif

#ifdef IS_12BIT
    yuvIn*=scale12to16;
#endif

    yuvIn+=stdbias;

#ifndef HAS_ALPHA
    yuvIn.a=1.0;
#endif

    outColor=vec4(dot(yuv2R, yuvIn),
                  dot(yuv2G, yuvIn),
                  dot(yuv2B, yuvIn),
                  yuvIn.a);

    outColor=processColorProfile(outColor);

#ifdef USE_MASK
    multiplyOpacity(outColor, texture(inputTexMask, fsTextureMask).a);
#endif

#ifdef USE_END_COLOR
    mixColor(outColor, endColor, outColor, endOpacity);
#endif

}
