TIFFGenerator.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2023, Lucas Chollet <lucas.chollet@serenityos.org>
  3. #
  4. # SPDX-License-Identifier: BSD-2-Clause
  5. import argparse
  6. import re
  7. from enum import Enum
  8. from collections import namedtuple
  9. from pathlib import Path
  10. from typing import List, Type
  11. class EnumWithExportName(Enum):
  12. @classmethod
  13. def export_name(cls) -> str:
  14. return cls.__name__
  15. class TIFFType(EnumWithExportName):
  16. @classmethod
  17. def export_name(cls) -> str:
  18. return "Type"
  19. Byte = 1
  20. ASCII = 2
  21. UnsignedShort = 3
  22. UnsignedLong = 4
  23. UnsignedRational = 5
  24. Undefined = 7
  25. SignedLong = 9
  26. SignedRational = 10
  27. Float = 11
  28. Double = 12
  29. UTF8 = 129
  30. class Predictor(EnumWithExportName):
  31. NoPrediction = 1
  32. HorizontalDifferencing = 2
  33. class Compression(EnumWithExportName):
  34. NoCompression = 1
  35. CCITT = 2
  36. Group3Fax = 3
  37. Group4Fax = 4
  38. LZW = 5
  39. JPEG = 6
  40. AdobeDeflate = 8
  41. PackBits = 32773
  42. class PhotometricInterpretation(EnumWithExportName):
  43. WhiteIsZero = 0
  44. BlackIsZero = 1
  45. RGB = 2
  46. RGBPalette = 3
  47. TransparencyMask = 4
  48. CMYK = 5
  49. YCbCr = 6
  50. CIELab = 8
  51. class Orientation(EnumWithExportName):
  52. Default = 1
  53. FlipHorizontally = 2
  54. Rotate180 = 3
  55. FlipVertically = 4
  56. Rotate90ClockwiseThenFlipHorizontally = 5
  57. Rotate90Clockwise = 6
  58. FlipHorizontallyThenRotate90Clockwise = 7
  59. Rotate90CounterClockwise = 8
  60. class PlanarConfiguration(EnumWithExportName):
  61. Chunky = 1
  62. Planar = 2
  63. class ResolutionUnit(EnumWithExportName):
  64. NoAbsolute = 1
  65. Inch = 2
  66. Centimeter = 3
  67. class SampleFormat(EnumWithExportName):
  68. Unsigned = 1
  69. Signed = 2
  70. Float = 3
  71. Undefined = 4
  72. class ExtraSample(EnumWithExportName):
  73. Unspecified = 0
  74. AssociatedAlpha = 1
  75. UnassociatedAlpha = 2
  76. tag_fields = ['id', 'types', 'counts', 'default', 'name', 'associated_enum', 'is_required']
  77. Tag = namedtuple(
  78. 'Tag',
  79. field_names=tag_fields,
  80. defaults=(None,) * len(tag_fields)
  81. )
  82. # FIXME: Some tag have only a few allowed values, we should ensure that
  83. known_tags: List[Tag] = [
  84. Tag('256', [TIFFType.UnsignedShort, TIFFType.UnsignedLong], [1], None, "ImageWidth", is_required=True),
  85. Tag('257', [TIFFType.UnsignedShort, TIFFType.UnsignedLong], [1], None, "ImageHeight", is_required=True),
  86. Tag('258', [TIFFType.UnsignedShort], [], None, "BitsPerSample", is_required=True),
  87. Tag('259', [TIFFType.UnsignedShort], [1], None, "Compression", Compression, is_required=True),
  88. Tag('262', [TIFFType.UnsignedShort], [1], None, "PhotometricInterpretation",
  89. PhotometricInterpretation, is_required=True),
  90. Tag('273', [TIFFType.UnsignedShort, TIFFType.UnsignedLong], [], None, "StripOffsets", is_required=True),
  91. Tag('274', [TIFFType.UnsignedShort], [1], Orientation.Default, "Orientation", Orientation),
  92. Tag('277', [TIFFType.UnsignedShort], [1], None, "SamplesPerPixel", is_required=True),
  93. Tag('278', [TIFFType.UnsignedShort, TIFFType.UnsignedLong], [1], None, "RowsPerStrip", is_required=True),
  94. Tag('279', [TIFFType.UnsignedShort, TIFFType.UnsignedLong], [], None, "StripByteCounts", is_required=True),
  95. Tag('282', [TIFFType.UnsignedRational], [1], None, "XResolution"),
  96. Tag('283', [TIFFType.UnsignedRational], [1], None, "YResolution"),
  97. Tag('284', [TIFFType.UnsignedShort], [1], PlanarConfiguration.Chunky, "PlanarConfiguration", PlanarConfiguration),
  98. Tag('285', [TIFFType.ASCII], [], None, "PageName"),
  99. Tag('296', [TIFFType.UnsignedShort], [1], ResolutionUnit.Inch, "ResolutionUnit", ResolutionUnit),
  100. Tag('339', [TIFFType.UnsignedShort], [], SampleFormat.Unsigned, "SampleFormat", SampleFormat),
  101. Tag('317', [TIFFType.UnsignedShort], [1], Predictor.NoPrediction, "Predictor", Predictor),
  102. Tag('320', [TIFFType.UnsignedShort], [], None, "ColorMap"),
  103. Tag('338', [TIFFType.UnsignedShort], [], None, "ExtraSamples", ExtraSample),
  104. Tag('34675', [TIFFType.Undefined], [], None, "ICCProfile"),
  105. ]
  106. HANDLE_TAG_SIGNATURE_TEMPLATE = ("ErrorOr<void> {namespace}handle_tag(Metadata& metadata, u16 tag,"
  107. " {namespace}Type type, u32 count, Vector<{namespace}Value>&& value)")
  108. HANDLE_TAG_SIGNATURE = HANDLE_TAG_SIGNATURE_TEMPLATE.format(namespace="")
  109. HANDLE_TAG_SIGNATURE_TIFF_NAMESPACE = HANDLE_TAG_SIGNATURE_TEMPLATE.format(namespace="TIFF::")
  110. ENSURE_BASELINE_TAG_PRESENCE = "ErrorOr<void> ensure_baseline_tags_presence(Metadata const& metadata)"
  111. LICENSE = R"""/*
  112. * Copyright (c) 2023, Lucas Chollet <lucas.chollet@serenityos.org>
  113. *
  114. * SPDX-License-Identifier: BSD-2-Clause
  115. */"""
  116. def export_enum_to_cpp(e: Type[EnumWithExportName]) -> str:
  117. output = f'enum class {e.export_name()} {{\n'
  118. for entry in e:
  119. output += f' {entry.name} = {entry.value},\n'
  120. output += "};\n"
  121. return output
  122. def export_enum_to_string_converter(enums: List[Type[EnumWithExportName]]) -> str:
  123. stringifier_internals = []
  124. for e in enums:
  125. single_stringifier = fR""" if constexpr (IsSame<E, {e.export_name()}>) {{
  126. switch (value) {{
  127. default:
  128. return "Invalid value for {e.export_name()}"sv;"""
  129. for entry in e:
  130. single_stringifier += fR"""
  131. case {e.export_name()}::{entry.name}:
  132. return "{entry.name}"sv;"""
  133. single_stringifier += R"""
  134. }
  135. }"""
  136. stringifier_internals.append(single_stringifier)
  137. stringifier_internals_str = '\n'.join(stringifier_internals)
  138. out = fR"""template<Enum E>
  139. StringView name_for_enum_tag_value(E value) {{
  140. {stringifier_internals_str}
  141. VERIFY_NOT_REACHED();
  142. }}"""
  143. return out
  144. def export_tag_related_enums(tags: List[Tag]) -> str:
  145. exported_enums = []
  146. for tag in tags:
  147. if tag.associated_enum:
  148. exported_enums.append(export_enum_to_cpp(tag.associated_enum))
  149. return '\n'.join(exported_enums)
  150. def promote_type(t: TIFFType) -> TIFFType:
  151. if t == TIFFType.UnsignedShort:
  152. return TIFFType.UnsignedLong
  153. return t
  154. def tiff_type_to_cpp(t: TIFFType, with_promotion: bool = True) -> str:
  155. # To simplify the code generator and the Metadata class API, all u16 are promoted to u32
  156. # Note that the Value<> type doesn't include u16 for this reason
  157. if with_promotion:
  158. t = promote_type(t)
  159. if t in [TIFFType.ASCII, TIFFType.UTF8]:
  160. return 'String'
  161. if t == TIFFType.Undefined:
  162. return 'ByteBuffer'
  163. if t == TIFFType.UnsignedShort:
  164. return 'u16'
  165. if t == TIFFType.UnsignedLong:
  166. return 'u32'
  167. if t == TIFFType.UnsignedRational:
  168. return 'TIFF::Rational<u32>'
  169. raise RuntimeError(f'Type "{t}" not recognized, please update tiff_type_to_read_only_cpp()')
  170. def is_container(t: TIFFType) -> bool:
  171. """
  172. Some TIFF types are defined on the unit scale but are intended to be used within a collection.
  173. An example of that are ASCII strings defined as N * byte. Let's intercept that and generate
  174. a nice API instead of Vector<u8>.
  175. """
  176. return t in [TIFFType.ASCII, TIFFType.Byte, TIFFType.Undefined, TIFFType.UTF8]
  177. def export_promoter() -> str:
  178. output = R"""template<typename T>
  179. struct TypePromoter {
  180. using Type = T;
  181. };
  182. """
  183. specialization_template = R"""template<>
  184. struct TypePromoter<{}> {{
  185. using Type = {};
  186. }};
  187. """
  188. for t in TIFFType:
  189. if promote_type(t) != t:
  190. output += specialization_template.format(tiff_type_to_cpp(t, with_promotion=False), tiff_type_to_cpp(t))
  191. return output
  192. def retrieve_biggest_type(types: List[TIFFType]) -> TIFFType:
  193. return TIFFType(max([t.value for t in types]))
  194. def pascal_case_to_snake_case(name: str) -> str:
  195. name = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
  196. return re.sub('([a-z0-9])([A-Z])', r'\1_\2', name).lower()
  197. def generate_getter(tag: Tag) -> str:
  198. biggest_type = retrieve_biggest_type(tag.types)
  199. variant_inner_type = tiff_type_to_cpp(biggest_type)
  200. extracted_value_template = f"(*possible_value)[{{}}].get<{variant_inner_type}>()"
  201. tag_final_type = variant_inner_type
  202. if tag.associated_enum:
  203. tag_final_type = f"TIFF::{tag.associated_enum.__name__}"
  204. extracted_value_template = f"static_cast<{tag_final_type}>({extracted_value_template})"
  205. if len(tag.counts) == 1 and tag.counts[0] == 1 or is_container(biggest_type):
  206. return_type = tag_final_type
  207. if is_container(biggest_type):
  208. return_type += ' const&'
  209. unpacked_if_needed = f"return {extracted_value_template.format(0)};"
  210. else:
  211. if len(tag.counts) == 1:
  212. container_type = f'Array<{tag_final_type}, {tag.counts[0]}>'
  213. container_initialization = f'{container_type} tmp{{}};'
  214. else:
  215. container_type = f'Vector<{tag_final_type}>'
  216. container_initialization = fR"""{container_type} tmp{{}};
  217. auto maybe_failure = tmp.try_resize(possible_value->size());
  218. if (maybe_failure.is_error())
  219. return OptionalNone {{}};
  220. """
  221. return_type = container_type
  222. unpacked_if_needed = fR"""
  223. {container_initialization}
  224. for (u32 i = 0; i < possible_value->size(); ++i)
  225. tmp[i] = {extracted_value_template.format('i')};
  226. return tmp;"""
  227. signature = fR" Optional<{return_type}> {pascal_case_to_snake_case(tag.name)}() const"
  228. body = fR"""
  229. {{
  230. auto const& possible_value = m_data.get("{tag.name}"sv);
  231. if (!possible_value.has_value())
  232. return OptionalNone {{}};
  233. {unpacked_if_needed}
  234. }}
  235. """
  236. return signature + body
  237. def generate_metadata_class(tags: List[Tag]) -> str:
  238. getters = '\n'.join([generate_getter(tag) for tag in tags])
  239. output = fR"""class Metadata {{
  240. public:
  241. {getters}
  242. private:
  243. friend {HANDLE_TAG_SIGNATURE_TIFF_NAMESPACE};
  244. void add_entry(StringView key, Vector<TIFF::Value>&& value) {{
  245. m_data.set(key, move(value));
  246. }}
  247. HashMap<StringView, Vector<TIFF::Value>> m_data;
  248. }};
  249. """
  250. return output
  251. def generate_metadata_file(tags: List[Tag]) -> str:
  252. output = fR"""{LICENSE}
  253. #pragma once
  254. #include <AK/HashMap.h>
  255. #include <AK/Variant.h>
  256. #include <AK/Vector.h>
  257. #include <LibGfx/Size.h>
  258. namespace Gfx {{
  259. class Metadata;
  260. namespace TIFF {{
  261. {export_enum_to_cpp(TIFFType)}
  262. template<OneOf<u32, i32> x32>
  263. struct Rational {{
  264. using Type = x32;
  265. x32 numerator;
  266. x32 denominator;
  267. }};
  268. {export_promoter()}
  269. // Note that u16 is not include on purpose
  270. using Value = Variant<ByteBuffer, String, u32, Rational<u32>, i32, Rational<i32>>;
  271. {export_tag_related_enums(known_tags)}
  272. {export_enum_to_string_converter([tag.associated_enum for tag in known_tags if tag.associated_enum] + [TIFFType])}
  273. {HANDLE_TAG_SIGNATURE};
  274. {ENSURE_BASELINE_TAG_PRESENCE};
  275. }}
  276. {generate_metadata_class(tags)}
  277. }}
  278. template<typename T>
  279. struct AK::Formatter<Gfx::TIFF::Rational<T>> : Formatter<FormatString> {{
  280. ErrorOr<void> format(FormatBuilder& builder, Gfx::TIFF::Rational<T> value)
  281. {{
  282. return Formatter<FormatString>::format(builder, "{{}} ({{}}/{{}})"sv,
  283. static_cast<double>(value.numerator) / value.denominator, value.numerator, value.denominator);
  284. }}
  285. }};
  286. template<>
  287. struct AK::Formatter<Gfx::TIFF::Value> : Formatter<FormatString> {{
  288. ErrorOr<void> format(FormatBuilder& builder, Gfx::TIFF::Value const& value)
  289. {{
  290. String content;
  291. value.visit(
  292. [&](ByteBuffer const& buffer) {{
  293. content = MUST(String::formatted("Buffer of size: {{}}"sv, buffer.size()));
  294. }},
  295. [&](auto const& other) {{
  296. content = MUST(String::formatted("{{}}", other));
  297. }}
  298. );
  299. return Formatter<FormatString>::format(builder, "{{}}"sv, content);
  300. }}
  301. }};
  302. """
  303. return output
  304. def generate_tag_handler(tag: Tag) -> str:
  305. not_in_type_list = f"({' && '.join([f'type != Type::{t.name}' for t in tag.types])})"
  306. not_in_count_list = ''
  307. if len(tag.counts) != 0:
  308. not_in_count_list = f"|| ({' && '.join([f'count != {c}' for c in tag.counts])})"
  309. pre_condition = fR"""if ({not_in_type_list}
  310. {not_in_count_list})
  311. return Error::from_string_literal("TIFFImageDecoderPlugin: Tag {tag.name} invalid");"""
  312. check_value = ''
  313. if tag.associated_enum is not None:
  314. not_in_value_list = f"({' && '.join([f'v != {v.value}' for v in tag.associated_enum])})"
  315. check_value = fR"""
  316. for (u32 i = 0; i < value.size(); ++i) {{
  317. TRY(value[i].visit(
  318. []({tiff_type_to_cpp(tag.types[0])} const& v) -> ErrorOr<void> {{
  319. if ({not_in_value_list})
  320. return Error::from_string_literal("TIFFImageDecoderPlugin: Invalid value for tag {tag.name}");
  321. return {{}};
  322. }},
  323. [&](auto const&) -> ErrorOr<void> {{
  324. VERIFY_NOT_REACHED();
  325. }})
  326. );
  327. }}
  328. """
  329. output = fR""" case {tag.id}:
  330. // {tag.name}
  331. dbgln_if(TIFF_DEBUG, "{tag.name}({{}}): {{}}", name_for_enum_tag_value(type), format_tiff_value(tag, value));
  332. {pre_condition}
  333. {check_value}
  334. metadata.add_entry("{tag.name}"sv, move(value));
  335. break;
  336. """
  337. return output
  338. def generate_tag_handler_file(tags: List[Tag]) -> str:
  339. formatter_for_tag_with_enum = '\n'.join([fR""" case {tag.id}:
  340. return MUST(String::from_utf8(
  341. name_for_enum_tag_value(static_cast<{tag.associated_enum.export_name()}>(v.get<u32>()))));"""
  342. for tag in tags if tag.associated_enum])
  343. ensure_tag_presence = '\n'.join([fR""" if (!metadata.{pascal_case_to_snake_case(tag.name)}().has_value())
  344. return Error::from_string_literal("Unable to decode image, missing required tag {tag.name}.");
  345. """ for tag in filter(lambda tag: tag.is_required, known_tags)])
  346. output = fR"""{LICENSE}
  347. #include <AK/Debug.h>
  348. #include <AK/String.h>
  349. #include <LibGfx/ImageFormats/TIFFMetadata.h>
  350. namespace Gfx::TIFF {{
  351. static String value_formatter(u32 tag_id, Value const& v) {{
  352. switch (tag_id) {{
  353. {formatter_for_tag_with_enum}
  354. default:
  355. return MUST(String::formatted("{{}}", v));
  356. }}
  357. }}
  358. [[maybe_unused]] static String format_tiff_value(u32 tag_id, Vector<Value> const& values) {{
  359. if (values.size() == 1)
  360. return MUST(String::formatted("{{}}", value_formatter(tag_id, values[0])));
  361. StringBuilder builder;
  362. builder.append('[');
  363. for (u32 i = 0; i < values.size(); ++i) {{
  364. builder.appendff("{{}}", value_formatter(tag_id, values[i]));
  365. if (i != values.size() - 1)
  366. builder.append(", "sv);
  367. }}
  368. builder.append(']');
  369. return MUST(builder.to_string());
  370. }}
  371. {ENSURE_BASELINE_TAG_PRESENCE}
  372. {{
  373. {ensure_tag_presence}
  374. return {{}};
  375. }}
  376. {HANDLE_TAG_SIGNATURE}
  377. {{
  378. switch (tag) {{
  379. """
  380. output += '\n'.join([generate_tag_handler(t) for t in tags])
  381. output += R"""
  382. default:
  383. dbgln_if(TIFF_DEBUG, "UnknownTag({}, {}): {}",
  384. tag, name_for_enum_tag_value(type), format_tiff_value(tag, value));
  385. }
  386. return {};
  387. }
  388. }
  389. """
  390. return output
  391. def update_file(target: Path, new_content: str):
  392. should_update = True
  393. if target.exists():
  394. with target.open('r') as file:
  395. content = file.read()
  396. if content == new_content:
  397. should_update = False
  398. if should_update:
  399. with target.open('w') as file:
  400. file.write(new_content)
  401. def main():
  402. parser = argparse.ArgumentParser()
  403. parser.add_argument('-o', '--output')
  404. args = parser.parse_args()
  405. output_path = Path(args.output)
  406. update_file(output_path / 'TIFFMetadata.h', generate_metadata_file(known_tags))
  407. update_file(output_path / 'TIFFTagHandler.cpp', generate_tag_handler_file(known_tags))
  408. if __name__ == '__main__':
  409. main()