#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 invPQGamma(vec3 val)
{
    const float m1 = 0.1593017578125;
    const float m2 = 78.84375;
    const float c2 = 18.8515625;
    const float c3 = 18.6875;
    const float c1 = 0.8359375;
    vec3 exVal = pow(val, vec3(1.0/m2));
    val = pow(max(exVal - c1, 0.0) / (c2 - c3 * exVal), vec3(1.0 / m1));
    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 = invPQGamma(col.rgb);
    col.rgb = fromBT2020Full * col.rgb;
    col.rgb *= 12.0;
    col.rgb = clamp(col.rgb,0.0001,0.999);
    col.rgb = toSRGBMatr * col.rgb;
    col.rgb = sRGBGamma(col.rgb);

    col.rgb = clamp(col.rgb,0.0,1.0);
    col.rgb = pow(col.rgb,vec3(1.0/1.6));

    fragmentColor = col;
}
