JPEGXLLoader.cpp 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185
  1. /*
  2. * Copyright (c) 2023, Lucas Chollet <lucas.chollet@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/BitStream.h>
  7. #include <AK/Endian.h>
  8. #include <AK/FixedArray.h>
  9. #include <AK/String.h>
  10. #include <LibCompress/Brotli.h>
  11. #include <LibGfx/ImageFormats/JPEGXLLoader.h>
  12. namespace Gfx {
  13. /// 4.2 - Functions
  14. static ALWAYS_INLINE i32 unpack_signed(u32 u)
  15. {
  16. if (u % 2 == 0)
  17. return static_cast<i32>(u / 2);
  18. return -static_cast<i32>((u + 1) / 2);
  19. }
  20. ///
  21. /// B.2 - Field types
  22. // This is defined as a macro in order to get lazy-evaluated parameter
  23. // Note that the lambda will capture your context by reference.
  24. #define U32(d0, d1, d2, d3) \
  25. ({ \
  26. u8 const selector = TRY(stream.read_bits(2)); \
  27. auto value = [&, selector]() -> ErrorOr<u32> { \
  28. if (selector == 0) \
  29. return (d0); \
  30. if (selector == 1) \
  31. return (d1); \
  32. if (selector == 2) \
  33. return (d2); \
  34. if (selector == 3) \
  35. return (d3); \
  36. VERIFY_NOT_REACHED(); \
  37. }(); \
  38. TRY(value); \
  39. })
  40. static ALWAYS_INLINE ErrorOr<u64> U64(LittleEndianInputBitStream& stream)
  41. {
  42. u8 const selector = TRY(stream.read_bits(2));
  43. if (selector == 0)
  44. return 0;
  45. if (selector == 1)
  46. return 1 + TRY(stream.read_bits(4));
  47. if (selector == 2)
  48. return 17 + TRY(stream.read_bits(8));
  49. VERIFY(selector == 3);
  50. u64 value = TRY(stream.read_bits(12));
  51. u8 shift = 12;
  52. while (TRY(stream.read_bits(1)) == 1) {
  53. if (shift == 60) {
  54. value += TRY(stream.read_bits(4)) << shift;
  55. break;
  56. }
  57. value += TRY(stream.read_bits(8)) << shift;
  58. shift += 8;
  59. }
  60. return value;
  61. }
  62. template<Enum E>
  63. ErrorOr<E> read_enum(LittleEndianInputBitStream& stream)
  64. {
  65. return static_cast<E>(U32(0, 1, 2 + TRY(stream.read_bits(4)), 18 + TRY(stream.read_bits(6))));
  66. }
  67. // This is not specified
  68. static ErrorOr<String> read_string(LittleEndianInputBitStream& stream)
  69. {
  70. auto const name_length = U32(0, TRY(stream.read_bits(4)), 16 + TRY(stream.read_bits(5)), 48 + TRY(stream.read_bits(10)));
  71. auto string_buffer = TRY(FixedArray<u8>::create(name_length));
  72. TRY(stream.read_until_filled(string_buffer.span()));
  73. return String::from_utf8(StringView { string_buffer.span() });
  74. }
  75. ///
  76. /// D.2 - Image dimensions
  77. struct SizeHeader {
  78. u32 height {};
  79. u32 width {};
  80. };
  81. static u32 aspect_ratio(u32 height, u32 ratio)
  82. {
  83. if (ratio == 1)
  84. return height;
  85. if (ratio == 2)
  86. return height * 12 / 10;
  87. if (ratio == 3)
  88. return height * 4 / 3;
  89. if (ratio == 4)
  90. return height * 3 / 2;
  91. if (ratio == 5)
  92. return height * 16 / 9;
  93. if (ratio == 6)
  94. return height * 5 / 4;
  95. if (ratio == 7)
  96. return height * 2 / 1;
  97. VERIFY_NOT_REACHED();
  98. }
  99. static ErrorOr<SizeHeader> read_size_header(LittleEndianInputBitStream& stream)
  100. {
  101. SizeHeader size {};
  102. auto const div8 = TRY(stream.read_bit());
  103. if (div8) {
  104. auto const h_div8 = 1 + TRY(stream.read_bits(5));
  105. size.height = 8 * h_div8;
  106. } else {
  107. size.height = U32(
  108. 1 + TRY(stream.read_bits(9)),
  109. 1 + TRY(stream.read_bits(13)),
  110. 1 + TRY(stream.read_bits(18)),
  111. 1 + TRY(stream.read_bits(30)));
  112. }
  113. auto const ratio = TRY(stream.read_bits(3));
  114. if (ratio == 0) {
  115. if (div8) {
  116. auto const w_div8 = 1 + TRY(stream.read_bits(5));
  117. size.width = 8 * w_div8;
  118. } else {
  119. size.width = U32(
  120. 1 + TRY(stream.read_bits(9)),
  121. 1 + TRY(stream.read_bits(13)),
  122. 1 + TRY(stream.read_bits(18)),
  123. 1 + TRY(stream.read_bits(30)));
  124. }
  125. } else {
  126. size.width = aspect_ratio(size.height, ratio);
  127. }
  128. return size;
  129. }
  130. ///
  131. /// D.3.5 - BitDepth
  132. struct BitDepth {
  133. u32 bits_per_sample { 8 };
  134. u8 exp_bits {};
  135. };
  136. static ErrorOr<BitDepth> read_bit_depth(LittleEndianInputBitStream& stream)
  137. {
  138. BitDepth bit_depth;
  139. bool const float_sample = TRY(stream.read_bit());
  140. if (float_sample) {
  141. bit_depth.bits_per_sample = U32(32, 16, 24, 1 + TRY(stream.read_bits(6)));
  142. bit_depth.exp_bits = 1 + TRY(stream.read_bits(4));
  143. } else {
  144. bit_depth.bits_per_sample = U32(8, 10, 12, 1 + TRY(stream.read_bits(6)));
  145. }
  146. return bit_depth;
  147. }
  148. ///
  149. /// E.2 - ColourEncoding
  150. struct ColourEncoding {
  151. enum class ColourSpace {
  152. kRGB = 0,
  153. kGrey = 1,
  154. kXYB = 2,
  155. kUnknown = 3,
  156. };
  157. enum class WhitePoint {
  158. kD65 = 1,
  159. kCustom = 2,
  160. kE = 10,
  161. kDCI = 11,
  162. };
  163. enum class Primaries {
  164. kSRGB = 1,
  165. kCustom = 2,
  166. k2100 = 3,
  167. kP3 = 11,
  168. };
  169. enum class RenderingIntent {
  170. kPerceptual = 0,
  171. kRelative = 1,
  172. kSaturation = 2,
  173. kAbsolute = 3,
  174. };
  175. struct Customxy {
  176. u32 ux {};
  177. u32 uy {};
  178. };
  179. bool want_icc = false;
  180. ColourSpace colour_space { ColourSpace::kRGB };
  181. WhitePoint white_point { WhitePoint::kD65 };
  182. Primaries primaries { Primaries::kSRGB };
  183. Customxy white {};
  184. Customxy red {};
  185. Customxy green {};
  186. Customxy blue {};
  187. RenderingIntent rendering_intent { RenderingIntent::kRelative };
  188. };
  189. [[maybe_unused]] static ErrorOr<ColourEncoding::Customxy> read_custom_xy(LittleEndianInputBitStream& stream)
  190. {
  191. ColourEncoding::Customxy custom_xy;
  192. auto const read_custom = [&stream]() -> ErrorOr<u32> {
  193. return U32(
  194. TRY(stream.read_bits(19)),
  195. 524288 + TRY(stream.read_bits(19)),
  196. 1048576 + TRY(stream.read_bits(20)),
  197. 2097152 + TRY(stream.read_bits(21)));
  198. };
  199. custom_xy.ux = TRY(read_custom());
  200. custom_xy.uy = TRY(read_custom());
  201. return custom_xy;
  202. }
  203. static ErrorOr<ColourEncoding> read_colour_encoding(LittleEndianInputBitStream& stream)
  204. {
  205. ColourEncoding colour_encoding;
  206. bool const all_default = TRY(stream.read_bit());
  207. if (!all_default) {
  208. TODO();
  209. }
  210. return colour_encoding;
  211. }
  212. ///
  213. /// B.3 - Extensions
  214. struct Extensions {
  215. u64 extensions {};
  216. };
  217. static ErrorOr<Extensions> read_extensions(LittleEndianInputBitStream& stream)
  218. {
  219. Extensions extensions;
  220. extensions.extensions = TRY(U64(stream));
  221. if (extensions.extensions != 0)
  222. TODO();
  223. return extensions;
  224. }
  225. ///
  226. /// K.2 - Non-separable upsampling
  227. Array s_d_up2 {
  228. -0.01716200, -0.03452303, -0.04022174, -0.02921014, -0.00624645,
  229. 0.14111091, 0.28896755, 0.00278718, -0.01610267, 0.56661550,
  230. 0.03777607, -0.01986694, -0.03144731, -0.01185068, -0.00213539
  231. };
  232. Array s_d_up4 = {
  233. -0.02419067, -0.03491987, -0.03693351, -0.03094285, -0.00529785,
  234. -0.01663432, -0.03556863, -0.03888905, -0.03516850, -0.00989469,
  235. 0.23651958, 0.33392945, -0.01073543, -0.01313181, -0.03556694,
  236. 0.13048175, 0.40103025, 0.03951150, -0.02077584, 0.46914198,
  237. -0.00209270, -0.01484589, -0.04064806, 0.18942530, 0.56279892,
  238. 0.06674400, -0.02335494, -0.03551682, -0.00754830, -0.02267919,
  239. -0.02363578, 0.00315804, -0.03399098, -0.01359519, -0.00091653,
  240. -0.00335467, -0.01163294, -0.01610294, -0.00974088, -0.00191622,
  241. -0.01095446, -0.03198464, -0.04455121, -0.02799790, -0.00645912,
  242. 0.06390599, 0.22963888, 0.00630981, -0.01897349, 0.67537268,
  243. 0.08483369, -0.02534994, -0.02205197, -0.01667999, -0.00384443
  244. };
  245. Array s_d_up8 {
  246. -0.02928613, -0.03706353, -0.03783812, -0.03324558, -0.00447632, -0.02519406, -0.03752601, -0.03901508, -0.03663285, -0.00646649,
  247. -0.02066407, -0.03838633, -0.04002101, -0.03900035, -0.00901973, -0.01626393, -0.03954148, -0.04046620, -0.03979621, -0.01224485,
  248. 0.29895328, 0.35757708, -0.02447552, -0.01081748, -0.04314594, 0.23903219, 0.41119301, -0.00573046, -0.01450239, -0.04246845,
  249. 0.17567618, 0.45220643, 0.02287757, -0.01936783, -0.03583255, 0.11572472, 0.47416733, 0.06284440, -0.02685066, 0.42720050,
  250. -0.02248939, -0.01155273, -0.04562755, 0.28689496, 0.49093869, -0.00007891, -0.01545926, -0.04562659, 0.21238920, 0.53980934,
  251. 0.03369474, -0.02070211, -0.03866988, 0.14229550, 0.56593398, 0.08045181, -0.02888298, -0.03680918, -0.00542229, -0.02920477,
  252. -0.02788574, -0.02118180, -0.03942402, -0.00775547, -0.02433614, -0.03193943, -0.02030828, -0.04044014, -0.01074016, -0.01930822,
  253. -0.03620399, -0.01974125, -0.03919545, -0.01456093, -0.00045072, -0.00360110, -0.01020207, -0.01231907, -0.00638988, -0.00071592,
  254. -0.00279122, -0.00957115, -0.01288327, -0.00730937, -0.00107783, -0.00210156, -0.00890705, -0.01317668, -0.00813895, -0.00153491,
  255. -0.02128481, -0.04173044, -0.04831487, -0.03293190, -0.00525260, -0.01720322, -0.04052736, -0.05045706, -0.03607317, -0.00738030,
  256. -0.01341764, -0.03965629, -0.05151616, -0.03814886, -0.01005819, 0.18968273, 0.33063684, -0.01300105, -0.01372950, -0.04017465,
  257. 0.13727832, 0.36402234, 0.01027890, -0.01832107, -0.03365072, 0.08734506, 0.38194295, 0.04338228, -0.02525993, 0.56408126,
  258. 0.00458352, -0.01648227, -0.04887868, 0.24585519, 0.62026135, 0.04314807, -0.02213737, -0.04158014, 0.16637289, 0.65027023,
  259. 0.09621636, -0.03101388, -0.04082742, -0.00904519, -0.02790922, -0.02117818, 0.00798662, -0.03995711, -0.01243427, -0.02231705,
  260. -0.02946266, 0.00992055, -0.03600283, -0.01684920, -0.00111684, -0.00411204, -0.01297130, -0.01723725, -0.01022545, -0.00165306,
  261. -0.00313110, -0.01218016, -0.01763266, -0.01125620, -0.00231663, -0.01374149, -0.03797620, -0.05142937, -0.03117307, -0.00581914,
  262. -0.01064003, -0.03608089, -0.05272168, -0.03375670, -0.00795586, 0.09628104, 0.27129991, -0.00353779, -0.01734151, -0.03153981,
  263. 0.05686230, 0.28500998, 0.02230594, -0.02374955, 0.68214326, 0.05018048, -0.02320852, -0.04383616, 0.18459474, 0.71517975,
  264. 0.10805613, -0.03263677, -0.03637639, -0.01394373, -0.02511203, -0.01728636, 0.05407331, -0.02867568, -0.01893131, -0.00240854,
  265. -0.00446511, -0.01636187, -0.02377053, -0.01522848, -0.00333334, -0.00819975, -0.02964169, -0.04499287, -0.02745350, -0.00612408,
  266. 0.02727416, 0.19446600, 0.00159832, -0.02232473, 0.74982506, 0.11452620, -0.03348048, -0.01605681, -0.02070339, -0.00458223
  267. };
  268. ///
  269. /// D.3 - Image metadata
  270. struct PreviewHeader {
  271. };
  272. struct AnimationHeader {
  273. };
  274. struct ExtraChannelInfo {
  275. enum class ExtraChannelType {
  276. kAlpha = 0,
  277. kDepth = 1,
  278. kSpotColour = 2,
  279. kSelectionMask = 3,
  280. kBlack = 4,
  281. kCFA = 5,
  282. kThermal = 6,
  283. kNonOptional = 15,
  284. kOptional = 16,
  285. };
  286. bool d_alpha { true };
  287. ExtraChannelType type { ExtraChannelType::kAlpha };
  288. BitDepth bit_depth {};
  289. u32 dim_shift {};
  290. String name;
  291. bool alpha_associated { false };
  292. };
  293. static ErrorOr<ExtraChannelInfo> read_extra_channel_info(LittleEndianInputBitStream& stream)
  294. {
  295. ExtraChannelInfo extra_channel_info;
  296. extra_channel_info.d_alpha = TRY(stream.read_bit());
  297. if (!extra_channel_info.d_alpha) {
  298. extra_channel_info.type = TRY(read_enum<ExtraChannelInfo::ExtraChannelType>(stream));
  299. extra_channel_info.bit_depth = TRY(read_bit_depth(stream));
  300. extra_channel_info.dim_shift = U32(0, 3, 4, 1 + TRY(stream.read_bits(3)));
  301. extra_channel_info.name = TRY(read_string(stream));
  302. if (extra_channel_info.type == ExtraChannelInfo::ExtraChannelType::kAlpha)
  303. extra_channel_info.alpha_associated = TRY(stream.read_bit());
  304. }
  305. if (extra_channel_info.type != ExtraChannelInfo::ExtraChannelType::kAlpha) {
  306. TODO();
  307. }
  308. return extra_channel_info;
  309. }
  310. struct ToneMapping {
  311. float intensity_target { 255 };
  312. float min_nits { 0 };
  313. bool relative_to_max_display { false };
  314. float linear_below { 0 };
  315. };
  316. static ErrorOr<ToneMapping> read_tone_mapping(LittleEndianInputBitStream& stream)
  317. {
  318. ToneMapping tone_mapping;
  319. bool const all_default = TRY(stream.read_bit());
  320. if (!all_default) {
  321. TODO();
  322. }
  323. return tone_mapping;
  324. }
  325. struct OpsinInverseMatrix {
  326. };
  327. static ErrorOr<OpsinInverseMatrix> read_opsin_inverse_matrix(LittleEndianInputBitStream&)
  328. {
  329. TODO();
  330. }
  331. struct ImageMetadata {
  332. u8 orientation { 1 };
  333. Optional<SizeHeader> intrinsic_size;
  334. Optional<PreviewHeader> preview;
  335. Optional<AnimationHeader> animation;
  336. BitDepth bit_depth;
  337. bool modular_16bit_buffers { true };
  338. u16 num_extra_channels {};
  339. Vector<ExtraChannelInfo, 4> ec_info;
  340. bool xyb_encoded { true };
  341. ColourEncoding colour_encoding;
  342. ToneMapping tone_mapping;
  343. Extensions extensions;
  344. bool default_m;
  345. OpsinInverseMatrix opsin_inverse_matrix;
  346. u8 cw_mask { 0 };
  347. Array<double, 15> up2_weight = s_d_up2;
  348. Array<double, 55> up4_weight = s_d_up4;
  349. Array<double, 210> up8_weight = s_d_up8;
  350. u16 number_of_color_channels() const
  351. {
  352. if (!xyb_encoded && colour_encoding.colour_space == ColourEncoding::ColourSpace::kGrey)
  353. return 1;
  354. return 3;
  355. }
  356. u16 number_of_channels() const
  357. {
  358. return number_of_color_channels() + num_extra_channels;
  359. }
  360. Optional<u16> alpha_channel() const
  361. {
  362. for (u16 i = 0; i < ec_info.size(); ++i) {
  363. if (ec_info[i].type == ExtraChannelInfo::ExtraChannelType::kAlpha)
  364. return i + number_of_color_channels();
  365. }
  366. return OptionalNone {};
  367. }
  368. };
  369. static ErrorOr<ImageMetadata> read_metadata_header(LittleEndianInputBitStream& stream)
  370. {
  371. ImageMetadata metadata;
  372. bool const all_default = TRY(stream.read_bit());
  373. if (!all_default) {
  374. bool const extra_fields = TRY(stream.read_bit());
  375. if (extra_fields) {
  376. metadata.orientation = 1 + TRY(stream.read_bits(3));
  377. bool const have_intr_size = TRY(stream.read_bit());
  378. if (have_intr_size)
  379. metadata.intrinsic_size = TRY(read_size_header(stream));
  380. bool const have_preview = TRY(stream.read_bit());
  381. if (have_preview)
  382. TODO();
  383. bool const have_animation = TRY(stream.read_bit());
  384. if (have_animation)
  385. TODO();
  386. }
  387. metadata.bit_depth = TRY(read_bit_depth(stream));
  388. metadata.modular_16bit_buffers = TRY(stream.read_bit());
  389. metadata.num_extra_channels = U32(0, 1, 2 + TRY(stream.read_bits(4)), 1 + TRY(stream.read_bits(12)));
  390. for (u16 i {}; i < metadata.num_extra_channels; ++i)
  391. metadata.ec_info.append(TRY(read_extra_channel_info(stream)));
  392. metadata.xyb_encoded = TRY(stream.read_bit());
  393. metadata.colour_encoding = TRY(read_colour_encoding(stream));
  394. if (extra_fields)
  395. metadata.tone_mapping = TRY(read_tone_mapping(stream));
  396. metadata.extensions = TRY(read_extensions(stream));
  397. }
  398. metadata.default_m = TRY(stream.read_bit());
  399. if (!metadata.default_m && metadata.xyb_encoded)
  400. metadata.opsin_inverse_matrix = TRY(read_opsin_inverse_matrix(stream));
  401. if (!metadata.default_m)
  402. metadata.cw_mask = TRY(stream.read_bits(3));
  403. if (metadata.cw_mask != 0)
  404. TODO();
  405. return metadata;
  406. }
  407. ///
  408. /// Table F.7 — BlendingInfo bundle
  409. struct BlendingInfo {
  410. enum class BlendMode {
  411. kReplace = 0,
  412. kAdd = 1,
  413. kBlend = 2,
  414. kMulAdd = 3,
  415. kMul = 4,
  416. };
  417. BlendMode mode {};
  418. u8 alpha_channel {};
  419. bool clamp { false };
  420. u8 source {};
  421. };
  422. static ErrorOr<BlendingInfo> read_blending_info(LittleEndianInputBitStream& stream, ImageMetadata const& metadata, bool full_frame)
  423. {
  424. BlendingInfo blending_info;
  425. blending_info.mode = static_cast<BlendingInfo::BlendMode>(U32(0, 1, 2, 3 + TRY(stream.read_bits(2))));
  426. bool const extra = metadata.num_extra_channels > 0;
  427. if (extra) {
  428. auto const blend_or_mul_add = blending_info.mode == BlendingInfo::BlendMode::kBlend
  429. || blending_info.mode == BlendingInfo::BlendMode::kMulAdd;
  430. if (blend_or_mul_add)
  431. blending_info.alpha_channel = U32(0, 1, 2, 3 + TRY(stream.read_bits(3)));
  432. if (blend_or_mul_add || blending_info.mode == BlendingInfo::BlendMode::kMul)
  433. blending_info.clamp = TRY(stream.read_bit());
  434. }
  435. if (blending_info.mode != BlendingInfo::BlendMode::kReplace
  436. || !full_frame) {
  437. blending_info.source = TRY(stream.read_bits(2));
  438. }
  439. return blending_info;
  440. }
  441. ///
  442. /// J.1 - General
  443. struct RestorationFilter {
  444. bool gab { true };
  445. u8 epf_iters { 2 };
  446. Extensions extensions;
  447. };
  448. static ErrorOr<RestorationFilter> read_restoration_filter(LittleEndianInputBitStream& stream)
  449. {
  450. RestorationFilter restoration_filter;
  451. auto const all_defaults = TRY(stream.read_bit());
  452. if (!all_defaults) {
  453. restoration_filter.gab = TRY(stream.read_bit());
  454. if (restoration_filter.gab) {
  455. TODO();
  456. }
  457. restoration_filter.epf_iters = TRY(stream.read_bits(2));
  458. if (restoration_filter.epf_iters != 0) {
  459. TODO();
  460. }
  461. restoration_filter.extensions = TRY(read_extensions(stream));
  462. }
  463. return restoration_filter;
  464. }
  465. ///
  466. /// Table F.6 — Passes bundle
  467. struct Passes {
  468. u8 num_passes { 1 };
  469. };
  470. static ErrorOr<Passes> read_passes(LittleEndianInputBitStream& stream)
  471. {
  472. Passes passes;
  473. passes.num_passes = U32(1, 2, 3, 4 + TRY(stream.read_bits(3)));
  474. if (passes.num_passes != 1) {
  475. TODO();
  476. }
  477. return passes;
  478. }
  479. ///
  480. /// F.2 - FrameHeader
  481. struct FrameHeader {
  482. enum class FrameType {
  483. kRegularFrame = 0,
  484. kLFFrame = 1,
  485. kReferenceOnly = 2,
  486. kSkipProgressive = 3,
  487. };
  488. enum class Encoding {
  489. kVarDCT = 0,
  490. kModular = 1,
  491. };
  492. enum class Flags {
  493. None = 0,
  494. kNoise = 1,
  495. kPatches = 1 << 1,
  496. kSplines = 1 << 4,
  497. kUseLfFrame = 1 << 5,
  498. kSkipAdaptiveLFSmoothing = 1 << 7,
  499. };
  500. FrameType frame_type { FrameType::kRegularFrame };
  501. Encoding encoding { Encoding::kVarDCT };
  502. Flags flags { Flags::None };
  503. bool do_YCbCr { false };
  504. Array<u8, 3> jpeg_upsampling {};
  505. u8 upsampling {};
  506. FixedArray<u8> ec_upsampling {};
  507. u8 group_size_shift { 1 };
  508. Passes passes {};
  509. u8 lf_level {};
  510. bool have_crop { false };
  511. BlendingInfo blending_info {};
  512. FixedArray<BlendingInfo> ec_blending_info {};
  513. u32 duration {};
  514. bool is_last { true };
  515. u8 save_as_reference {};
  516. bool save_before_ct {};
  517. String name {};
  518. RestorationFilter restoration_filter {};
  519. Extensions extensions {};
  520. };
  521. static int operator&(FrameHeader::Flags first, FrameHeader::Flags second)
  522. {
  523. return static_cast<int>(first) & static_cast<int>(second);
  524. }
  525. static ErrorOr<FrameHeader> read_frame_header(LittleEndianInputBitStream& stream, ImageMetadata const& metadata)
  526. {
  527. FrameHeader frame_header;
  528. bool const all_default = TRY(stream.read_bit());
  529. if (!all_default) {
  530. frame_header.frame_type = static_cast<FrameHeader::FrameType>(TRY(stream.read_bits(2)));
  531. frame_header.encoding = static_cast<FrameHeader::Encoding>(TRY(stream.read_bits(1)));
  532. frame_header.flags = static_cast<FrameHeader::Flags>(TRY(U64(stream)));
  533. if (!metadata.xyb_encoded)
  534. frame_header.do_YCbCr = TRY(stream.read_bit());
  535. if (!(frame_header.flags & FrameHeader::Flags::kUseLfFrame)) {
  536. if (frame_header.do_YCbCr) {
  537. frame_header.jpeg_upsampling[0] = TRY(stream.read_bits(2));
  538. frame_header.jpeg_upsampling[1] = TRY(stream.read_bits(2));
  539. frame_header.jpeg_upsampling[2] = TRY(stream.read_bits(2));
  540. }
  541. frame_header.upsampling = U32(1, 2, 4, 8);
  542. frame_header.ec_upsampling = TRY(FixedArray<u8>::create(metadata.num_extra_channels));
  543. for (u16 i {}; i < metadata.num_extra_channels; ++i)
  544. frame_header.ec_upsampling[i] = U32(1, 2, 4, 8);
  545. }
  546. if (frame_header.encoding == FrameHeader::Encoding::kModular)
  547. frame_header.group_size_shift = TRY(stream.read_bits(2));
  548. if (frame_header.encoding == FrameHeader::Encoding::kVarDCT)
  549. TODO();
  550. if (frame_header.frame_type != FrameHeader::FrameType::kReferenceOnly)
  551. frame_header.passes = TRY(read_passes(stream));
  552. if (frame_header.frame_type == FrameHeader::FrameType::kLFFrame)
  553. TODO();
  554. if (frame_header.frame_type != FrameHeader::FrameType::kLFFrame)
  555. frame_header.have_crop = TRY(stream.read_bit());
  556. if (frame_header.have_crop)
  557. TODO();
  558. bool const normal_frame = frame_header.frame_type == FrameHeader::FrameType::kRegularFrame
  559. || frame_header.frame_type == FrameHeader::FrameType::kSkipProgressive;
  560. // FIXME: also consider "cropped" image of the dimension of the frame
  561. VERIFY(!frame_header.have_crop);
  562. bool const full_frame = !frame_header.have_crop;
  563. if (normal_frame) {
  564. frame_header.blending_info = TRY(read_blending_info(stream, metadata, full_frame));
  565. frame_header.ec_blending_info = TRY(FixedArray<BlendingInfo>::create(metadata.num_extra_channels));
  566. for (u16 i {}; i < metadata.num_extra_channels; ++i)
  567. frame_header.ec_blending_info[i] = TRY(read_blending_info(stream, metadata, full_frame));
  568. if (metadata.animation.has_value())
  569. TODO();
  570. frame_header.is_last = TRY(stream.read_bit());
  571. }
  572. // FIXME: Ensure that is_last has the correct default value
  573. VERIFY(normal_frame);
  574. auto const resets_canvas = full_frame && frame_header.blending_info.mode == BlendingInfo::BlendMode::kReplace;
  575. auto const can_reference = !frame_header.is_last && (frame_header.duration == 0 || frame_header.save_as_reference != 0) && frame_header.frame_type != FrameHeader::FrameType::kLFFrame;
  576. if (frame_header.frame_type != FrameHeader::FrameType::kLFFrame) {
  577. if (!frame_header.is_last)
  578. TODO();
  579. }
  580. frame_header.save_before_ct = !normal_frame;
  581. if (frame_header.frame_type == FrameHeader::FrameType::kReferenceOnly || (resets_canvas && can_reference))
  582. frame_header.save_before_ct = TRY(stream.read_bit());
  583. frame_header.name = TRY(read_string(stream));
  584. frame_header.restoration_filter = TRY(read_restoration_filter(stream));
  585. frame_header.extensions = TRY(read_extensions(stream));
  586. }
  587. return frame_header;
  588. }
  589. ///
  590. /// F.3 TOC
  591. struct TOC {
  592. FixedArray<u32> entries;
  593. FixedArray<u32> group_offsets;
  594. };
  595. static u64 num_toc_entries(FrameHeader const& frame_header, u64 num_groups, u64 num_lf_groups)
  596. {
  597. // F.3.1 - General
  598. if (num_groups == 1 && frame_header.passes.num_passes == 1)
  599. return 1;
  600. return 1 + num_lf_groups + 1 + num_groups * frame_header.passes.num_passes;
  601. }
  602. static ErrorOr<TOC> read_toc(LittleEndianInputBitStream& stream, FrameHeader const& frame_header, u64 num_groups, u64 num_lf_groups)
  603. {
  604. TOC toc;
  605. bool const permuted_toc = TRY(stream.read_bit());
  606. if (permuted_toc) {
  607. // Read permutations
  608. TODO();
  609. }
  610. // F.3.3 - Decoding TOC
  611. stream.align_to_byte_boundary();
  612. auto const toc_entries = num_toc_entries(frame_header, num_groups, num_lf_groups);
  613. toc.entries = TRY(FixedArray<u32>::create(toc_entries));
  614. toc.group_offsets = TRY(FixedArray<u32>::create(toc_entries));
  615. for (u32 i {}; i < toc_entries; ++i) {
  616. auto const new_entry = U32(
  617. TRY(stream.read_bits(10)),
  618. 1024 + TRY(stream.read_bits(14)),
  619. 17408 + TRY(stream.read_bits(22)),
  620. 4211712 + TRY(stream.read_bits(30)));
  621. toc.entries[i] = new_entry;
  622. toc.group_offsets[i] = (i == 0 ? 0 : toc.group_offsets[i - 1]) + new_entry;
  623. }
  624. if (permuted_toc)
  625. TODO();
  626. stream.align_to_byte_boundary();
  627. return toc;
  628. }
  629. ///
  630. /// G.1.2 - LF channel dequantization weights
  631. struct LfChannelDequantization {
  632. float m_x_lf_unscaled { 4096 };
  633. float m_y_lf_unscaled { 512 };
  634. float m_b_lf_unscaled { 256 };
  635. };
  636. static ErrorOr<LfChannelDequantization> read_lf_channel_dequantization(LittleEndianInputBitStream& stream)
  637. {
  638. LfChannelDequantization lf_channel_dequantization;
  639. auto const all_default = TRY(stream.read_bit());
  640. if (!all_default) {
  641. TODO();
  642. }
  643. return lf_channel_dequantization;
  644. }
  645. ///
  646. /// C - Entropy decoding
  647. class EntropyDecoder {
  648. using BrotliCanonicalCode = Compress::Brotli::CanonicalCode;
  649. public:
  650. static ErrorOr<EntropyDecoder> create(LittleEndianInputBitStream& stream, u8 initial_num_distrib)
  651. {
  652. EntropyDecoder entropy_decoder;
  653. // C.2 - Distribution decoding
  654. entropy_decoder.m_lz77_enabled = TRY(stream.read_bit());
  655. if (entropy_decoder.m_lz77_enabled) {
  656. TODO();
  657. }
  658. TRY(entropy_decoder.read_pre_clustered_distributions(stream, initial_num_distrib));
  659. bool const use_prefix_code = TRY(stream.read_bit());
  660. if (!use_prefix_code)
  661. entropy_decoder.m_log_alphabet_size = 5 + TRY(stream.read_bits(2));
  662. for (auto& config : entropy_decoder.m_configs)
  663. config = TRY(entropy_decoder.read_config(stream));
  664. if (use_prefix_code) {
  665. entropy_decoder.m_distributions = Vector<BrotliCanonicalCode> {};
  666. auto& distributions = entropy_decoder.m_distributions.get<Vector<BrotliCanonicalCode>>();
  667. TRY(distributions.try_resize(entropy_decoder.m_configs.size()));
  668. Vector<u16> counts;
  669. TRY(counts.try_resize(entropy_decoder.m_configs.size()));
  670. for (auto& count : counts) {
  671. if (TRY(stream.read_bit())) {
  672. auto const n = TRY(stream.read_bits(4));
  673. count = 1 + (1 << n) + TRY(stream.read_bits(n));
  674. } else {
  675. count = 1;
  676. }
  677. }
  678. // After reading the counts, the decoder reads each D[i] (implicitly
  679. // described by a prefix code) as specified in C.2.4, with alphabet_size = count[i].
  680. for (u32 i {}; i < distributions.size(); ++i) {
  681. // The alphabet size mentioned in the [Brotli] RFC is explicitly specified as parameter alphabet_size
  682. // when the histogram is being decoded, except in the special case of alphabet_size == 1, where no
  683. // histogram is read, and all decoded symbols are zero without reading any bits at all.
  684. if (counts[i] != 1)
  685. distributions[i] = TRY(BrotliCanonicalCode::read_prefix_code(stream, counts[i]));
  686. else
  687. distributions[i] = BrotliCanonicalCode { { 1 }, { 0 } };
  688. }
  689. } else {
  690. TODO();
  691. }
  692. return entropy_decoder;
  693. }
  694. ErrorOr<u32> decode_hybrid_uint(LittleEndianInputBitStream& stream, u16 context)
  695. {
  696. // C.3.3 - Hybrid integer decoding
  697. if (m_lz77_enabled)
  698. TODO();
  699. // Read symbol from entropy coded stream using D[clusters[ctx]]
  700. u32 token {};
  701. TRY(m_distributions.visit(
  702. [&](Vector<BrotliCanonicalCode> const& distributions) -> ErrorOr<void> {
  703. token = TRY(distributions[m_clusters[context]].read_symbol(stream));
  704. return {};
  705. }));
  706. auto r = TRY(read_uint(stream, m_configs[m_clusters[context]], token));
  707. return r;
  708. }
  709. private:
  710. struct HybridUint {
  711. u32 split_exponent {};
  712. u32 split {};
  713. u32 msb_in_token {};
  714. u32 lsb_in_token {};
  715. };
  716. static ErrorOr<u32> read_uint(LittleEndianInputBitStream& stream, HybridUint const& config, u32 token)
  717. {
  718. if (token < config.split)
  719. return token;
  720. auto const n = config.split_exponent
  721. - config.msb_in_token
  722. - config.lsb_in_token
  723. + ((token - config.split) >> (config.msb_in_token + config.lsb_in_token));
  724. VERIFY(n < 32);
  725. u32 const low_bits = token & ((1 << config.lsb_in_token) - 1);
  726. token = token >> config.lsb_in_token;
  727. token &= (1 << config.msb_in_token) - 1;
  728. token |= (1 << config.msb_in_token);
  729. auto const result = ((token << n | TRY(stream.read_bits(n))) << config.lsb_in_token) | low_bits;
  730. VERIFY(result < (1ul << 32));
  731. return result;
  732. }
  733. ErrorOr<void> read_pre_clustered_distributions(LittleEndianInputBitStream& stream, u8 num_distrib)
  734. {
  735. // C.2.2 Distribution clustering
  736. if (num_distrib == 1)
  737. TODO();
  738. TRY(m_clusters.try_resize(num_distrib));
  739. bool const is_simple = TRY(stream.read_bit());
  740. u16 num_clusters = 0;
  741. if (is_simple) {
  742. u8 const nbits = TRY(stream.read_bits(2));
  743. for (u8 i {}; i < num_distrib; ++i) {
  744. m_clusters[i] = TRY(stream.read_bits(nbits));
  745. if (m_clusters[i] >= num_clusters)
  746. num_clusters = m_clusters[i] + 1;
  747. }
  748. } else {
  749. TODO();
  750. }
  751. TRY(m_configs.try_resize(num_clusters));
  752. return {};
  753. }
  754. ErrorOr<HybridUint> read_config(LittleEndianInputBitStream& stream) const
  755. {
  756. // C.2.3 - Hybrid integer configuration
  757. HybridUint config {};
  758. config.split_exponent = TRY(stream.read_bits(ceil(log2(m_log_alphabet_size + 1))));
  759. if (config.split_exponent != m_log_alphabet_size) {
  760. auto nbits = ceil(log2(config.split_exponent + 1));
  761. config.msb_in_token = TRY(stream.read_bits(nbits));
  762. nbits = ceil(log2(config.split_exponent - config.msb_in_token + 1));
  763. config.lsb_in_token = TRY(stream.read_bits(nbits));
  764. } else {
  765. config.msb_in_token = 0;
  766. config.lsb_in_token = 0;
  767. }
  768. config.split = 1 << config.split_exponent;
  769. return config;
  770. }
  771. bool m_lz77_enabled {};
  772. Vector<u32> m_clusters;
  773. Vector<HybridUint> m_configs;
  774. u8 m_log_alphabet_size { 15 };
  775. Variant<Vector<BrotliCanonicalCode>> m_distributions { Vector<BrotliCanonicalCode> {} }; // D in the spec
  776. };
  777. ///
  778. /// H.4.2 - MA tree decoding
  779. class MATree {
  780. public:
  781. struct LeafNode {
  782. u8 ctx {};
  783. u8 predictor {};
  784. i32 offset {};
  785. u32 multiplier {};
  786. };
  787. static ErrorOr<MATree> decode(LittleEndianInputBitStream& stream, Optional<EntropyDecoder>& decoder)
  788. {
  789. // G.1.3 - GlobalModular
  790. MATree tree;
  791. // 1 / 2 Read the 6 pre-clustered distributions
  792. auto const num_distrib = 6;
  793. if (!decoder.has_value())
  794. decoder = TRY(EntropyDecoder::create(stream, num_distrib));
  795. // 2 / 2 Decode the tree
  796. u64 ctx_id = 0;
  797. u64 nodes_left = 1;
  798. tree.m_tree.clear();
  799. while (nodes_left > 0) {
  800. nodes_left--;
  801. i32 const property = TRY(decoder->decode_hybrid_uint(stream, 1)) - 1;
  802. if (property >= 0) {
  803. DecisionNode decision_node;
  804. decision_node.property = property;
  805. decision_node.value = unpack_signed(TRY(decoder->decode_hybrid_uint(stream, 0)));
  806. decision_node.left_child = tree.m_tree.size() + nodes_left + 1;
  807. decision_node.right_child = tree.m_tree.size() + nodes_left + 2;
  808. tree.m_tree.empend(decision_node);
  809. nodes_left += 2;
  810. } else {
  811. LeafNode leaf_node;
  812. leaf_node.ctx = ctx_id++;
  813. leaf_node.predictor = TRY(decoder->decode_hybrid_uint(stream, 2));
  814. leaf_node.offset = unpack_signed(TRY(decoder->decode_hybrid_uint(stream, 3)));
  815. auto const mul_log = TRY(decoder->decode_hybrid_uint(stream, 4));
  816. auto const mul_bits = TRY(decoder->decode_hybrid_uint(stream, 5));
  817. leaf_node.multiplier = (mul_bits + 1) << mul_log;
  818. tree.m_tree.empend(leaf_node);
  819. }
  820. }
  821. // Finally, the decoder reads (tree.size() + 1) / 2 pre-clustered distributions D as specified in C.1.
  822. auto const num_pre_clustered_distributions = (tree.m_tree.size() + 1) / 2;
  823. decoder = TRY(decoder->create(stream, num_pre_clustered_distributions));
  824. return tree;
  825. }
  826. LeafNode get_leaf(Vector<i32> const& properties) const
  827. {
  828. // To find the MA leaf node, the MA tree is traversed, starting at the root node tree[0]
  829. // and for each decision node d, testing if property[d.property] > d.value, proceeding to
  830. // the node tree[d.left_child] if the test evaluates to true and to the node tree[d.right_child]
  831. // otherwise, until a leaf node is reached.
  832. DecisionNode node { m_tree[0].get<DecisionNode>() };
  833. while (true) {
  834. auto const next_node = [this, &properties, &node]() {
  835. // Note: The behavior when trying to access a non-existing property is taken from jxl-oxide
  836. if (node.property < properties.size() && properties[node.property] > node.value)
  837. return m_tree[node.left_child];
  838. return m_tree[node.right_child];
  839. }();
  840. if (next_node.has<LeafNode>())
  841. return next_node.get<LeafNode>();
  842. node = next_node.get<DecisionNode>();
  843. }
  844. }
  845. private:
  846. struct DecisionNode {
  847. u64 property {};
  848. i64 value {};
  849. u64 left_child {};
  850. u64 right_child {};
  851. };
  852. Vector<Variant<DecisionNode, LeafNode>> m_tree;
  853. };
  854. ///
  855. /// H.5 - Self-correcting predictor
  856. struct WPHeader {
  857. u8 wp_p1 { 16 };
  858. u8 wp_p2 { 10 };
  859. u8 wp_p3a { 7 };
  860. u8 wp_p3b { 7 };
  861. u8 wp_p3c { 7 };
  862. u8 wp_p3d { 0 };
  863. u8 wp_p3e { 0 };
  864. Array<u8, 4> wp_w { 13, 12, 12, 12 };
  865. };
  866. static ErrorOr<WPHeader> read_self_correcting_predictor(LittleEndianInputBitStream& stream)
  867. {
  868. WPHeader self_correcting_predictor {};
  869. bool const default_wp = TRY(stream.read_bit());
  870. if (!default_wp) {
  871. TODO();
  872. }
  873. return self_correcting_predictor;
  874. }
  875. ///
  876. ///
  877. struct TransformInfo {
  878. enum class TransformId {
  879. kRCT = 0,
  880. kPalette = 1,
  881. kSqueeze = 2,
  882. };
  883. TransformId tr {};
  884. u32 begin_c {};
  885. u32 rct_type {};
  886. };
  887. static ErrorOr<TransformInfo> read_transform_info(LittleEndianInputBitStream& stream)
  888. {
  889. TransformInfo transform_info;
  890. transform_info.tr = static_cast<TransformInfo::TransformId>(TRY(stream.read_bits(2)));
  891. if (transform_info.tr != TransformInfo::TransformId::kSqueeze) {
  892. transform_info.begin_c = U32(
  893. TRY(stream.read_bits(3)),
  894. 8 + TRY(stream.read_bits(3)),
  895. 72 + TRY(stream.read_bits(10)),
  896. 1096 + TRY(stream.read_bits(13)));
  897. }
  898. if (transform_info.tr == TransformInfo::TransformId::kRCT) {
  899. transform_info.rct_type = U32(
  900. 6,
  901. TRY(stream.read_bits(2)),
  902. 2 + TRY(stream.read_bits(4)),
  903. 10 + TRY(stream.read_bits(6)));
  904. }
  905. if (transform_info.tr != TransformInfo::TransformId::kRCT)
  906. TODO();
  907. return transform_info;
  908. }
  909. ///
  910. /// Local abstractions to store the decoded image
  911. class Channel {
  912. public:
  913. static ErrorOr<Channel> create(u32 width, u32 height)
  914. {
  915. Channel channel;
  916. channel.m_width = width;
  917. channel.m_height = height;
  918. TRY(channel.m_pixels.try_resize(channel.m_width * channel.m_height));
  919. return channel;
  920. }
  921. i32 get(u32 x, u32 y) const
  922. {
  923. return m_pixels[x * m_width + y];
  924. }
  925. void set(u32 x, u32 y, i32 value)
  926. {
  927. m_pixels[x * m_width + y] = value;
  928. }
  929. u32 width() const
  930. {
  931. return m_width;
  932. }
  933. u32 height() const
  934. {
  935. return m_height;
  936. }
  937. u32 hshift() const
  938. {
  939. return m_hshift;
  940. }
  941. u32 vshift() const
  942. {
  943. return m_vshift;
  944. }
  945. bool decoded() const
  946. {
  947. return m_decoded;
  948. }
  949. void set_decoded(bool decoded)
  950. {
  951. m_decoded = decoded;
  952. }
  953. private:
  954. u32 m_width {};
  955. u32 m_height {};
  956. u32 m_hshift {};
  957. u32 m_vshift {};
  958. bool m_decoded { false };
  959. Vector<i32> m_pixels {};
  960. };
  961. class Image {
  962. public:
  963. static ErrorOr<Image> create(IntSize size, ImageMetadata const& metadata)
  964. {
  965. Image image {};
  966. for (u16 i = 0; i < metadata.number_of_channels(); ++i) {
  967. if (i < metadata.number_of_color_channels()) {
  968. TRY(image.m_channels.try_append(TRY(Channel::create(size.width(), size.height()))));
  969. } else {
  970. auto const dim_shift = metadata.ec_info[i - metadata.number_of_color_channels()].dim_shift;
  971. TRY(image.m_channels.try_append(TRY(Channel::create(size.width() >> dim_shift, size.height() >> dim_shift))));
  972. }
  973. }
  974. return image;
  975. }
  976. ErrorOr<NonnullRefPtr<Bitmap>> to_bitmap(ImageMetadata& metadata) const
  977. {
  978. // FIXME: which channel size should we use?
  979. auto const width = m_channels[0].width();
  980. auto const height = m_channels[0].height();
  981. auto bitmap = TRY(Bitmap::create(BitmapFormat::BGRA8888, { width, height }));
  982. auto const alpha_channel = metadata.alpha_channel();
  983. auto const bits_per_sample = metadata.bit_depth.bits_per_sample;
  984. VERIFY(bits_per_sample >= 8);
  985. for (u32 y {}; y < height; ++y) {
  986. for (u32 x {}; x < width; ++x) {
  987. auto const to_u8 = [&, bits_per_sample](i32 sample) -> u8 {
  988. // FIXME: Don't truncate the result to 8 bits
  989. static constexpr auto maximum_supported_bit_depth = 8;
  990. if (bits_per_sample > maximum_supported_bit_depth)
  991. sample >>= (bits_per_sample - maximum_supported_bit_depth);
  992. return clamp(sample + .5, 0, (1 << maximum_supported_bit_depth) - 1);
  993. };
  994. auto const color = [&]() -> Color {
  995. if (!alpha_channel.has_value()) {
  996. return { to_u8(m_channels[0].get(x, y)),
  997. to_u8(m_channels[1].get(x, y)),
  998. to_u8(m_channels[2].get(x, y)) };
  999. }
  1000. return {
  1001. to_u8(m_channels[0].get(x, y)),
  1002. to_u8(m_channels[1].get(x, y)),
  1003. to_u8(m_channels[2].get(x, y)),
  1004. to_u8(m_channels[*alpha_channel].get(x, y)),
  1005. };
  1006. }();
  1007. bitmap->set_pixel(x, y, color);
  1008. }
  1009. }
  1010. return bitmap;
  1011. }
  1012. Vector<Channel>& channels()
  1013. {
  1014. return m_channels;
  1015. }
  1016. private:
  1017. Vector<Channel> m_channels;
  1018. };
  1019. ///
  1020. /// H.5 - Self-correcting predictor
  1021. struct Neighborhood {
  1022. i32 N {};
  1023. i32 NW {};
  1024. i32 NE {};
  1025. i32 W {};
  1026. i32 NN {};
  1027. i32 WW {};
  1028. i32 NEE {};
  1029. };
  1030. class SelfCorrectingData {
  1031. public:
  1032. struct Predictions {
  1033. i32 prediction {};
  1034. Array<i32, 4> subpred {};
  1035. i32 max_error {};
  1036. i32 true_err {};
  1037. Array<i32, 4> err {};
  1038. };
  1039. static ErrorOr<SelfCorrectingData> create(WPHeader const& wp_params, u32 width)
  1040. {
  1041. SelfCorrectingData self_correcting_data { wp_params };
  1042. self_correcting_data.m_width = width;
  1043. self_correcting_data.m_previous = TRY(FixedArray<Predictions>::create(width));
  1044. self_correcting_data.m_current_row = TRY(FixedArray<Predictions>::create(width));
  1045. self_correcting_data.m_next_row = TRY(FixedArray<Predictions>::create(width));
  1046. return self_correcting_data;
  1047. }
  1048. void register_next_row()
  1049. {
  1050. auto tmp = move(m_previous);
  1051. m_previous = move(m_current_row);
  1052. m_current_row = move(m_next_row);
  1053. // We reuse m_previous to avoid an allocation, no values are kept
  1054. // everything will be overridden.
  1055. m_next_row = move(tmp);
  1056. m_current_row_index++;
  1057. }
  1058. Predictions compute_predictions(Neighborhood const& neighborhood, u32 x)
  1059. {
  1060. auto& current_predictions = m_next_row[x];
  1061. auto const N3 = neighborhood.N << 3;
  1062. auto const NW3 = neighborhood.NW << 3;
  1063. auto const NE3 = neighborhood.NE << 3;
  1064. auto const W3 = neighborhood.W << 3;
  1065. auto const NN3 = neighborhood.NN << 3;
  1066. auto const predictions_W = predictions_for(x, Direction::West);
  1067. auto const predictions_N = predictions_for(x, Direction::North);
  1068. auto const predictions_NE = predictions_for(x, Direction::NorthEast);
  1069. auto const predictions_NW = predictions_for(x, Direction::NorthWest);
  1070. auto const predictions_WW = predictions_for(x, Direction::WestWest);
  1071. current_predictions.subpred[0] = W3 + NE3 - N3;
  1072. current_predictions.subpred[1] = N3 - (((predictions_W.true_err + predictions_N.true_err + predictions_NE.true_err) * wp_params.wp_p1) >> 5);
  1073. current_predictions.subpred[2] = W3 - (((predictions_W.true_err + predictions_N.true_err + predictions_NW.true_err) * wp_params.wp_p2) >> 5);
  1074. current_predictions.subpred[3] = N3 - ((predictions_NW.true_err * wp_params.wp_p3a + predictions_N.true_err * wp_params.wp_p3b + predictions_NE.true_err * wp_params.wp_p3c + (NN3 - N3) * wp_params.wp_p3d + (NW3 - W3) * wp_params.wp_p3e) >> 5);
  1075. auto const error2weight = [](i32 err_sum, u8 maxweight) -> i32 {
  1076. i32 shift = floor(log2(err_sum + 1)) - 5;
  1077. if (shift < 0)
  1078. shift = 0;
  1079. return 4 + ((static_cast<u64>(maxweight) * ((1 << 24) / ((err_sum >> shift) + 1))) >> shift);
  1080. };
  1081. Array<i32, 4> weight {};
  1082. for (u8 i = 0; i < weight.size(); ++i) {
  1083. auto err_sum = predictions_N.err[i] + predictions_W.err[i] + predictions_NW.err[i] + predictions_WW.err[i] + predictions_NE.err[i];
  1084. if (x == m_width - 1)
  1085. err_sum += predictions_W.err[i];
  1086. weight[i] = error2weight(err_sum, wp_params.wp_w[i]);
  1087. }
  1088. auto sum_weights = weight[0] + weight[1] + weight[2] + weight[3];
  1089. i32 const log_weight = floor(log2(sum_weights)) + 1;
  1090. for (u8 i = 0; i < 4; i++)
  1091. weight[i] = weight[i] >> (log_weight - 5);
  1092. sum_weights = weight[0] + weight[1] + weight[2] + weight[3];
  1093. auto s = (sum_weights >> 1) - 1;
  1094. for (u8 i = 0; i < 4; i++)
  1095. s += current_predictions.subpred[i] * weight[i];
  1096. current_predictions.prediction = static_cast<u64>(s) * ((1 << 24) / sum_weights) >> 24;
  1097. // if true_err_N, true_err_W and true_err_NW don't have the same sign
  1098. if (((predictions_N.true_err ^ predictions_W.true_err) | (predictions_N.true_err ^ predictions_NW.true_err)) <= 0) {
  1099. current_predictions.prediction = clamp(current_predictions.prediction, min(W3, min(N3, NE3)), max(W3, max(N3, NE3)));
  1100. }
  1101. auto& max_error = current_predictions.max_error;
  1102. max_error = predictions_W.true_err;
  1103. if (abs(predictions_N.true_err) > abs(max_error))
  1104. max_error = predictions_N.true_err;
  1105. if (abs(predictions_NW.true_err) > abs(max_error))
  1106. max_error = predictions_NW.true_err;
  1107. if (abs(predictions_NE.true_err) > abs(max_error))
  1108. max_error = predictions_NE.true_err;
  1109. return current_predictions;
  1110. }
  1111. // H.5.1 - General
  1112. void compute_errors(u32 x, i32 true_value)
  1113. {
  1114. auto& current_predictions = m_next_row[x];
  1115. current_predictions.true_err = current_predictions.prediction - (true_value << 3);
  1116. for (u8 i = 0; i < 4; ++i)
  1117. current_predictions.err[i] = (abs(current_predictions.subpred[i] - (true_value << 3)) + 3) >> 3;
  1118. }
  1119. private:
  1120. SelfCorrectingData(WPHeader const& wp)
  1121. : wp_params(wp)
  1122. {
  1123. }
  1124. enum class Direction {
  1125. North,
  1126. NorthWest,
  1127. NorthEast,
  1128. West,
  1129. NorthNorth,
  1130. WestWest
  1131. };
  1132. Predictions predictions_for(u32 x, Direction direction) const
  1133. {
  1134. // H.5.2 - Prediction
  1135. auto const north = [&]() {
  1136. return m_current_row_index < 1 ? Predictions {} : m_current_row[x];
  1137. };
  1138. switch (direction) {
  1139. case Direction::North:
  1140. return north();
  1141. case Direction::NorthWest:
  1142. return x < 1 ? north() : m_current_row[x - 1];
  1143. case Direction::NorthEast:
  1144. return x + 1 >= m_current_row.size() ? north() : m_current_row[x + 1];
  1145. case Direction::West:
  1146. return x < 1 ? Predictions {} : m_next_row[x - 1];
  1147. case Direction::NorthNorth:
  1148. return m_current_row_index < 2 ? Predictions {} : m_previous[x];
  1149. case Direction::WestWest:
  1150. return x < 2 ? Predictions {} : m_next_row[x - 2];
  1151. }
  1152. VERIFY_NOT_REACHED();
  1153. }
  1154. WPHeader const& wp_params {};
  1155. u32 m_width {};
  1156. u32 m_current_row_index {};
  1157. FixedArray<Predictions> m_previous {};
  1158. FixedArray<Predictions> m_current_row {};
  1159. FixedArray<Predictions> m_next_row {};
  1160. };
  1161. ///
  1162. /// H.2 - Image decoding
  1163. struct ModularHeader {
  1164. bool use_global_tree {};
  1165. WPHeader wp_params {};
  1166. Vector<TransformInfo> transform {};
  1167. };
  1168. static ErrorOr<Vector<i32>> get_properties(Vector<Channel> const& channels, u16 i, u32 x, u32 y, i32 max_error)
  1169. {
  1170. Vector<i32> properties;
  1171. // Table H.4 - Property definitions
  1172. TRY(properties.try_append(i));
  1173. // FIXME: Handle other cases than GlobalModular
  1174. TRY(properties.try_append(0));
  1175. TRY(properties.try_append(y));
  1176. TRY(properties.try_append(x));
  1177. i32 const W = x > 0 ? channels[i].get(x - 1, y) : (y > 0 ? channels[i].get(x, y - 1) : 0);
  1178. i32 const N = y > 0 ? channels[i].get(x, y - 1) : W;
  1179. i32 const NW = x > 0 && y > 0 ? channels[i].get(x - 1, y - 1) : W;
  1180. i32 const NE = x + 1 < channels[i].width() && y > 0 ? channels[i].get(x + 1, y - 1) : N;
  1181. i32 const NN = y > 1 ? channels[i].get(x, y - 2) : N;
  1182. i32 const WW = x > 1 ? channels[i].get(x - 2, y) : W;
  1183. TRY(properties.try_append(abs(N)));
  1184. TRY(properties.try_append(abs(W)));
  1185. TRY(properties.try_append(N));
  1186. TRY(properties.try_append(W));
  1187. // x > 0 ? W - /* (the value of property 9 at position (x - 1, y)) */ : W
  1188. if (x > 0) {
  1189. auto const x_1 = x - 1;
  1190. i32 const W_x_1 = x_1 > 0 ? channels[i].get(x_1 - 1, y) : (y > 0 ? channels[i].get(x_1, y - 1) : 0);
  1191. i32 const N_x_1 = y > 0 ? channels[i].get(x_1, y - 1) : W_x_1;
  1192. i32 const NW_x_1 = x_1 > 0 && y > 0 ? channels[i].get(x_1 - 1, y - 1) : W_x_1;
  1193. TRY(properties.try_append(W - (W_x_1 + N_x_1 - NW_x_1)));
  1194. } else {
  1195. TRY(properties.try_append(W));
  1196. }
  1197. TRY(properties.try_append(W + N - NW));
  1198. TRY(properties.try_append(W - NW));
  1199. TRY(properties.try_append(NW - N));
  1200. TRY(properties.try_append(N - NE));
  1201. TRY(properties.try_append(N - NN));
  1202. TRY(properties.try_append(W - WW));
  1203. TRY(properties.try_append(max_error));
  1204. for (i16 j = i - 1; j >= 0; j--) {
  1205. if (channels[j].width() != channels[i].width())
  1206. continue;
  1207. if (channels[j].height() != channels[i].height())
  1208. continue;
  1209. if (channels[j].hshift() != channels[i].hshift())
  1210. continue;
  1211. if (channels[j].vshift() != channels[i].vshift())
  1212. continue;
  1213. auto rC = channels[j].get(x, y);
  1214. auto rW = (x > 0 ? channels[j].get(x - 1, y) : 0);
  1215. auto rN = (y > 0 ? channels[j].get(x, y - 1) : rW);
  1216. auto rNW = (x > 0 && y > 0 ? channels[j].get(x - 1, y - 1) : rW);
  1217. auto rG = clamp(rW + rN - rNW, min(rW, rN), max(rW, rN));
  1218. TRY(properties.try_append(abs(rC)));
  1219. TRY(properties.try_append(rC));
  1220. TRY(properties.try_append(abs(rC - rG)));
  1221. TRY(properties.try_append(rC - rG));
  1222. }
  1223. return properties;
  1224. }
  1225. static i32 prediction(Neighborhood const& neighborhood, i32 self_correcting, u32 predictor)
  1226. {
  1227. switch (predictor) {
  1228. case 0:
  1229. return 0;
  1230. case 1:
  1231. return neighborhood.W;
  1232. case 2:
  1233. return neighborhood.N;
  1234. case 3:
  1235. return (neighborhood.W + neighborhood.N) / 2;
  1236. case 4:
  1237. return abs(neighborhood.N - neighborhood.NW) < abs(neighborhood.W - neighborhood.NW) ? neighborhood.W : neighborhood.N;
  1238. case 5:
  1239. return clamp(neighborhood.W + neighborhood.N - neighborhood.NW, min(neighborhood.W, neighborhood.N), max(neighborhood.W, neighborhood.N));
  1240. case 6:
  1241. return (self_correcting + 3) >> 3;
  1242. case 7:
  1243. return neighborhood.NE;
  1244. case 8:
  1245. return neighborhood.NW;
  1246. case 9:
  1247. return neighborhood.WW;
  1248. case 10:
  1249. return (neighborhood.W + neighborhood.NW) / 2;
  1250. case 11:
  1251. return (neighborhood.N + neighborhood.NW) / 2;
  1252. case 12:
  1253. return (neighborhood.N + neighborhood.NE) / 2;
  1254. case 13:
  1255. return (6 * neighborhood.N - 2 * neighborhood.NN + 7 * neighborhood.W + neighborhood.WW + neighborhood.NEE + 3 * neighborhood.NE + 8) / 16;
  1256. }
  1257. VERIFY_NOT_REACHED();
  1258. }
  1259. static Neighborhood retrieve_neighborhood(Channel const& channel, u32 x, u32 y)
  1260. {
  1261. i32 const W = x > 0 ? channel.get(x - 1, y) : (y > 0 ? channel.get(x, y - 1) : 0);
  1262. i32 const N = y > 0 ? channel.get(x, y - 1) : W;
  1263. i32 const NW = x > 0 && y > 0 ? channel.get(x - 1, y - 1) : W;
  1264. i32 const NE = x + 1 < channel.width() && y > 0 ? channel.get(x + 1, y - 1) : N;
  1265. i32 const NN = y > 1 ? channel.get(x, y - 2) : N;
  1266. i32 const WW = x > 1 ? channel.get(x - 2, y) : W;
  1267. i32 const NEE = x + 2 < channel.width() && y > 0 ? channel.get(x + 2, y - 1) : NE;
  1268. Neighborhood const neighborhood {
  1269. .N = N,
  1270. .NW = NW,
  1271. .NE = NE,
  1272. .W = W,
  1273. .NN = NN,
  1274. .WW = WW,
  1275. .NEE = NEE,
  1276. };
  1277. return neighborhood;
  1278. }
  1279. static ErrorOr<ModularHeader> read_modular_header(LittleEndianInputBitStream& stream,
  1280. Image& image,
  1281. Optional<EntropyDecoder>& decoder,
  1282. MATree const& global_tree,
  1283. u16 num_channels)
  1284. {
  1285. ModularHeader modular_header;
  1286. modular_header.use_global_tree = TRY(stream.read_bit());
  1287. modular_header.wp_params = TRY(read_self_correcting_predictor(stream));
  1288. auto const nb_transforms = U32(0, 1, 2 + TRY(stream.read_bits(4)), 18 + TRY(stream.read_bits(8)));
  1289. TRY(modular_header.transform.try_resize(nb_transforms));
  1290. for (u32 i {}; i < nb_transforms; ++i)
  1291. modular_header.transform[i] = TRY(read_transform_info(stream));
  1292. Optional<MATree> local_tree;
  1293. if (!modular_header.use_global_tree)
  1294. TODO();
  1295. // The decoder then starts an entropy-coded stream (C.1) and decodes the data for each channel
  1296. // (in ascending order of index) as specified in H.3, skipping any channels having width or height
  1297. // zero. Finally, the inverse transformations are applied (from last to first) as described in H.6.
  1298. auto const& tree = local_tree.has_value() ? *local_tree : global_tree;
  1299. for (u16 i {}; i < num_channels; ++i) {
  1300. auto self_correcting_data = TRY(SelfCorrectingData::create(modular_header.wp_params, image.channels()[i].width()));
  1301. for (u32 y {}; y < image.channels()[i].height(); y++) {
  1302. for (u32 x {}; x < image.channels()[i].width(); x++) {
  1303. auto const neighborhood = retrieve_neighborhood(image.channels()[i], x, y);
  1304. auto const self_prediction = self_correcting_data.compute_predictions(neighborhood, x);
  1305. auto const properties = TRY(get_properties(image.channels(), i, x, y, self_prediction.max_error));
  1306. auto const leaf_node = tree.get_leaf(properties);
  1307. auto diff = unpack_signed(TRY(decoder->decode_hybrid_uint(stream, leaf_node.ctx)));
  1308. diff = (diff * leaf_node.multiplier) + leaf_node.offset;
  1309. auto const total = diff + prediction(neighborhood, self_prediction.prediction, leaf_node.predictor);
  1310. self_correcting_data.compute_errors(x, total);
  1311. image.channels()[i].set(x, y, total);
  1312. }
  1313. self_correcting_data.register_next_row();
  1314. }
  1315. image.channels()[i].set_decoded(true);
  1316. }
  1317. return modular_header;
  1318. }
  1319. ///
  1320. /// G.1.2 - LF channel dequantization weights
  1321. struct GlobalModular {
  1322. MATree ma_tree;
  1323. ModularHeader modular_header;
  1324. };
  1325. static ErrorOr<GlobalModular> read_global_modular(LittleEndianInputBitStream& stream,
  1326. Image& image,
  1327. FrameHeader const& frame_header,
  1328. ImageMetadata const& metadata,
  1329. Optional<EntropyDecoder>& entropy_decoder)
  1330. {
  1331. GlobalModular global_modular;
  1332. auto const decode_ma_tree = TRY(stream.read_bit());
  1333. if (decode_ma_tree)
  1334. global_modular.ma_tree = TRY(MATree::decode(stream, entropy_decoder));
  1335. // The decoder then decodes a modular sub-bitstream (Annex H), where
  1336. // the number of channels is computed as follows:
  1337. auto num_channels = metadata.num_extra_channels;
  1338. if (frame_header.encoding == FrameHeader::Encoding::kModular) {
  1339. if (!frame_header.do_YCbCr && !metadata.xyb_encoded
  1340. && metadata.colour_encoding.colour_space == ColourEncoding::ColourSpace::kGrey) {
  1341. num_channels += 1;
  1342. } else {
  1343. num_channels += 3;
  1344. }
  1345. }
  1346. // FIXME: Ensure this spec comment:
  1347. // However, the decoder only decodes the first nb_meta_channels channels and any further channels
  1348. // that have a width and height that are both at most group_dim. At that point, it stops decoding.
  1349. // No inverse transforms are applied yet.
  1350. global_modular.modular_header = TRY(read_modular_header(stream, image, entropy_decoder, global_modular.ma_tree, num_channels));
  1351. return global_modular;
  1352. }
  1353. ///
  1354. /// G.1 - LfGlobal
  1355. struct LfGlobal {
  1356. LfChannelDequantization lf_dequant;
  1357. GlobalModular gmodular;
  1358. };
  1359. static ErrorOr<LfGlobal> read_lf_global(LittleEndianInputBitStream& stream,
  1360. Image& image,
  1361. FrameHeader const& frame_header,
  1362. ImageMetadata const& metadata,
  1363. Optional<EntropyDecoder>& entropy_decoder)
  1364. {
  1365. LfGlobal lf_global;
  1366. if (frame_header.flags != FrameHeader::Flags::None)
  1367. TODO();
  1368. lf_global.lf_dequant = TRY(read_lf_channel_dequantization(stream));
  1369. if (frame_header.encoding == FrameHeader::Encoding::kVarDCT)
  1370. TODO();
  1371. lf_global.gmodular = TRY(read_global_modular(stream, image, frame_header, metadata, entropy_decoder));
  1372. return lf_global;
  1373. }
  1374. ///
  1375. /// G.2 - LfGroup
  1376. static ErrorOr<void> read_lf_group(LittleEndianInputBitStream&,
  1377. Image& image,
  1378. FrameHeader const& frame_header)
  1379. {
  1380. // LF coefficients
  1381. if (frame_header.encoding == FrameHeader::Encoding::kVarDCT) {
  1382. TODO();
  1383. }
  1384. // ModularLfGroup
  1385. for (auto const& channel : image.channels()) {
  1386. if (channel.decoded())
  1387. continue;
  1388. if (channel.hshift() < 3 || channel.vshift() < 3)
  1389. continue;
  1390. // This code actually only detect that we need to read a null image
  1391. // so a no-op. It should be fully rewritten when we add proper support
  1392. // for LfGroup.
  1393. TODO();
  1394. }
  1395. // HF metadata
  1396. if (frame_header.encoding == FrameHeader::Encoding::kVarDCT) {
  1397. TODO();
  1398. }
  1399. return {};
  1400. }
  1401. ///
  1402. /// H.6 - Transformations
  1403. static void apply_rct(Image& image, TransformInfo const& transformation)
  1404. {
  1405. auto& channels = image.channels();
  1406. for (u32 y {}; y < channels[transformation.begin_c].height(); y++) {
  1407. for (u32 x {}; x < channels[transformation.begin_c].width(); x++) {
  1408. auto a = channels[transformation.begin_c + 0].get(x, y);
  1409. auto b = channels[transformation.begin_c + 1].get(x, y);
  1410. auto c = channels[transformation.begin_c + 2].get(x, y);
  1411. i32 d {};
  1412. i32 e {};
  1413. i32 f {};
  1414. auto const permutation = transformation.rct_type / 7;
  1415. auto const type = transformation.rct_type % 7;
  1416. if (type == 6) { // YCgCo
  1417. auto const tmp = a - (c >> 1);
  1418. e = c + tmp;
  1419. f = tmp - (b >> 1);
  1420. d = f + b;
  1421. } else {
  1422. if (type & 1)
  1423. c = c + a;
  1424. if ((type >> 1) == 1)
  1425. b = b + a;
  1426. if ((type >> 1) == 2)
  1427. b = b + ((a + c) >> 1);
  1428. d = a;
  1429. e = b;
  1430. f = c;
  1431. }
  1432. Array<i32, 3> v {};
  1433. v[permutation % 3] = d;
  1434. v[(permutation + 1 + (permutation / 3)) % 3] = e;
  1435. v[(permutation + 2 - (permutation / 3)) % 3] = f;
  1436. channels[transformation.begin_c + 0].set(x, y, v[0]);
  1437. channels[transformation.begin_c + 1].set(x, y, v[1]);
  1438. channels[transformation.begin_c + 2].set(x, y, v[2]);
  1439. }
  1440. }
  1441. }
  1442. static void apply_transformation(Image& image, TransformInfo const& transformation)
  1443. {
  1444. switch (transformation.tr) {
  1445. case TransformInfo::TransformId::kRCT:
  1446. apply_rct(image, transformation);
  1447. break;
  1448. case TransformInfo::TransformId::kPalette:
  1449. case TransformInfo::TransformId::kSqueeze:
  1450. TODO();
  1451. default:
  1452. VERIFY_NOT_REACHED();
  1453. }
  1454. }
  1455. ///
  1456. /// G.3.2 - PassGroup
  1457. static ErrorOr<void> read_pass_group(LittleEndianInputBitStream& stream,
  1458. Image& image,
  1459. FrameHeader const& frame_header,
  1460. u32 group_dim)
  1461. {
  1462. if (frame_header.encoding == FrameHeader::Encoding::kVarDCT) {
  1463. (void)stream;
  1464. TODO();
  1465. }
  1466. auto& channels = image.channels();
  1467. for (u16 i {}; i < channels.size(); ++i) {
  1468. // Skip meta-channels
  1469. // FIXME: Also test if the channel has already been decoded
  1470. // See: nb_meta_channels in the spec
  1471. bool const is_meta_channel = channels[i].width() <= group_dim
  1472. || channels[i].height() <= group_dim
  1473. || channels[i].hshift() >= 3
  1474. || channels[i].vshift() >= 3;
  1475. if (!is_meta_channel)
  1476. TODO();
  1477. }
  1478. return {};
  1479. }
  1480. ///
  1481. /// Table F.1 — Frame bundle
  1482. struct Frame {
  1483. FrameHeader frame_header;
  1484. TOC toc;
  1485. LfGlobal lf_global;
  1486. u64 width {};
  1487. u64 height {};
  1488. u64 num_groups {};
  1489. u64 num_lf_groups {};
  1490. };
  1491. static ErrorOr<Frame> read_frame(LittleEndianInputBitStream& stream,
  1492. Image& image,
  1493. SizeHeader const& size_header,
  1494. ImageMetadata const& metadata,
  1495. Optional<EntropyDecoder>& entropy_decoder)
  1496. {
  1497. // F.1 - General
  1498. // Each Frame is byte-aligned by invoking ZeroPadToByte() (B.2.7)
  1499. stream.align_to_byte_boundary();
  1500. Frame frame;
  1501. frame.frame_header = TRY(read_frame_header(stream, metadata));
  1502. if (!frame.frame_header.have_crop) {
  1503. frame.width = size_header.width;
  1504. frame.height = size_header.height;
  1505. } else {
  1506. TODO();
  1507. }
  1508. if (frame.frame_header.upsampling > 1) {
  1509. frame.width = ceil(static_cast<double>(frame.width) / frame.frame_header.upsampling);
  1510. frame.height = ceil(static_cast<double>(frame.height) / frame.frame_header.upsampling);
  1511. }
  1512. if (frame.frame_header.lf_level > 0)
  1513. TODO();
  1514. // F.2 - FrameHeader
  1515. auto const group_dim = 128 << frame.frame_header.group_size_shift;
  1516. auto const frame_width = static_cast<double>(frame.width);
  1517. auto const frame_height = static_cast<double>(frame.height);
  1518. frame.num_groups = ceil(frame_width / group_dim) * ceil(frame_height / group_dim);
  1519. frame.num_lf_groups = ceil(frame_width / (group_dim * 8)) * ceil(frame_height / (group_dim * 8));
  1520. frame.toc = TRY(read_toc(stream, frame.frame_header, frame.num_groups, frame.num_lf_groups));
  1521. image = TRY(Image::create({ frame.width, frame.height }, metadata));
  1522. frame.lf_global = TRY(read_lf_global(stream, image, frame.frame_header, metadata, entropy_decoder));
  1523. for (u32 i {}; i < frame.num_lf_groups; ++i)
  1524. TRY(read_lf_group(stream, image, frame.frame_header));
  1525. if (frame.frame_header.encoding == FrameHeader::Encoding::kVarDCT) {
  1526. TODO();
  1527. }
  1528. auto const num_pass_group = frame.num_groups * frame.frame_header.passes.num_passes;
  1529. auto const& transform_infos = frame.lf_global.gmodular.modular_header.transform;
  1530. for (u64 i {}; i < num_pass_group; ++i)
  1531. TRY(read_pass_group(stream, image, frame.frame_header, group_dim));
  1532. // G.4.2 - Modular group data
  1533. // When all modular groups are decoded, the inverse transforms are applied to
  1534. // the at that point fully decoded GlobalModular image, as specified in H.6.
  1535. for (auto const& transformation : transform_infos.in_reverse())
  1536. apply_transformation(image, transformation);
  1537. return frame;
  1538. }
  1539. ///
  1540. /// 5.2 - Mirroring
  1541. static u32 mirror_1d(i32 coord, u32 size)
  1542. {
  1543. if (coord < 0)
  1544. return mirror_1d(-coord - 1, size);
  1545. else if (static_cast<u32>(coord) >= size)
  1546. return mirror_1d(2 * size - 1 - coord, size);
  1547. else
  1548. return coord;
  1549. }
  1550. ///
  1551. /// K - Image features
  1552. static ErrorOr<void> apply_upsampling(Image& image, ImageMetadata const& metadata, Frame const& frame)
  1553. {
  1554. Optional<u32> ec_max;
  1555. for (auto upsampling : frame.frame_header.ec_upsampling) {
  1556. if (!ec_max.has_value() || upsampling > *ec_max)
  1557. ec_max = upsampling;
  1558. }
  1559. if (frame.frame_header.upsampling > 1 || ec_max.value_or(0) > 1) {
  1560. if (ec_max.value_or(0) > 2)
  1561. TODO();
  1562. auto const k = frame.frame_header.upsampling;
  1563. auto weight = [k, &metadata](u8 index) -> double {
  1564. if (k == 2)
  1565. return metadata.up2_weight[index];
  1566. if (k == 4)
  1567. return metadata.up4_weight[index];
  1568. return metadata.up8_weight[index];
  1569. };
  1570. // FIXME: Use ec_upsampling for extra-channels
  1571. for (auto& channel : image.channels()) {
  1572. auto upsampled = TRY(Channel::create(k * channel.width(), k * channel.height()));
  1573. // Loop over the original image
  1574. for (u32 y {}; y < channel.height(); y++) {
  1575. for (u32 x {}; x < channel.width(); x++) {
  1576. // Loop over the upsampling factor
  1577. for (u8 kx {}; kx < k; ++kx) {
  1578. for (u8 ky {}; ky < k; ++ky) {
  1579. double sum {};
  1580. // Loop over the W window
  1581. double W_min = NumericLimits<double>::max();
  1582. double W_max = -NumericLimits<double>::max();
  1583. for (u8 ix {}; ix < 5; ++ix) {
  1584. for (u8 iy {}; iy < 5; ++iy) {
  1585. auto const j = (ky < k / 2) ? (iy + 5 * ky) : ((4 - iy) + 5 * (k - 1 - ky));
  1586. auto const i = (kx < k / 2) ? (ix + 5 * kx) : ((4 - ix) + 5 * (k - 1 - kx));
  1587. auto const minimum = min(i, j);
  1588. auto const maximum = max(i, j);
  1589. auto const index = 5 * k * minimum / 2 - minimum * (minimum - 1) / 2 + maximum - minimum;
  1590. auto const origin_sample_x = mirror_1d(x + ix - 2, channel.width());
  1591. auto const origin_sample_y = mirror_1d(y + iy - 2, channel.height());
  1592. auto const origin_sample = channel.get(origin_sample_x, origin_sample_y);
  1593. W_min = min(W_min, origin_sample);
  1594. W_max = max(W_max, origin_sample);
  1595. sum += origin_sample * weight(index);
  1596. }
  1597. }
  1598. // The resulting sample is clamped to the range [a, b] where a and b are
  1599. // the minimum and maximum of the samples in W.
  1600. sum = clamp(sum, W_min, W_max);
  1601. upsampled.set(x * k + kx, y * k + ky, sum);
  1602. }
  1603. }
  1604. }
  1605. }
  1606. channel = move(upsampled);
  1607. }
  1608. }
  1609. return {};
  1610. }
  1611. static ErrorOr<void> apply_image_features(Image& image, ImageMetadata const& metadata, Frame const& frame)
  1612. {
  1613. TRY(apply_upsampling(image, metadata, frame));
  1614. if (frame.frame_header.flags != FrameHeader::Flags::None)
  1615. TODO();
  1616. return {};
  1617. }
  1618. ///
  1619. /// L.4 - Extra channel rendering
  1620. static ErrorOr<void> render_extra_channels(Image&, ImageMetadata const& metadata)
  1621. {
  1622. for (u16 i = metadata.number_of_color_channels(); i < metadata.number_of_channels(); ++i) {
  1623. auto const ec_index = i - metadata.number_of_color_channels();
  1624. if (metadata.ec_info[ec_index].dim_shift != 0)
  1625. TODO();
  1626. }
  1627. return {};
  1628. }
  1629. ///
  1630. class JPEGXLLoadingContext {
  1631. public:
  1632. JPEGXLLoadingContext(NonnullOwnPtr<Stream> stream)
  1633. : m_stream(move(stream))
  1634. {
  1635. }
  1636. ErrorOr<void> decode_image_header()
  1637. {
  1638. constexpr auto JPEGXL_SIGNATURE = 0xFF0A;
  1639. auto const signature = TRY(m_stream.read_value<BigEndian<u16>>());
  1640. if (signature != JPEGXL_SIGNATURE)
  1641. return Error::from_string_literal("Unrecognized signature");
  1642. m_header = TRY(read_size_header(m_stream));
  1643. m_metadata = TRY(read_metadata_header(m_stream));
  1644. m_state = State::HeaderDecoded;
  1645. return {};
  1646. }
  1647. ErrorOr<void> decode_frame()
  1648. {
  1649. Image image {};
  1650. auto const frame = TRY(read_frame(m_stream, image, m_header, m_metadata, m_entropy_decoder));
  1651. if (frame.frame_header.restoration_filter.gab || frame.frame_header.restoration_filter.epf_iters != 0)
  1652. TODO();
  1653. TRY(apply_image_features(image, m_metadata, frame));
  1654. // FIXME: Do a proper color transformation with metadata.colour_encoding
  1655. if (m_metadata.xyb_encoded || frame.frame_header.do_YCbCr)
  1656. TODO();
  1657. TRY(render_extra_channels(image, m_metadata));
  1658. m_bitmap = TRY(image.to_bitmap(m_metadata));
  1659. return {};
  1660. }
  1661. ErrorOr<void> decode()
  1662. {
  1663. auto result = [this]() -> ErrorOr<void> {
  1664. // A.1 - Codestream structure
  1665. // The header is already decoded in JPEGXLImageDecoderPlugin::create()
  1666. if (m_metadata.colour_encoding.want_icc)
  1667. TODO();
  1668. if (m_metadata.preview.has_value())
  1669. TODO();
  1670. TRY(decode_frame());
  1671. return {};
  1672. }();
  1673. m_state = result.is_error() ? State::Error : State::FrameDecoded;
  1674. return result;
  1675. }
  1676. enum class State {
  1677. NotDecoded = 0,
  1678. Error,
  1679. HeaderDecoded,
  1680. FrameDecoded,
  1681. };
  1682. State state() const
  1683. {
  1684. return m_state;
  1685. }
  1686. IntSize size() const
  1687. {
  1688. return { m_header.width, m_header.height };
  1689. }
  1690. RefPtr<Bitmap> bitmap() const
  1691. {
  1692. return m_bitmap;
  1693. }
  1694. private:
  1695. State m_state { State::NotDecoded };
  1696. LittleEndianInputBitStream m_stream;
  1697. RefPtr<Gfx::Bitmap> m_bitmap;
  1698. Optional<EntropyDecoder> m_entropy_decoder {};
  1699. SizeHeader m_header;
  1700. ImageMetadata m_metadata;
  1701. FrameHeader m_frame_header;
  1702. TOC m_toc;
  1703. };
  1704. JPEGXLImageDecoderPlugin::JPEGXLImageDecoderPlugin(NonnullOwnPtr<FixedMemoryStream> stream)
  1705. {
  1706. m_context = make<JPEGXLLoadingContext>(move(stream));
  1707. }
  1708. JPEGXLImageDecoderPlugin::~JPEGXLImageDecoderPlugin() = default;
  1709. IntSize JPEGXLImageDecoderPlugin::size()
  1710. {
  1711. return m_context->size();
  1712. }
  1713. bool JPEGXLImageDecoderPlugin::sniff(ReadonlyBytes data)
  1714. {
  1715. return data.size() > 2
  1716. && data.data()[0] == 0xFF
  1717. && data.data()[1] == 0x0A;
  1718. }
  1719. ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> JPEGXLImageDecoderPlugin::create(ReadonlyBytes data)
  1720. {
  1721. auto stream = TRY(try_make<FixedMemoryStream>(data));
  1722. auto plugin = TRY(adopt_nonnull_own_or_enomem(new (nothrow) JPEGXLImageDecoderPlugin(move(stream))));
  1723. TRY(plugin->m_context->decode_image_header());
  1724. return plugin;
  1725. }
  1726. bool JPEGXLImageDecoderPlugin::is_animated()
  1727. {
  1728. return false;
  1729. }
  1730. size_t JPEGXLImageDecoderPlugin::loop_count()
  1731. {
  1732. return 0;
  1733. }
  1734. size_t JPEGXLImageDecoderPlugin::frame_count()
  1735. {
  1736. return 1;
  1737. }
  1738. size_t JPEGXLImageDecoderPlugin::first_animated_frame_index()
  1739. {
  1740. return 0;
  1741. }
  1742. ErrorOr<ImageFrameDescriptor> JPEGXLImageDecoderPlugin::frame(size_t index, Optional<IntSize>)
  1743. {
  1744. if (index > 0)
  1745. return Error::from_string_literal("JPEGXLImageDecoderPlugin: Invalid frame index");
  1746. if (m_context->state() == JPEGXLLoadingContext::State::Error)
  1747. return Error::from_string_literal("JPEGXLImageDecoderPlugin: Decoding failed");
  1748. if (m_context->state() < JPEGXLLoadingContext::State::FrameDecoded)
  1749. TRY(m_context->decode());
  1750. return ImageFrameDescriptor { m_context->bitmap(), 0 };
  1751. }
  1752. ErrorOr<Optional<ReadonlyBytes>> JPEGXLImageDecoderPlugin::icc_data()
  1753. {
  1754. return OptionalNone {};
  1755. }
  1756. }