/*
        Frank Lyonnet 1993
*/

/*
 * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
 * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
 * The conversion equations to be implemented are therefore
 *      R = Y                + 1.40200 * Cr
 *      G = Y - 0.34414 * Cb - 0.71414 * Cr
 *      B = Y + 1.77200 * Cb
 * where Cb and Cr represent the incoming values less MAXJSAMPLE/2.
 * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
 *
 * To avoid floating-point arithmetic, we represent the fractional constants
 * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
 * the products by 2^16, with appropriate rounding, to get the correct answer.
 * Notice that Y, being an integral input, does not contribute any fraction
 * so it need not participate in the rounding.
 *
 * For even more speed, we avoid doing any multiplications in the inner loop
 * by precalculating the constants times Cb and Cr for all possible values.
 * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
 * for 12-bit samples it is still acceptable.  It's not very reasonable for
 * 16-bit samples, but if you want lossless storage you shouldn't be changing
 * colorspace anyway.
 * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
 * values for the G calculation are left scaled up, since we must add them
 * together before rounding.
 */

#define SCALEBITS       16      /* speediest right-shift on some machines */
#define ONE_HALF        ((int) 1 << (SCALEBITS-1))
#define FIX(x)          ((int) ((x) * (1L<<SCALEBITS) + 0.5))

#define RIGHT_SHIFT(x,shft)     ((x) >> (shft))

#define MAXJSAMPLE 255

static int RRBuffer[MAXJSAMPLE+1];
static int BBBuffer[MAXJSAMPLE+1];
static int RGBuffer[MAXJSAMPLE+1];
static int BGBuffer[MAXJSAMPLE+1];

/*
 * Initialize for YCC->RGB colorspace conversion.
 */

void init_yuv_to_rgb_convert(int * RRBuffer , int * BBBuffer , int * RGBuffer , int * BGBuffer )
{
  int i, x2;

  for (i = 0; i <= MAXJSAMPLE; i++) {
    /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
    /* The Cb or Cr value we are thinking of is x = i - MAXJSAMPLE/2 */
    x2 = 2*i - MAXJSAMPLE;      /* twice x */
    /* Cr=>R value is nearest int to 1.40200 * x */
    RRBuffer[i] = (int)
                    RIGHT_SHIFT(FIX(1.40200/2) * x2 + ONE_HALF, SCALEBITS);
    /* Cb=>B value is nearest int to 1.77200 * x */
    BBBuffer[i] = (int)
                    RIGHT_SHIFT(FIX(1.77200/2) * x2 + ONE_HALF, SCALEBITS);
    /* Cr=>G value is scaled-up -0.71414 * x */
    RGBuffer[i] = (- FIX(0.71414/2)) * x2;
    /* Cb=>G value is scaled-up -0.34414 * x */
    /* We also add in ONE_HALF so that need not do it in inner loop */
    BGBuffer[i] = (- FIX(0.34414/2)) * x2 + ONE_HALF;
  }
}



