#version 330

#include "alpha.h"

uniform sampler2DRect inputTex;
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  );

in vec2 fsTexture;
in vec2 fsTextureMask;
out vec4 outColor;

void main()
{
    float isOddLine;
    float isOddUV;
    vec2 tc00;
    vec2 tc10;
    vec2 tc20;
    vec4 c00;
    vec4 c10;
    vec4 c20;
    vec4 avg;

    tc10=fsTexture.xy;

#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
    isOddUV = floor(fract(tc10.x * 0.5) * 2.0);

    tc10.x*=.5;

    //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;

#ifdef YUYV
    c00 = texture(inputTex, tc00).abgr;
    c10 = texture(inputTex, tc10).abgr;
    c20 = texture(inputTex, tc20).abgr;
#endif

#ifdef UYVY
    c00 = texture(inputTex, tc00);
    c10 = texture(inputTex, tc10);
    c20 = texture(inputTex, tc20);
#endif

    c00.g=mix(c00.g,c00.a,isOddUV);
    c10.g=mix(c10.g,c10.a,isOddUV);
    c20.g=mix(c20.g,c20.a,isOddUV);

    avg=(c00+c20)*0.5;

    if(c10.g>=c00.g)
    {
        if(c10.g>c20.g)
            c10=avg;
    }
    else
    {
        if(c10.g<c20.g)
            c10=avg;
    }
    c10+=stdbias;

    outColor=vec4(dot(std709R, c10),
                  dot(std709G, c10),
                  dot(std709B, c10),
                  1.0);

#ifdef USE_MASK
    multiplyOpacity(outColor, texture(inputTexMask, fsTextureMask).a);
#endif
    
#ifdef USE_END_COLOR
    mixColor(outColor, endColor, outColor, endOpacity);
#endif

}
