ColorSpace.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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(DeprecatedFlyString const& name)
  29. {
  30. // Simple color spaces with no parameters, which can be specified directly
  31. if (name == CommonNames::DeviceGray)
  32. return DeviceGrayColorSpace::the();
  33. if (name == CommonNames::DeviceRGB)
  34. return DeviceRGBColorSpace::the();
  35. if (name == CommonNames::DeviceCMYK)
  36. return DeviceCMYKColorSpace::the();
  37. if (name == CommonNames::Pattern)
  38. return Error::rendering_unsupported_error("Pattern color spaces not yet implemented");
  39. VERIFY_NOT_REACHED();
  40. }
  41. PDFErrorOr<NonnullRefPtr<ColorSpace>> ColorSpace::create(Document* document, NonnullRefPtr<ArrayObject> color_space_array)
  42. {
  43. auto color_space_name = TRY(color_space_array->get_name_at(document, 0))->name();
  44. Vector<Value> parameters;
  45. parameters.ensure_capacity(color_space_array->size() - 1);
  46. for (size_t i = 1; i < color_space_array->size(); i++)
  47. parameters.unchecked_append(color_space_array->at(i));
  48. if (color_space_name == CommonNames::CalRGB)
  49. return TRY(CalRGBColorSpace::create(document, move(parameters)));
  50. if (color_space_name == CommonNames::DeviceN)
  51. return TRY(DeviceNColorSpace::create(document, move(parameters)));
  52. if (color_space_name == CommonNames::ICCBased)
  53. return TRY(ICCBasedColorSpace::create(document, move(parameters)));
  54. if (color_space_name == CommonNames::Indexed)
  55. return Error::rendering_unsupported_error("Indexed color spaces not yet implemented");
  56. if (color_space_name == CommonNames::Lab)
  57. return TRY(LabColorSpace::create(document, move(parameters)));
  58. if (color_space_name == CommonNames::Pattern)
  59. return Error::rendering_unsupported_error("Pattern color spaces not yet implemented");
  60. if (color_space_name == CommonNames::Separation)
  61. return TRY(SeparationColorSpace::create(document, move(parameters)));
  62. dbgln("Unknown color space: {}", color_space_name);
  63. return Error::rendering_unsupported_error("unknown color space");
  64. }
  65. NonnullRefPtr<DeviceGrayColorSpace> DeviceGrayColorSpace::the()
  66. {
  67. static auto instance = adopt_ref(*new DeviceGrayColorSpace());
  68. return instance;
  69. }
  70. PDFErrorOr<Color> DeviceGrayColorSpace::color(ReadonlySpan<Value> arguments) const
  71. {
  72. VERIFY(arguments.size() == 1);
  73. auto gray = static_cast<u8>(arguments[0].to_float() * 255.0f);
  74. return Color(gray, gray, gray);
  75. }
  76. Vector<float> DeviceGrayColorSpace::default_decode() const
  77. {
  78. return { 0.0f, 1.0f };
  79. }
  80. NonnullRefPtr<DeviceRGBColorSpace> DeviceRGBColorSpace::the()
  81. {
  82. static auto instance = adopt_ref(*new DeviceRGBColorSpace());
  83. return instance;
  84. }
  85. PDFErrorOr<Color> DeviceRGBColorSpace::color(ReadonlySpan<Value> arguments) const
  86. {
  87. VERIFY(arguments.size() == 3);
  88. auto r = static_cast<u8>(arguments[0].to_float() * 255.0f);
  89. auto g = static_cast<u8>(arguments[1].to_float() * 255.0f);
  90. auto b = static_cast<u8>(arguments[2].to_float() * 255.0f);
  91. return Color(r, g, b);
  92. }
  93. Vector<float> DeviceRGBColorSpace::default_decode() const
  94. {
  95. return { 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f };
  96. }
  97. NonnullRefPtr<DeviceCMYKColorSpace> DeviceCMYKColorSpace::the()
  98. {
  99. static auto instance = adopt_ref(*new DeviceCMYKColorSpace());
  100. return instance;
  101. }
  102. PDFErrorOr<Color> DeviceCMYKColorSpace::color(ReadonlySpan<Value> arguments) const
  103. {
  104. VERIFY(arguments.size() == 4);
  105. auto c = arguments[0].to_float();
  106. auto m = arguments[1].to_float();
  107. auto y = arguments[2].to_float();
  108. auto k = arguments[3].to_float();
  109. return Color::from_cmyk(c, m, y, k);
  110. }
  111. Vector<float> DeviceCMYKColorSpace::default_decode() const
  112. {
  113. return { 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f };
  114. }
  115. PDFErrorOr<NonnullRefPtr<DeviceNColorSpace>> DeviceNColorSpace::create(Document*, Vector<Value>&& parameters)
  116. {
  117. // "[ /DeviceN names alternateSpace tintTransform ]
  118. // or
  119. // [ /DeviceN names alternateSpace tintTransform attributes ]"
  120. if (parameters.size() != 4 && parameters.size() != 5)
  121. return Error { Error::Type::MalformedPDF, "DevicN color space expects 4 or 5 parameters" };
  122. // "The names parameter is an array of name objects specifying the individual color components.
  123. // The length of the array determines the number of components in the DeviceN color space"
  124. auto names = parameters[0].get<NonnullRefPtr<Object>>()->cast<ArrayObject>();
  125. // "The alternateSpace parameter is an array or name object that can be any device or CIE-based color space
  126. // but not another special color space (Pattern, Indexed, Separation, or DeviceN)."
  127. // FIXME: Implement.
  128. return adopt_ref(*new DeviceNColorSpace(names->size()));
  129. }
  130. PDFErrorOr<Color> DeviceNColorSpace::color(ReadonlySpan<Value>) const
  131. {
  132. return Error::rendering_unsupported_error("DeviceN color spaces not yet implemented");
  133. }
  134. int DeviceNColorSpace::number_of_components() const
  135. {
  136. return m_number_of_components;
  137. }
  138. Vector<float> DeviceNColorSpace::default_decode() const
  139. {
  140. Vector<float> decoding_ranges;
  141. for (u8 i = 0; i < number_of_components(); i++) {
  142. decoding_ranges.append(0.0);
  143. decoding_ranges.append(1.0);
  144. }
  145. return decoding_ranges;
  146. }
  147. DeviceNColorSpace::DeviceNColorSpace(size_t number_of_components)
  148. : m_number_of_components(number_of_components)
  149. {
  150. }
  151. constexpr Array<float, 3> matrix_multiply(Array<float, 9> a, Array<float, 3> b)
  152. {
  153. return Array<float, 3> {
  154. a[0] * b[0] + a[1] * b[1] + a[2] * b[2],
  155. a[3] * b[0] + a[4] * b[1] + a[5] * b[2],
  156. a[6] * b[0] + a[7] * b[1] + a[8] * b[2]
  157. };
  158. }
  159. // Converts to a flat XYZ space with white point = (1, 1, 1)
  160. // Step 2 of https://www.color.org/adobebpc.pdf
  161. constexpr Array<float, 3> flatten_and_normalize_whitepoint(Array<float, 3> whitepoint, Array<float, 3> xyz)
  162. {
  163. VERIFY(whitepoint[1] == 1.0f);
  164. return {
  165. (1.0f / whitepoint[0]) * xyz[0],
  166. xyz[1],
  167. (1.0f / whitepoint[2]) * xyz[2],
  168. };
  169. }
  170. constexpr float decode_l(float input)
  171. {
  172. constexpr float decode_l_scaling_constant = 0.00110705646f; // (((8 + 16) / 116) ^ 3) / 8
  173. if (input < 0.0f)
  174. return -decode_l(-input);
  175. if (input >= 0.0f && input <= 8.0f)
  176. return input * decode_l_scaling_constant;
  177. return powf(((input + 16.0f) / 116.0f), 3.0f);
  178. }
  179. constexpr Array<float, 3> scale_black_point(Array<float, 3> blackpoint, Array<float, 3> xyz)
  180. {
  181. auto y_dst = decode_l(0); // DestinationBlackPoint is just [0, 0, 0]
  182. auto y_src = decode_l(blackpoint[0]);
  183. auto scale = (1 - y_dst) / (1 - y_src);
  184. auto offset = 1 - scale;
  185. return {
  186. xyz[0] * scale + offset,
  187. xyz[1] * scale + offset,
  188. xyz[2] * scale + offset,
  189. };
  190. }
  191. // https://en.wikipedia.org/wiki/Illuminant_D65
  192. constexpr Array<float, 3> convert_to_d65(Array<float, 3> xyz)
  193. {
  194. constexpr float d65x = 0.95047f;
  195. constexpr float d65y = 1.0f;
  196. constexpr float d65z = 1.08883f;
  197. return { xyz[0] * d65x, xyz[1] * d65y, xyz[2] * d65z };
  198. }
  199. // https://en.wikipedia.org/wiki/SRGB
  200. constexpr Array<float, 3> convert_to_srgb(Array<float, 3> xyz)
  201. {
  202. // See the sRGB D65 [M]^-1 matrix in the following page
  203. // http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
  204. constexpr Array<float, 9> conversion_matrix = {
  205. 3.2404542,
  206. -1.5371385,
  207. -0.4985314,
  208. -0.969266,
  209. 1.8760108,
  210. 0.0415560,
  211. 0.0556434,
  212. -0.2040259,
  213. 1.0572252,
  214. };
  215. auto linear_srgb = matrix_multiply(conversion_matrix, xyz);
  216. // FIXME: Use the real sRGB curve by replacing this function with Gfx::ICC::sRGB().from_pcs().
  217. 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) };
  218. }
  219. PDFErrorOr<NonnullRefPtr<CalRGBColorSpace>> CalRGBColorSpace::create(Document* document, Vector<Value>&& parameters)
  220. {
  221. if (parameters.size() != 1)
  222. return Error { Error::Type::MalformedPDF, "RGB color space expects one parameter" };
  223. auto param = parameters[0];
  224. if (!param.has<NonnullRefPtr<Object>>() || !param.get<NonnullRefPtr<Object>>()->is<DictObject>())
  225. return Error { Error::Type::MalformedPDF, "RGB color space expects a dict parameter" };
  226. auto dict = param.get<NonnullRefPtr<Object>>()->cast<DictObject>();
  227. if (!dict->contains(CommonNames::WhitePoint))
  228. return Error { Error::Type::MalformedPDF, "RGB color space expects a Whitepoint key" };
  229. auto white_point_array = TRY(dict->get_array(document, CommonNames::WhitePoint));
  230. if (white_point_array->size() != 3)
  231. return Error { Error::Type::MalformedPDF, "RGB color space expects 3 Whitepoint parameters" };
  232. auto color_space = adopt_ref(*new CalRGBColorSpace());
  233. color_space->m_whitepoint[0] = white_point_array->at(0).to_float();
  234. color_space->m_whitepoint[1] = white_point_array->at(1).to_float();
  235. color_space->m_whitepoint[2] = white_point_array->at(2).to_float();
  236. if (color_space->m_whitepoint[1] != 1.0f)
  237. return Error { Error::Type::MalformedPDF, "RGB color space expects 2nd Whitepoint to be 1.0" };
  238. if (dict->contains(CommonNames::BlackPoint)) {
  239. auto black_point_array = TRY(dict->get_array(document, CommonNames::BlackPoint));
  240. if (black_point_array->size() == 3) {
  241. color_space->m_blackpoint[0] = black_point_array->at(0).to_float();
  242. color_space->m_blackpoint[1] = black_point_array->at(1).to_float();
  243. color_space->m_blackpoint[2] = black_point_array->at(2).to_float();
  244. }
  245. }
  246. if (dict->contains(CommonNames::Gamma)) {
  247. auto gamma_array = TRY(dict->get_array(document, CommonNames::Gamma));
  248. if (gamma_array->size() == 3) {
  249. color_space->m_gamma[0] = gamma_array->at(0).to_float();
  250. color_space->m_gamma[1] = gamma_array->at(1).to_float();
  251. color_space->m_gamma[2] = gamma_array->at(2).to_float();
  252. }
  253. }
  254. if (dict->contains(CommonNames::Matrix)) {
  255. auto matrix_array = TRY(dict->get_array(document, CommonNames::Matrix));
  256. if (matrix_array->size() == 9) {
  257. color_space->m_matrix[0] = matrix_array->at(0).to_float();
  258. color_space->m_matrix[1] = matrix_array->at(1).to_float();
  259. color_space->m_matrix[2] = matrix_array->at(2).to_float();
  260. color_space->m_matrix[3] = matrix_array->at(3).to_float();
  261. color_space->m_matrix[4] = matrix_array->at(4).to_float();
  262. color_space->m_matrix[5] = matrix_array->at(5).to_float();
  263. color_space->m_matrix[6] = matrix_array->at(6).to_float();
  264. color_space->m_matrix[7] = matrix_array->at(7).to_float();
  265. color_space->m_matrix[8] = matrix_array->at(8).to_float();
  266. }
  267. }
  268. return color_space;
  269. }
  270. PDFErrorOr<Color> CalRGBColorSpace::color(ReadonlySpan<Value> arguments) const
  271. {
  272. VERIFY(arguments.size() == 3);
  273. auto a = clamp(arguments[0].to_float(), 0.0f, 1.0f);
  274. auto b = clamp(arguments[1].to_float(), 0.0f, 1.0f);
  275. auto c = clamp(arguments[2].to_float(), 0.0f, 1.0f);
  276. auto agr = powf(a, m_gamma[0]);
  277. auto bgg = powf(b, m_gamma[1]);
  278. auto cgb = powf(c, m_gamma[2]);
  279. auto x = m_matrix[0] * agr + m_matrix[3] * bgg + m_matrix[6] * cgb;
  280. auto y = m_matrix[1] * agr + m_matrix[4] * bgg + m_matrix[7] * cgb;
  281. auto z = m_matrix[2] * agr + m_matrix[5] * bgg + m_matrix[8] * cgb;
  282. auto flattened_xyz = flatten_and_normalize_whitepoint(m_whitepoint, { x, y, z });
  283. auto scaled_black_point_xyz = scale_black_point(m_blackpoint, flattened_xyz);
  284. auto d65_normalized = convert_to_d65(scaled_black_point_xyz);
  285. auto srgb = convert_to_srgb(d65_normalized);
  286. auto red = static_cast<u8>(clamp(srgb[0], 0.0f, 1.0f) * 255.0f);
  287. auto green = static_cast<u8>(clamp(srgb[1], 0.0f, 1.0f) * 255.0f);
  288. auto blue = static_cast<u8>(clamp(srgb[2], 0.0f, 1.0f) * 255.0f);
  289. return Color(red, green, blue);
  290. }
  291. Vector<float> CalRGBColorSpace::default_decode() const
  292. {
  293. return { 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f };
  294. }
  295. PDFErrorOr<NonnullRefPtr<ColorSpace>> ICCBasedColorSpace::create(Document* document, Vector<Value>&& parameters)
  296. {
  297. if (parameters.is_empty())
  298. return Error { Error::Type::MalformedPDF, "ICCBased color space expected one parameter" };
  299. auto param = TRY(document->resolve(parameters[0]));
  300. if (!param.has<NonnullRefPtr<Object>>() || !param.get<NonnullRefPtr<Object>>()->is<StreamObject>())
  301. return Error { Error::Type::MalformedPDF, "ICCBased color space expects a stream parameter" };
  302. auto stream = param.get<NonnullRefPtr<Object>>()->cast<StreamObject>();
  303. auto dict = stream->dict();
  304. auto maybe_profile = Gfx::ICC::Profile::try_load_from_externally_owned_memory(stream->bytes());
  305. if (!maybe_profile.is_error())
  306. return adopt_ref(*new ICCBasedColorSpace(maybe_profile.release_value()));
  307. if (dict->contains(CommonNames::Alternate)) {
  308. auto alternate_color_space_object = MUST(dict->get_object(document, CommonNames::Alternate));
  309. if (alternate_color_space_object->is<NameObject>())
  310. return ColorSpace::create(alternate_color_space_object->cast<NameObject>()->name());
  311. return Error { Error::Type::Internal, "Alternate color spaces in array format are not supported" };
  312. }
  313. return Error { Error::Type::MalformedPDF, "Failed to load ICC color space with malformed profile and no alternate" };
  314. }
  315. ICCBasedColorSpace::ICCBasedColorSpace(NonnullRefPtr<Gfx::ICC::Profile> profile)
  316. : m_profile(profile)
  317. {
  318. }
  319. PDFErrorOr<Color> ICCBasedColorSpace::color(ReadonlySpan<Value> arguments) const
  320. {
  321. if (!s_srgb_profile)
  322. s_srgb_profile = TRY(Gfx::ICC::sRGB());
  323. Vector<u8> bytes;
  324. for (auto const& arg : arguments) {
  325. VERIFY(arg.has_number());
  326. bytes.append(static_cast<u8>(arg.to_float() * 255.0f));
  327. }
  328. auto pcs = TRY(m_profile->to_pcs(bytes));
  329. Array<u8, 3> output;
  330. TRY(s_srgb_profile->from_pcs(pcs, output.span()));
  331. return Color(output[0], output[1], output[2]);
  332. }
  333. int ICCBasedColorSpace::number_of_components() const
  334. {
  335. return Gfx::ICC::number_of_components_in_color_space(m_profile->data_color_space());
  336. }
  337. Vector<float> ICCBasedColorSpace::default_decode() const
  338. {
  339. auto color_space = m_profile->data_color_space();
  340. switch (color_space) {
  341. case Gfx::ICC::ColorSpace::Gray:
  342. return { 0.0, 1.0 };
  343. case Gfx::ICC::ColorSpace::RGB:
  344. return { 0.0, 1.0, 0.0, 1.0, 0.0, 1.0 };
  345. case Gfx::ICC::ColorSpace::CMYK:
  346. return { 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0 };
  347. default:
  348. warnln("PDF: Unknown default_decode params for color space {}", Gfx::ICC::data_color_space_name(color_space));
  349. Vector<float> decoding_ranges;
  350. for (u8 i = 0; i < Gfx::ICC::number_of_components_in_color_space(color_space); i++) {
  351. decoding_ranges.append(0.0);
  352. decoding_ranges.append(1.0);
  353. }
  354. return decoding_ranges;
  355. }
  356. }
  357. PDFErrorOr<NonnullRefPtr<LabColorSpace>> LabColorSpace::create(Document*, Vector<Value>&& parameters)
  358. {
  359. if (parameters.size() != 1)
  360. return Error { Error::Type::MalformedPDF, "Lab color space expects one parameter" };
  361. auto color_space = adopt_ref(*new LabColorSpace());
  362. // FIXME: Implement.
  363. return color_space;
  364. }
  365. PDFErrorOr<Color> LabColorSpace::color(ReadonlySpan<Value>) const
  366. {
  367. return Error::rendering_unsupported_error("Lab color spaces not yet implemented");
  368. }
  369. Vector<float> LabColorSpace::default_decode() const
  370. {
  371. return { 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f };
  372. }
  373. PDFErrorOr<NonnullRefPtr<SeparationColorSpace>> SeparationColorSpace::create(Document*, Vector<Value>&&)
  374. {
  375. auto color_space = adopt_ref(*new SeparationColorSpace());
  376. // FIXME: Implement.
  377. return color_space;
  378. }
  379. PDFErrorOr<Color> SeparationColorSpace::color(ReadonlySpan<Value>) const
  380. {
  381. return Error::rendering_unsupported_error("Separation color spaces not yet implemented");
  382. }
  383. Vector<float> SeparationColorSpace::default_decode() const
  384. {
  385. return { 0.0f, 1.0f };
  386. }
  387. }