ColorSpace.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  1. /*
  2. * Copyright (c) 2021-2022, Matthew Olsson <mattco@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibGfx/ICC/WellKnownProfiles.h>
  7. #include <LibPDF/ColorSpace.h>
  8. #include <LibPDF/CommonNames.h>
  9. #include <LibPDF/Document.h>
  10. #include <LibPDF/ObjectDerivatives.h>
  11. #include <LibPDF/Renderer.h>
  12. namespace PDF {
  13. RefPtr<Gfx::ICC::Profile> ICCBasedColorSpace::s_srgb_profile;
  14. #define ENUMERATE(name, may_be_specified_directly) \
  15. ColorSpaceFamily ColorSpaceFamily::name { #name, may_be_specified_directly };
  16. ENUMERATE_COLOR_SPACE_FAMILIES(ENUMERATE);
  17. #undef ENUMERATE
  18. PDFErrorOr<ColorSpaceFamily> ColorSpaceFamily::get(DeprecatedFlyString const& family_name)
  19. {
  20. #define ENUMERATE(f_name, may_be_specified_directly) \
  21. if (family_name == f_name.name()) { \
  22. return ColorSpaceFamily::f_name; \
  23. }
  24. ENUMERATE_COLOR_SPACE_FAMILIES(ENUMERATE)
  25. #undef ENUMERATE
  26. dbgln_if(PDF_DEBUG, "Unknown ColorSpace family: {}", family_name);
  27. return Error(Error::Type::MalformedPDF, "Unknown ColorSpace family"_string);
  28. }
  29. PDFErrorOr<NonnullRefPtr<ColorSpace>> ColorSpace::create(Document* document, NonnullRefPtr<Object> color_space_object, Renderer& renderer)
  30. {
  31. // "A color space is defined by an array object whose first element is a name object identifying the color space family.
  32. // The remaining array elements, if any, are parameters that further characterize the color space;
  33. // their number and types vary according to the particular family.
  34. // For families that do not require parameters, the color space can be specified simply by the family name itself instead of an array."
  35. if (color_space_object->is<NameObject>())
  36. return ColorSpace::create(color_space_object->cast<NameObject>()->name(), renderer);
  37. if (color_space_object->is<ArrayObject>())
  38. return ColorSpace::create(document, color_space_object->cast<ArrayObject>(), renderer);
  39. return Error { Error::Type::MalformedPDF, "Color space must be name or array" };
  40. }
  41. PDFErrorOr<NonnullRefPtr<ColorSpace>> ColorSpace::create(DeprecatedFlyString const& name, Renderer&)
  42. {
  43. // Simple color spaces with no parameters, which can be specified directly
  44. if (name == CommonNames::DeviceGray)
  45. return DeviceGrayColorSpace::the();
  46. if (name == CommonNames::DeviceRGB)
  47. return DeviceRGBColorSpace::the();
  48. if (name == CommonNames::DeviceCMYK)
  49. return TRY(DeviceCMYKColorSpace::the());
  50. if (name == CommonNames::Pattern)
  51. return Error::rendering_unsupported_error("Pattern color spaces not yet implemented");
  52. VERIFY_NOT_REACHED();
  53. }
  54. PDFErrorOr<NonnullRefPtr<ColorSpace>> ColorSpace::create(Document* document, NonnullRefPtr<ArrayObject> color_space_array, Renderer& renderer)
  55. {
  56. auto color_space_name = TRY(color_space_array->get_name_at(document, 0))->name();
  57. Vector<Value> parameters;
  58. parameters.ensure_capacity(color_space_array->size() - 1);
  59. for (size_t i = 1; i < color_space_array->size(); i++)
  60. parameters.unchecked_append(color_space_array->at(i));
  61. if (color_space_name == CommonNames::CalGray)
  62. return TRY(CalGrayColorSpace::create(document, move(parameters)));
  63. if (color_space_name == CommonNames::CalRGB)
  64. return TRY(CalRGBColorSpace::create(document, move(parameters)));
  65. if (color_space_name == CommonNames::DeviceN)
  66. return TRY(DeviceNColorSpace::create(document, move(parameters), renderer));
  67. if (color_space_name == CommonNames::ICCBased)
  68. return TRY(ICCBasedColorSpace::create(document, move(parameters), renderer));
  69. if (color_space_name == CommonNames::Indexed)
  70. return TRY(IndexedColorSpace::create(document, move(parameters), renderer));
  71. if (color_space_name == CommonNames::Lab)
  72. return TRY(LabColorSpace::create(document, move(parameters)));
  73. if (color_space_name == CommonNames::Pattern)
  74. return Error::rendering_unsupported_error("Pattern color spaces not yet implemented");
  75. if (color_space_name == CommonNames::Separation)
  76. return TRY(SeparationColorSpace::create(document, move(parameters), renderer));
  77. dbgln("Unknown color space: {}", color_space_name);
  78. return Error::rendering_unsupported_error("unknown color space");
  79. }
  80. NonnullRefPtr<DeviceGrayColorSpace> DeviceGrayColorSpace::the()
  81. {
  82. static auto instance = adopt_ref(*new DeviceGrayColorSpace());
  83. return instance;
  84. }
  85. PDFErrorOr<ColorOrStyle> DeviceGrayColorSpace::style(ReadonlySpan<float> arguments) const
  86. {
  87. VERIFY(arguments.size() == 1);
  88. auto gray = static_cast<u8>(arguments[0] * 255.0f);
  89. return Color(gray, gray, gray);
  90. }
  91. Vector<float> DeviceGrayColorSpace::default_decode() const
  92. {
  93. return { 0.0f, 1.0f };
  94. }
  95. NonnullRefPtr<DeviceRGBColorSpace> DeviceRGBColorSpace::the()
  96. {
  97. static auto instance = adopt_ref(*new DeviceRGBColorSpace());
  98. return instance;
  99. }
  100. PDFErrorOr<ColorOrStyle> DeviceRGBColorSpace::style(ReadonlySpan<float> arguments) const
  101. {
  102. VERIFY(arguments.size() == 3);
  103. auto r = static_cast<u8>(arguments[0] * 255.0f);
  104. auto g = static_cast<u8>(arguments[1] * 255.0f);
  105. auto b = static_cast<u8>(arguments[2] * 255.0f);
  106. return Color(r, g, b);
  107. }
  108. Vector<float> DeviceRGBColorSpace::default_decode() const
  109. {
  110. return { 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f };
  111. }
  112. static RefPtr<Gfx::ICC::Profile> s_default_cmyk_profile;
  113. static RefPtr<Core::Resource> s_default_cmyk_resource;
  114. static ErrorOr<void> load_default_cmyk_profile()
  115. {
  116. auto resource = TRY(Core::Resource::load_from_uri("resource://icc/Adobe/CMYK/USWebCoatedSWOP.icc"sv));
  117. auto profile = TRY(Gfx::ICC::Profile::try_load_from_externally_owned_memory(resource->data()));
  118. s_default_cmyk_resource = move(resource);
  119. s_default_cmyk_profile = move(profile);
  120. return {};
  121. }
  122. ErrorOr<NonnullRefPtr<DeviceCMYKColorSpace>> DeviceCMYKColorSpace::the()
  123. {
  124. if (s_default_cmyk_profile.is_null())
  125. TRY(load_default_cmyk_profile());
  126. static auto instance = adopt_ref(*new DeviceCMYKColorSpace());
  127. return instance;
  128. }
  129. PDFErrorOr<ColorOrStyle> DeviceCMYKColorSpace::style(ReadonlySpan<float> arguments) const
  130. {
  131. VERIFY(arguments.size() == 4);
  132. u8 bytes[4];
  133. bytes[0] = static_cast<u8>(arguments[0] * 255.0f);
  134. bytes[1] = static_cast<u8>(arguments[1] * 255.0f);
  135. bytes[2] = static_cast<u8>(arguments[2] * 255.0f);
  136. bytes[3] = static_cast<u8>(arguments[3] * 255.0f);
  137. auto pcs = TRY(s_default_cmyk_profile->to_pcs(bytes));
  138. Array<u8, 3> output;
  139. TRY(ICCBasedColorSpace::sRGB()->from_pcs(*s_default_cmyk_profile, pcs, output.span()));
  140. return Color(output[0], output[1], output[2]);
  141. }
  142. Vector<float> DeviceCMYKColorSpace::default_decode() const
  143. {
  144. return { 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f };
  145. }
  146. PDFErrorOr<NonnullRefPtr<DeviceNColorSpace>> DeviceNColorSpace::create(Document* document, Vector<Value>&& parameters, Renderer& renderer)
  147. {
  148. // "[ /DeviceN names alternateSpace tintTransform ]
  149. // or
  150. // [ /DeviceN names alternateSpace tintTransform attributes ]"
  151. // (`/DeviceN` is already stripped from the array by the time we get here.)
  152. if (parameters.size() != 3 && parameters.size() != 4)
  153. return Error { Error::Type::MalformedPDF, "DeviceN color space expects 4 or 5 parameters" };
  154. // "The names parameter is an array of name objects specifying the individual color components.
  155. // The length of the array determines the number of components in the DeviceN color space"
  156. auto names_array = TRY(document->resolve_to<ArrayObject>(parameters[0]));
  157. Vector<ByteString> names;
  158. for (size_t i = 0; i < names_array->size(); ++i)
  159. names.append(names_array->get_name_at(i)->name());
  160. // "The alternateSpace parameter is an array or name object that can be any device or CIE-based color space
  161. // but not another special color space (Pattern, Indexed, Separation, or DeviceN)."
  162. auto alternate_space_object = TRY(document->resolve_to<Object>(parameters[1]));
  163. auto alternate_space = TRY(ColorSpace::create(document, alternate_space_object, renderer));
  164. auto family = alternate_space->family();
  165. if (family == ColorSpaceFamily::Pattern || family == ColorSpaceFamily::Indexed || family == ColorSpaceFamily::Separation || family == ColorSpaceFamily::DeviceN)
  166. return Error { Error::Type::MalformedPDF, "DeviceN color space has invalid alternate color space" };
  167. // "The tintTransform parameter specifies a function"
  168. auto tint_transform_object = TRY(document->resolve_to<Object>(parameters[2]));
  169. auto tint_transform = TRY(Function::create(document, tint_transform_object));
  170. // FIXME: If `attributes` is present and has /Subtype set to /NChannel, possibly
  171. // do slightly different processing.
  172. auto color_space = adopt_ref(*new DeviceNColorSpace(move(alternate_space), move(tint_transform)));
  173. color_space->m_names = move(names);
  174. return color_space;
  175. }
  176. DeviceNColorSpace::DeviceNColorSpace(NonnullRefPtr<ColorSpace> alternate_space, NonnullRefPtr<Function> tint_transform)
  177. : m_alternate_space(move(alternate_space))
  178. , m_tint_transform(move(tint_transform))
  179. {
  180. }
  181. PDFErrorOr<ColorOrStyle> DeviceNColorSpace::style(ReadonlySpan<float> arguments) const
  182. {
  183. // FIXME: Does this need handling for the special colorant name "None"?
  184. // FIXME: When drawing to a printer, do something else.
  185. auto tint_output = TRY(m_tint_transform->evaluate(arguments));
  186. m_tint_output_values.resize(tint_output.size());
  187. for (size_t i = 0; i < tint_output.size(); ++i)
  188. m_tint_output_values[i] = tint_output[i];
  189. return m_alternate_space->style(m_tint_output_values);
  190. }
  191. int DeviceNColorSpace::number_of_components() const
  192. {
  193. return m_names.size();
  194. }
  195. Vector<float> DeviceNColorSpace::default_decode() const
  196. {
  197. Vector<float> decoding_ranges;
  198. for (u8 i = 0; i < number_of_components(); i++) {
  199. decoding_ranges.append(0.0);
  200. decoding_ranges.append(1.0);
  201. }
  202. return decoding_ranges;
  203. }
  204. constexpr Array<float, 3> matrix_multiply(Array<float, 9> a, Array<float, 3> b)
  205. {
  206. return Array<float, 3> {
  207. a[0] * b[0] + a[1] * b[1] + a[2] * b[2],
  208. a[3] * b[0] + a[4] * b[1] + a[5] * b[2],
  209. a[6] * b[0] + a[7] * b[1] + a[8] * b[2]
  210. };
  211. }
  212. // Converts to a flat XYZ space with white point = (1, 1, 1)
  213. // Step 2 of https://www.color.org/adobebpc.pdf
  214. constexpr Array<float, 3> flatten_and_normalize_whitepoint(Array<float, 3> whitepoint, Array<float, 3> xyz)
  215. {
  216. VERIFY(whitepoint[1] == 1.0f);
  217. return {
  218. (1.0f / whitepoint[0]) * xyz[0],
  219. xyz[1],
  220. (1.0f / whitepoint[2]) * xyz[2],
  221. };
  222. }
  223. constexpr float decode_l(float input)
  224. {
  225. constexpr float decode_l_scaling_constant = 0.00110705646f; // (((8 + 16) / 116) ^ 3) / 8
  226. if (input < 0.0f)
  227. return -decode_l(-input);
  228. if (input >= 0.0f && input <= 8.0f)
  229. return input * decode_l_scaling_constant;
  230. return powf(((input + 16.0f) / 116.0f), 3.0f);
  231. }
  232. constexpr Array<float, 3> scale_black_point(Array<float, 3> blackpoint, Array<float, 3> xyz)
  233. {
  234. auto y_dst = decode_l(0); // DestinationBlackPoint is just [0, 0, 0]
  235. auto y_src = decode_l(blackpoint[0]);
  236. auto scale = (1 - y_dst) / (1 - y_src);
  237. auto offset = 1 - scale;
  238. return {
  239. xyz[0] * scale + offset,
  240. xyz[1] * scale + offset,
  241. xyz[2] * scale + offset,
  242. };
  243. }
  244. // https://en.wikipedia.org/wiki/Illuminant_D65
  245. constexpr Array<float, 3> convert_to_d65(Array<float, 3> xyz)
  246. {
  247. constexpr float d65x = 0.95047f;
  248. constexpr float d65y = 1.0f;
  249. constexpr float d65z = 1.08883f;
  250. return { xyz[0] * d65x, xyz[1] * d65y, xyz[2] * d65z };
  251. }
  252. // https://en.wikipedia.org/wiki/SRGB
  253. constexpr Array<float, 3> convert_to_srgb(Array<float, 3> xyz)
  254. {
  255. // See the sRGB D65 [M]^-1 matrix in the following page
  256. // http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
  257. constexpr Array<float, 9> conversion_matrix = {
  258. 3.2404542,
  259. -1.5371385,
  260. -0.4985314,
  261. -0.969266,
  262. 1.8760108,
  263. 0.0415560,
  264. 0.0556434,
  265. -0.2040259,
  266. 1.0572252,
  267. };
  268. auto linear_srgb = matrix_multiply(conversion_matrix, xyz);
  269. linear_srgb[0] = clamp(linear_srgb[0], 0.0f, 1.0f);
  270. linear_srgb[1] = clamp(linear_srgb[1], 0.0f, 1.0f);
  271. linear_srgb[2] = clamp(linear_srgb[2], 0.0f, 1.0f);
  272. // FIXME: Use the real sRGB curve by replacing this function with Gfx::ICC::sRGB().from_pcs().
  273. return { pow(linear_srgb[0], 1.0f / 2.2f), pow(linear_srgb[1], 1.0f / 2.2f), pow(linear_srgb[2], 1.0f / 2.2f) };
  274. }
  275. PDFErrorOr<NonnullRefPtr<CalGrayColorSpace>> CalGrayColorSpace::create(Document* document, Vector<Value>&& parameters)
  276. {
  277. if (parameters.size() != 1)
  278. return Error { Error::Type::MalformedPDF, "Gray color space expects one parameter" };
  279. auto dict = TRY(document->resolve_to<DictObject>(parameters[0]));
  280. if (!dict->contains(CommonNames::WhitePoint))
  281. return Error { Error::Type::MalformedPDF, "Gray color space expects a Whitepoint key" };
  282. auto white_point_array = TRY(dict->get_array(document, CommonNames::WhitePoint));
  283. if (white_point_array->size() != 3)
  284. return Error { Error::Type::MalformedPDF, "Gray color space expects 3 Whitepoint parameters" };
  285. auto color_space = adopt_ref(*new CalGrayColorSpace());
  286. color_space->m_whitepoint[0] = white_point_array->at(0).to_float();
  287. color_space->m_whitepoint[1] = white_point_array->at(1).to_float();
  288. color_space->m_whitepoint[2] = white_point_array->at(2).to_float();
  289. if (color_space->m_whitepoint[1] != 1.0f)
  290. return Error { Error::Type::MalformedPDF, "Gray color space expects 2nd Whitepoint to be 1.0" };
  291. if (dict->contains(CommonNames::BlackPoint)) {
  292. auto black_point_array = TRY(dict->get_array(document, CommonNames::BlackPoint));
  293. if (black_point_array->size() == 3) {
  294. color_space->m_blackpoint[0] = black_point_array->at(0).to_float();
  295. color_space->m_blackpoint[1] = black_point_array->at(1).to_float();
  296. color_space->m_blackpoint[2] = black_point_array->at(2).to_float();
  297. }
  298. }
  299. if (dict->contains(CommonNames::Gamma)) {
  300. color_space->m_gamma = TRY(document->resolve(dict->get_value(CommonNames::Gamma))).to_float();
  301. }
  302. return color_space;
  303. }
  304. PDFErrorOr<ColorOrStyle> CalGrayColorSpace::style(ReadonlySpan<float> arguments) const
  305. {
  306. VERIFY(arguments.size() == 1);
  307. auto a = clamp(arguments[0], 0.0f, 1.0f);
  308. auto ag = powf(a, m_gamma);
  309. auto x = m_whitepoint[0] * ag;
  310. auto y = m_whitepoint[1] * ag;
  311. auto z = m_whitepoint[2] * ag;
  312. auto flattened_xyz = flatten_and_normalize_whitepoint(m_whitepoint, { x, y, z });
  313. auto scaled_black_point_xyz = scale_black_point(m_blackpoint, flattened_xyz);
  314. auto d65_normalized = convert_to_d65(scaled_black_point_xyz);
  315. auto srgb = convert_to_srgb(d65_normalized);
  316. auto red = static_cast<u8>(clamp(srgb[0], 0.0f, 1.0f) * 255.0f);
  317. auto green = static_cast<u8>(clamp(srgb[1], 0.0f, 1.0f) * 255.0f);
  318. auto blue = static_cast<u8>(clamp(srgb[2], 0.0f, 1.0f) * 255.0f);
  319. return Color(red, green, blue);
  320. }
  321. Vector<float> CalGrayColorSpace::default_decode() const
  322. {
  323. return { 0.0f, 1.0f };
  324. }
  325. PDFErrorOr<NonnullRefPtr<CalRGBColorSpace>> CalRGBColorSpace::create(Document* document, Vector<Value>&& parameters)
  326. {
  327. if (parameters.size() != 1)
  328. return Error { Error::Type::MalformedPDF, "RGB color space expects one parameter" };
  329. auto dict = TRY(document->resolve_to<DictObject>(parameters[0]));
  330. if (!dict->contains(CommonNames::WhitePoint))
  331. return Error { Error::Type::MalformedPDF, "RGB color space expects a Whitepoint key" };
  332. auto white_point_array = TRY(dict->get_array(document, CommonNames::WhitePoint));
  333. if (white_point_array->size() != 3)
  334. return Error { Error::Type::MalformedPDF, "RGB color space expects 3 Whitepoint parameters" };
  335. auto color_space = adopt_ref(*new CalRGBColorSpace());
  336. color_space->m_whitepoint[0] = white_point_array->at(0).to_float();
  337. color_space->m_whitepoint[1] = white_point_array->at(1).to_float();
  338. color_space->m_whitepoint[2] = white_point_array->at(2).to_float();
  339. if (color_space->m_whitepoint[1] != 1.0f)
  340. return Error { Error::Type::MalformedPDF, "RGB color space expects 2nd Whitepoint to be 1.0" };
  341. if (dict->contains(CommonNames::BlackPoint)) {
  342. auto black_point_array = TRY(dict->get_array(document, CommonNames::BlackPoint));
  343. if (black_point_array->size() == 3) {
  344. color_space->m_blackpoint[0] = black_point_array->at(0).to_float();
  345. color_space->m_blackpoint[1] = black_point_array->at(1).to_float();
  346. color_space->m_blackpoint[2] = black_point_array->at(2).to_float();
  347. }
  348. }
  349. if (dict->contains(CommonNames::Gamma)) {
  350. auto gamma_array = TRY(dict->get_array(document, CommonNames::Gamma));
  351. if (gamma_array->size() == 3) {
  352. color_space->m_gamma[0] = gamma_array->at(0).to_float();
  353. color_space->m_gamma[1] = gamma_array->at(1).to_float();
  354. color_space->m_gamma[2] = gamma_array->at(2).to_float();
  355. }
  356. }
  357. if (dict->contains(CommonNames::Matrix)) {
  358. auto matrix_array = TRY(dict->get_array(document, CommonNames::Matrix));
  359. if (matrix_array->size() == 9) {
  360. color_space->m_matrix[0] = matrix_array->at(0).to_float();
  361. color_space->m_matrix[1] = matrix_array->at(1).to_float();
  362. color_space->m_matrix[2] = matrix_array->at(2).to_float();
  363. color_space->m_matrix[3] = matrix_array->at(3).to_float();
  364. color_space->m_matrix[4] = matrix_array->at(4).to_float();
  365. color_space->m_matrix[5] = matrix_array->at(5).to_float();
  366. color_space->m_matrix[6] = matrix_array->at(6).to_float();
  367. color_space->m_matrix[7] = matrix_array->at(7).to_float();
  368. color_space->m_matrix[8] = matrix_array->at(8).to_float();
  369. }
  370. }
  371. return color_space;
  372. }
  373. PDFErrorOr<ColorOrStyle> CalRGBColorSpace::style(ReadonlySpan<float> arguments) const
  374. {
  375. VERIFY(arguments.size() == 3);
  376. auto a = clamp(arguments[0], 0.0f, 1.0f);
  377. auto b = clamp(arguments[1], 0.0f, 1.0f);
  378. auto c = clamp(arguments[2], 0.0f, 1.0f);
  379. auto agr = powf(a, m_gamma[0]);
  380. auto bgg = powf(b, m_gamma[1]);
  381. auto cgb = powf(c, m_gamma[2]);
  382. auto x = m_matrix[0] * agr + m_matrix[3] * bgg + m_matrix[6] * cgb;
  383. auto y = m_matrix[1] * agr + m_matrix[4] * bgg + m_matrix[7] * cgb;
  384. auto z = m_matrix[2] * agr + m_matrix[5] * bgg + m_matrix[8] * cgb;
  385. auto flattened_xyz = flatten_and_normalize_whitepoint(m_whitepoint, { x, y, z });
  386. auto scaled_black_point_xyz = scale_black_point(m_blackpoint, flattened_xyz);
  387. auto d65_normalized = convert_to_d65(scaled_black_point_xyz);
  388. auto srgb = convert_to_srgb(d65_normalized);
  389. auto red = static_cast<u8>(clamp(srgb[0], 0.0f, 1.0f) * 255.0f);
  390. auto green = static_cast<u8>(clamp(srgb[1], 0.0f, 1.0f) * 255.0f);
  391. auto blue = static_cast<u8>(clamp(srgb[2], 0.0f, 1.0f) * 255.0f);
  392. return Color(red, green, blue);
  393. }
  394. Vector<float> CalRGBColorSpace::default_decode() const
  395. {
  396. return { 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f };
  397. }
  398. PDFErrorOr<NonnullRefPtr<ColorSpace>> ICCBasedColorSpace::create(Document* document, Vector<Value>&& parameters, Renderer& renderer)
  399. {
  400. if (parameters.is_empty())
  401. return Error { Error::Type::MalformedPDF, "ICCBased color space expected one parameter" };
  402. auto stream = TRY(document->resolve_to<StreamObject>(parameters[0]));
  403. auto dict = stream->dict();
  404. auto maybe_profile = Gfx::ICC::Profile::try_load_from_externally_owned_memory(stream->bytes());
  405. if (!maybe_profile.is_error())
  406. return adopt_ref(*new ICCBasedColorSpace(maybe_profile.release_value()));
  407. if (dict->contains(CommonNames::Alternate)) {
  408. auto alternate_color_space_object = MUST(dict->get_object(document, CommonNames::Alternate));
  409. if (alternate_color_space_object->is<NameObject>())
  410. return ColorSpace::create(alternate_color_space_object->cast<NameObject>()->name(), renderer);
  411. return Error { Error::Type::Internal, "Alternate color spaces in array format are not supported" };
  412. }
  413. return maybe_profile.release_error();
  414. }
  415. ICCBasedColorSpace::ICCBasedColorSpace(NonnullRefPtr<Gfx::ICC::Profile> profile)
  416. : m_profile(profile)
  417. {
  418. m_map = sRGB()->matrix_matrix_conversion(profile);
  419. }
  420. PDFErrorOr<ColorOrStyle> ICCBasedColorSpace::style(ReadonlySpan<float> arguments) const
  421. {
  422. if (m_profile->data_color_space() == Gfx::ICC::ColorSpace::CIELAB) {
  423. m_components.resize(arguments.size());
  424. for (size_t i = 0; i < arguments.size(); ++i) {
  425. float number = arguments[i];
  426. // CIELAB channels go from 0..100 and -128..127 instead of from 0..1.
  427. // FIXME: We should probably have an API on Gfx::ICC::Profile that takes floats instead of bytes and that does this internally instead.
  428. if (i == 0)
  429. number /= 100.0f;
  430. else
  431. number = (number + 128.0f) / 255.0f;
  432. m_components[i] = number;
  433. }
  434. arguments = m_components;
  435. }
  436. if (m_map.has_value())
  437. return m_map->map(FloatVector3 { arguments[0], arguments[1], arguments[2] });
  438. m_bytes.resize(arguments.size());
  439. for (size_t i = 0; i < arguments.size(); ++i)
  440. m_bytes[i] = static_cast<u8>(arguments[i] * 255.0f);
  441. auto pcs = TRY(m_profile->to_pcs(m_bytes));
  442. Array<u8, 3> output;
  443. TRY(sRGB()->from_pcs(m_profile, pcs, output.span()));
  444. return Color(output[0], output[1], output[2]);
  445. }
  446. int ICCBasedColorSpace::number_of_components() const
  447. {
  448. return Gfx::ICC::number_of_components_in_color_space(m_profile->data_color_space());
  449. }
  450. Vector<float> ICCBasedColorSpace::default_decode() const
  451. {
  452. auto color_space = m_profile->data_color_space();
  453. switch (color_space) {
  454. case Gfx::ICC::ColorSpace::Gray:
  455. return { 0.0, 1.0 };
  456. case Gfx::ICC::ColorSpace::RGB:
  457. return { 0.0, 1.0, 0.0, 1.0, 0.0, 1.0 };
  458. case Gfx::ICC::ColorSpace::CMYK:
  459. return { 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0 };
  460. default:
  461. warnln("PDF: Unknown default_decode params for color space {}", Gfx::ICC::data_color_space_name(color_space));
  462. Vector<float> decoding_ranges;
  463. for (u8 i = 0; i < Gfx::ICC::number_of_components_in_color_space(color_space); i++) {
  464. decoding_ranges.append(0.0);
  465. decoding_ranges.append(1.0);
  466. }
  467. return decoding_ranges;
  468. }
  469. }
  470. NonnullRefPtr<Gfx::ICC::Profile> ICCBasedColorSpace::sRGB()
  471. {
  472. if (!s_srgb_profile)
  473. s_srgb_profile = MUST(Gfx::ICC::sRGB());
  474. return *s_srgb_profile;
  475. }
  476. PDFErrorOr<NonnullRefPtr<LabColorSpace>> LabColorSpace::create(Document* document, Vector<Value>&& parameters)
  477. {
  478. if (parameters.size() != 1)
  479. return Error { Error::Type::MalformedPDF, "Lab color space expects one parameter" };
  480. auto dict = TRY(document->resolve_to<DictObject>(parameters[0]));
  481. if (!dict->contains(CommonNames::WhitePoint))
  482. return Error { Error::Type::MalformedPDF, "Lab color space expects a Whitepoint key" };
  483. auto white_point_array = TRY(dict->get_array(document, CommonNames::WhitePoint));
  484. if (white_point_array->size() != 3)
  485. return Error { Error::Type::MalformedPDF, "Lab color space expects 3 Whitepoint parameters" };
  486. auto color_space = adopt_ref(*new LabColorSpace());
  487. color_space->m_whitepoint[0] = white_point_array->at(0).to_float();
  488. color_space->m_whitepoint[1] = white_point_array->at(1).to_float();
  489. color_space->m_whitepoint[2] = white_point_array->at(2).to_float();
  490. if (color_space->m_whitepoint[1] != 1.0f)
  491. return Error { Error::Type::MalformedPDF, "Lab color space expects 2nd Whitepoint to be 1.0" };
  492. if (dict->contains(CommonNames::BlackPoint)) {
  493. auto black_point_array = TRY(dict->get_array(document, CommonNames::BlackPoint));
  494. if (black_point_array->size() == 3) {
  495. color_space->m_blackpoint[0] = black_point_array->at(0).to_float();
  496. color_space->m_blackpoint[1] = black_point_array->at(1).to_float();
  497. color_space->m_blackpoint[2] = black_point_array->at(2).to_float();
  498. }
  499. }
  500. if (dict->contains(CommonNames::Range)) {
  501. auto range_array = TRY(dict->get_array(document, CommonNames::Range));
  502. if (range_array->size() == 4) {
  503. color_space->m_range[0] = range_array->at(0).to_float();
  504. color_space->m_range[1] = range_array->at(1).to_float();
  505. color_space->m_range[2] = range_array->at(2).to_float();
  506. color_space->m_range[3] = range_array->at(3).to_float();
  507. }
  508. }
  509. return color_space;
  510. }
  511. PDFErrorOr<ColorOrStyle> LabColorSpace::style(ReadonlySpan<float> arguments) const
  512. {
  513. VERIFY(arguments.size() == 3);
  514. auto L_star = clamp(arguments[0], 0.0f, 100.0f);
  515. auto a_star = clamp(arguments[1], m_range[0], m_range[1]);
  516. auto b_star = clamp(arguments[2], m_range[2], m_range[3]);
  517. auto L = (L_star + 16) / 116 + a_star / 500;
  518. auto M = (L_star + 16) / 116;
  519. auto N = (L_star + 16) / 116 - b_star / 200;
  520. auto g = [](float x) {
  521. if (x >= 6.0f / 29.0f)
  522. return powf(x, 3);
  523. return 108.0f / 841.0f * (x - 4.0f / 29.0f);
  524. };
  525. auto x = m_whitepoint[0] * g(L);
  526. auto y = m_whitepoint[1] * g(M);
  527. auto z = m_whitepoint[2] * g(N);
  528. auto flattened_xyz = flatten_and_normalize_whitepoint(m_whitepoint, { x, y, z });
  529. auto scaled_black_point_xyz = scale_black_point(m_blackpoint, flattened_xyz);
  530. auto d65_normalized = convert_to_d65(scaled_black_point_xyz);
  531. auto srgb = convert_to_srgb(d65_normalized);
  532. auto red = static_cast<u8>(clamp(srgb[0], 0.0f, 1.0f) * 255.0f);
  533. auto green = static_cast<u8>(clamp(srgb[1], 0.0f, 1.0f) * 255.0f);
  534. auto blue = static_cast<u8>(clamp(srgb[2], 0.0f, 1.0f) * 255.0f);
  535. return Color(red, green, blue);
  536. }
  537. Vector<float> LabColorSpace::default_decode() const
  538. {
  539. return { 0.0f, 100.0f, m_range[0], m_range[1], m_range[2], m_range[3] };
  540. }
  541. PDFErrorOr<NonnullRefPtr<ColorSpace>> IndexedColorSpace::create(Document* document, Vector<Value>&& parameters, Renderer& renderer)
  542. {
  543. if (parameters.size() != 3)
  544. return Error { Error::Type::MalformedPDF, "Indexed color space expected three parameters" };
  545. // "The base parameter is an array or name that identifies the base color space in which the values
  546. // in the color table are to be interpreted. It can be any device or CIE-based color space or (in PDF 1.3)
  547. // a Separation or DeviceN space, but not a Pattern space or another Indexed space."
  548. auto base_object = TRY(document->resolve_to<Object>(parameters[0]));
  549. auto base = TRY(ColorSpace::create(document, base_object, renderer));
  550. if (base->family() == ColorSpaceFamily::Pattern || base->family() == ColorSpaceFamily::Indexed)
  551. return Error { Error::Type::MalformedPDF, "Indexed color space has invalid base color space" };
  552. // "The hival parameter is an integer that specifies the maximum valid index value. In other words,
  553. // the color table is to be indexed by integers in the range 0 to hival. hival can be no greater than 255"
  554. auto hival = TRY(document->resolve_to<int>(parameters[1]));
  555. if (hival < 0 || hival > 255)
  556. return Error { Error::Type::MalformedPDF, "Indexed color space hival out of range" };
  557. // "The color table is defined by the lookup parameter, which can be either a stream or (in PDF 1.2) a byte string.
  558. // It provides the mapping between index values and the corresponding colors in the base color space.
  559. // The color table data must be m × (hival + 1) bytes long, where m is the number of color components in the
  560. // base color space. Each byte is an unsigned integer in the range 0 to 255 that is scaled to the range of
  561. // the corresponding color component in the base color space; that is, 0 corresponds to the minimum value
  562. // in the range for that component, and 255 corresponds to the maximum."
  563. auto lookup_object = TRY(document->resolve_to<Object>(parameters[2]));
  564. Vector<u8> lookup;
  565. if (lookup_object->is<StreamObject>()) {
  566. lookup = Vector<u8> { lookup_object->cast<StreamObject>()->bytes() };
  567. } else if (lookup_object->is<StringObject>()) {
  568. // FIXME: Check if it's a hex string.
  569. auto const& string = lookup_object->cast<StringObject>()->string();
  570. lookup = Vector<u8> { ReadonlyBytes { string.characters(), string.length() } };
  571. } else {
  572. return Error { Error::Type::MalformedPDF, "Indexed color space expects stream or string for third arg" };
  573. }
  574. size_t needed_size = (hival + 1) * base->number_of_components();
  575. if (lookup.size() - 1 == needed_size) {
  576. // FIXME: Could do this if lookup.size() > needed_size generally, but so far I've only seen files that had one byte too much.
  577. lookup.resize(needed_size);
  578. }
  579. if (lookup.size() != needed_size) {
  580. dbgln("lookup size {} doesn't match hival {} and base components {}", lookup.size(), hival, base->number_of_components());
  581. return Error { Error::Type::MalformedPDF, "Indexed color space lookup table doesn't match size" };
  582. }
  583. auto color_space = adopt_ref(*new IndexedColorSpace(move(base)));
  584. color_space->m_hival = hival;
  585. color_space->m_lookup = move(lookup);
  586. return color_space;
  587. }
  588. IndexedColorSpace::IndexedColorSpace(NonnullRefPtr<ColorSpace> base)
  589. : m_base(move(base))
  590. {
  591. }
  592. PDFErrorOr<ColorOrStyle> IndexedColorSpace::style(ReadonlySpan<float> arguments) const
  593. {
  594. VERIFY(arguments.size() == 1);
  595. auto index = static_cast<int>(arguments[0]);
  596. if (index < 0 || index > m_hival)
  597. return Error { Error::Type::MalformedPDF, "Indexed color space index out of range" };
  598. Vector<Value, 4> components;
  599. size_t const n = m_base->number_of_components();
  600. for (size_t i = 0; i < n; ++i)
  601. TRY(components.try_append(Value(m_lookup[index * n + i] / 255.0f)));
  602. return m_base->style(components);
  603. }
  604. Vector<float> IndexedColorSpace::default_decode() const
  605. {
  606. return { 0.0, 255.0 };
  607. }
  608. PDFErrorOr<NonnullRefPtr<SeparationColorSpace>> SeparationColorSpace::create(Document* document, Vector<Value>&& parameters, Renderer& renderer)
  609. {
  610. if (parameters.size() != 3)
  611. return Error { Error::Type::MalformedPDF, "Separation color space expected three parameters" };
  612. // "The name parameter is a name object specifying the name of the colorant that this Separation color space
  613. // is intended to represent (or one of the special names All or None; see below)"
  614. auto name_object = TRY(document->resolve_to<NameObject>(parameters[0]));
  615. auto name = name_object->cast<NameObject>()->name();
  616. // "The alternateSpace parameter must be an array or name object that identifies the alternate color space,
  617. // which can be any device or CIE-based color space but not another special color space
  618. // (Pattern, Indexed, Separation, or DeviceN)."
  619. auto alternate_space_object = TRY(document->resolve_to<Object>(parameters[1]));
  620. auto alternate_space = TRY(ColorSpace::create(document, alternate_space_object, renderer));
  621. auto family = alternate_space->family();
  622. if (family == ColorSpaceFamily::Pattern || family == ColorSpaceFamily::Indexed || family == ColorSpaceFamily::Separation || family == ColorSpaceFamily::DeviceN)
  623. return Error { Error::Type::MalformedPDF, "Separation color space has invalid alternate color space" };
  624. // "The tintTransform parameter must be a function"
  625. auto tint_transform_object = TRY(document->resolve_to<Object>(parameters[2]));
  626. auto tint_transform = TRY(Function::create(document, tint_transform_object));
  627. auto color_space = adopt_ref(*new SeparationColorSpace(move(alternate_space), move(tint_transform)));
  628. color_space->m_name = move(name);
  629. return color_space;
  630. }
  631. SeparationColorSpace::SeparationColorSpace(NonnullRefPtr<ColorSpace> alternate_space, NonnullRefPtr<Function> tint_transform)
  632. : m_alternate_space(move(alternate_space))
  633. , m_tint_transform(move(tint_transform))
  634. {
  635. }
  636. PDFErrorOr<ColorOrStyle> SeparationColorSpace::style(ReadonlySpan<float> arguments) const
  637. {
  638. // "For an additive device such as a computer display, a Separation color space never applies a process colorant directly;
  639. // it always reverts to the alternate color space as described below."
  640. // "During subsequent painting operations, an application calls [the tint] function to transform a tint value into
  641. // color component values in the alternate color space."
  642. // FIXME: Does this need handling for the special colorant names "All" and "None"?
  643. // FIXME: When drawing to a printer, do something else.
  644. VERIFY(arguments.size() == 1);
  645. auto a = arguments[0];
  646. auto tint_output = TRY(m_tint_transform->evaluate(ReadonlySpan<float> { &a, 1 }));
  647. m_tint_output_values.resize(tint_output.size());
  648. for (size_t i = 0; i < tint_output.size(); ++i)
  649. m_tint_output_values[i] = tint_output[i];
  650. return m_alternate_space->style(m_tint_output_values);
  651. }
  652. Vector<float> SeparationColorSpace::default_decode() const
  653. {
  654. return { 0.0f, 1.0f };
  655. }
  656. }