/*
 * Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

param sampler lumaTex;
param sampler crTex;
param sampler cbTex;
param sampler alphaTex;

/**
 * All textures are normalized to 0..1 so we don't have to care that
 * the Cb and Cr textures may be 1/2 or 1/4 the size of luma and alpha
 *
 * Texture scale values are determined by physical versus content sizes
 * so we can adjust the actual sampler coords.
 *
 * All YCbCr images start at (0,0) so we don't have to deal with
 * coordinate offsets, we only need to scale texCoord to fit
 * in the content size of the texture
 */
param float4 lumaAlphaScale;    // x,y = luma scale, z,w = alpha scale
param float4 cbCrScale;         // x,y = Cb scale, z,w = Cr scale

const float Y_ADJUST = 16.0 / 255.0;

float4 paint(float2 texCoord)
{
    float2 imgCoord;

    // fetch luma sample
    float luma = 1.1644 * (sample(lumaTex, texCoord * lumaAlphaScale.xy).a - Y_ADJUST);
    float cb = sample(cbTex, texCoord * cbCrScale.xy).a - 0.5;
    float cr = sample(crTex, texCoord * cbCrScale.zw).a - 0.5;

    float4 RGBA;
    RGBA.r = luma + (1.5966 * cr);
    RGBA.g = luma - (0.3920 * cb) - (0.8132 * cr);
    RGBA.b = luma + (2.0184 * cb);

    // nonzero alpha scale indicates the presence of an alpha channel, otherwise it's set to 1.0
    if (lumaAlphaScale.z > 0.0) {
        RGBA.a = sample(alphaTex, texCoord * lumaAlphaScale.zw).a;
        RGBA.rgb *= RGBA.a; // premultiply alpha so it looks correct
    } else {
        RGBA.a = 1.0;
    }

    return RGBA;
}
