#include "inputShaderHelper.h"
#include "commonMLDX.h"
#include "alpha.h"
#include "inputColorHelper.h"

fragment float4 fragmentFunc(inputVertexType input [[stage_in]]
                                 ,texture2d<half> inputTex0 [[ texture(0) ]]
                                 ,texture2d<half> inputTex1 [[ texture(1) ]]
                                 ,texture2d<half> inputTex2 [[ texture(2) ]]
                                 ,texture2d<half> inputTex3 [[ texture(3) ]]
                                 ,texture2d<half> maskTex [[ texture(4) ]]
                                 ,constant planarUniforms& uniforms[[ buffer(0) ]]
)
{
#ifdef AYUV
    // input format:  AYUV
    // output format: RGBA
    // we require:
    // output.R == input.V
    // output.G == input.Y
    // output.B == input.U
    // output.A == input.A

    float4 yuvIn = textureFetchNearest(inputTex0, input.texCoordY).agbr;
    yuvIn += stdbias;

    float4 outColor = float4(dot(yuv2R, yuvIn),
                             dot(yuv2G, yuvIn),
                             dot(yuv2B, yuvIn),
                             yuvIn.a);

    outColor=processColorProfile(outColor);

#  ifdef USE_MASK
    multiplyOpacity(outColor, textureFetchNearest(maskTex, input.maskCoord).a);
#endif

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

    return outColor;
#else
    float4 y0;
    float4 y1;
    
    float isOddUV;
    
    isOddUV = floor(fract(input.texCoordPS.x * 0.5) * 2.0);
    float2 texCoord=input.texCoordY*float2(.5,1.0);

    float alpha = 1.0;
#  ifdef YUYV
    y0 = float4(inputTex0.sample(nearestSampler,texCoord)).argb;
#endif

#ifdef Y1UY0V
    y0 = float4(inputTex0.sample(nearestSampler,texCoord)).abgr;
#endif

#ifdef UYVY
    y0 = float4(inputTex0.sample(nearestSampler,texCoord));
#endif

#ifdef YUVA
    y0 = float4(inputTex0.sample(nearestSampler,texCoord));
    alpha = float4(inputTex1.sample(nearestSampler,texCoord)).r;
#endif

    y1=y0;
    y1.g=y0.a;
    y0=mix(y0,y1,isOddUV);
    
    y0+=stdbias;
    
    float4 outColor=float4(dot(yuv2R, y0),
                  dot(yuv2G, y0),
                  dot(yuv2B, y0),
                  alpha);

    outColor=processColorProfile(outColor);

#ifdef USE_MASK
    multiplyOpacity(outColor, textureFetchNearest(maskTex, input.maskCoord).a);
#endif

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

    return outColor;
#endif
}
