ColorSpace.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. /*
  2. * Copyright (c) 2021-2022, Matthew Olsson <mattco@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibPDF/ColorSpace.h>
  7. #include <LibPDF/CommonNames.h>
  8. #include <LibPDF/Document.h>
  9. #include <LibPDF/ObjectDerivatives.h>
  10. namespace PDF {
  11. #define ENUMERATE(name, ever_needs_parameters) \
  12. ColorSpaceFamily ColorSpaceFamily::name { #name, ever_needs_parameters };
  13. ENUMERATE_COLOR_SPACE_FAMILIES(ENUMERATE);
  14. #undef ENUMERATE
  15. PDFErrorOr<ColorSpaceFamily> ColorSpaceFamily::get(DeprecatedFlyString const& family_name)
  16. {
  17. #define ENUMERATE(f_name, ever_needs_parameters) \
  18. if (family_name == f_name.name()) { \
  19. return ColorSpaceFamily::f_name; \
  20. }
  21. ENUMERATE_COLOR_SPACE_FAMILIES(ENUMERATE)
  22. #undef ENUMERATE
  23. return Error(Error::Type::MalformedPDF, DeprecatedString::formatted("Unknown ColorSpace family {}", family_name));
  24. }
  25. PDFErrorOr<NonnullRefPtr<ColorSpace>> ColorSpace::create(DeprecatedFlyString const& name)
  26. {
  27. // Simple color spaces with no parameters, which can be specified directly
  28. if (name == CommonNames::DeviceGray)
  29. return DeviceGrayColorSpace::the();
  30. if (name == CommonNames::DeviceRGB)
  31. return DeviceRGBColorSpace::the();
  32. if (name == CommonNames::DeviceCMYK)
  33. return DeviceCMYKColorSpace::the();
  34. if (name == CommonNames::Pattern)
  35. TODO();
  36. VERIFY_NOT_REACHED();
  37. }
  38. PDFErrorOr<NonnullRefPtr<ColorSpace>> ColorSpace::create(Document* document, NonnullRefPtr<ArrayObject> color_space_array)
  39. {
  40. auto color_space_name = TRY(color_space_array->get_name_at(document, 0))->name();
  41. Vector<Value> parameters;
  42. parameters.ensure_capacity(color_space_array->size() - 1);
  43. for (size_t i = 1; i < color_space_array->size(); i++)
  44. parameters.unchecked_append(color_space_array->at(i));
  45. if (color_space_name == CommonNames::CalRGB)
  46. return TRY(CalRGBColorSpace::create(document, move(parameters)));
  47. if (color_space_name == CommonNames::ICCBased)
  48. return TRY(ICCBasedColorSpace::create(document, move(parameters)));
  49. dbgln("Unknown color space: {}", color_space_name);
  50. TODO();
  51. }
  52. NonnullRefPtr<DeviceGrayColorSpace> DeviceGrayColorSpace::the()
  53. {
  54. static auto instance = adopt_ref(*new DeviceGrayColorSpace());
  55. return instance;
  56. }
  57. Color DeviceGrayColorSpace::color(Vector<Value> const& arguments) const
  58. {
  59. VERIFY(arguments.size() == 1);
  60. auto gray = static_cast<u8>(arguments[0].to_float() * 255.0f);
  61. return Color(gray, gray, gray);
  62. }
  63. Vector<float> DeviceGrayColorSpace::default_decode() const
  64. {
  65. return { 0.0f, 1.0f };
  66. }
  67. NonnullRefPtr<DeviceRGBColorSpace> DeviceRGBColorSpace::the()
  68. {
  69. static auto instance = adopt_ref(*new DeviceRGBColorSpace());
  70. return instance;
  71. }
  72. Color DeviceRGBColorSpace::color(Vector<Value> const& arguments) const
  73. {
  74. VERIFY(arguments.size() == 3);
  75. auto r = static_cast<u8>(arguments[0].to_float() * 255.0f);
  76. auto g = static_cast<u8>(arguments[1].to_float() * 255.0f);
  77. auto b = static_cast<u8>(arguments[2].to_float() * 255.0f);
  78. return Color(r, g, b);
  79. }
  80. Vector<float> DeviceRGBColorSpace::default_decode() const
  81. {
  82. return { 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f };
  83. }
  84. NonnullRefPtr<DeviceCMYKColorSpace> DeviceCMYKColorSpace::the()
  85. {
  86. static auto instance = adopt_ref(*new DeviceCMYKColorSpace());
  87. return instance;
  88. }
  89. Color DeviceCMYKColorSpace::color(Vector<Value> const& arguments) const
  90. {
  91. VERIFY(arguments.size() == 4);
  92. auto c = arguments[0].to_float();
  93. auto m = arguments[1].to_float();
  94. auto y = arguments[2].to_float();
  95. auto k = arguments[3].to_float();
  96. return Color::from_cmyk(c, m, y, k);
  97. }
  98. Vector<float> DeviceCMYKColorSpace::default_decode() const
  99. {
  100. return { 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f };
  101. }
  102. PDFErrorOr<NonnullRefPtr<CalRGBColorSpace>> CalRGBColorSpace::create(Document* document, Vector<Value>&& parameters)
  103. {
  104. if (parameters.size() != 1)
  105. return Error { Error::Type::MalformedPDF, "RGB color space expects one parameter" };
  106. auto param = parameters[0];
  107. if (!param.has<NonnullRefPtr<Object>>() || !param.get<NonnullRefPtr<Object>>()->is<DictObject>())
  108. return Error { Error::Type::MalformedPDF, "RGB color space expects a dict parameter" };
  109. auto dict = param.get<NonnullRefPtr<Object>>()->cast<DictObject>();
  110. if (!dict->contains(CommonNames::WhitePoint))
  111. return Error { Error::Type::MalformedPDF, "RGB color space expects a Whitepoint key" };
  112. auto white_point_array = TRY(dict->get_array(document, CommonNames::WhitePoint));
  113. if (white_point_array->size() != 3)
  114. return Error { Error::Type::MalformedPDF, "RGB color space expects 3 Whitepoint parameters" };
  115. auto color_space = adopt_ref(*new CalRGBColorSpace());
  116. color_space->m_whitepoint[0] = white_point_array->at(0).to_float();
  117. color_space->m_whitepoint[1] = white_point_array->at(1).to_float();
  118. color_space->m_whitepoint[2] = white_point_array->at(2).to_float();
  119. if (color_space->m_whitepoint[1] != 1.0f)
  120. return Error { Error::Type::MalformedPDF, "RGB color space expects 2nd Whitepoint to be 1.0" };
  121. if (dict->contains(CommonNames::BlackPoint)) {
  122. auto black_point_array = TRY(dict->get_array(document, CommonNames::BlackPoint));
  123. if (black_point_array->size() == 3) {
  124. color_space->m_blackpoint[0] = black_point_array->at(0).to_float();
  125. color_space->m_blackpoint[1] = black_point_array->at(1).to_float();
  126. color_space->m_blackpoint[2] = black_point_array->at(2).to_float();
  127. }
  128. }
  129. if (dict->contains(CommonNames::Gamma)) {
  130. auto gamma_array = TRY(dict->get_array(document, CommonNames::Gamma));
  131. if (gamma_array->size() == 3) {
  132. color_space->m_gamma[0] = gamma_array->at(0).to_float();
  133. color_space->m_gamma[1] = gamma_array->at(1).to_float();
  134. color_space->m_gamma[2] = gamma_array->at(2).to_float();
  135. }
  136. }
  137. if (dict->contains(CommonNames::Matrix)) {
  138. auto matrix_array = TRY(dict->get_array(document, CommonNames::Matrix));
  139. if (matrix_array->size() == 3) {
  140. color_space->m_matrix[0] = matrix_array->at(0).to_float();
  141. color_space->m_matrix[1] = matrix_array->at(1).to_float();
  142. color_space->m_matrix[2] = matrix_array->at(2).to_float();
  143. color_space->m_matrix[3] = matrix_array->at(3).to_float();
  144. color_space->m_matrix[4] = matrix_array->at(4).to_float();
  145. color_space->m_matrix[5] = matrix_array->at(5).to_float();
  146. color_space->m_matrix[6] = matrix_array->at(6).to_float();
  147. color_space->m_matrix[7] = matrix_array->at(7).to_float();
  148. color_space->m_matrix[8] = matrix_array->at(8).to_float();
  149. }
  150. }
  151. return color_space;
  152. }
  153. constexpr Array<float, 3> matrix_multiply(Array<float, 9> a, Array<float, 3> b)
  154. {
  155. return Array<float, 3> {
  156. a[0] * b[0] + a[1] * b[1] + a[2] * b[2],
  157. a[3] * b[0] + a[4] * b[1] + a[5] * b[2],
  158. a[6] * b[0] + a[7] * b[1] + a[8] * b[2]
  159. };
  160. }
  161. // Converts to a flat XYZ space with white point = (1, 1, 1)
  162. // Step 2 of https://www.adobe.com/content/dam/acom/en/devnet/photoshop/sdk/AdobeBPC.pdf
  163. constexpr Array<float, 3> flatten_and_normalize_whitepoint(Array<float, 3> whitepoint, Array<float, 3> xyz)
  164. {
  165. VERIFY(whitepoint[1] == 1.0f);
  166. return {
  167. (1.0f / whitepoint[0]) * xyz[0],
  168. xyz[1],
  169. (1.0f / whitepoint[2]) * xyz[2],
  170. };
  171. }
  172. constexpr float decode_l(float input)
  173. {
  174. constexpr float decode_l_scaling_constant = 0.00110705646f; // (((8 + 16) / 116) ^ 3) / 8
  175. if (input < 0.0f)
  176. return -decode_l(-input);
  177. if (input >= 0.0f && input <= 8.0f)
  178. return input * decode_l_scaling_constant;
  179. return powf(((input + 16.0f) / 116.0f), 3.0f);
  180. }
  181. constexpr Array<float, 3> scale_black_point(Array<float, 3> blackpoint, Array<float, 3> xyz)
  182. {
  183. auto y_dst = decode_l(0); // DestinationBlackPoint is just [0, 0, 0]
  184. auto y_src = decode_l(blackpoint[0]);
  185. auto scale = (1 - y_dst) / (1 - y_src);
  186. auto offset = 1 - scale;
  187. return {
  188. xyz[0] * scale + offset,
  189. xyz[1] * scale + offset,
  190. xyz[2] * scale + offset,
  191. };
  192. }
  193. // https://en.wikipedia.org/wiki/Illuminant_D65
  194. constexpr Array<float, 3> convert_to_d65(Array<float, 3> whitepoint, Array<float, 3> xyz)
  195. {
  196. constexpr float d65x = 0.95047f;
  197. constexpr float d65y = 1.0f;
  198. constexpr float d65z = 1.08883f;
  199. return {
  200. (xyz[0] * d65x) / whitepoint[0],
  201. (xyz[1] * d65y) / whitepoint[1],
  202. (xyz[2] * d65z) / whitepoint[2],
  203. };
  204. }
  205. // https://en.wikipedia.org/wiki/SRGB
  206. constexpr Array<float, 3> convert_to_srgb(Array<float, 3> xyz)
  207. {
  208. // See the sRGB D65 [M]^-1 matrix in the following page
  209. // http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
  210. constexpr Array<float, 9> conversion_matrix = {
  211. 3.2404542,
  212. -1.5371385,
  213. -0.4985314,
  214. -0.969266,
  215. 1.8760108,
  216. 0.0415560,
  217. 0.0556434,
  218. -0.2040259,
  219. 1.0572252,
  220. };
  221. return matrix_multiply(conversion_matrix, xyz);
  222. }
  223. Color CalRGBColorSpace::color(Vector<Value> const& arguments) const
  224. {
  225. VERIFY(arguments.size() == 3);
  226. auto a = clamp(arguments[0].to_float(), 0.0f, 1.0f);
  227. auto b = clamp(arguments[1].to_float(), 0.0f, 1.0f);
  228. auto c = clamp(arguments[2].to_float(), 0.0f, 1.0f);
  229. auto agr = powf(a, m_gamma[0]);
  230. auto bgg = powf(b, m_gamma[1]);
  231. auto cgb = powf(c, m_gamma[2]);
  232. auto x = m_matrix[0] * agr + m_matrix[3] * bgg + m_matrix[6] * cgb;
  233. auto y = m_matrix[1] * agr + m_matrix[4] * bgg + m_matrix[7] * cgb;
  234. auto z = m_matrix[2] * agr + m_matrix[5] * bgg + m_matrix[8] * cgb;
  235. auto flattened_xyz = flatten_and_normalize_whitepoint(m_whitepoint, { x, y, z });
  236. auto scaled_black_point_xyz = scale_black_point(m_blackpoint, flattened_xyz);
  237. auto d65_normalized = convert_to_d65(m_whitepoint, scaled_black_point_xyz);
  238. auto srgb = convert_to_srgb(d65_normalized);
  239. auto red = static_cast<u8>(srgb[0] * 255.0f);
  240. auto green = static_cast<u8>(srgb[1] * 255.0f);
  241. auto blue = static_cast<u8>(srgb[2] * 255.0f);
  242. return Color(red, green, blue);
  243. }
  244. Vector<float> CalRGBColorSpace::default_decode() const
  245. {
  246. return { 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f };
  247. }
  248. PDFErrorOr<NonnullRefPtr<ColorSpace>> ICCBasedColorSpace::create(Document* document, Vector<Value>&& parameters)
  249. {
  250. if (parameters.is_empty())
  251. return Error { Error::Type::MalformedPDF, "ICCBased color space expected one parameter" };
  252. auto param = TRY(document->resolve(parameters[0]));
  253. if (!param.has<NonnullRefPtr<Object>>() || !param.get<NonnullRefPtr<Object>>()->is<StreamObject>())
  254. return Error { Error::Type::MalformedPDF, "ICCBased color space expects a stream parameter" };
  255. auto dict = param.get<NonnullRefPtr<Object>>()->cast<StreamObject>()->dict();
  256. DeprecatedFlyString name;
  257. if (!dict->contains(CommonNames::Alternate)) {
  258. auto number_of_components = dict->get_value(CommonNames::N).to_int();
  259. if (number_of_components == 1)
  260. name = CommonNames::DeviceGray;
  261. else if (number_of_components == 3)
  262. name = CommonNames::DeviceRGB;
  263. else if (number_of_components == 4)
  264. name = CommonNames::DeviceCMYK;
  265. else
  266. VERIFY_NOT_REACHED();
  267. return ColorSpace::create(name);
  268. }
  269. auto alternate_color_space_object = MUST(dict->get_object(document, CommonNames::Alternate));
  270. if (alternate_color_space_object->is<NameObject>()) {
  271. return ColorSpace::create(alternate_color_space_object->cast<NameObject>()->name());
  272. }
  273. dbgln("Alternate color spaces in array format not supported yet ");
  274. TODO();
  275. }
  276. Color ICCBasedColorSpace::color(Vector<Value> const&) const
  277. {
  278. VERIFY_NOT_REACHED();
  279. }
  280. Vector<float> ICCBasedColorSpace::default_decode() const
  281. {
  282. VERIFY_NOT_REACHED();
  283. }
  284. }