1 // Copyright 2014 PDFium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
6 
7 #include <algorithm>
8 #include <limits>
9 #include <memory>
10 #include <vector>
11 
12 #include "core/fpdfapi/page/cpdf_colorspace.h"
13 #include "core/fxcodec/codec/codec_int.h"
14 #include "core/fxcodec/fx_codec.h"
15 #include "core/fxcrt/fx_safe_types.h"
16 #include "third_party/lcms2-2.6/include/lcms2.h"
17 #include "third_party/libopenjpeg20/openjpeg.h"
18 
fx_error_callback(const char * msg,void * client_data)19 static void fx_error_callback(const char* msg, void* client_data) {
20   (void)client_data;
21 }
fx_warning_callback(const char * msg,void * client_data)22 static void fx_warning_callback(const char* msg, void* client_data) {
23   (void)client_data;
24 }
fx_info_callback(const char * msg,void * client_data)25 static void fx_info_callback(const char* msg, void* client_data) {
26   (void)client_data;
27 }
28 
opj_read_from_memory(void * p_buffer,OPJ_SIZE_T nb_bytes,void * p_user_data)29 OPJ_SIZE_T opj_read_from_memory(void* p_buffer,
30                                 OPJ_SIZE_T nb_bytes,
31                                 void* p_user_data) {
32   DecodeData* srcData = static_cast<DecodeData*>(p_user_data);
33   if (!srcData || !srcData->src_data || srcData->src_size == 0) {
34     return static_cast<OPJ_SIZE_T>(-1);
35   }
36   // Reads at EOF return an error code.
37   if (srcData->offset >= srcData->src_size) {
38     return static_cast<OPJ_SIZE_T>(-1);
39   }
40   OPJ_SIZE_T bufferLength = srcData->src_size - srcData->offset;
41   OPJ_SIZE_T readlength = nb_bytes < bufferLength ? nb_bytes : bufferLength;
42   memcpy(p_buffer, &srcData->src_data[srcData->offset], readlength);
43   srcData->offset += readlength;
44   return readlength;
45 }
46 
opj_write_from_memory(void * p_buffer,OPJ_SIZE_T nb_bytes,void * p_user_data)47 OPJ_SIZE_T opj_write_from_memory(void* p_buffer,
48                                  OPJ_SIZE_T nb_bytes,
49                                  void* p_user_data) {
50   DecodeData* srcData = static_cast<DecodeData*>(p_user_data);
51   if (!srcData || !srcData->src_data || srcData->src_size == 0) {
52     return static_cast<OPJ_SIZE_T>(-1);
53   }
54   // Writes at EOF return an error code.
55   if (srcData->offset >= srcData->src_size) {
56     return static_cast<OPJ_SIZE_T>(-1);
57   }
58   OPJ_SIZE_T bufferLength = srcData->src_size - srcData->offset;
59   OPJ_SIZE_T writeLength = nb_bytes < bufferLength ? nb_bytes : bufferLength;
60   memcpy(&srcData->src_data[srcData->offset], p_buffer, writeLength);
61   srcData->offset += writeLength;
62   return writeLength;
63 }
64 
opj_skip_from_memory(OPJ_OFF_T nb_bytes,void * p_user_data)65 OPJ_OFF_T opj_skip_from_memory(OPJ_OFF_T nb_bytes, void* p_user_data) {
66   DecodeData* srcData = static_cast<DecodeData*>(p_user_data);
67   if (!srcData || !srcData->src_data || srcData->src_size == 0) {
68     return static_cast<OPJ_OFF_T>(-1);
69   }
70   // Offsets are signed and may indicate a negative skip. Do not support this
71   // because of the strange return convention where either bytes skipped or
72   // -1 is returned. Following that convention, a successful relative seek of
73   // -1 bytes would be required to to give the same result as the error case.
74   if (nb_bytes < 0) {
75     return static_cast<OPJ_OFF_T>(-1);
76   }
77   // FIXME: use std::make_unsigned<OPJ_OFF_T>::type once c++11 lib is OK'd.
78   uint64_t unsignedNbBytes = static_cast<uint64_t>(nb_bytes);
79   // Additionally, the offset may take us beyond the range of a size_t (e.g.
80   // 32-bit platforms). If so, just clamp at EOF.
81   if (unsignedNbBytes >
82       std::numeric_limits<OPJ_SIZE_T>::max() - srcData->offset) {
83     srcData->offset = srcData->src_size;
84   } else {
85     OPJ_SIZE_T checkedNbBytes = static_cast<OPJ_SIZE_T>(unsignedNbBytes);
86     // Otherwise, mimic fseek() semantics to always succeed, even past EOF,
87     // clamping at EOF.  We can get away with this since we don't actually
88     // provide negative relative skips from beyond EOF back to inside the
89     // data, which would be the only reason to need to know exactly how far
90     // beyond EOF we are.
91     srcData->offset =
92         std::min(srcData->offset + checkedNbBytes, srcData->src_size);
93   }
94   return nb_bytes;
95 }
96 
opj_seek_from_memory(OPJ_OFF_T nb_bytes,void * p_user_data)97 OPJ_BOOL opj_seek_from_memory(OPJ_OFF_T nb_bytes, void* p_user_data) {
98   DecodeData* srcData = static_cast<DecodeData*>(p_user_data);
99   if (!srcData || !srcData->src_data || srcData->src_size == 0) {
100     return OPJ_FALSE;
101   }
102   // Offsets are signed and may indicate a negative position, which would
103   // be before the start of the file. Do not support this.
104   if (nb_bytes < 0) {
105     return OPJ_FALSE;
106   }
107   // FIXME: use std::make_unsigned<OPJ_OFF_T>::type once c++11 lib is OK'd.
108   uint64_t unsignedNbBytes = static_cast<uint64_t>(nb_bytes);
109   // Additionally, the offset may take us beyond the range of a size_t (e.g.
110   // 32-bit platforms). If so, just clamp at EOF.
111   if (unsignedNbBytes > std::numeric_limits<OPJ_SIZE_T>::max()) {
112     srcData->offset = srcData->src_size;
113   } else {
114     OPJ_SIZE_T checkedNbBytes = static_cast<OPJ_SIZE_T>(nb_bytes);
115     // Otherwise, mimic fseek() semantics to always succeed, even past EOF,
116     // again clamping at EOF.
117     srcData->offset = std::min(checkedNbBytes, srcData->src_size);
118   }
119   return OPJ_TRUE;
120 }
fx_opj_stream_create_memory_stream(DecodeData * data,OPJ_SIZE_T p_size,OPJ_BOOL p_is_read_stream)121 opj_stream_t* fx_opj_stream_create_memory_stream(DecodeData* data,
122                                                  OPJ_SIZE_T p_size,
123                                                  OPJ_BOOL p_is_read_stream) {
124   opj_stream_t* l_stream = 00;
125   if (!data || !data->src_data || data->src_size <= 0) {
126     return nullptr;
127   }
128   l_stream = opj_stream_create(p_size, p_is_read_stream);
129   if (!l_stream) {
130     return nullptr;
131   }
132   opj_stream_set_user_data(l_stream, data, nullptr);
133   opj_stream_set_user_data_length(l_stream, data->src_size);
134   opj_stream_set_read_function(l_stream, opj_read_from_memory);
135   opj_stream_set_write_function(l_stream, opj_write_from_memory);
136   opj_stream_set_skip_function(l_stream, opj_skip_from_memory);
137   opj_stream_set_seek_function(l_stream, opj_seek_from_memory);
138   return l_stream;
139 }
sycc_to_rgb(int offset,int upb,int y,int cb,int cr,int * out_r,int * out_g,int * out_b)140 static void sycc_to_rgb(int offset,
141                         int upb,
142                         int y,
143                         int cb,
144                         int cr,
145                         int* out_r,
146                         int* out_g,
147                         int* out_b) {
148   int r, g, b;
149   cb -= offset;
150   cr -= offset;
151   r = y + (int)(1.402 * (float)cr);
152   if (r < 0) {
153     r = 0;
154   } else if (r > upb) {
155     r = upb;
156   }
157   *out_r = r;
158   g = y - (int)(0.344 * (float)cb + 0.714 * (float)cr);
159   if (g < 0) {
160     g = 0;
161   } else if (g > upb) {
162     g = upb;
163   }
164   *out_g = g;
165   b = y + (int)(1.772 * (float)cb);
166   if (b < 0) {
167     b = 0;
168   } else if (b > upb) {
169     b = upb;
170   }
171   *out_b = b;
172 }
173 
sycc444_to_rgb(opj_image_t * img)174 static void sycc444_to_rgb(opj_image_t* img) {
175   int prec = img->comps[0].prec;
176   int offset = 1 << (prec - 1);
177   int upb = (1 << prec) - 1;
178   OPJ_UINT32 maxw =
179       std::min({img->comps[0].w, img->comps[1].w, img->comps[2].w});
180   OPJ_UINT32 maxh =
181       std::min({img->comps[0].h, img->comps[1].h, img->comps[2].h});
182   FX_SAFE_SIZE_T max_size = maxw;
183   max_size *= maxh;
184   if (!max_size.IsValid())
185     return;
186 
187   const int* y = img->comps[0].data;
188   const int* cb = img->comps[1].data;
189   const int* cr = img->comps[2].data;
190   if (!y || !cb || !cr)
191     return;
192 
193   int* r = FX_Alloc(int, max_size.ValueOrDie());
194   int* g = FX_Alloc(int, max_size.ValueOrDie());
195   int* b = FX_Alloc(int, max_size.ValueOrDie());
196   int* d0 = r;
197   int* d1 = g;
198   int* d2 = b;
199   for (size_t i = 0; i < max_size.ValueOrDie(); ++i) {
200     sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
201     ++y;
202     ++cb;
203     ++cr;
204     ++r;
205     ++g;
206     ++b;
207   }
208   FX_Free(img->comps[0].data);
209   FX_Free(img->comps[1].data);
210   FX_Free(img->comps[2].data);
211   img->comps[0].data = d0;
212   img->comps[1].data = d1;
213   img->comps[2].data = d2;
214 }
215 
sycc420_422_size_is_valid(opj_image_t * img)216 static bool sycc420_422_size_is_valid(opj_image_t* img) {
217   return (img && img->comps[0].w != std::numeric_limits<OPJ_UINT32>::max() &&
218           (img->comps[0].w + 1) / 2 == img->comps[1].w &&
219           img->comps[1].w == img->comps[2].w &&
220           img->comps[1].h == img->comps[2].h);
221 }
sycc420_size_is_valid(opj_image_t * img)222 static bool sycc420_size_is_valid(opj_image_t* img) {
223   return (sycc420_422_size_is_valid(img) &&
224           img->comps[0].h != std::numeric_limits<OPJ_UINT32>::max() &&
225           (img->comps[0].h + 1) / 2 == img->comps[1].h);
226 }
sycc422_size_is_valid(opj_image_t * img)227 static bool sycc422_size_is_valid(opj_image_t* img) {
228   return (sycc420_422_size_is_valid(img) && img->comps[0].h == img->comps[1].h);
229 }
sycc422_to_rgb(opj_image_t * img)230 static void sycc422_to_rgb(opj_image_t* img) {
231   if (!sycc422_size_is_valid(img))
232     return;
233 
234   int prec = img->comps[0].prec;
235   if (prec <= 0 || prec >= 32)
236     return;
237 
238   int offset = 1 << (prec - 1);
239   int upb = (1 << prec) - 1;
240 
241   OPJ_UINT32 maxw = img->comps[0].w;
242   OPJ_UINT32 maxh = img->comps[0].h;
243   FX_SAFE_SIZE_T max_size = maxw;
244   max_size *= maxh;
245   if (!max_size.IsValid())
246     return;
247 
248   const int* y = img->comps[0].data;
249   const int* cb = img->comps[1].data;
250   const int* cr = img->comps[2].data;
251   if (!y || !cb || !cr)
252     return;
253 
254   int *d0, *d1, *d2, *r, *g, *b;
255   d0 = r = FX_Alloc(int, max_size.ValueOrDie());
256   d1 = g = FX_Alloc(int, max_size.ValueOrDie());
257   d2 = b = FX_Alloc(int, max_size.ValueOrDie());
258   for (uint32_t i = 0; i < maxh; ++i) {
259     OPJ_UINT32 j;
260     for (j = 0; j < (maxw & ~static_cast<OPJ_UINT32>(1)); j += 2) {
261       sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
262       ++y;
263       ++r;
264       ++g;
265       ++b;
266       sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
267       ++y;
268       ++r;
269       ++g;
270       ++b;
271       ++cb;
272       ++cr;
273     }
274     if (j < maxw) {
275       sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
276       ++y;
277       ++r;
278       ++g;
279       ++b;
280       ++cb;
281       ++cr;
282     }
283   }
284   FX_Free(img->comps[0].data);
285   img->comps[0].data = d0;
286   FX_Free(img->comps[1].data);
287   img->comps[1].data = d1;
288   FX_Free(img->comps[2].data);
289   img->comps[2].data = d2;
290   img->comps[1].w = maxw;
291   img->comps[1].h = maxh;
292   img->comps[2].w = maxw;
293   img->comps[2].h = maxh;
294   img->comps[1].dx = img->comps[0].dx;
295   img->comps[2].dx = img->comps[0].dx;
296   img->comps[1].dy = img->comps[0].dy;
297   img->comps[2].dy = img->comps[0].dy;
298 }
sycc420_must_extend_cbcr(OPJ_UINT32 y,OPJ_UINT32 cbcr)299 static bool sycc420_must_extend_cbcr(OPJ_UINT32 y, OPJ_UINT32 cbcr) {
300   return (y & 1) && (cbcr == y / 2);
301 }
sycc420_to_rgb(opj_image_t * img)302 void sycc420_to_rgb(opj_image_t* img) {
303   if (!sycc420_size_is_valid(img))
304     return;
305 
306   OPJ_UINT32 prec = img->comps[0].prec;
307   if (!prec)
308     return;
309   OPJ_UINT32 offset = 1 << (prec - 1);
310   OPJ_UINT32 upb = (1 << prec) - 1;
311   OPJ_UINT32 yw = img->comps[0].w;
312   OPJ_UINT32 yh = img->comps[0].h;
313   OPJ_UINT32 cbw = img->comps[1].w;
314   OPJ_UINT32 cbh = img->comps[1].h;
315   OPJ_UINT32 crw = img->comps[2].w;
316   bool extw = sycc420_must_extend_cbcr(yw, cbw);
317   bool exth = sycc420_must_extend_cbcr(yh, cbh);
318   FX_SAFE_UINT32 safeSize = yw;
319   safeSize *= yh;
320   if (!safeSize.IsValid())
321     return;
322   int* r = FX_Alloc(int, safeSize.ValueOrDie());
323   int* g = FX_Alloc(int, safeSize.ValueOrDie());
324   int* b = FX_Alloc(int, safeSize.ValueOrDie());
325   int* d0 = r;
326   int* d1 = g;
327   int* d2 = b;
328   const int* y = img->comps[0].data;
329   const int* cb = img->comps[1].data;
330   const int* cr = img->comps[2].data;
331   if (!y || !cb || !cr)
332     return;
333 
334   const int* ny = nullptr;
335   int* nr = nullptr;
336   int* ng = nullptr;
337   int* nb = nullptr;
338   OPJ_UINT32 i = 0;
339   OPJ_UINT32 j = 0;
340   for (i = 0; i < (yh & ~(OPJ_UINT32)1); i += 2) {
341     ny = y + yw;
342     nr = r + yw;
343     ng = g + yw;
344     nb = b + yw;
345     for (j = 0; j < (yw & ~(OPJ_UINT32)1); j += 2) {
346       sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
347       ++y;
348       ++r;
349       ++g;
350       ++b;
351       sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
352       ++y;
353       ++r;
354       ++g;
355       ++b;
356       sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb);
357       ++ny;
358       ++nr;
359       ++ng;
360       ++nb;
361       sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb);
362       ++ny;
363       ++nr;
364       ++ng;
365       ++nb;
366       ++cb;
367       ++cr;
368     }
369     if (j < yw) {
370       if (extw) {
371         --cb;
372         --cr;
373       }
374       sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
375       ++y;
376       ++r;
377       ++g;
378       ++b;
379       sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb);
380       ++ny;
381       ++nr;
382       ++ng;
383       ++nb;
384       ++cb;
385       ++cr;
386     }
387     y += yw;
388     r += yw;
389     g += yw;
390     b += yw;
391   }
392   if (i < yh) {
393     if (exth) {
394       cb -= cbw;
395       cr -= crw;
396     }
397     for (j = 0; j < (yw & ~(OPJ_UINT32)1); j += 2) {
398       sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
399       ++y;
400       ++r;
401       ++g;
402       ++b;
403       sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
404       ++y;
405       ++r;
406       ++g;
407       ++b;
408       ++cb;
409       ++cr;
410     }
411     if (j < yw) {
412       if (extw) {
413         --cb;
414         --cr;
415       }
416       sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
417     }
418   }
419 
420   FX_Free(img->comps[0].data);
421   img->comps[0].data = d0;
422   FX_Free(img->comps[1].data);
423   img->comps[1].data = d1;
424   FX_Free(img->comps[2].data);
425   img->comps[2].data = d2;
426   img->comps[1].w = yw;
427   img->comps[1].h = yh;
428   img->comps[2].w = yw;
429   img->comps[2].h = yh;
430   img->comps[1].w = yw;
431   img->comps[1].h = yh;
432   img->comps[2].w = yw;
433   img->comps[2].h = yh;
434   img->comps[1].dx = img->comps[0].dx;
435   img->comps[2].dx = img->comps[0].dx;
436   img->comps[1].dy = img->comps[0].dy;
437   img->comps[2].dy = img->comps[0].dy;
438 }
color_sycc_to_rgb(opj_image_t * img)439 void color_sycc_to_rgb(opj_image_t* img) {
440   if (img->numcomps < 3) {
441     img->color_space = OPJ_CLRSPC_GRAY;
442     return;
443   }
444   if ((img->comps[0].dx == 1) && (img->comps[1].dx == 2) &&
445       (img->comps[2].dx == 2) && (img->comps[0].dy == 1) &&
446       (img->comps[1].dy == 2) && (img->comps[2].dy == 2)) {
447     sycc420_to_rgb(img);
448   } else if ((img->comps[0].dx == 1) && (img->comps[1].dx == 2) &&
449              (img->comps[2].dx == 2) && (img->comps[0].dy == 1) &&
450              (img->comps[1].dy == 1) && (img->comps[2].dy == 1)) {
451     sycc422_to_rgb(img);
452   } else if ((img->comps[0].dx == 1) && (img->comps[1].dx == 1) &&
453              (img->comps[2].dx == 1) && (img->comps[0].dy == 1) &&
454              (img->comps[1].dy == 1) && (img->comps[2].dy == 1)) {
455     sycc444_to_rgb(img);
456   } else {
457     return;
458   }
459   img->color_space = OPJ_CLRSPC_SRGB;
460 }
color_apply_icc_profile(opj_image_t * image)461 void color_apply_icc_profile(opj_image_t* image) {
462   cmsHPROFILE out_prof;
463   cmsUInt32Number in_type;
464   cmsUInt32Number out_type;
465   int* r;
466   int* g;
467   int* b;
468   int max;
469   cmsHPROFILE in_prof =
470       cmsOpenProfileFromMem(image->icc_profile_buf, image->icc_profile_len);
471   if (!in_prof) {
472     return;
473   }
474   cmsColorSpaceSignature out_space = cmsGetColorSpace(in_prof);
475   cmsUInt32Number intent = cmsGetHeaderRenderingIntent(in_prof);
476   int max_w = (int)image->comps[0].w;
477   int max_h = (int)image->comps[0].h;
478   int prec = (int)image->comps[0].prec;
479   OPJ_COLOR_SPACE oldspace = image->color_space;
480   if (out_space == cmsSigRgbData) {
481     if (prec <= 8) {
482       in_type = TYPE_RGB_8;
483       out_type = TYPE_RGB_8;
484     } else {
485       in_type = TYPE_RGB_16;
486       out_type = TYPE_RGB_16;
487     }
488     out_prof = cmsCreate_sRGBProfile();
489     image->color_space = OPJ_CLRSPC_SRGB;
490   } else if (out_space == cmsSigGrayData) {
491     if (prec <= 8) {
492       in_type = TYPE_GRAY_8;
493       out_type = TYPE_RGB_8;
494     } else {
495       in_type = TYPE_GRAY_16;
496       out_type = TYPE_RGB_16;
497     }
498     out_prof = cmsCreate_sRGBProfile();
499     image->color_space = OPJ_CLRSPC_SRGB;
500   } else if (out_space == cmsSigYCbCrData) {
501     in_type = TYPE_YCbCr_16;
502     out_type = TYPE_RGB_16;
503     out_prof = cmsCreate_sRGBProfile();
504     image->color_space = OPJ_CLRSPC_SRGB;
505   } else {
506     return;
507   }
508   cmsHTRANSFORM transform =
509       cmsCreateTransform(in_prof, in_type, out_prof, out_type, intent, 0);
510   cmsCloseProfile(in_prof);
511   cmsCloseProfile(out_prof);
512   if (!transform) {
513     image->color_space = oldspace;
514     return;
515   }
516   if (image->numcomps > 2) {
517     if (prec <= 8) {
518       unsigned char *inbuf, *outbuf, *in, *out;
519       max = max_w * max_h;
520       cmsUInt32Number nr_samples = max * 3 * sizeof(unsigned char);
521       in = inbuf = FX_Alloc(unsigned char, nr_samples);
522       out = outbuf = FX_Alloc(unsigned char, nr_samples);
523       r = image->comps[0].data;
524       g = image->comps[1].data;
525       b = image->comps[2].data;
526       for (int i = 0; i < max; ++i) {
527         *in++ = (unsigned char)*r++;
528         *in++ = (unsigned char)*g++;
529         *in++ = (unsigned char)*b++;
530       }
531       cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max);
532       r = image->comps[0].data;
533       g = image->comps[1].data;
534       b = image->comps[2].data;
535       for (int i = 0; i < max; ++i) {
536         *r++ = (int)*out++;
537         *g++ = (int)*out++;
538         *b++ = (int)*out++;
539       }
540       FX_Free(inbuf);
541       FX_Free(outbuf);
542     } else {
543       unsigned short *inbuf, *outbuf, *in, *out;
544       max = max_w * max_h;
545       cmsUInt32Number nr_samples = max * 3 * sizeof(unsigned short);
546       in = inbuf = FX_Alloc(unsigned short, nr_samples);
547       out = outbuf = FX_Alloc(unsigned short, nr_samples);
548       r = image->comps[0].data;
549       g = image->comps[1].data;
550       b = image->comps[2].data;
551       for (int i = 0; i < max; ++i) {
552         *in++ = (unsigned short)*r++;
553         *in++ = (unsigned short)*g++;
554         *in++ = (unsigned short)*b++;
555       }
556       cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max);
557       r = image->comps[0].data;
558       g = image->comps[1].data;
559       b = image->comps[2].data;
560       for (int i = 0; i < max; ++i) {
561         *r++ = (int)*out++;
562         *g++ = (int)*out++;
563         *b++ = (int)*out++;
564       }
565       FX_Free(inbuf);
566       FX_Free(outbuf);
567     }
568   } else {
569     unsigned char *in, *inbuf, *out, *outbuf;
570     max = max_w * max_h;
571     cmsUInt32Number nr_samples =
572         (cmsUInt32Number)max * 3 * sizeof(unsigned char);
573     in = inbuf = FX_Alloc(unsigned char, nr_samples);
574     out = outbuf = FX_Alloc(unsigned char, nr_samples);
575     image->comps = (opj_image_comp_t*)realloc(
576         image->comps, (image->numcomps + 2) * sizeof(opj_image_comp_t));
577     if (image->numcomps == 2) {
578       image->comps[3] = image->comps[1];
579     }
580     image->comps[1] = image->comps[0];
581     image->comps[2] = image->comps[0];
582     image->comps[1].data = FX_Alloc(int, (size_t)max);
583     FXSYS_memset(image->comps[1].data, 0, sizeof(int) * (size_t)max);
584     image->comps[2].data = FX_Alloc(int, (size_t)max);
585     FXSYS_memset(image->comps[2].data, 0, sizeof(int) * (size_t)max);
586     image->numcomps += 2;
587     r = image->comps[0].data;
588     for (int i = 0; i < max; ++i) {
589       *in++ = (unsigned char)*r++;
590     }
591     cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max);
592     r = image->comps[0].data;
593     g = image->comps[1].data;
594     b = image->comps[2].data;
595     for (int i = 0; i < max; ++i) {
596       *r++ = (int)*out++;
597       *g++ = (int)*out++;
598       *b++ = (int)*out++;
599     }
600     FX_Free(inbuf);
601     FX_Free(outbuf);
602   }
603   cmsDeleteTransform(transform);
604 }
color_apply_conversion(opj_image_t * image)605 void color_apply_conversion(opj_image_t* image) {
606   int* row;
607   int enumcs, numcomps;
608   numcomps = image->numcomps;
609   if (numcomps < 3) {
610     return;
611   }
612   row = (int*)image->icc_profile_buf;
613   enumcs = row[0];
614   if (enumcs == 14) {
615     int *L, *a, *b, *red, *green, *blue, *src0, *src1, *src2;
616     double rl, ol, ra, oa, rb, ob, prec0, prec1, prec2;
617     double minL, maxL, mina, maxa, minb, maxb;
618     unsigned int default_type;
619     unsigned int i, max;
620     cmsHPROFILE in, out;
621     cmsHTRANSFORM transform;
622     cmsUInt16Number RGB[3];
623     cmsCIELab Lab;
624     in = cmsCreateLab4Profile(nullptr);
625     out = cmsCreate_sRGBProfile();
626     transform = cmsCreateTransform(in, TYPE_Lab_DBL, out, TYPE_RGB_16,
627                                    INTENT_PERCEPTUAL, 0);
628     cmsCloseProfile(in);
629     cmsCloseProfile(out);
630     if (!transform) {
631       return;
632     }
633     prec0 = (double)image->comps[0].prec;
634     prec1 = (double)image->comps[1].prec;
635     prec2 = (double)image->comps[2].prec;
636     default_type = row[1];
637     if (default_type == 0x44454600) {
638       rl = 100;
639       ra = 170;
640       rb = 200;
641       ol = 0;
642       oa = pow(2, prec1 - 1);
643       ob = pow(2, prec2 - 2) + pow(2, prec2 - 3);
644     } else {
645       rl = row[2];
646       ra = row[4];
647       rb = row[6];
648       ol = row[3];
649       oa = row[5];
650       ob = row[7];
651     }
652     L = src0 = image->comps[0].data;
653     a = src1 = image->comps[1].data;
654     b = src2 = image->comps[2].data;
655     max = image->comps[0].w * image->comps[0].h;
656     red = FX_Alloc(int, max);
657     image->comps[0].data = red;
658     green = FX_Alloc(int, max);
659     image->comps[1].data = green;
660     blue = FX_Alloc(int, max);
661     image->comps[2].data = blue;
662     minL = -(rl * ol) / (pow(2, prec0) - 1);
663     maxL = minL + rl;
664     mina = -(ra * oa) / (pow(2, prec1) - 1);
665     maxa = mina + ra;
666     minb = -(rb * ob) / (pow(2, prec2) - 1);
667     maxb = minb + rb;
668     for (i = 0; i < max; ++i) {
669       Lab.L = minL + (double)(*L) * (maxL - minL) / (pow(2, prec0) - 1);
670       ++L;
671       Lab.a = mina + (double)(*a) * (maxa - mina) / (pow(2, prec1) - 1);
672       ++a;
673       Lab.b = minb + (double)(*b) * (maxb - minb) / (pow(2, prec2) - 1);
674       ++b;
675       cmsDoTransform(transform, &Lab, RGB, 1);
676       *red++ = RGB[0];
677       *green++ = RGB[1];
678       *blue++ = RGB[2];
679     }
680     cmsDeleteTransform(transform);
681     FX_Free(src0);
682     FX_Free(src1);
683     FX_Free(src2);
684     image->color_space = OPJ_CLRSPC_SRGB;
685     image->comps[0].prec = 16;
686     image->comps[1].prec = 16;
687     image->comps[2].prec = 16;
688     return;
689   }
690 }
691 class CJPX_Decoder {
692  public:
693   explicit CJPX_Decoder(CPDF_ColorSpace* cs);
694   ~CJPX_Decoder();
695   bool Init(const unsigned char* src_data, uint32_t src_size);
696   void GetInfo(uint32_t* width, uint32_t* height, uint32_t* components);
697   bool Decode(uint8_t* dest_buf,
698               int pitch,
699               const std::vector<uint8_t>& offsets);
700 
701  private:
702   const uint8_t* m_SrcData;
703   uint32_t m_SrcSize;
704   opj_image_t* image;
705   opj_codec_t* l_codec;
706   opj_stream_t* l_stream;
707   const CPDF_ColorSpace* const m_ColorSpace;
708 };
709 
CJPX_Decoder(CPDF_ColorSpace * cs)710 CJPX_Decoder::CJPX_Decoder(CPDF_ColorSpace* cs)
711     : image(nullptr), l_codec(nullptr), l_stream(nullptr), m_ColorSpace(cs) {}
712 
~CJPX_Decoder()713 CJPX_Decoder::~CJPX_Decoder() {
714   if (l_codec) {
715     opj_destroy_codec(l_codec);
716   }
717   if (l_stream) {
718     opj_stream_destroy(l_stream);
719   }
720   if (image) {
721     opj_image_destroy(image);
722   }
723 }
724 
Init(const unsigned char * src_data,uint32_t src_size)725 bool CJPX_Decoder::Init(const unsigned char* src_data, uint32_t src_size) {
726   static const unsigned char szJP2Header[] = {
727       0x00, 0x00, 0x00, 0x0c, 0x6a, 0x50, 0x20, 0x20, 0x0d, 0x0a, 0x87, 0x0a};
728   if (!src_data || src_size < sizeof(szJP2Header))
729     return false;
730 
731   image = nullptr;
732   m_SrcData = src_data;
733   m_SrcSize = src_size;
734   DecodeData srcData(const_cast<unsigned char*>(src_data), src_size);
735   l_stream = fx_opj_stream_create_memory_stream(&srcData,
736                                                 OPJ_J2K_STREAM_CHUNK_SIZE, 1);
737   if (!l_stream) {
738     return false;
739   }
740   opj_dparameters_t parameters;
741   opj_set_default_decoder_parameters(&parameters);
742   parameters.decod_format = 0;
743   parameters.cod_format = 3;
744   if (FXSYS_memcmp(m_SrcData, szJP2Header, sizeof(szJP2Header)) == 0) {
745     l_codec = opj_create_decompress(OPJ_CODEC_JP2);
746     parameters.decod_format = 1;
747   } else {
748     l_codec = opj_create_decompress(OPJ_CODEC_J2K);
749   }
750   if (!l_codec) {
751     return false;
752   }
753   if (m_ColorSpace && m_ColorSpace->GetFamily() == PDFCS_INDEXED)
754     parameters.flags |= OPJ_DPARAMETERS_IGNORE_PCLR_CMAP_CDEF_FLAG;
755   opj_set_info_handler(l_codec, fx_info_callback, 00);
756   opj_set_warning_handler(l_codec, fx_warning_callback, 00);
757   opj_set_error_handler(l_codec, fx_error_callback, 00);
758   if (!opj_setup_decoder(l_codec, &parameters)) {
759     return false;
760   }
761   if (!opj_read_header(l_stream, l_codec, &image)) {
762     image = nullptr;
763     return false;
764   }
765   image->pdfium_use_colorspace = !!m_ColorSpace;
766 
767   if (!parameters.nb_tile_to_decode) {
768     if (!opj_set_decode_area(l_codec, image, parameters.DA_x0, parameters.DA_y0,
769                              parameters.DA_x1, parameters.DA_y1)) {
770       opj_image_destroy(image);
771       image = nullptr;
772       return false;
773     }
774     if (!(opj_decode(l_codec, l_stream, image) &&
775           opj_end_decompress(l_codec, l_stream))) {
776       opj_image_destroy(image);
777       image = nullptr;
778       return false;
779     }
780   } else {
781     if (!opj_get_decoded_tile(l_codec, l_stream, image,
782                               parameters.tile_index)) {
783       return false;
784     }
785   }
786   opj_stream_destroy(l_stream);
787   l_stream = nullptr;
788   if (image->color_space != OPJ_CLRSPC_SYCC && image->numcomps == 3 &&
789       image->comps[0].dx == image->comps[0].dy && image->comps[1].dx != 1) {
790     image->color_space = OPJ_CLRSPC_SYCC;
791   } else if (image->numcomps <= 2) {
792     image->color_space = OPJ_CLRSPC_GRAY;
793   }
794   if (image->color_space == OPJ_CLRSPC_SYCC) {
795     color_sycc_to_rgb(image);
796   }
797   if (image->icc_profile_buf) {
798     FX_Free(image->icc_profile_buf);
799     image->icc_profile_buf = nullptr;
800     image->icc_profile_len = 0;
801   }
802   if (!image) {
803     return false;
804   }
805   return true;
806 }
807 
GetInfo(uint32_t * width,uint32_t * height,uint32_t * components)808 void CJPX_Decoder::GetInfo(uint32_t* width,
809                            uint32_t* height,
810                            uint32_t* components) {
811   *width = (uint32_t)image->x1;
812   *height = (uint32_t)image->y1;
813   *components = (uint32_t)image->numcomps;
814 }
815 
Decode(uint8_t * dest_buf,int pitch,const std::vector<uint8_t> & offsets)816 bool CJPX_Decoder::Decode(uint8_t* dest_buf,
817                           int pitch,
818                           const std::vector<uint8_t>& offsets) {
819   if (image->comps[0].w != image->x1 || image->comps[0].h != image->y1)
820     return false;
821 
822   if (pitch<(int)(image->comps[0].w * 8 * image->numcomps + 31)>> 5 << 2)
823     return false;
824 
825   FXSYS_memset(dest_buf, 0xff, image->y1 * pitch);
826   std::vector<uint8_t*> channel_bufs(image->numcomps);
827   std::vector<int> adjust_comps(image->numcomps);
828   for (uint32_t i = 0; i < image->numcomps; i++) {
829     channel_bufs[i] = dest_buf + offsets[i];
830     adjust_comps[i] = image->comps[i].prec - 8;
831     if (i > 0) {
832       if (image->comps[i].dx != image->comps[i - 1].dx ||
833           image->comps[i].dy != image->comps[i - 1].dy ||
834           image->comps[i].prec != image->comps[i - 1].prec) {
835         return false;
836       }
837     }
838   }
839   int width = image->comps[0].w;
840   int height = image->comps[0].h;
841   for (uint32_t channel = 0; channel < image->numcomps; ++channel) {
842     uint8_t* pChannel = channel_bufs[channel];
843     if (adjust_comps[channel] < 0) {
844       for (int row = 0; row < height; ++row) {
845         uint8_t* pScanline = pChannel + row * pitch;
846         for (int col = 0; col < width; ++col) {
847           uint8_t* pPixel = pScanline + col * image->numcomps;
848           if (!image->comps[channel].data)
849             continue;
850 
851           int src = image->comps[channel].data[row * width + col];
852           src += image->comps[channel].sgnd
853                      ? 1 << (image->comps[channel].prec - 1)
854                      : 0;
855           if (adjust_comps[channel] > 0) {
856             *pPixel = 0;
857           } else {
858             *pPixel = (uint8_t)(src << -adjust_comps[channel]);
859           }
860         }
861       }
862     } else {
863       for (int row = 0; row < height; ++row) {
864         uint8_t* pScanline = pChannel + row * pitch;
865         for (int col = 0; col < width; ++col) {
866           uint8_t* pPixel = pScanline + col * image->numcomps;
867           if (!image->comps[channel].data)
868             continue;
869 
870           int src = image->comps[channel].data[row * width + col];
871           src += image->comps[channel].sgnd
872                      ? 1 << (image->comps[channel].prec - 1)
873                      : 0;
874           if (adjust_comps[channel] - 1 < 0) {
875             *pPixel = (uint8_t)((src >> adjust_comps[channel]));
876           } else {
877             int tmpPixel = (src >> adjust_comps[channel]) +
878                            ((src >> (adjust_comps[channel] - 1)) % 2);
879             if (tmpPixel > 255) {
880               tmpPixel = 255;
881             } else if (tmpPixel < 0) {
882               tmpPixel = 0;
883             }
884             *pPixel = (uint8_t)tmpPixel;
885           }
886         }
887       }
888     }
889   }
890   return true;
891 }
892 
CCodec_JpxModule()893 CCodec_JpxModule::CCodec_JpxModule() {}
~CCodec_JpxModule()894 CCodec_JpxModule::~CCodec_JpxModule() {}
895 
CreateDecoder(const uint8_t * src_buf,uint32_t src_size,CPDF_ColorSpace * cs)896 CJPX_Decoder* CCodec_JpxModule::CreateDecoder(const uint8_t* src_buf,
897                                               uint32_t src_size,
898                                               CPDF_ColorSpace* cs) {
899   std::unique_ptr<CJPX_Decoder> decoder(new CJPX_Decoder(cs));
900   return decoder->Init(src_buf, src_size) ? decoder.release() : nullptr;
901 }
902 
GetImageInfo(CJPX_Decoder * pDecoder,uint32_t * width,uint32_t * height,uint32_t * components)903 void CCodec_JpxModule::GetImageInfo(CJPX_Decoder* pDecoder,
904                                     uint32_t* width,
905                                     uint32_t* height,
906                                     uint32_t* components) {
907   pDecoder->GetInfo(width, height, components);
908 }
909 
Decode(CJPX_Decoder * pDecoder,uint8_t * dest_data,int pitch,const std::vector<uint8_t> & offsets)910 bool CCodec_JpxModule::Decode(CJPX_Decoder* pDecoder,
911                               uint8_t* dest_data,
912                               int pitch,
913                               const std::vector<uint8_t>& offsets) {
914   return pDecoder->Decode(dest_data, pitch, offsets);
915 }
916 
DestroyDecoder(CJPX_Decoder * pDecoder)917 void CCodec_JpxModule::DestroyDecoder(CJPX_Decoder* pDecoder) {
918   delete pDecoder;
919 }
920