// actualy not used HLG shader

//#define V1GL_HLG_KOEFFS hlg

uniform sampler2DRect Ytex;
uniform sampler2DRect Utex,Vtex;
uniform vec3 offset;
uniform vec4 cspace;
// RGB coefficients
uniform vec3 Rcoeff;
uniform vec3 Gcoeff;
uniform vec3 Bcoeff;
uniform vec4  V1GL_HLG_KOEFFS ;
uniform float imgHeight;

void main(void) {
    vec3 YUV, RGB;
    float nx,ny,nxuv,nyuv;
    float r,r1;
    nx=0.5 + gl_TexCoord[0].x;
    ny=imgHeight - gl_TexCoord[0].y;
    nxuv=nx / cspace.r;
    nyuv=ny / cspace.g;
    YUV.x=texture2DRect(Ytex,vec2(nx,ny)).r / cspace.b     + texture2DRect(Ytex,vec2(nx,ny)).g * cspace.a;
    YUV.y=texture2DRect(Utex,vec2(nxuv,nyuv)).r / cspace.b +  texture2DRect(Utex,vec2(nxuv,nyuv)).g * cspace.a;
    YUV.z=texture2DRect(Vtex,vec2(nxuv,nyuv)).r / cspace.b +  texture2DRect(Vtex,vec2(nxuv,nyuv)).g * cspace.a;

    YUV += offset;

    RGB.r = dot(YUV, Rcoeff);
    RGB.g = dot(YUV, Gcoeff);
    RGB.b = dot(YUV, Bcoeff);

    r1 = 18.8515625 - 18.6875 * pow( RGB.r, 1.0 / 78.84375);
    r = max( pow( RGB.r, 1.0 / 78.84375 ) - 0.8359375, 0.0 ) ;
    if( r > 1.0 ) r = 1.0; else if( r < 0.0 ) r = 0.0;
    RGB.r = 1000 * pow( r / r1, 1.0 / 0.1593017578 );

    r1 = 18.8515625 - 18.6875 * pow( RGB.g, 1.0 / 78.84375);
    r = max( pow( RGB.g, 1.0 / 78.84375 ) - 0.8359375, 0.0 ) ;
    if( r > 1.0 ) r = 1.0; else if( r < 0.0 ) r = 0.0;
    RGB.g = 1000 * pow( r / r1, 1.0 / 0.1593017578 );

    r1 = 18.8515625 - 18.6875 * pow( RGB.b, 1.0 / 78.84375);
    r = max( pow( RGB.b, 1.0 / 78.84375 ) - 0.8359375, 0.0 ) ;
    if( r > 1.0 ) r = 1.0; else if( r < 0.0 ) r = 0.0;
    RGB.b = 1000 * pow( r / r1, 1.0 / 0.1593017578 );

    float Yd = 0.262700* RGB.r + 0.678000 * RGB.g + 0.059300 *  RGB.b -  V1GL_HLG_KOEFFS .g;
    if( Yd <= 0. )
    {
        RGB.r = 0.;;
        RGB.g =0.;
        RGB.b = 0.;
    }
    else {
        float mYs = pow((Yd ) /  V1GL_HLG_KOEFFS .r,  V1GL_HLG_KOEFFS .a );
        float Rs =  ( RGB.r -  V1GL_HLG_KOEFFS .g ) / ( V1GL_HLG_KOEFFS .r * mYs);
        if( Rs < 0. ) Rs = 0.; else if( Rs > 12. ) Rs = 12.;
        float Gs =  ( RGB.g -  V1GL_HLG_KOEFFS .g ) / ( V1GL_HLG_KOEFFS .r * mYs);
        if( Gs < 0. ) Gs = 0.; else if( Gs > 12. ) Gs = 12.;
        float Bs =  ( RGB.b -  V1GL_HLG_KOEFFS .g ) / ( V1GL_HLG_KOEFFS .r * mYs);
        if( Bs < 0. ) Bs = 0.;  else if( Bs > 12. ) Bs = 12.;
        RGB.r = Rs < 1.0 ? 0.5 * sqrt(Rs) : 0.17883277 * log(Rs - 0.28466892) + 0.55991073;
        if( RGB.r > 1.0 ) RGB.r = 1.0; else if( RGB.r < 0.0 ) RGB.r = 0.0;
        RGB.g = Gs < 1.0 ? 0.5 * sqrt(Gs) : 0.17883277 * log(Gs - 0.28466892) + 0.55991073;
        if( RGB.g > 1.0 ) RGB.g = 1.0; else if( RGB.g < 0.0 ) RGB.g = 0.0;
        RGB.b = Bs < 1.0 ? 0.5 * sqrt(Bs) : 0.17883277 * log(Bs - 0.28466892) + 0.55991073;
        if( RGB.b > 1.0 ) RGB.b = 1.0; else if( RGB.b < 0.0 ) RGB.b = 0.0;
    }

    gl_FragColor = vec4(RGB, 1.0);
}


