#version 330

#include "commonMLDX.h"
#include "alpha.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;


const vec4 std709R = vec4( 1.793,1.164383, 0.000000,0.0  );
const vec4 std709G = vec4(-0.534,1.164383,-0.213,0.0  );
const vec4 std709B = vec4( 0.000000,1.164383, 2.115,0.0  );
const vec4 stdbias = vec4(-0.5  , -0.0625,  -0.5   ,0.0  );
const vec4 scale10to16 = vec4(64.0, 64.0, 64.0, 64.0);
const vec4 scale12to16 = vec4(16.0, 16.0, 16.0, 16.0);



uniform float vScale;
uniform float hScale;

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

void main()
{
    float isOddLine;
    vec4 yuv0;
    vec4 yuv1;
    vec4 yuv2;
    vec4 avg;
    vec2 tc00;
    vec2 tc10;
    vec2 tc20;

    tc10=fsTexY;

#ifdef IS_ODD
    isOddLine=1.0 - floor(fract(tc10.y * 0.5) * 2.0);
#else
    isOddLine=floor(fract(tc10.y * 0.5) * 2.0);
#endif

    //above and below lines start with same coordinates
    tc00=tc10;
    tc20=tc10;
    //for above line, subtract 1
    tc00.y-=isOddLine;
    //for below line, add 1
    tc20.y+=isOddLine;


    yuv0.g = texture(inputTex0, tc00).r;
    yuv1.g = texture(inputTex0, tc10).r;
    yuv2.g = texture(inputTex0, tc20).r;

    tc00*=vec2(hScale,vScale);
    tc10*=vec2(hScale,vScale);
    tc20*=vec2(hScale,vScale);

    yuv0.b = texture(inputTex1, tc00).r;
    yuv1.b = texture(inputTex1, tc10).r;
    yuv2.b = texture(inputTex1, tc20).r;

    yuv0.r = texture(inputTex2, tc00).r;
    yuv1.r = texture(inputTex2, tc10).r;
    yuv2.r = texture(inputTex2, tc20).r;

#ifdef HAS_ALPHA
    yuv0.a = texture(inputTex3, tc00).r;
    yuv1.a = texture(inputTex3, tc10).r;
    yuv2.a = texture(inputTex3, tc20).r;
#endif


    avg=(yuv0+yuv2)*0.5;

    if(yuv1.g>=yuv0.g)
    {
        if(yuv1.g>yuv2.g)
            yuv1=avg;
    }
    else
    {
        if(yuv1.g<yuv2.g)
            yuv1=avg;
    }

#ifdef IS_10BIT
    yuv1*=scale10to16;
#endif

#ifdef IS_12BIT
    yuv1*=scale12to16;
#endif

#ifndef HAS_ALPHA
    yuv1.a=1.0;
#endif

    yuv1+=stdbias;

    outColor=vec4(dot(std709R, yuv1),
                  dot(std709G, yuv1),
                  dot(std709B, yuv1),
                  yuv1.a);

    outColor=processColorProfile(outColor);

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

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