1/*
2 * jccolor.c
3 *
4 * Copyright (C) 1991-1996, Thomas G. Lane.
5 * This file is part of the Independent JPEG Group's software.
6 * For conditions of distribution and use, see the accompanying README file.
7 *
8 * This file contains input colorspace conversion routines.
9 */
10
11#define JPEG_INTERNALS
12#include "jinclude.h"
13#include "jpeglib.h"
14
15// this enables unrolling null_convert's loop, and reading/write ints for speed
16#define ENABLE_ANDROID_NULL_CONVERT
17
18/* Private subobject */
19
20typedef struct {
21  struct jpeg_color_converter pub; /* public fields */
22
23  /* Private state for RGB->YCC conversion */
24  INT32 * rgb_ycc_tab;		/* => table for RGB to YCbCr conversion */
25} my_color_converter;
26
27typedef my_color_converter * my_cconvert_ptr;
28
29
30/**************** RGB -> YCbCr conversion: most common case **************/
31
32/*
33 * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
34 * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
35 * The conversion equations to be implemented are therefore
36 *	Y  =  0.29900 * R + 0.58700 * G + 0.11400 * B
37 *	Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B  + CENTERJSAMPLE
38 *	Cr =  0.50000 * R - 0.41869 * G - 0.08131 * B  + CENTERJSAMPLE
39 * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
40 * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
41 * rather than CENTERJSAMPLE, for Cb and Cr.  This gave equal positive and
42 * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
43 * were not represented exactly.  Now we sacrifice exact representation of
44 * maximum red and maximum blue in order to get exact grayscales.
45 *
46 * To avoid floating-point arithmetic, we represent the fractional constants
47 * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
48 * the products by 2^16, with appropriate rounding, to get the correct answer.
49 *
50 * For even more speed, we avoid doing any multiplications in the inner loop
51 * by precalculating the constants times R,G,B for all possible values.
52 * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
53 * for 12-bit samples it is still acceptable.  It's not very reasonable for
54 * 16-bit samples, but if you want lossless storage you shouldn't be changing
55 * colorspace anyway.
56 * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
57 * in the tables to save adding them separately in the inner loop.
58 */
59
60#define SCALEBITS	16	/* speediest right-shift on some machines */
61#define CBCR_OFFSET	((INT32) CENTERJSAMPLE << SCALEBITS)
62#define ONE_HALF	((INT32) 1 << (SCALEBITS-1))
63#define FIX(x)		((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
64
65/* We allocate one big table and divide it up into eight parts, instead of
66 * doing eight alloc_small requests.  This lets us use a single table base
67 * address, which can be held in a register in the inner loops on many
68 * machines (more than can hold all eight addresses, anyway).
69 */
70
71#define R_Y_OFF		0			/* offset to R => Y section */
72#define G_Y_OFF		(1*(MAXJSAMPLE+1))	/* offset to G => Y section */
73#define B_Y_OFF		(2*(MAXJSAMPLE+1))	/* etc. */
74#define R_CB_OFF	(3*(MAXJSAMPLE+1))
75#define G_CB_OFF	(4*(MAXJSAMPLE+1))
76#define B_CB_OFF	(5*(MAXJSAMPLE+1))
77#define R_CR_OFF	B_CB_OFF		/* B=>Cb, R=>Cr are the same */
78#define G_CR_OFF	(6*(MAXJSAMPLE+1))
79#define B_CR_OFF	(7*(MAXJSAMPLE+1))
80#define TABLE_SIZE	(8*(MAXJSAMPLE+1))
81
82
83/*
84 * Initialize for RGB->YCC colorspace conversion.
85 */
86
87METHODDEF(void)
88rgb_ycc_start (j_compress_ptr cinfo)
89{
90  my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
91  INT32 * rgb_ycc_tab;
92  INT32 i;
93
94  /* Allocate and fill in the conversion tables. */
95  cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
96    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
97				(TABLE_SIZE * SIZEOF(INT32)));
98
99  for (i = 0; i <= MAXJSAMPLE; i++) {
100    rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
101    rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
102    rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i     + ONE_HALF;
103    rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
104    rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
105    /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
106     * This ensures that the maximum output will round to MAXJSAMPLE
107     * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
108     */
109    rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i    + CBCR_OFFSET + ONE_HALF-1;
110/*  B=>Cb and R=>Cr tables are the same
111    rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i    + CBCR_OFFSET + ONE_HALF-1;
112*/
113    rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
114    rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
115  }
116}
117
118
119/*
120 * Convert some rows of samples to the JPEG colorspace.
121 *
122 * Note that we change from the application's interleaved-pixel format
123 * to our internal noninterleaved, one-plane-per-component format.
124 * The input buffer is therefore three times as wide as the output buffer.
125 *
126 * A starting row offset is provided only for the output buffer.  The caller
127 * can easily adjust the passed input_buf value to accommodate any row
128 * offset required on that side.
129 */
130
131METHODDEF(void)
132rgb_ycc_convert (j_compress_ptr cinfo,
133		 JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
134		 JDIMENSION output_row, int num_rows)
135{
136  my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
137  register int r, g, b;
138  register INT32 * ctab = cconvert->rgb_ycc_tab;
139  register JSAMPROW inptr;
140  register JSAMPROW outptr0, outptr1, outptr2;
141  register JDIMENSION col;
142  JDIMENSION num_cols = cinfo->image_width;
143
144  while (--num_rows >= 0) {
145    inptr = *input_buf++;
146    outptr0 = output_buf[0][output_row];
147    outptr1 = output_buf[1][output_row];
148    outptr2 = output_buf[2][output_row];
149    output_row++;
150    for (col = 0; col < num_cols; col++) {
151      r = GETJSAMPLE(inptr[RGB_RED]);
152      g = GETJSAMPLE(inptr[RGB_GREEN]);
153      b = GETJSAMPLE(inptr[RGB_BLUE]);
154      inptr += RGB_PIXELSIZE;
155      /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
156       * must be too; we do not need an explicit range-limiting operation.
157       * Hence the value being shifted is never negative, and we don't
158       * need the general RIGHT_SHIFT macro.
159       */
160      /* Y */
161      outptr0[col] = (JSAMPLE)
162		((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
163		 >> SCALEBITS);
164      /* Cb */
165      outptr1[col] = (JSAMPLE)
166		((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
167		 >> SCALEBITS);
168      /* Cr */
169      outptr2[col] = (JSAMPLE)
170		((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
171		 >> SCALEBITS);
172    }
173  }
174}
175
176
177/**************** Cases other than RGB -> YCbCr **************/
178
179
180/*
181 * Convert some rows of samples to the JPEG colorspace.
182 * This version handles RGB->grayscale conversion, which is the same
183 * as the RGB->Y portion of RGB->YCbCr.
184 * We assume rgb_ycc_start has been called (we only use the Y tables).
185 */
186
187METHODDEF(void)
188rgb_gray_convert (j_compress_ptr cinfo,
189		  JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
190		  JDIMENSION output_row, int num_rows)
191{
192  my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
193  register int r, g, b;
194  register INT32 * ctab = cconvert->rgb_ycc_tab;
195  register JSAMPROW inptr;
196  register JSAMPROW outptr;
197  register JDIMENSION col;
198  JDIMENSION num_cols = cinfo->image_width;
199
200  while (--num_rows >= 0) {
201    inptr = *input_buf++;
202    outptr = output_buf[0][output_row];
203    output_row++;
204    for (col = 0; col < num_cols; col++) {
205      r = GETJSAMPLE(inptr[RGB_RED]);
206      g = GETJSAMPLE(inptr[RGB_GREEN]);
207      b = GETJSAMPLE(inptr[RGB_BLUE]);
208      inptr += RGB_PIXELSIZE;
209      /* Y */
210      outptr[col] = (JSAMPLE)
211		((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
212		 >> SCALEBITS);
213    }
214  }
215}
216
217
218/*
219 * Convert some rows of samples to the JPEG colorspace.
220 * This version handles Adobe-style CMYK->YCCK conversion,
221 * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
222 * conversion as above, while passing K (black) unchanged.
223 * We assume rgb_ycc_start has been called.
224 */
225
226METHODDEF(void)
227cmyk_ycck_convert (j_compress_ptr cinfo,
228		   JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
229		   JDIMENSION output_row, int num_rows)
230{
231  my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
232  register int r, g, b;
233  register INT32 * ctab = cconvert->rgb_ycc_tab;
234  register JSAMPROW inptr;
235  register JSAMPROW outptr0, outptr1, outptr2, outptr3;
236  register JDIMENSION col;
237  JDIMENSION num_cols = cinfo->image_width;
238
239  while (--num_rows >= 0) {
240    inptr = *input_buf++;
241    outptr0 = output_buf[0][output_row];
242    outptr1 = output_buf[1][output_row];
243    outptr2 = output_buf[2][output_row];
244    outptr3 = output_buf[3][output_row];
245    output_row++;
246    for (col = 0; col < num_cols; col++) {
247      r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
248      g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
249      b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
250      /* K passes through as-is */
251      outptr3[col] = inptr[3];	/* don't need GETJSAMPLE here */
252      inptr += 4;
253      /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
254       * must be too; we do not need an explicit range-limiting operation.
255       * Hence the value being shifted is never negative, and we don't
256       * need the general RIGHT_SHIFT macro.
257       */
258      /* Y */
259      outptr0[col] = (JSAMPLE)
260		((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
261		 >> SCALEBITS);
262      /* Cb */
263      outptr1[col] = (JSAMPLE)
264		((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
265		 >> SCALEBITS);
266      /* Cr */
267      outptr2[col] = (JSAMPLE)
268		((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
269		 >> SCALEBITS);
270    }
271  }
272}
273
274
275/*
276 * Convert some rows of samples to the JPEG colorspace.
277 * This version handles grayscale output with no conversion.
278 * The source can be either plain grayscale or YCbCr (since Y == gray).
279 */
280
281METHODDEF(void)
282grayscale_convert (j_compress_ptr cinfo,
283		   JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
284		   JDIMENSION output_row, int num_rows)
285{
286  register JSAMPROW inptr;
287  register JSAMPROW outptr;
288  register JDIMENSION col;
289  JDIMENSION num_cols = cinfo->image_width;
290  int instride = cinfo->input_components;
291
292  while (--num_rows >= 0) {
293    inptr = *input_buf++;
294    outptr = output_buf[0][output_row];
295    output_row++;
296    for (col = 0; col < num_cols; col++) {
297      outptr[col] = inptr[0];	/* don't need GETJSAMPLE() here */
298      inptr += instride;
299    }
300  }
301}
302
303#ifdef ENABLE_ANDROID_NULL_CONVERT
304
305typedef unsigned int UINT32;
306
307#define B0(n)   ((n) & 0xFF)
308#define B1(n)   (((n) >> 8) & 0xFF)
309#define B2(n)   (((n) >> 16) & 0xFF)
310#define B3(n)   ((n) >> 24)
311
312#define PACK(a, b, c, d)    ((a) | ((b) << 8) | ((c) << 16) | ((d) << 24))
313
314static int ptr_is_quad(const void* p)
315{
316    return (((const char*)p - (const char*)0) & 3) == 0;
317}
318
319static void copyquads(const UINT32 in[], UINT32 out0[], UINT32 out1[], UINT32 out2[], int col4)
320{
321    do {
322        UINT32 src0 = *in++;
323        UINT32 src1 = *in++;
324        UINT32 src2 = *in++;
325        // LEndian
326        *out0++ = PACK(B0(src0), B3(src0), B2(src1), B1(src2));
327        *out1++ = PACK(B1(src0), B0(src1), B3(src1), B2(src2));
328        *out2++ = PACK(B2(src0), B1(src1), B0(src2), B3(src2));
329    } while (--col4 != 0);
330}
331
332#endif
333
334/*
335 * Convert some rows of samples to the JPEG colorspace.
336 * This version handles multi-component colorspaces without conversion.
337 * We assume input_components == num_components.
338 */
339
340METHODDEF(void)
341null_convert (j_compress_ptr cinfo,
342	      JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
343	      JDIMENSION output_row, int num_rows)
344{
345  register JSAMPROW inptr;
346  register JSAMPROW outptr;
347  register JDIMENSION col;
348  register int ci;
349  int nc = cinfo->num_components;
350  JDIMENSION num_cols = cinfo->image_width;
351
352#ifdef ENABLE_ANDROID_NULL_CONVERT
353    if (1 == num_rows && 3 == nc && num_cols > 0) {
354        JSAMPROW inptr = *input_buf;
355        JSAMPROW outptr0 = output_buf[0][output_row];
356        JSAMPROW outptr1 = output_buf[1][output_row];
357        JSAMPROW outptr2 = output_buf[2][output_row];
358
359        int col = num_cols;
360        int col4 = col >> 2;
361        if (col4 > 0 && ptr_is_quad(inptr) && ptr_is_quad(outptr0) &&
362                        ptr_is_quad(outptr1) && ptr_is_quad(outptr2)) {
363
364            const UINT32* in = (const UINT32*)inptr;
365            UINT32* out0 = (UINT32*)outptr0;
366            UINT32* out1 = (UINT32*)outptr1;
367            UINT32* out2 = (UINT32*)outptr2;
368            copyquads(in, out0, out1, out2, col4);
369            col &= 3;
370            if (0 == col)
371                return;
372            col4 <<= 2;
373            inptr += col4 * 3;  /* we read this 3 times per in copyquads */
374            outptr0 += col4;
375            outptr1 += col4;
376            outptr2 += col4;
377            /* fall through to while-loop */
378        }
379        do {
380            *outptr0++ = *inptr++;
381            *outptr1++ = *inptr++;
382            *outptr2++ = *inptr++;
383        } while (--col != 0);
384        return;
385    }
386SLOW:
387#endif
388  while (--num_rows >= 0) {
389    /* It seems fastest to make a separate pass for each component. */
390    for (ci = 0; ci < nc; ci++) {
391      inptr = *input_buf;
392      outptr = output_buf[ci][output_row];
393      for (col = 0; col < num_cols; col++) {
394	outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
395	inptr += nc;
396      }
397    }
398    input_buf++;
399    output_row++;
400  }
401}
402
403
404/*
405 * Empty method for start_pass.
406 */
407
408METHODDEF(void)
409null_method (j_compress_ptr cinfo)
410{
411  /* no work needed */
412}
413
414
415/*
416 * Module initialization routine for input colorspace conversion.
417 */
418
419GLOBAL(void)
420jinit_color_converter (j_compress_ptr cinfo)
421{
422  my_cconvert_ptr cconvert;
423
424  cconvert = (my_cconvert_ptr)
425    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
426				SIZEOF(my_color_converter));
427  cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
428  /* set start_pass to null method until we find out differently */
429  cconvert->pub.start_pass = null_method;
430
431  /* Make sure input_components agrees with in_color_space */
432  switch (cinfo->in_color_space) {
433  case JCS_GRAYSCALE:
434    if (cinfo->input_components != 1)
435      ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
436    break;
437
438  case JCS_RGB:
439#if RGB_PIXELSIZE != 3
440    if (cinfo->input_components != RGB_PIXELSIZE)
441      ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
442    break;
443#endif /* else share code with YCbCr */
444
445  case JCS_YCbCr:
446    if (cinfo->input_components != 3)
447      ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
448    break;
449
450  case JCS_CMYK:
451  case JCS_YCCK:
452    if (cinfo->input_components != 4)
453      ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
454    break;
455
456  default:			/* JCS_UNKNOWN can be anything */
457    if (cinfo->input_components < 1)
458      ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
459    break;
460  }
461
462  /* Check num_components, set conversion method based on requested space */
463  switch (cinfo->jpeg_color_space) {
464  case JCS_GRAYSCALE:
465    if (cinfo->num_components != 1)
466      ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
467    if (cinfo->in_color_space == JCS_GRAYSCALE)
468      cconvert->pub.color_convert = grayscale_convert;
469    else if (cinfo->in_color_space == JCS_RGB) {
470      cconvert->pub.start_pass = rgb_ycc_start;
471      cconvert->pub.color_convert = rgb_gray_convert;
472    } else if (cinfo->in_color_space == JCS_YCbCr)
473      cconvert->pub.color_convert = grayscale_convert;
474    else
475      ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
476    break;
477
478  case JCS_RGB:
479    if (cinfo->num_components != 3)
480      ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
481    if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
482      cconvert->pub.color_convert = null_convert;
483    else
484      ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
485    break;
486
487  case JCS_YCbCr:
488    if (cinfo->num_components != 3)
489      ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
490    if (cinfo->in_color_space == JCS_RGB) {
491      cconvert->pub.start_pass = rgb_ycc_start;
492      cconvert->pub.color_convert = rgb_ycc_convert;
493    } else if (cinfo->in_color_space == JCS_YCbCr)
494      cconvert->pub.color_convert = null_convert;
495    else
496      ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
497    break;
498
499  case JCS_CMYK:
500    if (cinfo->num_components != 4)
501      ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
502    if (cinfo->in_color_space == JCS_CMYK)
503      cconvert->pub.color_convert = null_convert;
504    else
505      ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
506    break;
507
508  case JCS_YCCK:
509    if (cinfo->num_components != 4)
510      ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
511    if (cinfo->in_color_space == JCS_CMYK) {
512      cconvert->pub.start_pass = rgb_ycc_start;
513      cconvert->pub.color_convert = cmyk_ycck_convert;
514    } else if (cinfo->in_color_space == JCS_YCCK)
515      cconvert->pub.color_convert = null_convert;
516    else
517      ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
518    break;
519
520  default:			/* allow null conversion of JCS_UNKNOWN */
521    if (cinfo->jpeg_color_space != cinfo->in_color_space ||
522	cinfo->num_components != cinfo->input_components)
523      ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
524    cconvert->pub.color_convert = null_convert;
525    break;
526  }
527}
528