ColorSpace.cpp 33 KB

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