#version 300 es
#extension GL_OES_EGL_image_external_essl3 : require

precision highp float;
//precision mediump float;

in vec2 vTextureCoord;

uniform lowp samplerExternalOES uSampler;
out vec4 fragmentColor;

vec3 sRGBGamma(in vec3 col)
{
    vec3 sV = step(col,vec3(0.0031308));
    return mix(max(1.055 * pow (col, vec3(1.0/2.4)) - 0.055,vec3(0.0)),(col*12.92),sV);
}

vec3 invHLGGamma(vec3 val)
{
    const float a = 0.17883277;
    const float b = 1.0 - (4.0 * a); //0.28466892;
    const float c = 0.5 - a * log(4.0 * a); //0.55991073
    const float e = 2.71828182845904523536;
    vec3 lowVal = pow(val, vec3(2.0)) / 3.0;
    vec3 highVal = (pow(vec3(e),vec3(((val - c)/a))) + b) / 12.0;
    val.r = val.r <= 0.5 ? lowVal.r : highVal.r;
    val.g = val.g <= 0.5 ? lowVal.g : highVal.g;
    val.b = val.b <= 0.5 ? lowVal.b : highVal.b;
    return val;
}

void main(void)
{
    const highp mat3 toSRGBMatr = mat3(2.034302,-0.228882,-0.00842285,
    -0.727295,1.23168945,-0.15332,
    -0.307007,-0.00280762,1.16174316);

    const highp mat3 fromBT2020Full = mat3(0.8352,0.05407,-0.002447,
    0.04872,0.9290,0.03639,
    0.1161,0.01695,0.9661);

    highp vec4 col = texture(uSampler, vTextureCoord.st);

    col.rgb = invHLGGamma(col.rgb);
    col.rgb = fromBT2020Full * col.rgb;
    col.rgb = clamp(col.rgb,0.0001,0.999);
    col.rgb = toSRGBMatr * col.rgb;
    col.rgb = clamp(col.rgb,0.0,1.0);
    col.rgb = sRGBGamma(col.rgb);
    fragmentColor = col;
}
